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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
import type { DeepReadonly } from '../../shared/lib/deep-readonly'
/* eslint-disable import/no-extraneous-dependencies */
import {
  renderToReadableStream,
  decodeReply,
  decodeReplyFromAsyncIterable,
  createTemporaryReferenceSet as createServerTemporaryReferenceSet,
} from 'react-server-dom-webpack/server'
import {
  createFromReadableStream,
  encodeReply,
  createTemporaryReferenceSet as createClientTemporaryReferenceSet,
} from 'react-server-dom-webpack/client'
import { unstable_prerender as prerender } from 'react-server-dom-webpack/static'
/* eslint-enable import/no-extraneous-dependencies */

import type { WorkStore } from '../app-render/work-async-storage.external'
import { workAsyncStorage } from '../app-render/work-async-storage.external'
import type {
  PrerenderStoreModernClient,
  PrivateUseCacheStore,
  RequestStore,
  RevalidateStore,
  UseCacheStore,
  WorkUnitStore,
} from '../app-render/work-unit-async-storage.external'
import {
  getHmrRefreshHash,
  getRenderResumeDataCache,
  getPrerenderResumeDataCache,
  workUnitAsyncStorage,
  getDraftModeProviderForCacheScope,
  getCacheSignal,
} from '../app-render/work-unit-async-storage.external'

import { makeHangingPromise } from '../dynamic-rendering-utils'

import type { ClientReferenceManifestForRsc } from '../../build/webpack/plugins/flight-manifest-plugin'

import {
  getClientReferenceManifestForRsc,
  getServerModuleMap,
} from '../app-render/encryption-utils'
import type { CacheEntry } from '../lib/cache-handlers/types'
import type { CacheSignal } from '../app-render/cache-signal'
import { decryptActionBoundArgs } from '../app-render/encryption'
import { InvariantError } from '../../shared/lib/invariant-error'
import { getDigestForWellKnownError } from '../app-render/create-error-handler'
import { DYNAMIC_EXPIRE, DYNAMIC_PREFETCH_DYNAMIC_STALE } from './constants'
import { getCacheHandler } from './handlers'
import { UseCacheTimeoutError } from './use-cache-errors'
import {
  createHangingInputAbortSignal,
  postponeWithTracking,
  throwToInterruptStaticGeneration,
} from '../app-render/dynamic-rendering'
import {
  makeErroringExoticSearchParamsForUseCache,
  type SearchParams,
} from '../request/search-params'
import type { Params } from '../request/params'
import React from 'react'
import { createLazyResult, isResolvedLazyResult } from '../lib/lazy-result'
import { dynamicAccessAsyncStorage } from '../app-render/dynamic-access-async-storage.external'
import { isReactLargeShellError } from '../app-render/react-large-shell-error'
import type { CacheLife } from './cache-life'

interface PrivateCacheContext {
  readonly kind: 'private'
  // TODO: Add dynamic prefetching store when this exists.
  readonly outerWorkUnitStore: RequestStore | PrivateUseCacheStore
}

interface PublicCacheContext {
  readonly kind: 'public'
  // TODO: We should probably forbid nesting "use cache" inside unstable_cache.
  readonly outerWorkUnitStore:
    | Exclude<WorkUnitStore, PrerenderStoreModernClient>
    | undefined
}

type CacheContext = PrivateCacheContext | PublicCacheContext

type CacheKeyParts =
  | [buildId: string, id: string, args: unknown[]]
  | [buildId: string, id: string, args: unknown[], hmrRefreshHash: string]

export interface UseCachePageComponentProps {
  params: Promise<Params>
  searchParams: Promise<SearchParams>
  $$isPageComponent: true
}

export type UseCacheLayoutComponentProps = {
  params: Promise<Params>
  $$isLayoutComponent: true
} & {
  // The value type should be React.ReactNode. But such an index signature would
  // be incompatible with the other two props.
  [slot: string]: any
}

const isEdgeRuntime = process.env.NEXT_RUNTIME === 'edge'

const debug = process.env.NEXT_PRIVATE_DEBUG_CACHE
  ? console.debug.bind(console, 'use-cache:')
  : undefined

const filterStackFrame =
  process.env.NODE_ENV !== 'production'
    ? (require('../lib/source-maps') as typeof import('../lib/source-maps'))
        .filterStackFrameDEV
    : undefined

function generateCacheEntry(
  workStore: WorkStore,
  cacheContext: CacheContext,
  clientReferenceManifest: DeepReadonly<ClientReferenceManifestForRsc>,
  encodedArguments: FormData | string,
  fn: (...args: unknown[]) => Promise<unknown>,
  sharedErrorStack: string | undefined
) {
  // We need to run this inside a clean AsyncLocalStorage snapshot so that the cache
  // generation cannot read anything from the context we're currently executing which
  // might include request specific things like cookies() inside a React.cache().
  // Note: It is important that we await at least once before this because it lets us
  // pop out of any stack specific contexts as well - aka "Sync" Local Storage.
  return workStore.runInCleanSnapshot(
    generateCacheEntryWithRestoredWorkStore,
    workStore,
    cacheContext,
    clientReferenceManifest,
    encodedArguments,
    fn,
    sharedErrorStack
  )
}

function generateCacheEntryWithRestoredWorkStore(
  workStore: WorkStore,
  cacheContext: CacheContext,
  clientReferenceManifest: DeepReadonly<ClientReferenceManifestForRsc>,
  encodedArguments: FormData | string,
  fn: (...args: unknown[]) => Promise<unknown>,
  sharedErrorStack: string | undefined
) {
  // Since we cleared the AsyncLocalStorage we need to restore the workStore.
  // Note: We explicitly don't restore the RequestStore nor the PrerenderStore.
  // We don't want any request specific information leaking an we don't want to create a
  // bloated fake request mock for every cache call. So any feature that currently lives
  // in RequestStore but should be available to Caches need to move to WorkStore.
  // PrerenderStore is not needed inside the cache scope because the outer most one will
  // be the one to report its result to the outer Prerender.
  return workAsyncStorage.run(
    workStore,
    generateCacheEntryWithCacheContext,
    workStore,
    cacheContext,
    clientReferenceManifest,
    encodedArguments,
    fn,
    sharedErrorStack
  )
}

function createUseCacheStore(
  workStore: WorkStore,
  cacheContext: CacheContext,
  defaultCacheLife: Required<CacheLife>
): UseCacheStore {
  if (cacheContext.kind === 'private') {
    const outerWorkUnitStore = cacheContext.outerWorkUnitStore

    return {
      type: 'private-cache',
      phase: 'render',
      implicitTags: outerWorkUnitStore?.implicitTags,
      revalidate: defaultCacheLife.revalidate,
      expire: defaultCacheLife.expire,
      stale: defaultCacheLife.stale,
      explicitRevalidate: undefined,
      explicitExpire: undefined,
      explicitStale: undefined,
      tags: null,
      hmrRefreshHash:
        outerWorkUnitStore && getHmrRefreshHash(workStore, outerWorkUnitStore),
      isHmrRefresh: outerWorkUnitStore?.isHmrRefresh ?? false,
      serverComponentsHmrCache: outerWorkUnitStore?.serverComponentsHmrCache,
      forceRevalidate: shouldForceRevalidate(workStore, outerWorkUnitStore),
      draftMode:
        outerWorkUnitStore &&
        getDraftModeProviderForCacheScope(workStore, outerWorkUnitStore),
      cookies: outerWorkUnitStore.cookies,
    }
  } else {
    let useCacheOrRequestStore: RequestStore | UseCacheStore | undefined
    const outerWorkUnitStore = cacheContext.outerWorkUnitStore

    if (outerWorkUnitStore) {
      switch (outerWorkUnitStore?.type) {
        case 'cache':
        case 'private-cache':
        case 'request':
          useCacheOrRequestStore = outerWorkUnitStore
          break
        case 'prerender':
        case 'prerender-ppr':
        case 'prerender-legacy':
        case 'unstable-cache':
          break
        default:
          outerWorkUnitStore satisfies never
      }
    }

    return {
      type: 'cache',
      phase: 'render',
      implicitTags: outerWorkUnitStore?.implicitTags,
      revalidate: defaultCacheLife.revalidate,
      expire: defaultCacheLife.expire,
      stale: defaultCacheLife.stale,
      explicitRevalidate: undefined,
      explicitExpire: undefined,
      explicitStale: undefined,
      tags: null,
      hmrRefreshHash:
        outerWorkUnitStore && getHmrRefreshHash(workStore, outerWorkUnitStore),
      isHmrRefresh: useCacheOrRequestStore?.isHmrRefresh ?? false,
      serverComponentsHmrCache:
        useCacheOrRequestStore?.serverComponentsHmrCache,
      forceRevalidate: shouldForceRevalidate(workStore, outerWorkUnitStore),
      draftMode:
        outerWorkUnitStore &&
        getDraftModeProviderForCacheScope(workStore, outerWorkUnitStore),
    }
  }
}

function assertDefaultCacheLife(
  defaultCacheLife: CacheLife | undefined
): asserts defaultCacheLife is Required<CacheLife> {
  if (
    !defaultCacheLife ||
    defaultCacheLife.revalidate == null ||
    defaultCacheLife.expire == null ||
    defaultCacheLife.stale == null
  ) {
    throw new InvariantError(
      'A default cacheLife profile must always be provided.'
    )
  }
}

function generateCacheEntryWithCacheContext(
  workStore: WorkStore,
  cacheContext: CacheContext,
  clientReferenceManifest: DeepReadonly<ClientReferenceManifestForRsc>,
  encodedArguments: FormData | string,
  fn: (...args: unknown[]) => Promise<unknown>,
  sharedErrorStack: string | undefined
) {
  if (!workStore.cacheLifeProfiles) {
    throw new InvariantError('cacheLifeProfiles should always be provided.')
  }
  const defaultCacheLife = workStore.cacheLifeProfiles['default']
  assertDefaultCacheLife(defaultCacheLife)

  // Initialize the Store for this Cache entry.
  const cacheStore = createUseCacheStore(
    workStore,
    cacheContext,
    defaultCacheLife
  )

  return workUnitAsyncStorage.run(cacheStore, () =>
    dynamicAccessAsyncStorage.run(
      { abortController: new AbortController() },
      generateCacheEntryImpl,
      workStore,
      cacheContext,
      cacheStore,
      clientReferenceManifest,
      encodedArguments,
      fn,
      sharedErrorStack
    )
  )
}

function propagateCacheLifeAndTagsToRevalidateStore(
  revalidateStore: RevalidateStore,
  entry: CacheEntry
): void {
  const outerTags = (revalidateStore.tags ??= [])

  for (const tag of entry.tags) {
    if (!outerTags.includes(tag)) {
      outerTags.push(tag)
    }
  }

  if (revalidateStore.stale > entry.stale) {
    revalidateStore.stale = entry.stale
  }

  if (revalidateStore.revalidate > entry.revalidate) {
    revalidateStore.revalidate = entry.revalidate
  }

  if (revalidateStore.expire > entry.expire) {
    revalidateStore.expire = entry.expire
  }
}

function propagateCacheLifeAndTags(
  cacheContext: CacheContext,
  entry: CacheEntry
): void {
  if (cacheContext.kind === 'private') {
    switch (cacheContext.outerWorkUnitStore?.type) {
      // TODO: Also propagate cache life and tags to dynamic prefetching stores.
      case 'private-cache':
        propagateCacheLifeAndTagsToRevalidateStore(
          cacheContext.outerWorkUnitStore,
          entry
        )
        break
      case 'request':
      case undefined:
        break
      default:
        cacheContext.outerWorkUnitStore satisfies never
    }
  } else {
    switch (cacheContext.outerWorkUnitStore?.type) {
      case 'cache':
      case 'private-cache':
      case 'prerender':
      case 'prerender-ppr':
      case 'prerender-legacy':
        propagateCacheLifeAndTagsToRevalidateStore(
          cacheContext.outerWorkUnitStore,
          entry
        )
        break
      case 'request':
      case 'unstable-cache':
      case undefined:
        break
      default:
        cacheContext.outerWorkUnitStore satisfies never
    }
  }
}

async function collectResult(
  savedStream: ReadableStream,
  workStore: WorkStore,
  cacheContext: CacheContext,
  innerCacheStore: UseCacheStore,
  startTime: number,
  errors: Array<unknown> // This is a live array that gets pushed into.
): Promise<CacheEntry> {
  // We create a buffered stream that collects all chunks until the end to
  // ensure that RSC has finished rendering and therefore we have collected
  // all tags. In the future the RSC API might allow for the equivalent of
  // the allReady Promise that exists on SSR streams.
  //
  // If something errored or rejected anywhere in the render, we close
  // the stream as errored. This lets a CacheHandler choose to save the
  // partial result up until that point for future hits for a while to avoid
  // unnecessary retries or not to retry. We use the end of the stream for
  // this to avoid another complicated side-channel. A receiver has to consider
  // that the stream might also error for other reasons anyway such as losing
  // connection.

  const buffer: any[] = []
  const reader = savedStream.getReader()

  try {
    for (let entry; !(entry = await reader.read()).done; ) {
      buffer.push(entry.value)
    }
  } catch (error) {
    errors.push(error)
  }

  let idx = 0
  const bufferStream = new ReadableStream({
    pull(controller) {
      if (workStore.invalidDynamicUsageError) {
        controller.error(workStore.invalidDynamicUsageError)
      } else if (idx < buffer.length) {
        controller.enqueue(buffer[idx++])
      } else if (errors.length > 0) {
        // TODO: Should we use AggregateError here?
        controller.error(errors[0])
      } else {
        controller.close()
      }
    },
  })

  const collectedTags = innerCacheStore.tags
  // If cacheLife() was used to set an explicit revalidate time we use that.
  // Otherwise, we use the lowest of all inner fetch()/unstable_cache() or nested "use cache".
  // If they're lower than our default.
  const collectedRevalidate =
    innerCacheStore.explicitRevalidate !== undefined
      ? innerCacheStore.explicitRevalidate
      : innerCacheStore.revalidate
  const collectedExpire =
    innerCacheStore.explicitExpire !== undefined
      ? innerCacheStore.explicitExpire
      : innerCacheStore.expire
  const collectedStale =
    innerCacheStore.explicitStale !== undefined
      ? innerCacheStore.explicitStale
      : innerCacheStore.stale

  const entry: CacheEntry = {
    value: bufferStream,
    timestamp: startTime,
    revalidate: collectedRevalidate,
    expire: collectedExpire,
    stale: collectedStale,
    tags: collectedTags === null ? [] : collectedTags,
  }

  // Propagate tags/revalidate to the parent context.
  if (cacheContext) {
    propagateCacheLifeAndTags(cacheContext, entry)
  }

  const cacheSignal = cacheContext.outerWorkUnitStore
    ? getCacheSignal(cacheContext.outerWorkUnitStore)
    : null

  if (cacheSignal) {
    cacheSignal.endRead()
  }

  return entry
}

type GenerateCacheEntryResult =
  | {
      readonly type: 'cached'
      readonly stream: ReadableStream
      readonly pendingCacheEntry: Promise<CacheEntry>
    }
  | {
      readonly type: 'prerender-dynamic'
      readonly hangingPromise: Promise<never>
    }

async function generateCacheEntryImpl(
  workStore: WorkStore,
  cacheContext: CacheContext,
  innerCacheStore: UseCacheStore,
  clientReferenceManifest: DeepReadonly<ClientReferenceManifestForRsc>,
  encodedArguments: FormData | string,
  fn: (...args: unknown[]) => Promise<unknown>,
  sharedErrorStack: string | undefined
): Promise<GenerateCacheEntryResult> {
  const temporaryReferences = createServerTemporaryReferenceSet()
  const outerWorkUnitStore = cacheContext.outerWorkUnitStore

  const [, , args] =
    typeof encodedArguments === 'string'
      ? await decodeReply<CacheKeyParts>(
          encodedArguments,
          getServerModuleMap(),
          { temporaryReferences }
        )
      : await decodeReplyFromAsyncIterable<CacheKeyParts>(
          {
            async *[Symbol.asyncIterator]() {
              for (const entry of encodedArguments) {
                yield entry
              }

              if (outerWorkUnitStore) {
                switch (outerWorkUnitStore.type) {
                  case 'prerender':
                    // The encoded arguments might contain hanging promises. In
                    // this case we don't want to reject with "Error: Connection
                    // closed.", so we intentionally keep the iterable alive.
                    // This is similar to the halting trick that we do while
                    // rendering.
                    await new Promise<void>((resolve) => {
                      if (outerWorkUnitStore.renderSignal.aborted) {
                        resolve()
                      } else {
                        outerWorkUnitStore.renderSignal.addEventListener(
                          'abort',
                          () => resolve(),
                          { once: true }
                        )
                      }
                    })
                    break
                  case 'prerender-ppr':
                  case 'prerender-legacy':
                  case 'request':
                  case 'cache':
                  case 'private-cache':
                  case 'unstable-cache':
                    break
                  default:
                    outerWorkUnitStore satisfies never
                }
              }
            },
          },
          getServerModuleMap(),
          { temporaryReferences }
        )

  // Track the timestamp when we started computing the result.
  const startTime = performance.timeOrigin + performance.now()

  // Invoke the inner function to load a new result. We delay the invocation
  // though, until React awaits the promise so that React's request store (ALS)
  // is available when the function is invoked. This allows us, for example, to
  // capture logs so that we can later replay them.
  const resultPromise = createLazyResult(() => fn.apply(null, args))

  let errors: Array<unknown> = []

  // In the "Cache" environment, we only need to make sure that the error
  // digests are handled correctly. Error formatting and reporting is not
  // necessary here; the errors are encoded in the stream, and will be reported
  // in the "Server" environment.
  const handleError = (error: unknown): string | undefined => {
    const digest = getDigestForWellKnownError(error)

    if (digest) {
      return digest
    }

    if (isReactLargeShellError(error)) {
      // TODO: Aggregate
      console.error(error)
      return undefined
    }

    if (process.env.NODE_ENV !== 'development') {
      // TODO: For now we're also reporting the error here, because in
      // production, the "Server" environment will only get the obfuscated
      // error (created by the Flight Client in the cache wrapper).
      console.error(error)
    }

    errors.push(error)
  }

  let stream: ReadableStream<Uint8Array>

  switch (outerWorkUnitStore?.type) {
    // TODO: Dynamic prefetches should also use the prerender variant.
    case 'prerender':
      const timeoutAbortController = new AbortController()

      // If we're prerendering, we give you 50 seconds to fill a cache entry.
      // Otherwise we assume you stalled on hanging input and de-opt. This needs
      // to be lower than just the general timeout of 60 seconds.
      const timer = setTimeout(() => {
        const error = new UseCacheTimeoutError()
        if (sharedErrorStack) {
          error.stack = error.name + ': ' + error.message + sharedErrorStack
        }
        workStore.invalidDynamicUsageError = error
        timeoutAbortController.abort(error)
      }, 50000)

      const dynamicAccessAbortSignal =
        dynamicAccessAsyncStorage.getStore()?.abortController.signal

      const abortSignal = dynamicAccessAbortSignal
        ? AbortSignal.any([
            dynamicAccessAbortSignal,
            outerWorkUnitStore.renderSignal,
            timeoutAbortController.signal,
          ])
        : timeoutAbortController.signal

      const { prelude } = await prerender(
        resultPromise,
        clientReferenceManifest.clientModules,
        {
          environmentName: 'Cache',
          filterStackFrame,
          signal: abortSignal,
          temporaryReferences,
          onError(error) {
            if (abortSignal.aborted && abortSignal.reason === error) {
              return undefined
            }

            return handleError(error)
          },
        }
      )

      clearTimeout(timer)

      if (timeoutAbortController.signal.aborted) {
        // When the timeout is reached we always error the stream. Even for
        // fallback shell prerenders we don't want to return a hanging promise,
        // which would allow the function to become a dynamic hole. Because that
        // would mean that a non-empty shell could be generated which would be
        // subject to revalidation, and we don't want to create long
        // revalidation times.
        stream = new ReadableStream({
          start(controller) {
            controller.error(timeoutAbortController.signal.reason)
          },
        })
      } else if (dynamicAccessAbortSignal?.aborted) {
        // If the prerender is aborted because of dynamic access (e.g. reading
        // fallback params), we return a hanging promise. This essentially makes
        // the "use cache" function dynamic.
        const hangingPromise = makeHangingPromise<never>(
          outerWorkUnitStore.renderSignal,
          abortSignal.reason
        )

        if (outerWorkUnitStore.cacheSignal) {
          outerWorkUnitStore.cacheSignal.endRead()
        }

        return { type: 'prerender-dynamic', hangingPromise }
      } else {
        stream = prelude
      }
      break
    case 'prerender-ppr':
    case 'prerender-legacy':
    case 'request':
    case 'cache':
    case 'private-cache':
    case 'unstable-cache':
    case undefined:
      stream = renderToReadableStream(
        resultPromise,
        clientReferenceManifest.clientModules,
        {
          environmentName: 'Cache',
          filterStackFrame,
          temporaryReferences,
          onError: handleError,
        }
      )
      break
    default:
      return outerWorkUnitStore satisfies never
  }

  const [returnStream, savedStream] = stream.tee()

  const pendingCacheEntry = collectResult(
    savedStream,
    workStore,
    cacheContext,
    innerCacheStore,
    startTime,
    errors
  )

  return {
    type: 'cached',
    // Return the stream as we're creating it. This means that if it ends up
    // erroring we cannot return a stale-if-error version but it allows
    // streaming back the result earlier.
    stream: returnStream,
    pendingCacheEntry,
  }
}

function cloneCacheEntry(entry: CacheEntry): [CacheEntry, CacheEntry] {
  const [streamA, streamB] = entry.value.tee()
  entry.value = streamA
  const clonedEntry: CacheEntry = {
    value: streamB,
    timestamp: entry.timestamp,
    revalidate: entry.revalidate,
    expire: entry.expire,
    stale: entry.stale,
    tags: entry.tags,
  }
  return [entry, clonedEntry]
}

async function clonePendingCacheEntry(
  pendingCacheEntry: Promise<CacheEntry>
): Promise<[CacheEntry, CacheEntry]> {
  const entry = await pendingCacheEntry
  return cloneCacheEntry(entry)
}

async function getNthCacheEntry(
  split: Promise<[CacheEntry, CacheEntry]>,
  i: number
): Promise<CacheEntry> {
  return (await split)[i]
}

async function encodeFormData(formData: FormData): Promise<string> {
  let result = ''
  for (let [key, value] of formData) {
    // We don't need this key to be serializable but from a security perspective it should not be
    // possible to generate a string that looks the same from a different structure. To ensure this
    // we need a delimeter between fields but just using a delimeter is not enough since a string
    // might contain that delimeter. We use the length of each field as the delimeter to avoid
    // escaping the values.
    result += key.length.toString(16) + ':' + key
    let stringValue
    if (typeof value === 'string') {
      stringValue = value
    } else {
      // The FormData might contain binary data that is not valid UTF-8 so this cache
      // key may generate a UCS-2 string. Passing this to another service needs to be
      // aware that the key might not be compatible.
      const arrayBuffer = await value.arrayBuffer()
      if (arrayBuffer.byteLength % 2 === 0) {
        stringValue = String.fromCodePoint(...new Uint16Array(arrayBuffer))
      } else {
        stringValue =
          String.fromCodePoint(
            ...new Uint16Array(arrayBuffer, 0, (arrayBuffer.byteLength - 1) / 2)
          ) +
          String.fromCodePoint(
            new Uint8Array(arrayBuffer, arrayBuffer.byteLength - 1, 1)[0]
          )
      }
    }
    result += stringValue.length.toString(16) + ':' + stringValue
  }
  return result
}

function createTrackedReadableStream(
  stream: ReadableStream,
  cacheSignal: CacheSignal
) {
  const reader = stream.getReader()
  return new ReadableStream({
    async pull(controller) {
      const { done, value } = await reader.read()
      if (done) {
        controller.close()
        cacheSignal.endRead()
      } else {
        controller.enqueue(value)
      }
    },
  })
}

function wrapAsInvalidDynamicUsageError(
  error: Error,
  sharedErrorStack: string | undefined,
  workStore: WorkStore
) {
  if (sharedErrorStack) {
    error.stack = error.name + ': ' + error.message + sharedErrorStack
  }

  workStore.invalidDynamicUsageError ??= error

  return error
}

export function cache(
  kind: string,
  id: string,
  boundArgsLength: number,
  originalFn: (...args: unknown[]) => Promise<unknown>
) {
  const isPrivate = kind === 'private'

  // Private caches are currently only stored in the Resume Data Cache (RDC),
  // and not in cache handlers.
  const cacheHandler = isPrivate ? undefined : getCacheHandler(kind)

  if (!isPrivate && !cacheHandler) {
    throw new Error('Unknown cache handler: ' + kind)
  }

  // Capture a better error stack in this scope.
  const sharedError = new Error()
  Error.captureStackTrace(sharedError, cache)
  const sharedErrorStack = sharedError.stack?.slice(
    sharedError.stack.indexOf('\n')
  )

  const name = originalFn.name
  const cachedFn = {
    [name]: async function (...args: any[]) {
      const workStore = workAsyncStorage.getStore()
      if (workStore === undefined) {
        throw new Error(
          '"use cache" cannot be used outside of App Router. Expected a WorkStore.'
        )
      }

      let fn = originalFn

      const workUnitStore = workUnitAsyncStorage.getStore()

      let cacheContext: CacheContext

      if (isPrivate) {
        const expression = '"use cache: private"'

        switch (workUnitStore?.type) {
          // "use cache: private" is dynamic in prerendering contexts.
          case 'prerender':
            return makeHangingPromise(workUnitStore.renderSignal, expression)
          case 'prerender-ppr':
            return postponeWithTracking(
              workStore.route,
              expression,
              workUnitStore.dynamicTracking
            )
          case 'prerender-legacy':
            return throwToInterruptStaticGeneration(
              expression,
              workStore,
              workUnitStore
            )
          case 'prerender-client':
            throw new InvariantError(
              `${expression} must not be used within a client component. Next.js should be preventing ${expression} from being allowed in client components statically, but did not in this case.`
            )
          case 'unstable-cache': {
            throw wrapAsInvalidDynamicUsageError(
              new Error(
                // TODO: Add a link to an error documentation page when we have one.
                `${expression} must not be used within \`unstable_cache()\`.`
              ),
              sharedErrorStack,
              workStore
            )
          }
          case 'cache': {
            throw wrapAsInvalidDynamicUsageError(
              new Error(
                // TODO: Add a link to an error documentation page when we have one.
                `${expression} must not be used within "use cache". It can only be nested inside of another ${expression}.`
              ),
              sharedErrorStack,
              workStore
            )
          }
          case 'request':
          case 'private-cache':
            cacheContext = {
              kind: 'private',
              outerWorkUnitStore: workUnitStore,
            }
            break
          case undefined:
            throw wrapAsInvalidDynamicUsageError(
              new Error(
                // TODO: Add a link to an error documentation page when we have one.
                `${expression} cannot be used outside of a request context.`
              ),
              sharedErrorStack,
              workStore
            )
          default:
            workUnitStore satisfies never
            // This is dead code, but without throwing an error here, TypeScript
            // will assume that cacheContext is used before being assigned.
            throw new InvariantError(`Unexpected work unit store.`)
        }
      } else {
        switch (workUnitStore?.type) {
          case 'prerender-client':
            const expression = '"use cache"'
            throw new InvariantError(
              `${expression} must not be used within a client component. Next.js should be preventing ${expression} from being allowed in client components statically, but did not in this case.`
            )
          case 'prerender':
          case 'prerender-ppr':
          case 'prerender-legacy':
          case 'request':
          case 'cache':
          case 'private-cache':
          // TODO: We should probably forbid nesting "use cache" inside
          // unstable_cache. (fallthrough)
          case 'unstable-cache':
          case undefined:
            cacheContext = {
              kind: 'public',
              outerWorkUnitStore: workUnitStore,
            }
            break
          default:
            workUnitStore satisfies never
            // This is dead code, but without throwing an error here, TypeScript
            // will assume that cacheContext is used before being assigned.
            throw new InvariantError(`Unexpected work unit store.`)
        }
      }

      // Get the clientReferenceManifest while we're still in the outer Context.
      // In case getClientReferenceManifestSingleton is implemented using AsyncLocalStorage.
      const clientReferenceManifest = getClientReferenceManifestForRsc()

      // Because the Action ID is not yet unique per implementation of that Action we can't
      // safely reuse the results across builds yet. In the meantime we add the buildId to the
      // arguments as a seed to ensure they're not reused. Remove this once Action IDs hash
      // the implementation.
      const buildId = workStore.buildId

      // In dev mode, when the HMR refresh hash is set, we include it in the
      // cache key. This ensures that cache entries are not reused when server
      // components have been edited. This is a very coarse approach. But it's
      // also only a temporary solution until Action IDs are unique per
      // implementation. Remove this once Action IDs hash the implementation.
      const hmrRefreshHash =
        workUnitStore && getHmrRefreshHash(workStore, workUnitStore)

      const hangingInputAbortSignal = workUnitStore
        ? createHangingInputAbortSignal(workUnitStore)
        : undefined

      let isPageOrLayout = false

      // For page and layout components, the cache function is overwritten,
      // which allows us to apply special handling for params and searchParams.
      // For pages and layouts we're using the outer params prop, and not the
      // inner one that was serialized/deserialized. While it's not generally
      // true for "use cache" args, in the case of `params` the inner and outer
      // object are essentially equivalent, so this is safe to do (including
      // fallback params that are hanging promises). It allows us to avoid
      // waiting for the timeout, when prerendering a fallback shell of a cached
      // page or layout that awaits params.
      if (isPageComponent(args)) {
        isPageOrLayout = true

        const [{ params: outerParams, searchParams: outerSearchParams }] = args
        const keepSearchParams = workStore.cacheComponentsEnabled || isPrivate

        args = [
          {
            params: outerParams,
            searchParams: keepSearchParams
              ? outerSearchParams
              : Promise.resolve({}),
            // omit $$isPageComponent.
          },
        ]

        fn = {
          [name]: async ({
            params: _innerParams,
            searchParams: innerSearchParams,
          }: Omit<UseCachePageComponentProps, '$$isPageComponent'>) =>
            originalFn.apply(null, [
              {
                params: outerParams,
                searchParams: keepSearchParams
                  ? innerSearchParams
                  : // When cacheComponents is not enabled, we can not encode
                    // searchParams as a hanging promise. To still avoid unused
                    // search params from making a page dynamic, we define them
                    // as a promise that resolves to an empty object above. And
                    // here, we're creating an erroring searchParams prop, when
                    // invoking the original function. This ensures that used
                    // searchParams inside of cached functions would still yield
                    // an error.
                    makeErroringExoticSearchParamsForUseCache(workStore),
              },
            ]),
        }[name] as (...args: unknown[]) => Promise<unknown>
      } else if (isLayoutComponent(args)) {
        isPageOrLayout = true

        const [{ params: outerParams, $$isLayoutComponent, ...outerSlots }] =
          args
        // Overwrite the props to omit $$isLayoutComponent.
        args = [{ params: outerParams, ...outerSlots }]

        fn = {
          [name]: async ({
            params: _innerParams,
            ...innerSlots
          }: Omit<UseCacheLayoutComponentProps, '$$isLayoutComponent'>) =>
            originalFn.apply(null, [{ params: outerParams, ...innerSlots }]),
        }[name] as (...args: unknown[]) => Promise<unknown>
      }

      if (boundArgsLength > 0) {
        if (args.length === 0) {
          throw new InvariantError(
            `Expected the "use cache" function ${JSON.stringify(fn.name)} to receive its encrypted bound arguments as the first argument.`
          )
        }

        const encryptedBoundArgs = args.shift()
        const boundArgs = await decryptActionBoundArgs(id, encryptedBoundArgs)

        if (!Array.isArray(boundArgs)) {
          throw new InvariantError(
            `Expected the bound arguments of "use cache" function ${JSON.stringify(fn.name)} to deserialize into an array, got ${typeof boundArgs} instead.`
          )
        }

        if (boundArgsLength !== boundArgs.length) {
          throw new InvariantError(
            `Expected the "use cache" function ${JSON.stringify(fn.name)} to receive ${boundArgsLength} bound arguments, got ${boundArgs.length} instead.`
          )
        }

        args.unshift(boundArgs)
      }

      const temporaryReferences = createClientTemporaryReferenceSet()

      // For private caches, which are allowed to read cookies, we still don't
      // need to include the cookies in the cache key. This is because we don't
      // store the cache entries in a cache handler, but only in the Resume Data
      // Cache (RDC). Private caches are only used during dynamic requests and
      // dynamic prefetches. For dynamic requests, the RDC is immutable, so it
      // does not include any private caches. For dynamic prefetches, the RDC is
      // mutable, but only lives as long as the request, so the key does not
      // need to include cookies.
      const cacheKeyParts: CacheKeyParts = hmrRefreshHash
        ? [buildId, id, args, hmrRefreshHash]
        : [buildId, id, args]

      const encodeCacheKeyParts = () =>
        encodeReply(cacheKeyParts, {
          temporaryReferences,
          signal: hangingInputAbortSignal,
        })

      let encodedCacheKeyParts: FormData | string

      switch (workUnitStore?.type) {
        case 'prerender':
          if (!isPageOrLayout) {
            // If the "use cache" function is not a page or a layout, we need to
            // track dynamic access already when encoding the arguments. If
            // params are passed explicitly into a "use cache" function (as
            // opposed to receiving them automatically in a page or layout), we
            // assume that the params are also accessed. This allows us to abort
            // early, and treat the function as dynamic, instead of waiting for
            // the timeout to be reached.
            const dynamicAccessAbortController = new AbortController()

            encodedCacheKeyParts = await dynamicAccessAsyncStorage.run(
              { abortController: dynamicAccessAbortController },
              encodeCacheKeyParts
            )

            if (dynamicAccessAbortController.signal.aborted) {
              return makeHangingPromise(
                workUnitStore.renderSignal,
                dynamicAccessAbortController.signal.reason.message
              )
            }
            break
          }
        // fallthrough
        case 'prerender-ppr':
        case 'prerender-legacy':
        case 'request':
        case 'cache':
        case 'private-cache':
        case 'unstable-cache':
        case undefined:
          encodedCacheKeyParts = await encodeCacheKeyParts()
          break
        default:
          return workUnitStore satisfies never
      }

      const serializedCacheKey =
        typeof encodedCacheKeyParts === 'string'
          ? // Fast path for the simple case for simple inputs. We let the CacheHandler
            // Convert it to an ArrayBuffer if it wants to.
            encodedCacheKeyParts
          : await encodeFormData(encodedCacheKeyParts)

      let stream: undefined | ReadableStream = undefined

      // Get an immutable and mutable versions of the resume data cache.
      const prerenderResumeDataCache = workUnitStore
        ? getPrerenderResumeDataCache(workUnitStore)
        : null
      const renderResumeDataCache = workUnitStore
        ? getRenderResumeDataCache(workUnitStore)
        : null

      if (renderResumeDataCache) {
        const cacheSignal = workUnitStore ? getCacheSignal(workUnitStore) : null

        if (cacheSignal) {
          cacheSignal.beginRead()
        }
        const cachedEntry = renderResumeDataCache.cache.get(serializedCacheKey)
        if (cachedEntry !== undefined) {
          const existingEntry = await cachedEntry
          propagateCacheLifeAndTags(cacheContext, existingEntry)

          if (workUnitStore !== undefined && existingEntry !== undefined) {
            if (
              existingEntry.revalidate === 0 ||
              existingEntry.expire < DYNAMIC_EXPIRE
            ) {
              switch (workUnitStore.type) {
                case 'prerender':
                  // In a Dynamic I/O prerender, if the cache entry has
                  // revalidate: 0 or if the expire time is under 5 minutes, then
                  // we consider this cache entry dynamic as it's not worth
                  // generating static pages for such data. It's better to leave a
                  // PPR hole that can be filled in dynamically with a potentially
                  // cached entry.
                  if (cacheSignal) {
                    cacheSignal.endRead()
                  }
                  return makeHangingPromise(
                    workUnitStore.renderSignal,
                    'dynamic "use cache"'
                  )
                case 'prerender-ppr':
                case 'prerender-legacy':
                case 'request':
                case 'cache':
                case 'private-cache':
                case 'unstable-cache':
                  break
                default:
                  workUnitStore satisfies never
              }
            }

            if (existingEntry.stale < DYNAMIC_PREFETCH_DYNAMIC_STALE) {
              // TODO: Return hanging promise for dynamic prefetches.
            }
          }

          const [streamA, streamB] = existingEntry.value.tee()
          existingEntry.value = streamB

          if (cacheSignal) {
            // When we have a cacheSignal we need to block on reading the cache
            // entry before ending the read.
            stream = createTrackedReadableStream(streamA, cacheSignal)
          } else {
            stream = streamA
          }
        } else {
          if (cacheSignal) {
            cacheSignal.endRead()
          }

          if (workUnitStore) {
            switch (workUnitStore.type) {
              case 'prerender':
                // If `allowEmptyStaticShell` is true, and thus a prefilled
                // resume data cache was provided, then a cache miss means that
                // params were part of the cache key. In this case, we can make
                // this cache function a dynamic hole in the shell (or produce
                // an empty shell if there's no parent suspense boundary).
                // Currently, this also includes layouts and pages that don't
                // read params, which will be improved when we implement
                // NAR-136. Otherwise, we assume that if params are passed
                // explicitly into a "use cache" function, that the params are
                // also accessed. This allows us to abort early, and treat the
                // function as dynamic, instead of waiting for the timeout to be
                // reached. Compared to the instrumentation-based params bailout
                // we do here, this also covers the case where params are
                // transformed with an async function, before being passed into
                // the "use cache" function, which escapes the instrumentation.
                if (workUnitStore.allowEmptyStaticShell) {
                  return makeHangingPromise(
                    workUnitStore.renderSignal,
                    'dynamic "use cache"'
                  )
                }
                break
              case 'prerender-ppr':
              case 'prerender-legacy':
              case 'request':
              case 'cache':
              case 'private-cache':
              case 'unstable-cache':
                break
              default:
                workUnitStore satisfies never
            }
          }
        }
      }

      if (stream === undefined) {
        const cacheSignal = workUnitStore ? getCacheSignal(workUnitStore) : null
        if (cacheSignal) {
          // Either the cache handler or the generation can be using I/O at this point.
          // We need to track when they start and when they complete.
          cacheSignal.beginRead()
        }

        const lazyRefreshTags = workStore.refreshTagsByCacheKind.get(kind)

        if (lazyRefreshTags && !isResolvedLazyResult(lazyRefreshTags)) {
          await lazyRefreshTags
        }

        let entry: CacheEntry | undefined

        // We ignore existing cache entries when force revalidating.
        if (cacheHandler && !shouldForceRevalidate(workStore, workUnitStore)) {
          entry = await cacheHandler.get(
            serializedCacheKey,
            workUnitStore?.implicitTags?.tags ?? []
          )
        }

        if (entry) {
          const implicitTags = workUnitStore?.implicitTags?.tags ?? []
          let implicitTagsExpiration = 0

          if (workUnitStore?.implicitTags) {
            const lazyExpiration =
              workUnitStore.implicitTags.expirationsByCacheKind.get(kind)

            if (lazyExpiration) {
              const expiration = isResolvedLazyResult(lazyExpiration)
                ? lazyExpiration.value
                : await lazyExpiration

              // If a cache handler returns an expiration time of Infinity, it
              // signals to Next.js that it handles checking cache entries for
              // staleness based on the expiration of the implicit tags passed
              // into the `get` method. In this case, we keep the default of 0,
              // which means that the implicit tags are not considered expired.
              if (expiration < Infinity) {
                implicitTagsExpiration = expiration
              }
            }
          }

          if (
            shouldDiscardCacheEntry(
              entry,
              workStore,
              workUnitStore,
              implicitTags,
              implicitTagsExpiration
            )
          ) {
            debug?.('discarding stale entry', serializedCacheKey)
            entry = undefined
          }
        }

        const currentTime = performance.timeOrigin + performance.now()
        if (
          workUnitStore !== undefined &&
          entry !== undefined &&
          (entry.revalidate === 0 || entry.expire < DYNAMIC_EXPIRE)
        ) {
          switch (workUnitStore.type) {
            case 'prerender':
              // In a Dynamic I/O prerender, if the cache entry has revalidate:
              // 0 or if the expire time is under 5 minutes, then we consider
              // this cache entry dynamic as it's not worth generating static
              // pages for such data. It's better to leave a PPR hole that can
              // be filled in dynamically with a potentially cached entry.
              if (cacheSignal) {
                cacheSignal.endRead()
              }
              return makeHangingPromise(
                workUnitStore.renderSignal,
                'dynamic "use cache"'
              )
            case 'prerender-ppr':
            case 'prerender-legacy':
            case 'request':
            case 'cache':
            case 'private-cache':
            case 'unstable-cache':
              break
            default:
              workUnitStore satisfies never
          }
        }

        if (
          entry === undefined ||
          currentTime > entry.timestamp + entry.expire * 1000 ||
          (workStore.isStaticGeneration &&
            currentTime > entry.timestamp + entry.revalidate * 1000)
        ) {
          // Miss. Generate a new result.

          // If the cache entry is stale and we're prerendering, we don't want to use the
          // stale entry since it would unnecessarily need to shorten the lifetime of the
          // prerender. We're not time constrained here so we can re-generated it now.

          // We need to run this inside a clean AsyncLocalStorage snapshot so that the cache
          // generation cannot read anything from the context we're currently executing which
          // might include request specific things like cookies() inside a React.cache().
          // Note: It is important that we await at least once before this because it lets us
          // pop out of any stack specific contexts as well - aka "Sync" Local Storage.

          if (entry) {
            if (currentTime > entry.timestamp + entry.expire * 1000) {
              debug?.('entry is expired', serializedCacheKey)
            }

            if (
              workStore.isStaticGeneration &&
              currentTime > entry.timestamp + entry.revalidate * 1000
            ) {
              debug?.('static generation, entry is stale', serializedCacheKey)
            }
          }

          const result = await generateCacheEntry(
            workStore,
            cacheContext,
            clientReferenceManifest,
            encodedCacheKeyParts,
            fn,
            sharedErrorStack
          )

          if (result.type === 'prerender-dynamic') {
            return result.hangingPromise
          }

          const { stream: newStream, pendingCacheEntry } = result

          // When draft mode is enabled, we must not save the cache entry.
          if (!workStore.isDraftMode) {
            let savedCacheEntry

            if (prerenderResumeDataCache) {
              // Create a clone that goes into the cache scope memory cache.
              const split = clonePendingCacheEntry(pendingCacheEntry)
              savedCacheEntry = getNthCacheEntry(split, 0)
              prerenderResumeDataCache.cache.set(
                serializedCacheKey,
                getNthCacheEntry(split, 1)
              )
            } else {
              savedCacheEntry = pendingCacheEntry
            }

            if (cacheHandler) {
              const promise = cacheHandler.set(
                serializedCacheKey,
                savedCacheEntry
              )

              workStore.pendingRevalidateWrites ??= []
              workStore.pendingRevalidateWrites.push(promise)
            }
          }

          stream = newStream
        } else {
          // If we have an entry at this point, this can't be a private cache
          // entry.
          if (cacheContext.kind === 'private') {
            throw new InvariantError(
              `A private cache entry must not be retrieved from the cache handler.`
            )
          }

          propagateCacheLifeAndTags(cacheContext, entry)

          // We want to return this stream, even if it's stale.
          stream = entry.value

          // If we have a cache scope, we need to clone the entry and set it on
          // the inner cache scope.
          if (prerenderResumeDataCache) {
            const [entryLeft, entryRight] = cloneCacheEntry(entry)
            if (cacheSignal) {
              stream = createTrackedReadableStream(entryLeft.value, cacheSignal)
            } else {
              stream = entryLeft.value
            }

            prerenderResumeDataCache.cache.set(
              serializedCacheKey,
              Promise.resolve(entryRight)
            )
          } else {
            // If we're not regenerating we need to signal that we've finished
            // putting the entry into the cache scope at this point. Otherwise we do
            // that inside generateCacheEntry.
            cacheSignal?.endRead()
          }

          if (currentTime > entry.timestamp + entry.revalidate * 1000) {
            // If this is stale, and we're not in a prerender (i.e. this is
            // dynamic render), then we should warm up the cache with a fresh
            // revalidated entry.
            const result = await generateCacheEntry(
              workStore,
              // This is not running within the context of this unit.
              { kind: cacheContext.kind, outerWorkUnitStore: undefined },
              clientReferenceManifest,
              encodedCacheKeyParts,
              fn,
              sharedErrorStack
            )

            if (result.type === 'cached') {
              const { stream: ignoredStream, pendingCacheEntry } = result
              let savedCacheEntry: Promise<CacheEntry>

              if (prerenderResumeDataCache) {
                const split = clonePendingCacheEntry(pendingCacheEntry)
                savedCacheEntry = getNthCacheEntry(split, 0)
                prerenderResumeDataCache.cache.set(
                  serializedCacheKey,
                  getNthCacheEntry(split, 1)
                )
              } else {
                savedCacheEntry = pendingCacheEntry
              }

              if (cacheHandler) {
                const promise = cacheHandler.set(
                  serializedCacheKey,
                  savedCacheEntry
                )

                workStore.pendingRevalidateWrites ??= []
                workStore.pendingRevalidateWrites.push(promise)
              }

              await ignoredStream.cancel()
            }
          }
        }
      }

      // Logs are replayed even if it's a hit - to ensure we see them on the client eventually.
      // If we didn't then the client wouldn't see the logs if it was seeded from a prewarm that
      // never made it to the client. However, this also means that you see logs even when the
      // cached function isn't actually re-executed. We should instead ensure prewarms always
      // make it to the client. Another issue is that this will cause double logging in the
      // server terminal. Once while generating the cache entry and once when replaying it on
      // the server, which is required to pick it up for replaying again on the client.
      const replayConsoleLogs = true

      const serverConsumerManifest = {
        // moduleLoading must be null because we don't want to trigger preloads of ClientReferences
        // to be added to the consumer. Instead, we'll wait for any ClientReference to be emitted
        // which themselves will handle the preloading.
        moduleLoading: null,
        moduleMap: isEdgeRuntime
          ? clientReferenceManifest.edgeRscModuleMapping
          : clientReferenceManifest.rscModuleMapping,
        serverModuleMap: getServerModuleMap(),
      }

      return createFromReadableStream(stream, {
        serverConsumerManifest,
        temporaryReferences,
        replayConsoleLogs,
        environmentName: 'Cache',
      })
    },
  }[name]

  return React.cache(cachedFn)
}

function isPageComponent(
  args: any[]
): args is [UseCachePageComponentProps, undefined] {
  if (args.length !== 2) {
    return false
  }

  const [props, ref] = args

  return (
    ref === undefined && // server components receive an undefined ref arg
    props !== null &&
    typeof props === 'object' &&
    (props as UseCachePageComponentProps).$$isPageComponent
  )
}

function isLayoutComponent(
  args: any[]
): args is [UseCacheLayoutComponentProps, undefined] {
  if (args.length !== 2) {
    return false
  }

  const [props, ref] = args

  return (
    ref === undefined && // server components receive an undefined ref arg
    props !== null &&
    typeof props === 'object' &&
    (props as UseCacheLayoutComponentProps).$$isLayoutComponent
  )
}

function shouldForceRevalidate(
  workStore: WorkStore,
  workUnitStore: WorkUnitStore | undefined
): boolean {
  if (workStore.isOnDemandRevalidate || workStore.isDraftMode) {
    return true
  }

  if (workStore.dev && workUnitStore) {
    switch (workUnitStore.type) {
      case 'request':
        return workUnitStore.headers.get('cache-control') === 'no-cache'
      case 'cache':
      case 'private-cache':
        return workUnitStore.forceRevalidate
      case 'prerender':
      case 'prerender-client':
      case 'prerender-ppr':
      case 'prerender-legacy':
      case 'unstable-cache':
        break
      default:
        workUnitStore satisfies never
    }
  }

  return false
}

function shouldDiscardCacheEntry(
  entry: CacheEntry,
  workStore: WorkStore,
  workUnitStore: WorkUnitStore | undefined,
  implicitTags: string[],
  implicitTagsExpiration: number
): boolean {
  // If the cache entry was created before any of the implicit tags were
  // revalidated last, we need to discard it.
  if (entry.timestamp <= implicitTagsExpiration) {
    debug?.(
      'entry was created at',
      entry.timestamp,
      'before implicit tags were revalidated at',
      implicitTagsExpiration
    )

    return true
  }

  // During prerendering, we ignore recently revalidated tags. In dev mode, we
  // can assume that the dynamic dev rendering will have discarded and recreated
  // the affected cache entries, and we don't want to discard those again during
  // the prerender validation. During build-time prerendering, there will never
  // be any pending revalidated tags.
  if (workUnitStore) {
    switch (workUnitStore.type) {
      case 'prerender':
        return false
      case 'prerender-client':
      case 'prerender-ppr':
      case 'prerender-legacy':
      case 'request':
      case 'cache':
      case 'private-cache':
      case 'unstable-cache':
        break
      default:
        workUnitStore satisfies never
    }
  }

  // If the cache entry contains revalidated tags that the cache handler might
  // not know about yet, we need to discard it.
  if (entry.tags.some((tag) => isRecentlyRevalidatedTag(tag, workStore))) {
    return true
  }

  // Finally, if any of the implicit tags have been revalidated recently, we
  // also need to discard the cache entry.
  if (implicitTags.some((tag) => isRecentlyRevalidatedTag(tag, workStore))) {
    return true
  }

  return false
}

function isRecentlyRevalidatedTag(tag: string, workStore: WorkStore): boolean {
  const { previouslyRevalidatedTags, pendingRevalidatedTags } = workStore

  // Was the tag previously revalidated (e.g. by a redirecting server action)?
  if (previouslyRevalidatedTags.includes(tag)) {
    debug?.('tag', tag, 'was previously revalidated')

    return true
  }

  // It could also have been revalidated by the currently running server action.
  // In this case the revalidation might not have been fully propagated by a
  // remote cache handler yet, so we read it from the pending tags in the work
  // store.
  if (pendingRevalidatedTags?.includes(tag)) {
    debug?.('tag', tag, 'was just revalidated')

    return true
  }

  return false
}