File size: 49,864 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
import type {
  CacheNodeSeedData,
  FlightRouterState,
  FlightSegmentPath,
  Segment,
} from '../../../server/app-render/types'
import type {
  CacheNode,
  ChildSegmentMap,
  HeadData,
  LoadingModuleData,
  ReadyCacheNode,
} from '../../../shared/lib/app-router-context.shared-runtime'
import { DEFAULT_SEGMENT_KEY } from '../../../shared/lib/segment'
import { matchSegment } from '../match-segments'
import { createRouterCacheKey } from './create-router-cache-key'
import type { FetchServerResponseResult } from './fetch-server-response'
import { isNavigatingToNewRootLayout } from './is-navigating-to-new-root-layout'
import { DYNAMIC_STALETIME_MS } from './prefetch-cache-utils'

// This is yet another tree type that is used to track pending promises that
// need to be fulfilled once the dynamic data is received. The terminal nodes of
// this tree represent the new Cache Node trees that were created during this
// request. We can't use the Cache Node tree or Route State tree directly
// because those include reused nodes, too. This tree is discarded as soon as
// the navigation response is received.
type SPANavigationTask = {
  // The router state that corresponds to the tree that this Task represents.
  route: FlightRouterState
  // The CacheNode that corresponds to the tree that this Task represents. If
  // `children` is null (i.e. if this is a terminal task node), then `node`
  // represents a brand new Cache Node tree, which way or may not need to be
  // filled with dynamic data from the server.
  node: CacheNode | null
  // The tree sent to the server during the dynamic request. This is the
  // same as `route`, except with the `refetch` marker set on dynamic segments.
  // If all the segments are static, then this will be null, and no server
  // request is required.
  dynamicRequestTree: FlightRouterState | null
  children: Map<string, SPANavigationTask> | null
}

// A special type used to bail out and trigger a full-page navigation.
type MPANavigationTask = {
  // MPA tasks are distinguised from SPA tasks by having a null `route`.
  route: null
  node: null
  dynamicRequestTree: null
  children: null
}

const MPA_NAVIGATION_TASK: MPANavigationTask = {
  route: null,
  node: null,
  dynamicRequestTree: null,
  children: null,
}

export type Task = SPANavigationTask | MPANavigationTask

// Creates a new Cache Node tree (i.e. copy-on-write) that represents the
// optimistic result of a navigation, using both the current Cache Node tree and
// data that was prefetched prior to navigation.
//
// At the moment we call this function, we haven't yet received the navigation
// response from the server. It could send back something completely different
// from the tree that was prefetched — due to rewrites, default routes, parallel
// routes, etc.
//
// But in most cases, it will return the same tree that we prefetched, just with
// the dynamic holes filled in. So we optimistically assume this will happen,
// and accept that the real result could be arbitrarily different.
//
// We'll reuse anything that was already in the previous tree, since that's what
// the server does.
//
// New segments (ones that don't appear in the old tree) are assigned an
// unresolved promise. The data for these promises will be fulfilled later, when
// the navigation response is received.
//
// The tree can be rendered immediately after it is created (that's why this is
// a synchronous function). Any new trees that do not have prefetch data will
// suspend during rendering, until the dynamic data streams in.
//
// Returns a Task object, which contains both the updated Cache Node and a path
// to the pending subtrees that need to be resolved by the navigation response.
//
// A return value of `null` means there were no changes, and the previous tree
// can be reused without initiating a server request.
export function startPPRNavigation(
  navigatedAt: number,
  oldCacheNode: CacheNode,
  oldRouterState: FlightRouterState,
  newRouterState: FlightRouterState,
  prefetchData: CacheNodeSeedData | null,
  prefetchHead: HeadData | null,
  isPrefetchHeadPartial: boolean,
  isSamePageNavigation: boolean,
  scrollableSegmentsResult: Array<FlightSegmentPath>
): Task | null {
  const segmentPath: Array<FlightSegmentPath> = []
  return updateCacheNodeOnNavigation(
    navigatedAt,
    oldCacheNode,
    oldRouterState,
    newRouterState,
    false,
    prefetchData,
    prefetchHead,
    isPrefetchHeadPartial,
    isSamePageNavigation,
    segmentPath,
    scrollableSegmentsResult
  )
}

function updateCacheNodeOnNavigation(
  navigatedAt: number,
  oldCacheNode: CacheNode,
  oldRouterState: FlightRouterState,
  newRouterState: FlightRouterState,
  didFindRootLayout: boolean,
  prefetchData: CacheNodeSeedData | null,
  prefetchHead: HeadData | null,
  isPrefetchHeadPartial: boolean,
  isSamePageNavigation: boolean,
  segmentPath: FlightSegmentPath,
  scrollableSegmentsResult: Array<FlightSegmentPath>
): Task | null {
  // Diff the old and new trees to reuse the shared layouts.
  const oldRouterStateChildren = oldRouterState[1]
  const newRouterStateChildren = newRouterState[1]
  const prefetchDataChildren = prefetchData !== null ? prefetchData[2] : null

  if (!didFindRootLayout) {
    // We're currently traversing the part of the tree that was also part of
    // the previous route. If we discover a root layout, then we don't need to
    // trigger an MPA navigation. See beginRenderingNewRouteTree for context.
    const isRootLayout = newRouterState[4] === true
    if (isRootLayout) {
      // Found a matching root layout.
      didFindRootLayout = true
    }
  }

  const oldParallelRoutes = oldCacheNode.parallelRoutes

  // Clone the current set of segment children, even if they aren't active in
  // the new tree.
  // TODO: We currently retain all the inactive segments indefinitely, until
  // there's an explicit refresh, or a parent layout is lazily refreshed. We
  // rely on this for popstate navigations, which update the Router State Tree
  // but do not eagerly perform a data fetch, because they expect the segment
  // data to already be in the Cache Node tree. For highly static sites that
  // are mostly read-only, this may happen only rarely, causing memory to
  // leak. We should figure out a better model for the lifetime of inactive
  // segments, so we can maintain instant back/forward navigations without
  // leaking memory indefinitely.
  const prefetchParallelRoutes = new Map(oldParallelRoutes)

  // As we diff the trees, we may sometimes modify (copy-on-write, not mutate)
  // the Route Tree that was returned by the server — for example, in the case
  // of default parallel routes, we preserve the currently active segment. To
  // avoid mutating the original tree, we clone the router state children along
  // the return path.
  let patchedRouterStateChildren: {
    [parallelRouteKey: string]: FlightRouterState
  } = {}
  let taskChildren = null

  // Most navigations require a request to fetch additional data from the
  // server, either because the data was not already prefetched, or because the
  // target route contains dynamic data that cannot be prefetched.
  //
  // However, if the target route is fully static, and it's already completely
  // loaded into the segment cache, then we can skip the server request.
  //
  // This starts off as `false`, and is set to `true` if any of the child
  // routes requires a dynamic request.
  let needsDynamicRequest = false
  // As we traverse the children, we'll construct a FlightRouterState that can
  // be sent to the server to request the dynamic data. If it turns out that
  // nothing in the subtree is dynamic (i.e. needsDynamicRequest is false at the
  // end), then this will be discarded.
  // TODO: We can probably optimize the format of this data structure to only
  // include paths that are dynamic. Instead of reusing the
  // FlightRouterState type.
  let dynamicRequestTreeChildren: {
    [parallelRouteKey: string]: FlightRouterState
  } = {}

  for (let parallelRouteKey in newRouterStateChildren) {
    const newRouterStateChild: FlightRouterState =
      newRouterStateChildren[parallelRouteKey]
    const oldRouterStateChild: FlightRouterState | void =
      oldRouterStateChildren[parallelRouteKey]
    const oldSegmentMapChild = oldParallelRoutes.get(parallelRouteKey)
    const prefetchDataChild: CacheNodeSeedData | void | null =
      prefetchDataChildren !== null
        ? prefetchDataChildren[parallelRouteKey]
        : null

    const newSegmentChild = newRouterStateChild[0]
    const newSegmentPathChild = segmentPath.concat([
      parallelRouteKey,
      newSegmentChild,
    ])
    const newSegmentKeyChild = createRouterCacheKey(newSegmentChild)

    const oldSegmentChild =
      oldRouterStateChild !== undefined ? oldRouterStateChild[0] : undefined

    const oldCacheNodeChild =
      oldSegmentMapChild !== undefined
        ? oldSegmentMapChild.get(newSegmentKeyChild)
        : undefined

    let taskChild: Task | null
    if (newSegmentChild === DEFAULT_SEGMENT_KEY) {
      // This is another kind of leaf segment — a default route.
      //
      // Default routes have special behavior. When there's no matching segment
      // for a parallel route, Next.js preserves the currently active segment
      // during a client navigation — but not for initial render. The server
      // leaves it to the client to account for this. So we need to handle
      // it here.
      if (oldRouterStateChild !== undefined) {
        // Reuse the existing Router State for this segment. We spawn a "task"
        // just to keep track of the updated router state; unlike most, it's
        // already fulfilled and won't be affected by the dynamic response.
        taskChild = spawnReusedTask(oldRouterStateChild)
      } else {
        // There's no currently active segment. Switch to the "create" path.
        taskChild = beginRenderingNewRouteTree(
          navigatedAt,
          oldRouterStateChild,
          newRouterStateChild,
          oldCacheNodeChild,
          didFindRootLayout,
          prefetchDataChild !== undefined ? prefetchDataChild : null,
          prefetchHead,
          isPrefetchHeadPartial,
          newSegmentPathChild,
          scrollableSegmentsResult
        )
      }
    } else if (
      isSamePageNavigation &&
      // Check if this is a page segment.
      // TODO: We're not consistent about how we do this check. Some places
      // check if the segment starts with PAGE_SEGMENT_KEY, but most seem to
      // check if there any any children, which is why I'm doing it here. We
      // should probably encode an empty children set as `null` though. Either
      // way, we should update all the checks to be consistent.
      Object.keys(newRouterStateChild[1]).length === 0
    ) {
      // We special case navigations to the exact same URL as the current
      // location. It's a common UI pattern for apps to refresh when you click a
      // link to the current page. So when this happens, we refresh the dynamic
      // data in the page segments.
      //
      // Note that this does not apply if the any part of the hash or search
      // query has changed. This might feel a bit weird but it makes more sense
      // when you consider that the way to trigger this behavior is to click
      // the same link multiple times.
      //
      // TODO: We should probably refresh the *entire* route when this case
      // occurs, not just the page segments. Essentially treating it the same as
      // a refresh() triggered by an action, which is the more explicit way of
      // modeling the UI pattern described above.
      //
      // Also note that this only refreshes the dynamic data, not static/
      // cached data. If the page segment is fully static and prefetched, the
      // request is skipped. (This is also how refresh() works.)
      taskChild = beginRenderingNewRouteTree(
        navigatedAt,
        oldRouterStateChild,
        newRouterStateChild,
        oldCacheNodeChild,
        didFindRootLayout,
        prefetchDataChild !== undefined ? prefetchDataChild : null,
        prefetchHead,
        isPrefetchHeadPartial,
        newSegmentPathChild,
        scrollableSegmentsResult
      )
    } else if (
      oldRouterStateChild !== undefined &&
      oldSegmentChild !== undefined &&
      matchSegment(newSegmentChild, oldSegmentChild)
    ) {
      if (
        oldCacheNodeChild !== undefined &&
        oldRouterStateChild !== undefined
      ) {
        // This segment exists in both the old and new trees. Recursively update
        // the children.
        taskChild = updateCacheNodeOnNavigation(
          navigatedAt,
          oldCacheNodeChild,
          oldRouterStateChild,
          newRouterStateChild,
          didFindRootLayout,
          prefetchDataChild,
          prefetchHead,
          isPrefetchHeadPartial,
          isSamePageNavigation,
          newSegmentPathChild,
          scrollableSegmentsResult
        )
      } else {
        // There's no existing Cache Node for this segment. Switch to the
        // "create" path.
        taskChild = beginRenderingNewRouteTree(
          navigatedAt,
          oldRouterStateChild,
          newRouterStateChild,
          oldCacheNodeChild,
          didFindRootLayout,
          prefetchDataChild !== undefined ? prefetchDataChild : null,
          prefetchHead,
          isPrefetchHeadPartial,
          newSegmentPathChild,
          scrollableSegmentsResult
        )
      }
    } else {
      // This is a new tree. Switch to the "create" path.
      taskChild = beginRenderingNewRouteTree(
        navigatedAt,
        oldRouterStateChild,
        newRouterStateChild,
        oldCacheNodeChild,
        didFindRootLayout,
        prefetchDataChild !== undefined ? prefetchDataChild : null,
        prefetchHead,
        isPrefetchHeadPartial,
        newSegmentPathChild,
        scrollableSegmentsResult
      )
    }

    if (taskChild !== null) {
      // Recursively propagate up the child tasks.

      if (taskChild.route === null) {
        // One of the child tasks discovered a change to the root layout.
        // Immediately unwind from this recursive traversal.
        return MPA_NAVIGATION_TASK
      }

      if (taskChildren === null) {
        taskChildren = new Map()
      }
      taskChildren.set(parallelRouteKey, taskChild)
      const newCacheNodeChild = taskChild.node
      if (newCacheNodeChild !== null) {
        const newSegmentMapChild: ChildSegmentMap = new Map(oldSegmentMapChild)
        newSegmentMapChild.set(newSegmentKeyChild, newCacheNodeChild)
        prefetchParallelRoutes.set(parallelRouteKey, newSegmentMapChild)
      }

      // The child tree's route state may be different from the prefetched
      // route sent by the server. We need to clone it as we traverse back up
      // the tree.
      const taskChildRoute = taskChild.route
      patchedRouterStateChildren[parallelRouteKey] = taskChildRoute

      const dynamicRequestTreeChild = taskChild.dynamicRequestTree
      if (dynamicRequestTreeChild !== null) {
        // Something in the child tree is dynamic.
        needsDynamicRequest = true
        dynamicRequestTreeChildren[parallelRouteKey] = dynamicRequestTreeChild
      } else {
        dynamicRequestTreeChildren[parallelRouteKey] = taskChildRoute
      }
    } else {
      // The child didn't change. We can use the prefetched router state.
      patchedRouterStateChildren[parallelRouteKey] = newRouterStateChild
      dynamicRequestTreeChildren[parallelRouteKey] = newRouterStateChild
    }
  }

  if (taskChildren === null) {
    // No new tasks were spawned.
    return null
  }

  const newCacheNode: ReadyCacheNode = {
    lazyData: null,
    rsc: oldCacheNode.rsc,
    // We intentionally aren't updating the prefetchRsc field, since this node
    // is already part of the current tree, because it would be weird for
    // prefetch data to be newer than the final data. It probably won't ever be
    // observable anyway, but it could happen if the segment is unmounted then
    // mounted again, because LayoutRouter will momentarily switch to rendering
    // prefetchRsc, via useDeferredValue.
    prefetchRsc: oldCacheNode.prefetchRsc,
    head: oldCacheNode.head,
    prefetchHead: oldCacheNode.prefetchHead,
    loading: oldCacheNode.loading,

    // Everything is cloned except for the children, which we computed above.
    parallelRoutes: prefetchParallelRoutes,

    navigatedAt,
  }

  return {
    // Return a cloned copy of the router state with updated children.
    route: patchRouterStateWithNewChildren(
      newRouterState,
      patchedRouterStateChildren
    ),
    node: newCacheNode,
    dynamicRequestTree: needsDynamicRequest
      ? patchRouterStateWithNewChildren(
          newRouterState,
          dynamicRequestTreeChildren
        )
      : null,
    children: taskChildren,
  }
}

function beginRenderingNewRouteTree(
  navigatedAt: number,
  oldRouterState: FlightRouterState | void,
  newRouterState: FlightRouterState,
  existingCacheNode: CacheNode | void,
  didFindRootLayout: boolean,
  prefetchData: CacheNodeSeedData | null,
  possiblyPartialPrefetchHead: HeadData | null,
  isPrefetchHeadPartial: boolean,
  segmentPath: FlightSegmentPath,
  scrollableSegmentsResult: Array<FlightSegmentPath>
): Task {
  if (!didFindRootLayout) {
    // The route tree changed before we reached a layout. (The highest-level
    // layout in a route tree is referred to as the "root" layout.) This could
    // mean that we're navigating between two different root layouts. When this
    // happens, we perform a full-page (MPA-style) navigation.
    //
    // However, the algorithm for deciding where to start rendering a route
    // (i.e. the one performed in order to reach this function) is stricter
    // than the one used to detect a change in the root layout. So just because
    // we're re-rendering a segment outside of the root layout does not mean we
    // should trigger a full-page navigation.
    //
    // Specifically, we handle dynamic parameters differently: two segments are
    // considered the same even if their parameter values are different.
    //
    // Refer to isNavigatingToNewRootLayout for details.
    //
    // Note that we only have to perform this extra traversal if we didn't
    // already discover a root layout in the part of the tree that is unchanged.
    // In the common case, this branch is skipped completely.
    if (
      oldRouterState === undefined ||
      isNavigatingToNewRootLayout(oldRouterState, newRouterState)
    ) {
      // The root layout changed. Perform a full-page navigation.
      return MPA_NAVIGATION_TASK
    }
  }
  return createCacheNodeOnNavigation(
    navigatedAt,
    newRouterState,
    existingCacheNode,
    prefetchData,
    possiblyPartialPrefetchHead,
    isPrefetchHeadPartial,
    segmentPath,
    scrollableSegmentsResult
  )
}

function createCacheNodeOnNavigation(
  navigatedAt: number,
  routerState: FlightRouterState,
  existingCacheNode: CacheNode | void,
  prefetchData: CacheNodeSeedData | null,
  possiblyPartialPrefetchHead: HeadData | null,
  isPrefetchHeadPartial: boolean,
  segmentPath: FlightSegmentPath,
  scrollableSegmentsResult: Array<FlightSegmentPath>
): SPANavigationTask {
  // Same traversal as updateCacheNodeNavigation, but we switch to this path
  // once we reach the part of the tree that was not in the previous route. We
  // don't need to diff against the old tree, we just need to create a new one.

  // The head is assigned to every leaf segment delivered by the server. Based
  // on corresponding logic in fill-lazy-items-till-leaf-with-head.ts
  const routerStateChildren = routerState[1]
  const isLeafSegment = Object.keys(routerStateChildren).length === 0

  // Even we're rendering inside the "new" part of the target tree, we may have
  // a locally cached segment that we can reuse. This may come from either 1)
  // the CacheNode tree, which lives in React state and is populated by previous
  // navigations; or 2) the prefetch cache, which is a separate cache that is
  // populated by prefetches.
  let rsc: React.ReactNode
  let loading: LoadingModuleData | Promise<LoadingModuleData>
  let head: HeadData | null
  let cacheNodeNavigatedAt: number
  if (
    existingCacheNode !== undefined &&
    // DYNAMIC_STALETIME_MS defaults to 0, but it can be increased using
    // the experimental.staleTimes.dynamic config. When set, we'll avoid
    // refetching dynamic data if it was fetched within the given threshold.
    existingCacheNode.navigatedAt + DYNAMIC_STALETIME_MS > navigatedAt
  ) {
    // We have an existing CacheNode for this segment, and it's not stale. We
    // should reuse it rather than request a new one.
    rsc = existingCacheNode.rsc
    loading = existingCacheNode.loading
    head = existingCacheNode.head

    // Don't update the navigatedAt timestamp, since we're reusing stale data.
    cacheNodeNavigatedAt = existingCacheNode.navigatedAt
  } else if (prefetchData !== null) {
    // There's no existing CacheNode for this segment, but we do have prefetch
    // data. If the prefetch data is fully static (i.e. does not contain any
    // dynamic holes), we don't need to request it from the server.
    rsc = prefetchData[1]
    loading = prefetchData[3]
    head = isLeafSegment ? possiblyPartialPrefetchHead : null
    // Even though we're accessing the data from the prefetch cache, this is
    // conceptually a new segment, not a reused one. So we should update the
    // navigatedAt timestamp.
    cacheNodeNavigatedAt = navigatedAt
    const isPrefetchRscPartial = prefetchData[4]
    if (
      // Check if the segment data is partial
      isPrefetchRscPartial ||
      // Check if the head is partial (only relevant if this is a leaf segment)
      (isPrefetchHeadPartial && isLeafSegment)
    ) {
      // We only have partial data from this segment. Like missing segments, we
      // must request the full data from the server.
      return spawnPendingTask(
        navigatedAt,
        routerState,
        prefetchData,
        possiblyPartialPrefetchHead,
        isPrefetchHeadPartial,
        segmentPath,
        scrollableSegmentsResult
      )
    } else {
      // The prefetch data is fully static, so we can omit it from the
      // navigation request.
    }
  } else {
    // There's no prefetch for this segment. Everything from this point will be
    // requested from the server, even if there are static children below it.
    // Create a terminal task node that will later be fulfilled by
    // server response.
    return spawnPendingTask(
      navigatedAt,
      routerState,
      null,
      possiblyPartialPrefetchHead,
      isPrefetchHeadPartial,
      segmentPath,
      scrollableSegmentsResult
    )
  }

  // We already have a full segment we can render, so we don't need to request a
  // new one from the server. Keep traversing down the tree until we reach
  // something that requires a dynamic request.
  const prefetchDataChildren = prefetchData !== null ? prefetchData[2] : null
  const taskChildren = new Map()
  const existingCacheNodeChildren =
    existingCacheNode !== undefined ? existingCacheNode.parallelRoutes : null
  const cacheNodeChildren = new Map(existingCacheNodeChildren)
  let dynamicRequestTreeChildren: {
    [parallelRouteKey: string]: FlightRouterState
  } = {}
  let needsDynamicRequest = false
  if (isLeafSegment) {
    // The segment path of every leaf segment (i.e. page) is collected into
    // a result array. This is used by the LayoutRouter to scroll to ensure that
    // new pages are visible after a navigation.
    // TODO: We should use a string to represent the segment path instead of
    // an array. We already use a string representation for the path when
    // accessing the Segment Cache, so we can use the same one.
    scrollableSegmentsResult.push(segmentPath)
  } else {
    for (let parallelRouteKey in routerStateChildren) {
      const routerStateChild: FlightRouterState =
        routerStateChildren[parallelRouteKey]
      const prefetchDataChild: CacheNodeSeedData | void | null =
        prefetchDataChildren !== null
          ? prefetchDataChildren[parallelRouteKey]
          : null
      const existingSegmentMapChild =
        existingCacheNodeChildren !== null
          ? existingCacheNodeChildren.get(parallelRouteKey)
          : undefined
      const segmentChild = routerStateChild[0]
      const segmentPathChild = segmentPath.concat([
        parallelRouteKey,
        segmentChild,
      ])
      const segmentKeyChild = createRouterCacheKey(segmentChild)

      const existingCacheNodeChild =
        existingSegmentMapChild !== undefined
          ? existingSegmentMapChild.get(segmentKeyChild)
          : undefined

      const taskChild = createCacheNodeOnNavigation(
        navigatedAt,
        routerStateChild,
        existingCacheNodeChild,
        prefetchDataChild,
        possiblyPartialPrefetchHead,
        isPrefetchHeadPartial,
        segmentPathChild,
        scrollableSegmentsResult
      )
      taskChildren.set(parallelRouteKey, taskChild)
      const dynamicRequestTreeChild = taskChild.dynamicRequestTree
      if (dynamicRequestTreeChild !== null) {
        // Something in the child tree is dynamic.
        needsDynamicRequest = true
        dynamicRequestTreeChildren[parallelRouteKey] = dynamicRequestTreeChild
      } else {
        dynamicRequestTreeChildren[parallelRouteKey] = routerStateChild
      }
      const newCacheNodeChild = taskChild.node
      if (newCacheNodeChild !== null) {
        const newSegmentMapChild: ChildSegmentMap = new Map()
        newSegmentMapChild.set(segmentKeyChild, newCacheNodeChild)
        cacheNodeChildren.set(parallelRouteKey, newSegmentMapChild)
      }
    }
  }

  return {
    // Since we're inside a new route tree, unlike the
    // `updateCacheNodeOnNavigation` path, the router state on the children
    // tasks is always the same as the router state we pass in. So we don't need
    // to clone/modify it.
    route: routerState,
    node: {
      lazyData: null,
      // Since this segment is already full, we don't need to use the
      // `prefetchRsc` field.
      rsc,
      prefetchRsc: null,
      head,
      prefetchHead: null,
      loading,
      parallelRoutes: cacheNodeChildren,
      navigatedAt: cacheNodeNavigatedAt,
    },
    dynamicRequestTree: needsDynamicRequest
      ? patchRouterStateWithNewChildren(routerState, dynamicRequestTreeChildren)
      : null,
    children: taskChildren,
  }
}

function patchRouterStateWithNewChildren(
  baseRouterState: FlightRouterState,
  newChildren: { [parallelRouteKey: string]: FlightRouterState }
): FlightRouterState {
  const clone: FlightRouterState = [baseRouterState[0], newChildren]
  // Based on equivalent logic in apply-router-state-patch-to-tree, but should
  // confirm whether we need to copy all of these fields. Not sure the server
  // ever sends, e.g. the refetch marker.
  if (2 in baseRouterState) {
    clone[2] = baseRouterState[2]
  }
  if (3 in baseRouterState) {
    clone[3] = baseRouterState[3]
  }
  if (4 in baseRouterState) {
    clone[4] = baseRouterState[4]
  }
  return clone
}

function spawnPendingTask(
  navigatedAt: number,
  routerState: FlightRouterState,
  prefetchData: CacheNodeSeedData | null,
  prefetchHead: HeadData | null,
  isPrefetchHeadPartial: boolean,
  segmentPath: FlightSegmentPath,
  scrollableSegmentsResult: Array<FlightSegmentPath>
): SPANavigationTask {
  // Create a task that will later be fulfilled by data from the server.

  // Clone the prefetched route tree and the `refetch` marker to it. We'll send
  // this to the server so it knows where to start rendering.
  const dynamicRequestTree = patchRouterStateWithNewChildren(
    routerState,
    routerState[1]
  )
  dynamicRequestTree[3] = 'refetch'

  const newTask: Task = {
    route: routerState,

    // Corresponds to the part of the route that will be rendered on the server.
    node: createPendingCacheNode(
      navigatedAt,
      routerState,
      prefetchData,
      prefetchHead,
      isPrefetchHeadPartial,
      segmentPath,
      scrollableSegmentsResult
    ),
    // Because this is non-null, and it gets propagated up through the parent
    // tasks, the root task will know that it needs to perform a server request.
    dynamicRequestTree,
    children: null,
  }
  return newTask
}

function spawnReusedTask(reusedRouterState: FlightRouterState): Task {
  // Create a task that reuses an existing segment, e.g. when reusing
  // the current active segment in place of a default route.
  return {
    route: reusedRouterState,
    node: null,
    dynamicRequestTree: null,
    children: null,
  }
}

// Writes a dynamic server response into the tree created by
// updateCacheNodeOnNavigation. All pending promises that were spawned by the
// navigation will be resolved, either with dynamic data from the server, or
// `null` to indicate that the data is missing.
//
// A `null` value will trigger a lazy fetch during render, which will then patch
// up the tree using the same mechanism as the non-PPR implementation
// (serverPatchReducer).
//
// Usually, the server will respond with exactly the subset of data that we're
// waiting for — everything below the nearest shared layout. But technically,
// the server can return anything it wants.
//
// This does _not_ create a new tree; it modifies the existing one in place.
// Which means it must follow the Suspense rules of cache safety.
export function listenForDynamicRequest(
  task: SPANavigationTask,
  responsePromise: Promise<FetchServerResponseResult>
) {
  responsePromise.then(
    ({ flightData }: FetchServerResponseResult) => {
      if (typeof flightData === 'string') {
        // Happens when navigating to page in `pages` from `app`. We shouldn't
        // get here because should have already handled this during
        // the prefetch.
        return
      }
      for (const normalizedFlightData of flightData) {
        const {
          segmentPath,
          tree: serverRouterState,
          seedData: dynamicData,
          head: dynamicHead,
        } = normalizedFlightData

        if (!dynamicData) {
          // This shouldn't happen. PPR should always send back a response.
          // However, `FlightDataPath` is a shared type and the pre-PPR handling of
          // this might return null.
          continue
        }

        writeDynamicDataIntoPendingTask(
          task,
          segmentPath,
          serverRouterState,
          dynamicData,
          dynamicHead
        )
      }

      // Now that we've exhausted all the data we received from the server, if
      // there are any remaining pending tasks in the tree, abort them now.
      // If there's any missing data, it will trigger a lazy fetch.
      abortTask(task, null)
    },
    (error: any) => {
      // This will trigger an error during render
      abortTask(task, error)
    }
  )
}

function writeDynamicDataIntoPendingTask(
  rootTask: SPANavigationTask,
  segmentPath: FlightSegmentPath,
  serverRouterState: FlightRouterState,
  dynamicData: CacheNodeSeedData,
  dynamicHead: HeadData
) {
  // The data sent by the server represents only a subtree of the app. We need
  // to find the part of the task tree that matches the server response, and
  // fulfill it using the dynamic data.
  //
  // segmentPath represents the parent path of subtree. It's a repeating pattern
  // of parallel route key and segment:
  //
  //   [string, Segment, string, Segment, string, Segment, ...]
  //
  // Iterate through the path and finish any tasks that match this payload.
  let task = rootTask
  for (let i = 0; i < segmentPath.length; i += 2) {
    const parallelRouteKey: string = segmentPath[i]
    const segment: Segment = segmentPath[i + 1]
    const taskChildren = task.children
    if (taskChildren !== null) {
      const taskChild = taskChildren.get(parallelRouteKey)
      if (taskChild !== undefined) {
        const taskSegment = taskChild.route[0]
        if (matchSegment(segment, taskSegment)) {
          // Found a match for this task. Keep traversing down the task tree.
          task = taskChild
          continue
        }
      }
    }
    // We didn't find a child task that matches the server data. Exit. We won't
    // abort the task, though, because a different FlightDataPath may be able to
    // fulfill it (see loop in listenForDynamicRequest). We only abort tasks
    // once we've run out of data.
    return
  }

  finishTaskUsingDynamicDataPayload(
    task,
    serverRouterState,
    dynamicData,
    dynamicHead
  )
}

function finishTaskUsingDynamicDataPayload(
  task: SPANavigationTask,
  serverRouterState: FlightRouterState,
  dynamicData: CacheNodeSeedData,
  dynamicHead: HeadData
) {
  if (task.dynamicRequestTree === null) {
    // Everything in this subtree is already complete. Bail out.
    return
  }

  // dynamicData may represent a larger subtree than the task. Before we can
  // finish the task, we need to line them up.
  const taskChildren = task.children
  const taskNode = task.node
  if (taskChildren === null) {
    // We've reached the leaf node of the pending task. The server data tree
    // lines up the pending Cache Node tree. We can now switch to the
    // normal algorithm.
    if (taskNode !== null) {
      finishPendingCacheNode(
        taskNode,
        task.route,
        serverRouterState,
        dynamicData,
        dynamicHead
      )
      // Set this to null to indicate that this task is now complete.
      task.dynamicRequestTree = null
    }
    return
  }
  // The server returned more data than we need to finish the task. Skip over
  // the extra segments until we reach the leaf task node.
  const serverChildren = serverRouterState[1]
  const dynamicDataChildren = dynamicData[2]

  for (const parallelRouteKey in serverRouterState) {
    const serverRouterStateChild: FlightRouterState =
      serverChildren[parallelRouteKey]
    const dynamicDataChild: CacheNodeSeedData | null | void =
      dynamicDataChildren[parallelRouteKey]

    const taskChild = taskChildren.get(parallelRouteKey)
    if (taskChild !== undefined) {
      const taskSegment = taskChild.route[0]
      if (
        matchSegment(serverRouterStateChild[0], taskSegment) &&
        dynamicDataChild !== null &&
        dynamicDataChild !== undefined
      ) {
        // Found a match for this task. Keep traversing down the task tree.
        return finishTaskUsingDynamicDataPayload(
          taskChild,
          serverRouterStateChild,
          dynamicDataChild,
          dynamicHead
        )
      }
    }
    // We didn't find a child task that matches the server data. We won't abort
    // the task, though, because a different FlightDataPath may be able to
    // fulfill it (see loop in listenForDynamicRequest). We only abort tasks
    // once we've run out of data.
  }
}

function createPendingCacheNode(
  navigatedAt: number,
  routerState: FlightRouterState,
  prefetchData: CacheNodeSeedData | null,
  prefetchHead: HeadData | null,
  isPrefetchHeadPartial: boolean,
  segmentPath: FlightSegmentPath,
  scrollableSegmentsResult: Array<FlightSegmentPath>
): ReadyCacheNode {
  const routerStateChildren = routerState[1]
  const prefetchDataChildren = prefetchData !== null ? prefetchData[2] : null

  const parallelRoutes = new Map()
  for (let parallelRouteKey in routerStateChildren) {
    const routerStateChild: FlightRouterState =
      routerStateChildren[parallelRouteKey]
    const prefetchDataChild: CacheNodeSeedData | null | void =
      prefetchDataChildren !== null
        ? prefetchDataChildren[parallelRouteKey]
        : null

    const segmentChild = routerStateChild[0]
    const segmentPathChild = segmentPath.concat([
      parallelRouteKey,
      segmentChild,
    ])
    const segmentKeyChild = createRouterCacheKey(segmentChild)

    const newCacheNodeChild = createPendingCacheNode(
      navigatedAt,
      routerStateChild,
      prefetchDataChild === undefined ? null : prefetchDataChild,
      prefetchHead,
      isPrefetchHeadPartial,
      segmentPathChild,
      scrollableSegmentsResult
    )

    const newSegmentMapChild: ChildSegmentMap = new Map()
    newSegmentMapChild.set(segmentKeyChild, newCacheNodeChild)
    parallelRoutes.set(parallelRouteKey, newSegmentMapChild)
  }

  // The head is assigned to every leaf segment delivered by the server. Based
  // on corresponding logic in fill-lazy-items-till-leaf-with-head.ts
  const isLeafSegment = parallelRoutes.size === 0

  if (isLeafSegment) {
    // The segment path of every leaf segment (i.e. page) is collected into
    // a result array. This is used by the LayoutRouter to scroll to ensure that
    // new pages are visible after a navigation.
    // TODO: We should use a string to represent the segment path instead of
    // an array. We already use a string representation for the path when
    // accessing the Segment Cache, so we can use the same one.
    scrollableSegmentsResult.push(segmentPath)
  }

  const maybePrefetchRsc = prefetchData !== null ? prefetchData[1] : null
  const maybePrefetchLoading = prefetchData !== null ? prefetchData[3] : null
  return {
    lazyData: null,
    parallelRoutes: parallelRoutes,

    prefetchRsc: maybePrefetchRsc !== undefined ? maybePrefetchRsc : null,
    prefetchHead: isLeafSegment ? prefetchHead : [null, null],

    // TODO: Technically, a loading boundary could contain dynamic data. We must
    // have separate `loading` and `prefetchLoading` fields to handle this, like
    // we do for the segment data and head.
    loading: maybePrefetchLoading !== undefined ? maybePrefetchLoading : null,

    // Create a deferred promise. This will be fulfilled once the dynamic
    // response is received from the server.
    rsc: createDeferredRsc() as React.ReactNode,
    head: isLeafSegment ? (createDeferredRsc() as React.ReactNode) : null,

    navigatedAt,
  }
}

function finishPendingCacheNode(
  cacheNode: CacheNode,
  taskState: FlightRouterState,
  serverState: FlightRouterState,
  dynamicData: CacheNodeSeedData,
  dynamicHead: HeadData
): void {
  // Writes a dynamic response into an existing Cache Node tree. This does _not_
  // create a new tree, it updates the existing tree in-place. So it must follow
  // the Suspense rules of cache safety — it can resolve pending promises, but
  // it cannot overwrite existing data. It can add segments to the tree (because
  // a missing segment will cause the layout router to suspend).
  // but it cannot delete them.
  //
  // We must resolve every promise in the tree, or else it will suspend
  // indefinitely. If we did not receive data for a segment, we will resolve its
  // data promise to `null` to trigger a lazy fetch during render.
  const taskStateChildren = taskState[1]
  const serverStateChildren = serverState[1]
  const dataChildren = dynamicData[2]

  // The router state that we traverse the tree with (taskState) is the same one
  // that we used to construct the pending Cache Node tree. That way we're sure
  // to resolve all the pending promises.
  const parallelRoutes = cacheNode.parallelRoutes
  for (let parallelRouteKey in taskStateChildren) {
    const taskStateChild: FlightRouterState =
      taskStateChildren[parallelRouteKey]
    const serverStateChild: FlightRouterState | void =
      serverStateChildren[parallelRouteKey]
    const dataChild: CacheNodeSeedData | null | void =
      dataChildren[parallelRouteKey]

    const segmentMapChild = parallelRoutes.get(parallelRouteKey)
    const taskSegmentChild = taskStateChild[0]
    const taskSegmentKeyChild = createRouterCacheKey(taskSegmentChild)

    const cacheNodeChild =
      segmentMapChild !== undefined
        ? segmentMapChild.get(taskSegmentKeyChild)
        : undefined

    if (cacheNodeChild !== undefined) {
      if (
        serverStateChild !== undefined &&
        matchSegment(taskSegmentChild, serverStateChild[0])
      ) {
        if (dataChild !== undefined && dataChild !== null) {
          // This is the happy path. Recursively update all the children.
          finishPendingCacheNode(
            cacheNodeChild,
            taskStateChild,
            serverStateChild,
            dataChild,
            dynamicHead
          )
        } else {
          // The server never returned data for this segment. Trigger a lazy
          // fetch during render. This shouldn't happen because the Route Tree
          // and the Seed Data tree sent by the server should always be the same
          // shape when part of the same server response.
          abortPendingCacheNode(taskStateChild, cacheNodeChild, null)
        }
      } else {
        // The server never returned data for this segment. Trigger a lazy
        // fetch during render.
        abortPendingCacheNode(taskStateChild, cacheNodeChild, null)
      }
    } else {
      // The server response matches what was expected to receive, but there's
      // no matching Cache Node in the task tree. This is a bug in the
      // implementation because we should have created a node for every
      // segment in the tree that's associated with this task.
    }
  }

  // Use the dynamic data from the server to fulfill the deferred RSC promise
  // on the Cache Node.
  const rsc = cacheNode.rsc
  const dynamicSegmentData = dynamicData[1]
  if (rsc === null) {
    // This is a lazy cache node. We can overwrite it. This is only safe
    // because we know that the LayoutRouter suspends if `rsc` is `null`.
    cacheNode.rsc = dynamicSegmentData
  } else if (isDeferredRsc(rsc)) {
    // This is a deferred RSC promise. We can fulfill it with the data we just
    // received from the server. If it was already resolved by a different
    // navigation, then this does nothing because we can't overwrite data.
    rsc.resolve(dynamicSegmentData)
  } else {
    // This is not a deferred RSC promise, nor is it empty, so it must have
    // been populated by a different navigation. We must not overwrite it.
  }

  // Check if this is a leaf segment. If so, it will have a `head` property with
  // a pending promise that needs to be resolved with the dynamic head from
  // the server.
  const head = cacheNode.head
  if (isDeferredRsc(head)) {
    head.resolve(dynamicHead)
  }
}

export function abortTask(task: SPANavigationTask, error: any): void {
  const cacheNode = task.node
  if (cacheNode === null) {
    // This indicates the task is already complete.
    return
  }

  const taskChildren = task.children
  if (taskChildren === null) {
    // Reached the leaf task node. This is the root of a pending cache
    // node tree.
    abortPendingCacheNode(task.route, cacheNode, error)
  } else {
    // This is an intermediate task node. Keep traversing until we reach a
    // task node with no children. That will be the root of the cache node tree
    // that needs to be resolved.
    for (const taskChild of taskChildren.values()) {
      abortTask(taskChild, error)
    }
  }

  // Set this to null to indicate that this task is now complete.
  task.dynamicRequestTree = null
}

function abortPendingCacheNode(
  routerState: FlightRouterState,
  cacheNode: CacheNode,
  error: any
): void {
  // For every pending segment in the tree, resolve its `rsc` promise to `null`
  // to trigger a lazy fetch during render.
  //
  // Or, if an error object is provided, it will error instead.
  const routerStateChildren = routerState[1]
  const parallelRoutes = cacheNode.parallelRoutes
  for (let parallelRouteKey in routerStateChildren) {
    const routerStateChild: FlightRouterState =
      routerStateChildren[parallelRouteKey]
    const segmentMapChild = parallelRoutes.get(parallelRouteKey)
    if (segmentMapChild === undefined) {
      // This shouldn't happen because we're traversing the same tree that was
      // used to construct the cache nodes in the first place.
      continue
    }
    const segmentChild = routerStateChild[0]
    const segmentKeyChild = createRouterCacheKey(segmentChild)
    const cacheNodeChild = segmentMapChild.get(segmentKeyChild)
    if (cacheNodeChild !== undefined) {
      abortPendingCacheNode(routerStateChild, cacheNodeChild, error)
    } else {
      // This shouldn't happen because we're traversing the same tree that was
      // used to construct the cache nodes in the first place.
    }
  }
  const rsc = cacheNode.rsc
  if (isDeferredRsc(rsc)) {
    if (error === null) {
      // This will trigger a lazy fetch during render.
      rsc.resolve(null)
    } else {
      // This will trigger an error during rendering.
      rsc.reject(error)
    }
  }

  // Check if this is a leaf segment. If so, it will have a `head` property with
  // a pending promise that needs to be resolved. If an error was provided, we
  // will not resolve it with an error, since this is rendered at the root of
  // the app. We want the segment to error, not the entire app.
  const head = cacheNode.head
  if (isDeferredRsc(head)) {
    head.resolve(null)
  }
}

export function updateCacheNodeOnPopstateRestoration(
  oldCacheNode: CacheNode,
  routerState: FlightRouterState
): ReadyCacheNode {
  // A popstate navigation reads data from the local cache. It does not issue
  // new network requests (unless the cache entries have been evicted). So, we
  // update the cache to drop the prefetch data for any segment whose dynamic
  // data was already received. This prevents an unnecessary flash back to PPR
  // state during a back/forward navigation.
  //
  // This function clones the entire cache node tree and sets the `prefetchRsc`
  // field to `null` to prevent it from being rendered. We can't mutate the node
  // in place because this is a concurrent data structure.

  const routerStateChildren = routerState[1]
  const oldParallelRoutes = oldCacheNode.parallelRoutes
  const newParallelRoutes = new Map(oldParallelRoutes)
  for (let parallelRouteKey in routerStateChildren) {
    const routerStateChild: FlightRouterState =
      routerStateChildren[parallelRouteKey]
    const segmentChild = routerStateChild[0]
    const segmentKeyChild = createRouterCacheKey(segmentChild)
    const oldSegmentMapChild = oldParallelRoutes.get(parallelRouteKey)
    if (oldSegmentMapChild !== undefined) {
      const oldCacheNodeChild = oldSegmentMapChild.get(segmentKeyChild)
      if (oldCacheNodeChild !== undefined) {
        const newCacheNodeChild = updateCacheNodeOnPopstateRestoration(
          oldCacheNodeChild,
          routerStateChild
        )
        const newSegmentMapChild = new Map(oldSegmentMapChild)
        newSegmentMapChild.set(segmentKeyChild, newCacheNodeChild)
        newParallelRoutes.set(parallelRouteKey, newSegmentMapChild)
      }
    }
  }

  // Only show prefetched data if the dynamic data is still pending.
  //
  // Tehnically, what we're actually checking is whether the dynamic network
  // response was received. But since it's a streaming response, this does not
  // mean that all the dynamic data has fully streamed in. It just means that
  // _some_ of the dynamic data was received. But as a heuristic, we assume that
  // the rest dynamic data will stream in quickly, so it's still better to skip
  // the prefetch state.
  const rsc = oldCacheNode.rsc
  const shouldUsePrefetch = isDeferredRsc(rsc) && rsc.status === 'pending'

  return {
    lazyData: null,
    rsc,
    head: oldCacheNode.head,

    prefetchHead: shouldUsePrefetch ? oldCacheNode.prefetchHead : [null, null],
    prefetchRsc: shouldUsePrefetch ? oldCacheNode.prefetchRsc : null,
    loading: oldCacheNode.loading,

    // These are the cloned children we computed above
    parallelRoutes: newParallelRoutes,

    navigatedAt: oldCacheNode.navigatedAt,
  }
}

const DEFERRED = Symbol()

type PendingDeferredRsc = Promise<React.ReactNode> & {
  status: 'pending'
  resolve: (value: React.ReactNode) => void
  reject: (error: any) => void
  tag: Symbol
}

type FulfilledDeferredRsc = Promise<React.ReactNode> & {
  status: 'fulfilled'
  value: React.ReactNode
  resolve: (value: React.ReactNode) => void
  reject: (error: any) => void
  tag: Symbol
}

type RejectedDeferredRsc = Promise<React.ReactNode> & {
  status: 'rejected'
  reason: any
  resolve: (value: React.ReactNode) => void
  reject: (error: any) => void
  tag: Symbol
}

type DeferredRsc =
  | PendingDeferredRsc
  | FulfilledDeferredRsc
  | RejectedDeferredRsc

// This type exists to distinguish a DeferredRsc from a Flight promise. It's a
// compromise to avoid adding an extra field on every Cache Node, which would be
// awkward because the pre-PPR parts of codebase would need to account for it,
// too. We can remove it once type Cache Node type is more settled.
function isDeferredRsc(value: any): value is DeferredRsc {
  return value && value.tag === DEFERRED
}

function createDeferredRsc(): PendingDeferredRsc {
  let resolve: any
  let reject: any
  const pendingRsc = new Promise<React.ReactNode>((res, rej) => {
    resolve = res
    reject = rej
  }) as PendingDeferredRsc
  pendingRsc.status = 'pending'
  pendingRsc.resolve = (value: React.ReactNode) => {
    if (pendingRsc.status === 'pending') {
      const fulfilledRsc: FulfilledDeferredRsc = pendingRsc as any
      fulfilledRsc.status = 'fulfilled'
      fulfilledRsc.value = value
      resolve(value)
    }
  }
  pendingRsc.reject = (error: any) => {
    if (pendingRsc.status === 'pending') {
      const rejectedRsc: RejectedDeferredRsc = pendingRsc as any
      rejectedRsc.status = 'rejected'
      rejectedRsc.reason = error
      reject(error)
    }
  }
  pendingRsc.tag = DEFERRED
  return pendingRsc
}