๐Ÿ“ฆ cloudflare / vinext

๐Ÿ“„ fetch-cache.test.ts ยท 1088 lines
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/**
 * Unit tests for fetch cache shim.
 *
 * Tests the patched fetch() with Next.js caching semantics:
 * - next.revalidate for TTL-based caching
 * - next.tags for tag-based invalidation
 * - cache: 'no-store' and cache: 'force-cache'
 * - Stale-while-revalidate behavior
 * - next property stripping
 * - Independent cache entries per URL
 */

import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";

// We need to mock fetch at the module level BEFORE fetch-cache.ts captures
// `originalFetch`. Use vi.stubGlobal to intercept at import time.
let requestCount = 0;
const fetchMock = vi.fn(async (input: string | URL | Request, _init?: RequestInit) => {
  requestCount++;
  const url = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
  return new Response(JSON.stringify({ url, count: requestCount }), {
    status: 200,
    headers: { "content-type": "application/json" },
  });
});

// Stub globalThis.fetch BEFORE importing modules that capture it
vi.stubGlobal("fetch", fetchMock);

// Now import โ€” these will capture fetchMock as "originalFetch"
const { withFetchCache, runWithFetchCache, getCollectedFetchTags, getOriginalFetch } = await import("../packages/vinext/src/shims/fetch-cache.js");
const { getCacheHandler, revalidateTag, MemoryCacheHandler, setCacheHandler } = await import("../packages/vinext/src/shims/cache.js");

describe("fetch cache shim", () => {
  let cleanup: (() => void) | null = null;

  beforeEach(() => {
    // Reset state
    requestCount = 0;
    fetchMock.mockClear();
    // Reset the cache handler to a fresh instance for each test
    setCacheHandler(new MemoryCacheHandler());
    // Install the patched fetch
    cleanup = withFetchCache();
  });

  afterEach(() => {
    cleanup?.();
    cleanup = null;
  });

  // โ”€โ”€ Basic caching with next.revalidate โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

  it("caches fetch with next.revalidate and returns cached on second call", async () => {
    const res1 = await fetch("https://api.example.com/data", {
      next: { revalidate: 60 },
    });
    const data1 = await res1.json();
    expect(data1.count).toBe(1);

    // Second call should return cached data (no new network request)
    const res2 = await fetch("https://api.example.com/data", {
      next: { revalidate: 60 },
    });
    const data2 = await res2.json();
    expect(data2.count).toBe(1); // Same count = cached
    expect(fetchMock).toHaveBeenCalledTimes(1); // Only one real fetch
  });

  it("cache: 'force-cache' caches indefinitely", async () => {
    const res1 = await fetch("https://api.example.com/force", {
      cache: "force-cache",
    });
    const data1 = await res1.json();
    expect(data1.count).toBe(1);

    const res2 = await fetch("https://api.example.com/force", {
      cache: "force-cache",
    });
    const data2 = await res2.json();
    expect(data2.count).toBe(1); // Cached
    expect(fetchMock).toHaveBeenCalledTimes(1);
  });

  // โ”€โ”€ No caching (no-store, revalidate: 0, revalidate: false) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

  it("cache: 'no-store' bypasses cache entirely", async () => {
    const res1 = await fetch("https://api.example.com/nostore", {
      cache: "no-store",
    });
    const data1 = await res1.json();
    expect(data1.count).toBe(1);

    const res2 = await fetch("https://api.example.com/nostore", {
      cache: "no-store",
    });
    const data2 = await res2.json();
    expect(data2.count).toBe(2); // Fresh fetch each time
    expect(fetchMock).toHaveBeenCalledTimes(2);
  });

  it("next.revalidate: 0 skips caching", async () => {
    const res1 = await fetch("https://api.example.com/rev0", {
      next: { revalidate: 0 },
    });
    const data1 = await res1.json();
    expect(data1.count).toBe(1);

    const res2 = await fetch("https://api.example.com/rev0", {
      next: { revalidate: 0 },
    });
    const data2 = await res2.json();
    expect(data2.count).toBe(2); // Not cached
    expect(fetchMock).toHaveBeenCalledTimes(2);
  });

  it("next.revalidate: false skips caching", async () => {
    const res1 = await fetch("https://api.example.com/revfalse", {
      next: { revalidate: false },
    });
    const data1 = await res1.json();
    expect(data1.count).toBe(1);

    const res2 = await fetch("https://api.example.com/revfalse", {
      next: { revalidate: false },
    });
    const data2 = await res2.json();
    expect(data2.count).toBe(2); // Not cached
    expect(fetchMock).toHaveBeenCalledTimes(2);
  });

  it("no cache or next options passes through without caching", async () => {
    const res1 = await fetch("https://api.example.com/passthrough");
    const data1 = await res1.json();
    expect(data1.count).toBe(1);

    const res2 = await fetch("https://api.example.com/passthrough");
    const data2 = await res2.json();
    expect(data2.count).toBe(2); // Pass-through, no caching
    expect(fetchMock).toHaveBeenCalledTimes(2);
  });

  // โ”€โ”€ Tag-based invalidation โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

  it("next.tags caches and revalidateTag invalidates", async () => {
    const res1 = await fetch("https://api.example.com/posts", {
      next: { tags: ["posts"] },
    });
    const data1 = await res1.json();
    expect(data1.count).toBe(1);

    // Cached
    const res2 = await fetch("https://api.example.com/posts", {
      next: { tags: ["posts"] },
    });
    const data2 = await res2.json();
    expect(data2.count).toBe(1);
    expect(fetchMock).toHaveBeenCalledTimes(1);

    // Invalidate via tag
    await revalidateTag("posts");

    // Should re-fetch after tag invalidation
    const res3 = await fetch("https://api.example.com/posts", {
      next: { tags: ["posts"] },
    });
    const data3 = await res3.json();
    expect(data3.count).toBe(2); // Fresh fetch
    expect(fetchMock).toHaveBeenCalledTimes(2);
  });

  it("revalidateTag only invalidates matching tags", async () => {
    // Cache two different tagged fetches
    await fetch("https://api.example.com/posts-tag", {
      next: { tags: ["posts"] },
    });
    await fetch("https://api.example.com/users-tag", {
      next: { tags: ["users"] },
    });
    expect(fetchMock).toHaveBeenCalledTimes(2);

    // Invalidate only "posts"
    await revalidateTag("posts");

    // Posts should re-fetch
    const postRes = await fetch("https://api.example.com/posts-tag", {
      next: { tags: ["posts"] },
    });
    const postData = await postRes.json();
    expect(postData.count).toBe(3); // Fresh fetch (count continues from 2)

    // Users should still be cached
    const userRes = await fetch("https://api.example.com/users-tag", {
      next: { tags: ["users"] },
    });
    const userData = await userRes.json();
    expect(userData.count).toBe(2); // Still the cached version
    expect(fetchMock).toHaveBeenCalledTimes(3); // Only posts re-fetched
  });

  // โ”€โ”€ TTL expiry (stale-while-revalidate) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

  it("returns stale data after TTL expires and triggers background refetch", async () => {
    const res1 = await fetch("https://api.example.com/stale-test", {
      next: { revalidate: 1 },
    });
    const data1 = await res1.json();
    expect(data1.count).toBe(1);

    // Manually expire the cache entry (key is a SHA-256 hash, find it dynamically)
    const handler = getCacheHandler() as InstanceType<typeof MemoryCacheHandler>;
    const store = (handler as any).store as Map<string, any>;
    for (const [, entry] of store) {
      entry.revalidateAt = Date.now() - 1000; // Expired 1 second ago
    }

    // Should return stale data immediately
    const res2 = await fetch("https://api.example.com/stale-test", {
      next: { revalidate: 1 },
    });
    const data2 = await res2.json();
    expect(data2.count).toBe(1); // Stale data (same as first fetch)

    // Wait for background refetch
    await new Promise((resolve) => setTimeout(resolve, 50));
    expect(fetchMock).toHaveBeenCalledTimes(2); // Original + background refetch
  });

  // โ”€โ”€ Independent cache entries per URL โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

  it("different URLs get independent cache entries", async () => {
    const res1 = await fetch("https://api.example.com/url-a", {
      next: { revalidate: 60 },
    });
    const data1 = await res1.json();
    expect(data1.url).toBe("https://api.example.com/url-a");
    expect(data1.count).toBe(1);

    const res2 = await fetch("https://api.example.com/url-b", {
      next: { revalidate: 60 },
    });
    const data2 = await res2.json();
    expect(data2.url).toBe("https://api.example.com/url-b");
    expect(data2.count).toBe(2); // Different URL = different cache

    // Re-fetch url-a should be cached
    const res3 = await fetch("https://api.example.com/url-a", {
      next: { revalidate: 60 },
    });
    const data3 = await res3.json();
    expect(data3.count).toBe(1); // Cached
    expect(fetchMock).toHaveBeenCalledTimes(2);
  });

  it("same URL with different methods get separate cache entries", async () => {
    const getRes = await fetch("https://api.example.com/method-test", {
      method: "GET",
      next: { revalidate: 60 },
    });
    const getData = await getRes.json();
    expect(getData.count).toBe(1);

    const postRes = await fetch("https://api.example.com/method-test", {
      method: "POST",
      body: "test",
      next: { revalidate: 60 },
    });
    const postData = await postRes.json();
    expect(postData.count).toBe(2); // Different method = different cache

    expect(fetchMock).toHaveBeenCalledTimes(2);
  });

  // โ”€โ”€ next property stripping โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

  it("strips next property before passing to real fetch", async () => {
    await fetch("https://api.example.com/strip-test", {
      next: { revalidate: 60, tags: ["test"] },
      headers: { "X-Custom": "value" },
    });

    // Verify the mock was called with init that does NOT have `next`
    const call = fetchMock.mock.calls[0];
    const init = call[1] as RequestInit;
    expect(init).toBeDefined();
    expect((init as any).next).toBeUndefined();
    expect((init as any).headers).toEqual({ "X-Custom": "value" });
  });

  it("strips next property for no-store fetches too", async () => {
    await fetch("https://api.example.com/strip-nostore", {
      cache: "no-store",
      next: { tags: ["test"] },
    });

    const call = fetchMock.mock.calls[0];
    const init = call[1] as RequestInit;
    expect((init as any).next).toBeUndefined();
  });

  // โ”€โ”€ Tag collection during rendering โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

  it("collects tags during render pass via getCollectedFetchTags", async () => {
    await fetch("https://api.example.com/tag-collect-a", {
      next: { tags: ["posts", "list"] },
    });
    await fetch("https://api.example.com/tag-collect-b", {
      next: { tags: ["users"] },
    });

    const tags = getCollectedFetchTags();
    expect(tags).toContain("posts");
    expect(tags).toContain("list");
    expect(tags).toContain("users");
    expect(tags).toHaveLength(3);
  });

  it("does not collect duplicate tags", async () => {
    await fetch("https://api.example.com/dup-tag-a", {
      next: { tags: ["data"] },
    });
    await fetch("https://api.example.com/dup-tag-b", {
      next: { tags: ["data"] },
    });

    const tags = getCollectedFetchTags();
    expect(tags.filter(t => t === "data")).toHaveLength(1);
  });

  // โ”€โ”€ Only caches successful responses โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

  it("does not cache non-2xx responses", async () => {
    // Override mock to return 404 once
    fetchMock.mockImplementationOnce(async () => {
      requestCount++;
      return new Response("Not found", { status: 404 });
    });

    const res1 = await fetch("https://api.example.com/missing-page", {
      next: { revalidate: 60 },
    });
    expect(res1.status).toBe(404);

    // Should re-fetch since 404 wasn't cached
    const res2 = await fetch("https://api.example.com/missing-page", {
      next: { revalidate: 60 },
    });
    expect(res2.status).toBe(200);
    expect(fetchMock).toHaveBeenCalledTimes(2);
  });

  // โ”€โ”€ URL and Request object inputs โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

  it("handles URL objects as input", async () => {
    const url = new URL("https://api.example.com/url-obj");
    const res = await fetch(url, { next: { revalidate: 60 } });
    expect(res.status).toBe(200);
    const data = await res.json();
    expect(data.count).toBe(1);

    // Cached on second call
    const res2 = await fetch(url, { next: { revalidate: 60 } });
    const data2 = await res2.json();
    expect(data2.count).toBe(1);
    expect(fetchMock).toHaveBeenCalledTimes(1);
  });

  it("handles Request objects as input", async () => {
    const req = new Request("https://api.example.com/req-obj");
    const res = await fetch(req, { next: { revalidate: 60 } });
    expect(res.status).toBe(200);
    const data = await res.json();
    expect(data.count).toBe(1);

    // Cached on second call with same URL
    const req2 = new Request("https://api.example.com/req-obj");
    const res2 = await fetch(req2, { next: { revalidate: 60 } });
    const data2 = await res2.json();
    expect(data2.count).toBe(1);
    expect(fetchMock).toHaveBeenCalledTimes(1);
  });

  // โ”€โ”€ force-cache with next.revalidate โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

  it("cache: 'force-cache' with next.revalidate uses the specified TTL", async () => {
    const res1 = await fetch("https://api.example.com/force-ttl", {
      cache: "force-cache",
      next: { revalidate: 1 },
    });
    const data1 = await res1.json();
    expect(data1.count).toBe(1);

    // Verify it's cached
    const res2 = await fetch("https://api.example.com/force-ttl", {
      cache: "force-cache",
      next: { revalidate: 1 },
    });
    const data2 = await res2.json();
    expect(data2.count).toBe(1);

    // Expire the cache manually (key is a SHA-256 hash, find it dynamically)
    const handler = getCacheHandler() as InstanceType<typeof MemoryCacheHandler>;
    const store = (handler as any).store as Map<string, any>;
    for (const [, entry] of store) {
      entry.revalidateAt = Date.now() - 1000;
    }

    // Should return stale
    const res3 = await fetch("https://api.example.com/force-ttl", {
      cache: "force-cache",
      next: { revalidate: 1 },
    });
    const data3 = await res3.json();
    expect(data3.count).toBe(1); // Stale data returned
    // Background refetch
    await new Promise((resolve) => setTimeout(resolve, 50));
    expect(fetchMock).toHaveBeenCalledTimes(2);
  });

  // โ”€โ”€ Cleanup clears per-request state โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

  it("cleanup function clears collected tags", async () => {
    // Collect some tags
    await fetch("https://api.example.com/cleanup-test", {
      next: { tags: ["cleanup-tag"] },
    });
    expect(getCollectedFetchTags()).toContain("cleanup-tag");

    // Cleanup should reset tag state
    cleanup!();
    cleanup = null;
    expect(getCollectedFetchTags()).toHaveLength(0);

    // Re-install for afterEach cleanup
    cleanup = withFetchCache();
  });

  // โ”€โ”€ getOriginalFetch โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

  it("getOriginalFetch returns the module-level original fetch", () => {
    const orig = getOriginalFetch();
    expect(typeof orig).toBe("function");
    // It should be fetchMock since that was the global fetch when the module loaded
    expect(orig).toBe(fetchMock);
  });

  // โ”€โ”€ next: {} empty passes through โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

  it("next: {} with no revalidate or tags passes through", async () => {
    const res1 = await fetch("https://api.example.com/empty-next", { next: {} });
    const data1 = await res1.json();
    expect(data1.count).toBe(1);

    const res2 = await fetch("https://api.example.com/empty-next", { next: {} });
    const data2 = await res2.json();
    expect(data2.count).toBe(2); // Not cached
    expect(fetchMock).toHaveBeenCalledTimes(2);
  });

  // โ”€โ”€ Concurrent request isolation via ALS โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

  it("concurrent runWithFetchCache calls have isolated tags", async () => {
    // Clean up the withFetchCache() from beforeEach โ€” runWithFetchCache
    // manages its own ALS scope.
    cleanup?.();
    cleanup = null;

    const [tags1, tags2] = await Promise.all([
      runWithFetchCache(async () => {
        await fetch("https://api.example.com/concurrent-a", {
          next: { tags: ["request-1"] },
        });
        return getCollectedFetchTags();
      }),
      runWithFetchCache(async () => {
        await fetch("https://api.example.com/concurrent-b", {
          next: { tags: ["request-2"] },
        });
        return getCollectedFetchTags();
      }),
    ]);

    expect(tags1).toEqual(["request-1"]);
    expect(tags2).toEqual(["request-2"]);

    // Re-install for afterEach
    cleanup = withFetchCache();
  });

  // โ”€โ”€ Auth header isolation in cache keys โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

  describe("auth header cache isolation", () => {
    it("different Authorization headers produce separate cache entries", async () => {
      // Alice fetches with her token โ€” explicitly opt into caching
      const res1 = await fetch("https://api.example.com/me", {
        headers: { Authorization: "Bearer alice-token" },
        next: { revalidate: 60 },
      });
      const data1 = await res1.json();
      expect(data1.count).toBe(1);

      // Bob fetches with his token โ€” should NOT get Alice's cached response
      const res2 = await fetch("https://api.example.com/me", {
        headers: { Authorization: "Bearer bob-token" },
        next: { revalidate: 60 },
      });
      const data2 = await res2.json();
      expect(data2.count).toBe(2); // Different cache entry
      expect(fetchMock).toHaveBeenCalledTimes(2);

      // Alice fetches again โ€” should get her cached response
      const res3 = await fetch("https://api.example.com/me", {
        headers: { Authorization: "Bearer alice-token" },
        next: { revalidate: 60 },
      });
      const data3 = await res3.json();
      expect(data3.count).toBe(1); // Cached from first request
      expect(fetchMock).toHaveBeenCalledTimes(2);
    });

    it("different Cookie headers produce separate cache entries", async () => {
      const res1 = await fetch("https://api.example.com/profile", {
        headers: { Cookie: "session=alice" },
        next: { revalidate: 60 },
      });
      const data1 = await res1.json();
      expect(data1.count).toBe(1);

      // Bob's cookie should get a separate cache entry
      const res2 = await fetch("https://api.example.com/profile", {
        headers: { Cookie: "session=bob" },
        next: { revalidate: 60 },
      });
      const data2 = await res2.json();
      expect(data2.count).toBe(2); // Fresh fetch, not Alice's data
      expect(fetchMock).toHaveBeenCalledTimes(2);
    });

    it("requests without auth headers share cache (public data)", async () => {
      const res1 = await fetch("https://api.example.com/public", {
        next: { revalidate: 60 },
      });
      const data1 = await res1.json();
      expect(data1.count).toBe(1);

      // No auth headers โ†’ same cache entry
      const res2 = await fetch("https://api.example.com/public", {
        next: { revalidate: 60 },
      });
      const data2 = await res2.json();
      expect(data2.count).toBe(1); // Cached
      expect(fetchMock).toHaveBeenCalledTimes(1);
    });

    it("auth headers with force-cache still produce per-user cache entries", async () => {
      const res1 = await fetch("https://api.example.com/forced", {
        headers: { Authorization: "Bearer alice" },
        cache: "force-cache",
      });
      const data1 = await res1.json();
      expect(data1.count).toBe(1);

      const res2 = await fetch("https://api.example.com/forced", {
        headers: { Authorization: "Bearer bob" },
        cache: "force-cache",
      });
      const data2 = await res2.json();
      expect(data2.count).toBe(2); // Separate cache entry
      expect(fetchMock).toHaveBeenCalledTimes(2);
    });

    it("auth headers with tags-only (no explicit revalidate) bypass cache", async () => {
      // When only tags are specified but no explicit revalidate or force-cache,
      // auth headers should cause a cache bypass
      const res1 = await fetch("https://api.example.com/tagged-auth", {
        headers: { Authorization: "Bearer alice" },
        next: { tags: ["user-data"] },
      });
      const data1 = await res1.json();
      expect(data1.count).toBe(1);

      // Same user, same tags โ€” should still bypass (no explicit cache opt-in)
      const res2 = await fetch("https://api.example.com/tagged-auth", {
        headers: { Authorization: "Bearer alice" },
        next: { tags: ["user-data"] },
      });
      const data2 = await res2.json();
      expect(data2.count).toBe(2); // Not cached โ€” safety bypass
      expect(fetchMock).toHaveBeenCalledTimes(2);
    });

    it("X-API-Key header is included in cache key", async () => {
      const res1 = await fetch("https://api.example.com/api-key", {
        headers: { "X-API-Key": "key-alice" },
        next: { revalidate: 60 },
      });
      const data1 = await res1.json();
      expect(data1.count).toBe(1);

      const res2 = await fetch("https://api.example.com/api-key", {
        headers: { "X-API-Key": "key-bob" },
        next: { revalidate: 60 },
      });
      const data2 = await res2.json();
      expect(data2.count).toBe(2); // Different key = different cache
      expect(fetchMock).toHaveBeenCalledTimes(2);
    });

    it("auth headers from Request object are included in cache key", async () => {
      const req1 = new Request("https://api.example.com/req-auth", {
        headers: { Authorization: "Bearer alice" },
      });
      const res1 = await fetch(req1, { next: { revalidate: 60 } });
      const data1 = await res1.json();
      expect(data1.count).toBe(1);

      const req2 = new Request("https://api.example.com/req-auth", {
        headers: { Authorization: "Bearer bob" },
      });
      const res2 = await fetch(req2, { next: { revalidate: 60 } });
      const data2 = await res2.json();
      expect(data2.count).toBe(2); // Different auth = different cache
      expect(fetchMock).toHaveBeenCalledTimes(2);
    });
  });

  // โ”€โ”€ cache: 'no-cache' bypass โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

  it("cache: 'no-cache' bypasses cache entirely", async () => {
    const res1 = await fetch("https://api.example.com/nocache", {
      cache: "no-cache" as RequestCache,
    });
    const data1 = await res1.json();
    expect(data1.count).toBe(1);

    const res2 = await fetch("https://api.example.com/nocache", {
      cache: "no-cache" as RequestCache,
    });
    const data2 = await res2.json();
    expect(data2.count).toBe(2); // Fresh fetch each time
    expect(fetchMock).toHaveBeenCalledTimes(2);
  });

  it("cache: 'no-store' with auth headers bypasses cache", async () => {
    const res1 = await fetch("https://api.example.com/nostore-auth", {
      cache: "no-store",
      headers: { Authorization: "Bearer token" },
    });
    const data1 = await res1.json();
    expect(data1.count).toBe(1);

    const res2 = await fetch("https://api.example.com/nostore-auth", {
      cache: "no-store",
      headers: { Authorization: "Bearer token" },
    });
    const data2 = await res2.json();
    expect(data2.count).toBe(2); // Always fresh
    expect(fetchMock).toHaveBeenCalledTimes(2);
  });

  it("cache: 'no-cache' with auth headers bypasses cache", async () => {
    const res1 = await fetch("https://api.example.com/nocache-auth", {
      cache: "no-cache" as RequestCache,
      headers: { Cookie: "session=alice" },
    });
    const data1 = await res1.json();
    expect(data1.count).toBe(1);

    const res2 = await fetch("https://api.example.com/nocache-auth", {
      cache: "no-cache" as RequestCache,
      headers: { Cookie: "session=bob" },
    });
    const data2 = await res2.json();
    expect(data2.count).toBe(2); // Always fresh
    expect(fetchMock).toHaveBeenCalledTimes(2);
  });

  // โ”€โ”€ Cache key: body type handling โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

  describe("cache key body type handling", () => {
    it("different string bodies produce separate cache entries", async () => {
      const res1 = await fetch("https://api.example.com/body-str", {
        method: "POST",
        body: '{"type":"a"}',
        next: { revalidate: 60 },
      });
      const data1 = await res1.json();
      expect(data1.count).toBe(1);

      const res2 = await fetch("https://api.example.com/body-str", {
        method: "POST",
        body: '{"type":"b"}',
        next: { revalidate: 60 },
      });
      const data2 = await res2.json();
      expect(data2.count).toBe(2); // Different body = different cache
      expect(fetchMock).toHaveBeenCalledTimes(2);
    });

    it("same string bodies hit the same cache entry", async () => {
      const res1 = await fetch("https://api.example.com/body-same", {
        method: "POST",
        body: '{"query":"test"}',
        next: { revalidate: 60 },
      });
      const data1 = await res1.json();
      expect(data1.count).toBe(1);

      const res2 = await fetch("https://api.example.com/body-same", {
        method: "POST",
        body: '{"query":"test"}',
        next: { revalidate: 60 },
      });
      const data2 = await res2.json();
      expect(data2.count).toBe(1); // Same body = same cache
      expect(fetchMock).toHaveBeenCalledTimes(1);
    });

    it("Uint8Array bodies are included in cache key", async () => {
      const bodyA = new TextEncoder().encode("payload-a");
      const bodyB = new TextEncoder().encode("payload-b");

      const res1 = await fetch("https://api.example.com/body-uint8", {
        method: "POST",
        body: bodyA,
        next: { revalidate: 60 },
      });
      const data1 = await res1.json();
      expect(data1.count).toBe(1);

      const res2 = await fetch("https://api.example.com/body-uint8", {
        method: "POST",
        body: bodyB,
        next: { revalidate: 60 },
      });
      const data2 = await res2.json();
      expect(data2.count).toBe(2); // Different binary body = different cache
      expect(fetchMock).toHaveBeenCalledTimes(2);
    });

    it("same Uint8Array bodies hit the same cache entry", async () => {
      const body1 = new TextEncoder().encode("same-payload");
      const body2 = new TextEncoder().encode("same-payload");

      const res1 = await fetch("https://api.example.com/body-uint8-same", {
        method: "POST",
        body: body1,
        next: { revalidate: 60 },
      });
      const data1 = await res1.json();
      expect(data1.count).toBe(1);

      const res2 = await fetch("https://api.example.com/body-uint8-same", {
        method: "POST",
        body: body2,
        next: { revalidate: 60 },
      });
      const data2 = await res2.json();
      expect(data2.count).toBe(1); // Same payload = same cache
      expect(fetchMock).toHaveBeenCalledTimes(1);
    });

    it("Blob bodies are included in cache key", async () => {
      const blobA = new Blob(["blob-content-a"], { type: "text/plain" });
      const blobB = new Blob(["blob-content-b"], { type: "text/plain" });

      const res1 = await fetch("https://api.example.com/body-blob", {
        method: "POST",
        body: blobA,
        next: { revalidate: 60 },
      });
      const data1 = await res1.json();
      expect(data1.count).toBe(1);

      const res2 = await fetch("https://api.example.com/body-blob", {
        method: "POST",
        body: blobB,
        next: { revalidate: 60 },
      });
      const data2 = await res2.json();
      expect(data2.count).toBe(2); // Different blob = different cache
      expect(fetchMock).toHaveBeenCalledTimes(2);
    });

    it("FormData bodies are included in cache key", async () => {
      const formA = new FormData();
      formA.append("name", "alice");

      const formB = new FormData();
      formB.append("name", "bob");

      const res1 = await fetch("https://api.example.com/body-form", {
        method: "POST",
        body: formA,
        next: { revalidate: 60 },
      });
      const data1 = await res1.json();
      expect(data1.count).toBe(1);

      const res2 = await fetch("https://api.example.com/body-form", {
        method: "POST",
        body: formB,
        next: { revalidate: 60 },
      });
      const data2 = await res2.json();
      expect(data2.count).toBe(2); // Different form data = different cache
      expect(fetchMock).toHaveBeenCalledTimes(2);
    });

    it("ReadableStream bodies are included in cache key", async () => {
      const streamA = new ReadableStream({
        start(controller) {
          controller.enqueue(new TextEncoder().encode("stream-a"));
          controller.close();
        },
      });
      const streamB = new ReadableStream({
        start(controller) {
          controller.enqueue(new TextEncoder().encode("stream-b"));
          controller.close();
        },
      });

      const res1 = await fetch("https://api.example.com/body-stream", {
        method: "POST",
        body: streamA,
        next: { revalidate: 60 },
      });
      const data1 = await res1.json();
      expect(data1.count).toBe(1);

      const res2 = await fetch("https://api.example.com/body-stream", {
        method: "POST",
        body: streamB,
        next: { revalidate: 60 },
      });
      const data2 = await res2.json();
      expect(data2.count).toBe(2); // Different stream = different cache
      expect(fetchMock).toHaveBeenCalledTimes(2);
    });
  });

  // โ”€โ”€ Cache key: header inclusion (all headers minus blocklist) โ”€โ”€โ”€โ”€โ”€โ”€

  describe("cache key header inclusion", () => {
    it("different Accept headers produce separate cache entries", async () => {
      const res1 = await fetch("https://api.example.com/accept-test", {
        headers: { Accept: "application/json" },
        next: { revalidate: 60 },
      });
      const data1 = await res1.json();
      expect(data1.count).toBe(1);

      const res2 = await fetch("https://api.example.com/accept-test", {
        headers: { Accept: "text/html" },
        next: { revalidate: 60 },
      });
      const data2 = await res2.json();
      expect(data2.count).toBe(2); // Different Accept = different cache
      expect(fetchMock).toHaveBeenCalledTimes(2);
    });

    it("different Accept-Language headers produce separate cache entries", async () => {
      const res1 = await fetch("https://api.example.com/lang-test", {
        headers: { "Accept-Language": "en-US" },
        next: { revalidate: 60 },
      });
      const data1 = await res1.json();
      expect(data1.count).toBe(1);

      const res2 = await fetch("https://api.example.com/lang-test", {
        headers: { "Accept-Language": "fr-FR" },
        next: { revalidate: 60 },
      });
      const data2 = await res2.json();
      expect(data2.count).toBe(2); // Different language = different cache
      expect(fetchMock).toHaveBeenCalledTimes(2);
    });

    it("custom headers are included in cache key", async () => {
      const res1 = await fetch("https://api.example.com/custom-hdr", {
        headers: { "X-Feature-Flag": "variant-a" },
        next: { revalidate: 60 },
      });
      const data1 = await res1.json();
      expect(data1.count).toBe(1);

      const res2 = await fetch("https://api.example.com/custom-hdr", {
        headers: { "X-Feature-Flag": "variant-b" },
        next: { revalidate: 60 },
      });
      const data2 = await res2.json();
      expect(data2.count).toBe(2); // Different custom header = different cache
      expect(fetchMock).toHaveBeenCalledTimes(2);
    });

    it("traceparent and tracestate headers are excluded from cache key", async () => {
      const res1 = await fetch("https://api.example.com/trace-test", {
        headers: {
          traceparent: "00-trace-id-1-01",
          tracestate: "vendor=value1",
          "X-Custom": "same",
        },
        next: { revalidate: 60 },
      });
      const data1 = await res1.json();
      expect(data1.count).toBe(1);

      // Same request but different trace headers โ€” should hit cache
      const res2 = await fetch("https://api.example.com/trace-test", {
        headers: {
          traceparent: "00-trace-id-2-01",
          tracestate: "vendor=value2",
          "X-Custom": "same",
        },
        next: { revalidate: 60 },
      });
      const data2 = await res2.json();
      expect(data2.count).toBe(1); // Cached โ€” trace headers excluded from key
      expect(fetchMock).toHaveBeenCalledTimes(1);
    });

    it("same headers produce same cache entry regardless of order", async () => {
      const res1 = await fetch("https://api.example.com/hdr-order", {
        headers: new Headers([
          ["X-First", "1"],
          ["X-Second", "2"],
        ]),
        next: { revalidate: 60 },
      });
      const data1 = await res1.json();
      expect(data1.count).toBe(1);

      // Headers in different construction order โ€” Headers object normalizes
      const res2 = await fetch("https://api.example.com/hdr-order", {
        headers: new Headers([
          ["X-Second", "2"],
          ["X-First", "1"],
        ]),
        next: { revalidate: 60 },
      });
      const data2 = await res2.json();
      expect(data2.count).toBe(1); // Same cache entry
      expect(fetchMock).toHaveBeenCalledTimes(1);
    });

    it("requests with no headers vs with headers get separate cache entries", async () => {
      const res1 = await fetch("https://api.example.com/hdr-vs-none", {
        next: { revalidate: 60 },
      });
      const data1 = await res1.json();
      expect(data1.count).toBe(1);

      const res2 = await fetch("https://api.example.com/hdr-vs-none", {
        headers: { "X-Extra": "present" },
        next: { revalidate: 60 },
      });
      const data2 = await res2.json();
      expect(data2.count).toBe(2); // Different cache entry
      expect(fetchMock).toHaveBeenCalledTimes(2);
    });
  });

  // โ”€โ”€ Body restoration after cache key generation โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

  describe("body restoration (_ogBody)", () => {
    it("ReadableStream body is correctly passed to real fetch after cache key generation", async () => {
      const stream = new ReadableStream({
        start(controller) {
          controller.enqueue(new TextEncoder().encode("stream-body-content"));
          controller.close();
        },
      });

      await fetch("https://api.example.com/stream-restore", {
        method: "POST",
        body: stream,
        next: { revalidate: 60 },
      });

      // Verify the mock was called and the body was not a spent stream
      expect(fetchMock).toHaveBeenCalledTimes(1);
      const call = fetchMock.mock.calls[0];
      const init = call[1] as RequestInit;
      // The body should be a Uint8Array (reconstructed from the consumed stream)
      expect(init.body).toBeInstanceOf(Uint8Array);
      const decoded = new TextDecoder().decode(init.body as Uint8Array);
      expect(decoded).toBe("stream-body-content");
    });

    it("Blob body is correctly passed to real fetch after cache key generation", async () => {
      const blob = new Blob(["blob-body-content"], { type: "text/plain" });

      await fetch("https://api.example.com/blob-restore", {
        method: "POST",
        body: blob,
        next: { revalidate: 60 },
      });

      expect(fetchMock).toHaveBeenCalledTimes(1);
      const call = fetchMock.mock.calls[0];
      const init = call[1] as RequestInit;
      // The body should be a Blob (reconstructed)
      expect(init.body).toBeInstanceOf(Blob);
      const text = await (init.body as Blob).text();
      expect(text).toBe("blob-body-content");
    });

    it("Uint8Array body is correctly passed to real fetch after cache key generation", async () => {
      const body = new TextEncoder().encode("uint8-body-content");

      await fetch("https://api.example.com/uint8-restore", {
        method: "POST",
        body: body,
        next: { revalidate: 60 },
      });

      expect(fetchMock).toHaveBeenCalledTimes(1);
      const call = fetchMock.mock.calls[0];
      const init = call[1] as RequestInit;
      expect(init.body).toBeInstanceOf(Uint8Array);
      const decoded = new TextDecoder().decode(init.body as Uint8Array);
      expect(decoded).toBe("uint8-body-content");
    });

    it("string body is correctly passed to real fetch after cache key generation", async () => {
      await fetch("https://api.example.com/string-restore", {
        method: "POST",
        body: '{"key":"value"}',
        next: { revalidate: 60 },
      });

      expect(fetchMock).toHaveBeenCalledTimes(1);
      const call = fetchMock.mock.calls[0];
      const init = call[1] as RequestInit;
      expect(init.body).toBe('{"key":"value"}');
    });
  });

  // โ”€โ”€ URLSearchParams body โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

  describe("URLSearchParams body", () => {
    it("different URLSearchParams bodies produce separate cache entries", async () => {
      const paramsA = new URLSearchParams({ q: "alpha" });
      const paramsB = new URLSearchParams({ q: "beta" });

      const res1 = await fetch("https://api.example.com/body-usp", {
        method: "POST",
        body: paramsA,
        next: { revalidate: 60 },
      });
      const data1 = await res1.json();
      expect(data1.count).toBe(1);

      const res2 = await fetch("https://api.example.com/body-usp", {
        method: "POST",
        body: paramsB,
        next: { revalidate: 60 },
      });
      const data2 = await res2.json();
      expect(data2.count).toBe(2); // Different params = different cache
      expect(fetchMock).toHaveBeenCalledTimes(2);
    });

    it("same URLSearchParams bodies hit the same cache entry", async () => {
      const params1 = new URLSearchParams({ q: "same" });
      const params2 = new URLSearchParams({ q: "same" });

      const res1 = await fetch("https://api.example.com/body-usp-same", {
        method: "POST",
        body: params1,
        next: { revalidate: 60 },
      });
      const data1 = await res1.json();
      expect(data1.count).toBe(1);

      const res2 = await fetch("https://api.example.com/body-usp-same", {
        method: "POST",
        body: params2,
        next: { revalidate: 60 },
      });
      const data2 = await res2.json();
      expect(data2.count).toBe(1); // Same params = cached
      expect(fetchMock).toHaveBeenCalledTimes(1);
    });
  });
});