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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
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
const { relative, basename, resolve, join, dirname } = require('path')
// eslint-disable-next-line import/no-extraneous-dependencies
const glob = require('glob')
// eslint-disable-next-line import/no-extraneous-dependencies
const fs = require('fs/promises')
// eslint-disable-next-line import/no-extraneous-dependencies
const resolveFrom = require('resolve-from')
const execa = require('execa')
const process = require('process')
const recast = require('recast')

export async function next__polyfill_nomodule(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('@next/polyfill-nomodule')))
    .target('dist/build/polyfills')
}

export async function next__polyfill_module(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('@next/polyfill-module')))
    .target('dist/build/polyfills')
}

export async function browser_polyfills(task, opts) {
  await task.parallel(
    ['next__polyfill_nomodule', 'next__polyfill_module'],
    opts
  )
}

// eslint-disable-next-line camelcase
export async function copy_regenerator_runtime(task, opts) {
  await task
    .source(join(dirname(require.resolve('regenerator-runtime')), '**/*'))
    .target('src/compiled/regenerator-runtime')
}

// eslint-disable-next-line camelcase
export async function copy_styled_jsx_assets(task, opts) {
  // we copy the styled-jsx types so that we can reference them
  // in the next-env.d.ts file so it doesn't matter if the styled-jsx
  // package is hoisted out of Next.js' node_modules or not
  const styledJsxPath = dirname(require.resolve('styled-jsx/package.json'))
  const typeFiles = glob.sync('*.d.ts', { cwd: styledJsxPath })
  const outputDir = join(__dirname, 'dist/styled-jsx')
  // Separate type files into different folders to avoid conflicts between
  // dev dep `styled-jsx` and `next/dist/styled-jsx` for duplicated declare modules
  const typesDir = join(outputDir, 'types')
  await fs.mkdir(typesDir, { recursive: true })

  for (const file of typeFiles) {
    const content = await fs.readFile(join(styledJsxPath, file), 'utf8')
    await fs.writeFile(join(typesDir, file), content)
  }
}

const externals = {
  // don't bundle caniuse-lite data so users can
  // update it manually
  'caniuse-lite': 'caniuse-lite',
  '/caniuse-lite(/.*)/': 'caniuse-lite$1',

  postcss: 'postcss',
  // Ensure latest version is used
  'postcss-safe-parser': 'next/dist/compiled/postcss-safe-parser',

  // sass-loader
  // (also responsible for these dependencies in package.json)
  'node-sass': 'node-sass',
  sass: 'sass',
  fibers: 'fibers',

  chokidar: 'chokidar',
  'jest-worker': 'jest-worker',

  'terser-webpack-plugin':
    'next/dist/build/webpack/plugins/terser-webpack-plugin/src',

  punycode: 'punycode/',
  // TODO: Add @swc/helpers to externals once @vercel/ncc switch to swc-loader
}
// eslint-disable-next-line camelcase
externals['node-html-parser'] = 'next/dist/compiled/node-html-parser'
export async function ncc_node_html_parser(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('node-html-parser')))
    .ncc({
      packageName: 'node-html-parser',
      externals,
      target: 'es5',
    })
    .target('src/compiled/node-html-parser')
}

// eslint-disable-next-line camelcase
externals['busboy'] = 'next/dist/compiled/busboy'
export async function ncc_busboy(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('busboy')))
    .ncc({
      packageName: 'busboy',
      externals,
      target: 'es5',
    })
    .target('src/compiled/busboy')
}

// eslint-disable-next-line camelcase
externals['@mswjs/interceptors/ClientRequest'] =
  'next/dist/compiled/@mswjs/interceptors/ClientRequest'
export async function ncc_mswjs_interceptors(task, opts) {
  await task
    .source(
      relative(__dirname, require.resolve('@mswjs/interceptors/ClientRequest'))
    )
    .ncc({
      packageName: '@mswjs/interceptors/ClientRequest',
      externals,
      target: 'es5',
    })
    .target('src/compiled/@mswjs/interceptors/ClientRequest')
}

export async function capsize_metrics() {
  const {
    entireMetricsCollection,
    // eslint-disable-next-line import/no-extraneous-dependencies
  } = require('@capsizecss/metrics/entireMetricsCollection')
  const outputPathDist = join(
    __dirname,
    'dist/server/capsize-font-metrics.json'
  )

  await writeJson(outputPathDist, entireMetricsCollection, { spaces: 2 })
}

// eslint-disable-next-line camelcase
externals['@babel/runtime'] = 'next/dist/compiled/@babel/runtime'
export async function copy_babel_runtime(task, opts) {
  const runtimeDir = dirname(require.resolve('@babel/runtime/package.json'))
  const outputDir = join(__dirname, 'src/compiled/@babel/runtime')
  const runtimeFiles = glob.sync('**/*', {
    cwd: runtimeDir,
    ignore: ['node_modules/**/*'],
  })

  for (const file of runtimeFiles) {
    const inputPath = join(runtimeDir, file)
    const outputPath = join(outputDir, file)

    if (!(await fs.stat(inputPath)).isFile()) {
      continue
    }
    let contents = await fs.readFile(inputPath, 'utf8')

    if (inputPath.endsWith('.js')) {
      contents = contents
        .replace(
          'regenerator-runtime',
          'next/dist/compiled/regenerator-runtime'
        )
        .replace('@babel/runtime', 'next/dist/compiled/@babel/runtime')
    }

    if (inputPath.endsWith('package.json')) {
      contents = JSON.stringify({
        ...JSON.parse(contents),
        dependencies: {},
      })
    }

    await fs.mkdir(dirname(outputPath), { recursive: true })
    await fs.writeFile(outputPath, contents)
  }
}

externals['@vercel/og'] = 'next/dist/compiled/@vercel/og'
export async function copy_vercel_og(task, opts) {
  function copy_og_asset(globPattern) {
    return task
      .source(
        join(
          relative(
            __dirname,
            dirname(require.resolve('@vercel/og/package.json'))
          ),
          globPattern
        )
      )
      .target('src/compiled/@vercel/og')
  }

  await copy_og_asset('./dist/*.ttf')
  await copy_og_asset('./dist/*.wasm')
  await copy_og_asset('LICENSE')
  await copy_og_asset('./dist/index.*.js')

  // Types are not bundled, include satori types here
  await task
    .source(
      join(dirname(require.resolve('satori/package.json')), 'dist/index.d.ts')
    )
    // eslint-disable-next-line require-yield
    .run({ every: true }, function* (file) {
      const source = file.data.toString()
      // Ignore yoga-wasm-web types
      file.data = source.replace(
        /import { Yoga } from ['"]yoga-wasm-web['"]/g,
        'type Yoga = any'
      )
    })
    .target('src/compiled/@vercel/og/satori')
  await task
    .source(join(dirname(require.resolve('satori/package.json')), 'LICENSE'))
    .target('src/compiled/@vercel/og/satori')

  await task
    .source(
      join(
        dirname(require.resolve('@vercel/og/package.json')),
        'dist/**/*.d.ts'
      )
    )
    // eslint-disable-next-line require-yield
    .run({ every: true }, function* (file) {
      const source = file.data.toString()
      // Refers to copied satori types
      file.data = source
        .replace(/['"]satori['"]/g, '"next/dist/compiled/@vercel/og/satori"')
        .replace("typeof import('@resvg/resvg-wasm')", 'any')
    })
    .target('src/compiled/@vercel/og')

  await writeJson(
    join(__dirname, 'src/compiled/@vercel/og/package.json'),
    {
      name: '@vercel/og',
      version: require('@vercel/og/package.json').version,
      license: 'MPL-2.0',
      type: 'module',
      main: './index.node.js',
      exports: {
        '.': {
          'edge-light': './index.edge.js',
          import: './index.node.js',
          node: './index.node.js',
          default: './index.node.js',
        },
        './package.json': './package.json',
      },
    },
    { spaces: 2 }
  )
}

externals['anser'] = 'next/dist/compiled/anser'
externals['next/dist/compiled/anser'] = 'next/dist/compiled/anser'
export async function ncc_node_anser(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('anser')))
    .ncc({ packageName: 'anser', externals })
    .target('src/compiled/anser')
}

externals['stacktrace-parser'] = 'next/dist/compiled/stacktrace-parser'
externals['next/dist/compiled/stacktrace-parser'] =
  'next/dist/compiled/stacktrace-parser'
export async function ncc_node_stacktrace_parser(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('stacktrace-parser')))
    .ncc({ packageName: 'stacktrace-parser', externals })
    .target('src/compiled/stacktrace-parser')
}

externals['data-uri-to-buffer'] = 'next/dist/compiled/data-uri-to-buffer'
externals['next/dist/compiled/data-uri-to-buffer'] =
  'next/dist/compiled/data-uri-to-buffer'
export async function ncc_node_data_uri_to_buffer(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('data-uri-to-buffer')))
    .ncc({ packageName: 'data-uri-to-buffer', externals })
    .target('src/compiled/data-uri-to-buffer')
}

externals['css.escape'] = 'next/dist/compiled/css.escape'
externals['next/dist/compiled/css.escape'] = 'next/dist/compiled/css.escape'
export async function ncc_node_cssescape(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('css.escape')))
    .ncc({ packageName: 'css.escape', externals })
    .target('src/compiled/css.escape')
}

externals['shell-quote'] = 'next/dist/compiled/shell-quote'
externals['next/dist/compiled/shell-quote'] = 'next/dist/compiled/shell-quote'
export async function ncc_node_shell_quote(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('shell-quote')))
    .ncc({ packageName: 'shell-quote', externals })
    .target('src/compiled/shell-quote')
}

// eslint-disable-next-line camelcase
externals['acorn'] = 'next/dist/compiled/acorn'
export async function ncc_acorn(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('acorn')))
    .ncc({ packageName: 'acorn', externals })
    .target('src/compiled/acorn')
}

// eslint-disable-next-line camelcase
externals['@edge-runtime/cookies'] = 'next/dist/compiled/@edge-runtime/cookies'

export async function ncc_edge_runtime_cookies() {
  // `@edge-runtime/cookies` is precompiled and pre-bundled
  // so we vendor the package as it is.
  const dest = 'src/compiled/@edge-runtime/cookies'
  const pkg = await readJson(
    require.resolve('@edge-runtime/cookies/package.json')
  )
  await rmrf(dest)
  await fs.mkdir(dest, { recursive: true })

  await writeJson(join(dest, 'package.json'), {
    name: '@edge-runtime/cookies',
    version: pkg.version,
    main: './index.js',
    license: pkg.license,
  })

  await fs.cp(
    require.resolve('@edge-runtime/cookies/dist/index.js'),
    join(dest, 'index.js')
  )
  await fs.cp(
    require.resolve('@edge-runtime/cookies/dist/index.d.ts'),
    join(dest, 'index.d.ts')
  )
}

// eslint-disable-next-line camelcase
externals['@edge-runtime/primitives'] =
  'next/dist/compiled/@edge-runtime/primitives'

export async function ncc_edge_runtime_primitives() {
  // `@edge-runtime/primitives` is precompiled and pre-bundled
  // so we vendor the package as it is.
  const dest = 'src/compiled/@edge-runtime/primitives'
  await fs.mkdir(dest, { recursive: true })
  const primitivesPath = dirname(
    require.resolve('@edge-runtime/primitives/package.json')
  )
  const pkg = await readJson(
    require.resolve('@edge-runtime/primitives/package.json')
  )
  await rmrf(dest)

  for (const file of await fs.readdir(join(primitivesPath, 'types'))) {
    await fs.cp(join(primitivesPath, 'types', file), join(dest, file))
  }

  for (const file of await fs.readdir(join(primitivesPath, 'dist'))) {
    await fs.cp(join(primitivesPath, 'dist', file), join(dest, file))
  }

  await writeJson(join(dest, 'package.json'), {
    name: '@edge-runtime/primitives',
    version: pkg.version,
    main: './index.js',
    license: pkg.license,
  })
  await fs.cp(
    require.resolve('@edge-runtime/primitives'),
    join(dest, 'index.js')
  )
  await fs.cp(
    require.resolve('@edge-runtime/primitives/types/index.d.ts'),
    join(dest, 'index.d.ts')
  )
}

// eslint-disable-next-line camelcase
externals['@edge-runtime/ponyfill'] =
  'next/dist/compiled/@edge-runtime/ponyfill'
export async function ncc_edge_runtime_ponyfill(task, opts) {
  const indexFile = await fs.readFile(
    require.resolve('@edge-runtime/ponyfill/src/index.js'),
    'utf8'
  )
  const dest = 'src/compiled/@edge-runtime/ponyfill'
  await fs.mkdir(dest, { recursive: true })
  await fs.writeFile(
    join(dest, 'index.js'),
    indexFile.replace(
      `require('@edge-runtime/primitives')`,
      `require(${JSON.stringify(externals['@edge-runtime/primitives'])})`
    )
  )
  await fs.cp(
    require.resolve('@edge-runtime/ponyfill/src/index.d.ts'),
    join(dest, 'index.d.ts')
  )

  const pkg = await readJson(
    require.resolve('@edge-runtime/ponyfill/package.json')
  )

  await writeJson(join(dest, 'package.json'), {
    name: '@edge-runtime/ponyfill',
    version: pkg.version,
    main: './index.js',
    types: './index.d.ts',
    license: pkg.license,
  })
}

// eslint-disable-next-line camelcase
externals['edge-runtime'] = 'next/dist/compiled/edge-runtime'
export async function ncc_edge_runtime(task, opts) {
  const vmPath = resolveFrom(
    dirname(require.resolve('edge-runtime')),
    '@edge-runtime/vm/dist/edge-vm'
  )

  const content = await fs.readFile(vmPath, 'utf8')

  // ensure ncc doesn't attempt to bundle dynamic requires
  // so that they work at runtime correctly
  await fs.writeFile(
    vmPath,
    content.replace(
      /require\.resolve\('@edge-runtime\/primitives/g,
      `__non_webpack_require__.resolve('next/dist/compiled/@edge-runtime/primitives`
    )
  )

  await task
    .source(relative(__dirname, require.resolve('edge-runtime')))
    .ncc({ packageName: 'edge-runtime', externals })
    .target('src/compiled/edge-runtime')

  const outputFile = join(__dirname, 'src/compiled/edge-runtime/index.js')

  await fs.writeFile(
    outputFile,
    (await fs.readFile(outputFile, 'utf8')).replace(
      /eval\("require"\)/g,
      'require'
    )
  )
}

// eslint-disable-next-line camelcase
export async function ncc_next_font(task, opts) {
  // `@next/font` can be copied as is, its only dependency is already NCCed
  const destDir = join(__dirname, 'dist/compiled/@next/font')
  const pkgPath = require.resolve('@next/font/package.json')
  const pkg = await readJson(pkgPath)
  const srcDir = dirname(pkgPath)
  await rmrf(destDir)
  await fs.mkdir(destDir, { recursive: true })

  const files = glob.sync('{dist,google,local}/**/*.{js,json,d.ts}', {
    cwd: srcDir,
  })

  for (const file of files) {
    const outputFile = join(destDir, file)
    await fs.mkdir(dirname(outputFile), { recursive: true })
    await fs.cp(join(srcDir, file), outputFile)
  }

  await writeJson(join(destDir, 'package.json'), {
    name: '@next/font',
    license: pkg.license,
    types: pkg.types,
  })
}

// eslint-disable-next-line camelcase
externals['watchpack'] = 'next/dist/compiled/watchpack'
export async function ncc_watchpack(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('watchpack')))
    .ncc({ packageName: 'watchpack', externals })
    .target('src/compiled/watchpack')
}

// eslint-disable-next-line camelcase
externals['jest-worker'] = 'next/dist/compiled/jest-worker'
export async function ncc_jest_worker(task, opts) {
  await rmrf(join(__dirname, 'src/compiled/jest-worker'))
  await fs.mkdir(join(__dirname, 'src/compiled/jest-worker/workers'), {
    recursive: true,
  })

  const workers = ['processChild.js', 'threadChild.js']

  await task
    .source(relative(__dirname, require.resolve('jest-worker')))
    .ncc({ packageName: 'jest-worker', externals })
    .target('src/compiled/jest-worker')

  for (const worker of workers) {
    const content = await fs.readFile(
      join(
        dirname(require.resolve('jest-worker/package.json')),
        'build/workers',
        worker
      ),
      'utf8'
    )
    await fs.writeFile(
      join(
        dirname(require.resolve('jest-worker/package.json')),
        'build/workers',
        worker + '.tmp.js'
      ),
      content.replace(/require\(file\)/g, '__non_webpack_require__(file)')
    )
    await task
      .source(
        relative(
          __dirname,
          join(
            dirname(require.resolve('jest-worker/package.json')),
            'build/workers',
            worker + '.tmp.js'
          )
        )
      )
      .ncc({ externals })
      .target('src/compiled/jest-worker/out')

    await fs.rename(
      join(__dirname, 'src/compiled/jest-worker/out', worker + '.tmp.js'),
      join(__dirname, 'src/compiled/jest-worker', worker)
    )
  }
  await rmrf(join(__dirname, 'src/compiled/jest-worker/workers'))
  await rmrf(join(__dirname, 'src/compiled/jest-worker/out'))
}

// eslint-disable-next-line camelcase
export async function ncc_react_refresh_utils(task, opts) {
  await rmrf(join(__dirname, 'dist/compiled/react-refresh'))
  await fs.cp(
    dirname(require.resolve('react-refresh/package.json')),
    join(__dirname, 'dist/compiled/react-refresh'),
    { recursive: true, force: true }
  )

  const srcDir = join(
    dirname(require.resolve('@next/react-refresh-utils/package.json')),
    'dist'
  )
  const destDir = join(
    __dirname,
    'dist/compiled/@next/react-refresh-utils/dist'
  )
  await rmrf(destDir)
  await fs.mkdir(destDir, { recursive: true })

  const files = glob.sync('**/*.{js,json,map}', { cwd: srcDir })

  for (const file of files) {
    if (file === 'tsconfig.json') continue

    const content = await fs.readFile(join(srcDir, file), 'utf8')
    const outputFile = join(destDir, file)

    await fs.mkdir(dirname(outputFile), { recursive: true })
    await fs.writeFile(
      outputFile,
      content.replace(
        /react-refresh\/runtime/g,
        'next/dist/compiled/react-refresh/runtime'
      )
    )
  }
}

// eslint-disable-next-line camelcase
externals['browserslist'] = 'next/dist/compiled/browserslist'
export async function ncc_browserslist(task, opts) {
  const browserslistModule = require.resolve('browserslist')
  const nodeFile = join(dirname(browserslistModule), 'node.js')

  const content = await fs.readFile(nodeFile, 'utf8')
  // ensure ncc doesn't attempt to bundle dynamic requires
  // so that they work at runtime correctly
  await fs.writeFile(
    nodeFile,
    content.replace(
      /require\(require\.resolve\(/g,
      `__non_webpack_require__(__non_webpack_require__.resolve(`
    )
  )

  await task
    .source(relative(__dirname, require.resolve('browserslist')))
    .ncc({ packageName: 'browserslist', externals })
    // eslint-disable-next-line require-yield
    .run({ every: true }, function* (file) {
      const source = file.data.toString()
      // We replace the module/chunk loading code with our own implementation in Next.js.
      file.data = source.replace(
        /process\.env\.BROWSERSLIST_IGNORE_OLD_DATA/g,
        'true'
      )
    })
    .target('src/compiled/browserslist')

  await fs.writeFile(nodeFile, content)
}

// eslint-disable-next-line camelcase
externals['@napi-rs/triples'] = 'next/dist/compiled/@napi-rs/triples'
export async function ncc_napirs_triples(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('@napi-rs/triples')))
    .ncc({ packageName: '@napi-rs/triples', externals })
    .target('src/compiled/@napi-rs/triples')
}

// eslint-disable-next-line camelcase
externals['p-limit'] = 'next/dist/compiled/p-limit'
export async function ncc_p_limit(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('p-limit')))
    .ncc({ packageName: 'p-limit', externals })
    .target('src/compiled/p-limit')
}

// eslint-disable-next-line camelcase
externals['p-queue'] = 'next/dist/compiled/p-queue'
export async function ncc_p_queue(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('p-queue')))
    .ncc({ packageName: 'p-queue', externals })
    .target('src/compiled/p-queue')
}

// eslint-disable-next-line camelcase
externals['raw-body'] = 'next/dist/compiled/raw-body'
export async function ncc_raw_body(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('raw-body')))
    .ncc({ packageName: 'raw-body', externals })
    .target('src/compiled/raw-body')
}

// eslint-disable-next-line camelcase
externals['image-size'] = 'next/dist/compiled/image-size'
export async function ncc_image_size(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('image-size')))
    .ncc({ packageName: 'image-size', externals })
    .target('src/compiled/image-size')
}

// eslint-disable-next-line camelcase
externals['@hapi/accept'] = 'next/dist/compiled/@hapi/accept'
export async function ncc_hapi_accept(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('@hapi/accept')))
    .ncc({ packageName: '@hapi/accept', externals })
    .target('src/compiled/@hapi/accept')
}

// eslint-disable-next-line camelcase
externals['amphtml-validator'] = 'next/dist/compiled/amphtml-validator'
export async function ncc_amphtml_validator(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('amphtml-validator')))
    .ncc({ packageName: 'amphtml-validator', externals })
    .target('src/compiled/amphtml-validator')

  const validatorRes = await fetch(
    'https://cdn.ampproject.org/v0/validator_wasm.js'
  ).catch((err) => {
    throw new Error('Failed to fetch AMP validator', { cause: err })
  })

  if (!validatorRes.ok) {
    throw new Error(
      `Failed to get the AMP validator, status: ${validatorRes.status}`
    )
  }

  await fs.writeFile(
    join(__dirname, 'src/compiled/amphtml-validator/validator_wasm.js'),
    require('buffer').Buffer.from(await validatorRes.arrayBuffer())
  )
}

// eslint-disable-next-line camelcase
export async function ncc_assert(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('assert/')))
    .ncc({
      packageName: 'assert',
      externals,
      mainFields: ['browser', 'main'],
      target: 'es5',
    })
    .target('src/compiled/assert')
}

// eslint-disable-next-line camelcase
export async function ncc_browser_zlib(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('browserify-zlib/')))
    .ncc({
      packageName: 'browserify-zlib',
      externals,
      mainFields: ['browser', 'main'],
      target: 'es5',
    })
    .target('src/compiled/browserify-zlib')
}

// eslint-disable-next-line camelcase
export async function ncc_buffer(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('buffer/')))
    .ncc({
      packageName: 'buffer',
      externals,
      mainFields: ['browser', 'main'],
      target: 'es5',
    })
    .target('src/compiled/buffer')
}

// eslint-disable-next-line camelcase
export async function copy_constants_browserify(task, opts) {
  await fs.mkdir(join(__dirname, 'src/compiled/constants-browserify'), {
    recursive: true,
  })
  await writeJson(
    join(__dirname, 'src/compiled/constants-browserify/package.json'),
    { name: 'constants-browserify', main: './constants.json' }
  )
  await task
    .source(require.resolve('constants-browserify'))
    .target('src/compiled/constants-browserify')
}

// eslint-disable-next-line camelcase
export async function ncc_crypto_browserify(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('crypto-browserify/')))
    .ncc({
      packageName: 'crypto-browserify',
      externals,
      mainFields: ['browser', 'main'],
      target: 'es5',
    })
    .target('src/compiled/crypto-browserify')
}

// eslint-disable-next-line camelcase
export async function ncc_domain_browser(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('domain-browser/')))
    .ncc({
      packageName: 'domain-browser',
      externals,
      mainFields: ['browser', 'main'],
      target: 'es5',
    })
    .target('src/compiled/domain-browser')
}

// eslint-disable-next-line camelcase
export async function ncc_events(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('events/')))
    .ncc({
      packageName: 'events',
      externals,
      mainFields: ['browser', 'main'],
      target: 'es5',
    })
    .target('src/compiled/events')
}

// eslint-disable-next-line camelcase
export async function ncc_stream_browserify(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('stream-browserify/')))
    .ncc({
      packageName: 'stream-browserify',
      mainFields: ['browser', 'main'],
      target: 'es5',
    })
    .target('src/compiled/stream-browserify')

  // while ncc'ing readable-stream the browser mapping does not replace the
  // require('stream') with require('events').EventEmitter correctly so we
  // patch this manually as leaving require('stream') causes a circular
  // reference breaking the browser polyfill
  const outputFile = join(__dirname, 'src/compiled/stream-browserify/index.js')

  await fs.writeFile(
    outputFile,
    (await fs.readFile(outputFile, 'utf8')).replace(
      `require("stream")`,
      `require("events").EventEmitter`
    )
  )
}

// eslint-disable-next-line camelcase
export async function ncc_stream_http(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('stream-http/')))
    .ncc({
      packageName: 'stream-http',
      externals,
      mainFields: ['browser', 'main'],
      target: 'es5',
    })
    .target('src/compiled/stream-http')
}

// eslint-disable-next-line camelcase
export async function ncc_https_browserify(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('https-browserify/')))
    .ncc({
      packageName: 'https-browserify',
      externals,
      mainFields: ['browser', 'main'],
      target: 'es5',
    })
    .target('src/compiled/https-browserify')
}

// eslint-disable-next-line camelcase
export async function ncc_os_browserify(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('os-browserify/browser')))
    .ncc({
      packageName: 'os-browserify',
      externals,
      mainFields: ['browser', 'main'],
      target: 'es5',
    })
    .target('src/compiled/os-browserify')
}

// eslint-disable-next-line camelcase
export async function ncc_path_browserify(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('path-browserify/')))
    .ncc({
      packageName: 'path-browserify',
      externals,
      mainFields: ['browser', 'main'],
      target: 'es5',
    })
    .target('src/compiled/path-browserify')

  const filePath = join(__dirname, 'src/compiled/path-browserify/index.js')
  const content = await fs.readFile(filePath, 'utf8')

  // Remove process usage from path-browserify polyfill for edge-runtime
  await fs.writeFile(filePath, content.replace(/process\.cwd\(\)/g, '""'))
}

// eslint-disable-next-line camelcase
export async function ncc_process(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('process/browser')))
    .ncc({
      packageName: 'process',
      externals,
      mainFields: ['browser', 'main'],
      target: 'es5',
    })
    .target('src/compiled/process')
}

// eslint-disable-next-line camelcase
export async function ncc_querystring_es3(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('querystring-es3/')))
    .ncc({
      packageName: 'querystring-es3',
      externals,
      mainFields: ['browser', 'main'],
      target: 'es5',
    })
    .target('src/compiled/querystring-es3')
}

// eslint-disable-next-line camelcase
export async function ncc_string_decoder(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('string_decoder/')))
    .ncc({
      packageName: 'string_decoder',
      externals,
      mainFields: ['browser', 'main'],
      target: 'es5',
    })
    .target('src/compiled/string_decoder')
}

// eslint-disable-next-line camelcase
export async function ncc_util(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('util/')))
    .ncc({
      packageName: 'util',
      externals,
      mainFields: ['browser', 'main'],
      target: 'es5',
    })
    .target('src/compiled/util')
}

// eslint-disable-next-line camelcase
export async function ncc_punycode(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('punycode/')))
    .ncc({
      packageName: 'punycode',
      externals,
      mainFields: ['browser', 'main'],
      target: 'es5',
    })
    .target('src/compiled/punycode')
}

// eslint-disable-next-line camelcase
export async function ncc_set_immediate(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('setimmediate/')))
    .ncc({
      packageName: 'setimmediate',
      externals,
      mainFields: ['browser', 'main'],
      target: 'es5',
    })
    .target('src/compiled/setimmediate')
}

// eslint-disable-next-line camelcase
export async function ncc_timers_browserify(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('timers-browserify/')))
    .ncc({
      packageName: 'timers-browserify',
      externals: {
        ...externals,
        setimmediate: 'next/dist/compiled/setimmediate',
      },
      mainFields: ['browser', 'main'],
      target: 'es5',
    })
    .target('src/compiled/timers-browserify')
}

// eslint-disable-next-line camelcase
export async function ncc_tty_browserify(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('tty-browserify/')))
    .ncc({
      packageName: 'tty-browserify',
      externals,
      mainFields: ['browser', 'main'],
      target: 'es5',
    })
    .target('src/compiled/tty-browserify')
}

// eslint-disable-next-line camelcase
export async function ncc_vm_browserify(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('vm-browserify/')))
    .ncc({
      packageName: 'vm-browserify',
      externals,
      mainFields: ['browser', 'main'],
      target: 'es5',
    })
    .target('src/compiled/vm-browserify')
}

// eslint-disable-next-line camelcase
externals['@ampproject/toolbox-optimizer'] =
  'next/dist/compiled/@ampproject/toolbox-optimizer'
export async function ncc_amp_optimizer(task, opts) {
  await task
    .source(
      relative(__dirname, require.resolve('@ampproject/toolbox-optimizer'))
    )
    .ncc({
      externals,
      packageName: '@ampproject/toolbox-optimizer',
    })
    .target('src/compiled/@ampproject/toolbox-optimizer')
}
// eslint-disable-next-line camelcase
externals['async-retry'] = 'next/dist/compiled/async-retry'
export async function ncc_async_retry(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('async-retry')))
    .ncc({
      packageName: 'async-retry',
      externals,
    })
    .target('src/compiled/async-retry')
}
// eslint-disable-next-line camelcase
externals['async-sema'] = 'next/dist/compiled/async-sema'
export async function ncc_async_sema(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('async-sema')))
    .ncc({ packageName: 'async-sema', externals })
    .target('src/compiled/async-sema')
}

externals['postcss-plugin-stub-for-cssnano-simple'] =
  'next/dist/compiled/postcss-plugin-stub-for-cssnano-simple'
// eslint-disable-next-line camelcase
export async function ncc_postcss_plugin_stub_for_cssnano_simple(task, opts) {
  await task
    .source('src/bundles/postcss-plugin-stub/index.js')
    .ncc({
      externals,
    })
    .target('src/compiled/postcss-plugin-stub-for-cssnano-simple')
}

const babelCorePackages = {
  'code-frame': 'next/dist/compiled/babel/code-frame',
  '@babel/generator': 'next/dist/compiled/babel/generator',
  '@babel/traverse': 'next/dist/compiled/babel/traverse',
  '@babel/types': 'next/dist/compiled/babel/types',
  '@babel/core': 'next/dist/compiled/babel/core',
  '@babel/parser': 'next/dist/compiled/babel/parser',
  '@babel/core/lib/config': 'next/dist/compiled/babel/core-lib-config',
  '@babel/core/lib/transformation/normalize-file':
    'next/dist/compiled/babel/core-lib-normalize-config',
  '@babel/core/lib/transformation/normalize-opts':
    'next/dist/compiled/babel/core-lib-normalize-opts',
  '@babel/core/lib/transformation/block-hoist-plugin':
    'next/dist/compiled/babel/core-lib-block-hoisting-plugin',
  '@babel/core/lib/transformation/plugin-pass':
    'next/dist/compiled/babel/core-lib-plugin-pass',
}
externals['next/dist/compiled/babel/code-frame'] =
  'next/dist/compiled/babel/code-frame'

Object.assign(externals, babelCorePackages)

// eslint-disable-next-line camelcase
export async function ncc_babel_bundle(task, opts) {
  const bundleExternals = {
    ...externals,
    'next/dist/compiled/babel-packages': 'next/dist/compiled/babel-packages',
  }
  for (const pkg of Object.keys(babelCorePackages)) {
    delete bundleExternals[pkg]
  }
  await task
    .source('src/bundles/babel/bundle.js')
    .ncc({
      packageName: '@babel/core',
      bundleName: 'babel',
      externals: bundleExternals,
    })
    .target('src/compiled/babel')
}

// eslint-disable-next-line camelcase
export async function ncc_babel_bundle_packages(task, opts) {
  const eslintParseFile = join(
    dirname(require.resolve('@babel/eslint-parser')),
    './parse.cjs'
  )
  const content = await fs.readFile(eslintParseFile, 'utf-8')
  // Let parser.cjs require @babel/parser directly
  const replacedContent = content
    .replace(
      `const babelParser = require((`,
      `function noop(){};\nconst babelParser = require('@babel/parser');noop((`
    )
    .replace(/require.resolve/g, 'noop')
  await fs.writeFile(eslintParseFile, replacedContent)

  await task
    .source('src/bundles/babel/packages-bundle.js')
    .ncc({
      externals: externals,
    })
    .target(`src/compiled/babel-packages`)

  await writeJson(join(__dirname, 'src/compiled/babel-packages/package.json'), {
    name: 'babel-packages',
    main: './packages-bundle.js',
  })

  await task.source('src/bundles/babel/packages/*').target('src/compiled/babel')
}

externals['cssnano-simple'] = 'next/dist/compiled/cssnano-simple'
// eslint-disable-next-line camelcase
export async function ncc_cssnano_simple_bundle(task, opts) {
  const bundleExternals = {
    ...externals,
    'postcss-svgo': 'next/dist/compiled/postcss-plugin-stub-for-cssnano-simple',
  }

  await task
    .source('src/bundles/cssnano-simple/index.js')
    .ncc({
      externals: bundleExternals,
    })
    .target('src/compiled/cssnano-simple')
}

// eslint-disable-next-line camelcase
externals['bytes'] = 'next/dist/compiled/bytes'
export async function ncc_bytes(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('bytes')))
    .ncc({ packageName: 'bytes', externals })
    .target('src/compiled/bytes')
}
// eslint-disable-next-line camelcase
externals['ci-info'] = 'next/dist/compiled/ci-info'
export async function ncc_ci_info(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('ci-info')))
    .ncc({ packageName: 'ci-info', externals })
    .target('src/compiled/ci-info')
}
// eslint-disable-next-line camelcase
externals['cli-select'] = 'next/dist/compiled/cli-select'
export async function ncc_cli_select(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('cli-select')))
    .ncc({ packageName: 'cli-select', externals })
    .target('src/compiled/cli-select')
}
externals['commander'] = 'next/dist/compiled/commander'
export async function ncc_commander(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('commander')))
    .ncc({ packageName: 'commander', externals })
    .target('src/compiled/commander')
}
externals['comment-json'] = 'next/dist/compiled/comment-json'
export async function ncc_comment_json(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('comment-json')))
    .ncc({ packageName: 'comment-json', externals })
    .target('src/compiled/comment-json')
}
// eslint-disable-next-line camelcase
externals['compression'] = 'next/dist/compiled/compression'
export async function ncc_compression(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('compression')))
    .ncc({ packageName: 'compression', externals })
    .target('src/compiled/compression')
}
// eslint-disable-next-line camelcase
externals['conf'] = 'next/dist/compiled/conf'
export async function ncc_conf(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('conf')))
    .ncc({ packageName: 'conf', externals })
    .target('src/compiled/conf')
}
// eslint-disable-next-line camelcase
externals['content-disposition'] = 'next/dist/compiled/content-disposition'
export async function ncc_content_disposition(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('content-disposition')))
    .ncc({ packageName: 'content-disposition', externals })
    .target('src/compiled/content-disposition')
}
// eslint-disable-next-line camelcase
externals['content-type'] = 'next/dist/compiled/content-type'
export async function ncc_content_type(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('content-type')))
    .ncc({ packageName: 'content-type', externals })
    .target('src/compiled/content-type')
}
// eslint-disable-next-line camelcase
externals['cookie'] = 'next/dist/compiled/cookie'
export async function ncc_cookie(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('cookie')))
    .ncc({ packageName: 'cookie', externals })
    .target('src/compiled/cookie')
}
// eslint-disable-next-line camelcase
externals['cross-spawn'] = 'next/dist/compiled/cross-spawn'
export async function ncc_cross_spawn(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('cross-spawn')))
    .ncc({ packageName: 'cross-spawn', externals })
    .target('src/compiled/cross-spawn')
}
// eslint-disable-next-line camelcase
externals['debug'] = 'next/dist/compiled/debug'
export async function ncc_debug(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('debug')))
    .ncc({ packageName: 'debug', externals })
    .target('src/compiled/debug')
}
// eslint-disable-next-line camelcase
externals['devalue'] = 'next/dist/compiled/devalue'
export async function ncc_devalue(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('devalue')))
    .ncc({ packageName: 'devalue', externals })
    .target('src/compiled/devalue')
}

// eslint-disable-next-line camelcase
externals['find-up'] = 'next/dist/compiled/find-up'
export async function ncc_find_up(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('find-up')))
    .ncc({ packageName: 'find-up', externals })
    .target('src/compiled/find-up')
}
// eslint-disable-next-line camelcase
externals['fresh'] = 'next/dist/compiled/fresh'
export async function ncc_fresh(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('fresh')))
    .ncc({ packageName: 'fresh', externals })
    .target('src/compiled/fresh')
}
// eslint-disable-next-line camelcase
externals['glob'] = 'next/dist/compiled/glob'
export async function ncc_glob(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('glob')))
    .ncc({ packageName: 'glob', externals })
    .target('src/compiled/glob')
}
// eslint-disable-next-line camelcase
externals['gzip-size'] = 'next/dist/compiled/gzip-size'
export async function ncc_gzip_size(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('gzip-size')))
    .ncc({ packageName: 'gzip-size', externals })
    .target('src/compiled/gzip-size')
}
// eslint-disable-next-line camelcase
externals['http-proxy'] = 'next/dist/compiled/http-proxy'
export async function ncc_http_proxy(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('http-proxy')))
    .ncc({ packageName: 'http-proxy', externals })
    .target('src/compiled/http-proxy')
}
// eslint-disable-next-line camelcase
externals['ignore-loader'] = 'next/dist/compiled/ignore-loader'
export async function ncc_ignore_loader(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('ignore-loader')))
    .ncc({ packageName: 'ignore-loader', externals })
    .target('src/compiled/ignore-loader')
}
// eslint-disable-next-line camelcase
externals['is-animated'] = 'next/dist/compiled/is-animated'
export async function ncc_is_animated(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('is-animated')))
    .ncc({ packageName: 'is-animated', externals })
    .target('src/compiled/is-animated')
}
// eslint-disable-next-line camelcase
externals['is-docker'] = 'next/dist/compiled/is-docker'
export async function ncc_is_docker(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('is-docker')))
    .ncc({ packageName: 'is-docker', externals })
    .target('src/compiled/is-docker')
}
// eslint-disable-next-line camelcase
externals['is-wsl'] = 'next/dist/compiled/is-wsl'
export async function ncc_is_wsl(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('is-wsl')))
    .ncc({ packageName: 'is-wsl', externals })
    .target('src/compiled/is-wsl')
}
// eslint-disable-next-line camelcase
externals['json5'] = 'next/dist/compiled/json5'
export async function ncc_json5(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('json5')))
    .ncc({ packageName: 'json5', externals })
    .target('src/compiled/json5')
}
// eslint-disable-next-line camelcase
externals['jsonwebtoken'] = 'next/dist/compiled/jsonwebtoken'
export async function ncc_jsonwebtoken(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('jsonwebtoken')))
    .ncc({
      packageName: 'jsonwebtoken',
      externals: {
        ...externals,
        semver: 'next/dist/lib/semver-noop',
      },
    })
    .target('src/compiled/jsonwebtoken')
}
// eslint-disable-next-line camelcase
externals['loader-runner'] = 'next/dist/compiled/loader-runner'
export async function ncc_loader_runner(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('loader-runner')))
    .ncc({ packageName: 'loader-runner', externals })
    .target('src/compiled/loader-runner')
}
// eslint-disable-next-line camelcase
externals['loader-utils'] = 'error loader-utils version not specified'
externals['loader-utils2'] = 'next/dist/compiled/loader-utils2'
export async function ncc_loader_utils2(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('loader-utils2')))
    .ncc({ packageName: 'loader-utils2', externals })
    .target('src/compiled/loader-utils2')
}
// eslint-disable-next-line camelcase
externals['loader-utils3'] = 'next/dist/compiled/loader-utils3'
export async function ncc_loader_utils3(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('loader-utils3')))
    .ncc({ packageName: 'loader-utils3', externals })
    .target('src/compiled/loader-utils3')
}
// eslint-disable-next-line camelcase
externals['lodash.curry'] = 'next/dist/compiled/lodash.curry'
export async function ncc_lodash_curry(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('lodash.curry')))
    .ncc({ packageName: 'lodash.curry', externals })
    .target('src/compiled/lodash.curry')
}
// eslint-disable-next-line camelcase
externals['lru-cache'] = 'next/dist/compiled/lru-cache'
export async function ncc_lru_cache(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('lru-cache')))
    .ncc({ packageName: 'lru-cache', externals })
    .target('src/compiled/lru-cache')
}
// eslint-disable-next-line camelcase
externals['nanoid'] = 'next/dist/compiled/nanoid'
export async function ncc_nanoid(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('nanoid')))
    .ncc({ packageName: 'nanoid', externals })
    .target('src/compiled/nanoid')
}
// eslint-disable-next-line camelcase
externals['native-url'] = 'next/dist/compiled/native-url'
export async function ncc_native_url(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('native-url')))
    .ncc({
      packageName: 'native-url',
      externals: {
        ...externals,
        querystring: 'next/dist/compiled/querystring-es3',
      },
      target: 'es5',
    })
    .target('src/compiled/native-url')
}
// eslint-disable-next-line camelcase
externals['neo-async'] = 'next/dist/compiled/neo-async'
export async function ncc_neo_async(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('neo-async')))
    .ncc({ packageName: 'neo-async', externals })
    .target('src/compiled/neo-async')
}

// eslint-disable-next-line camelcase
externals['ora'] = 'next/dist/compiled/ora'
export async function ncc_ora(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('ora')))
    .ncc({ packageName: 'ora', externals })
    .target('src/compiled/ora')
}
// eslint-disable-next-line camelcase
externals['postcss-flexbugs-fixes'] =
  'next/dist/compiled/postcss-flexbugs-fixes'
export async function ncc_postcss_flexbugs_fixes(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('postcss-flexbugs-fixes')))
    .ncc({ packageName: 'postcss-flexbugs-fixes', externals })
    .target('src/compiled/postcss-flexbugs-fixes')
}
// eslint-disable-next-line camelcase
export async function ncc_postcss_safe_parser(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('postcss-safe-parser')))
    .ncc({ packageName: 'postcss-safe-parser', externals })
    .target('src/compiled/postcss-safe-parser')
}
// eslint-disable-next-line camelcase
externals['postcss-preset-env'] = 'next/dist/compiled/postcss-preset-env'
export async function ncc_postcss_preset_env(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('postcss-preset-env')))
    .ncc({ packageName: 'postcss-preset-env', externals })
    .target('src/compiled/postcss-preset-env')
}
// eslint-disable-next-line camelcase
externals['postcss-scss'] = 'next/dist/compiled/postcss-scss'
export async function ncc_postcss_scss(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('postcss-scss')))
    .ncc({
      packageName: 'postcss-scss',
      externals: {
        'postcss/lib/parser': 'postcss/lib/parser',
        ...externals,
      },
    })
    .target('src/compiled/postcss-scss')
}
// eslint-disable-next-line camelcase
externals['postcss-modules-extract-imports'] =
  'next/dist/compiled/postcss-modules-extract-imports'
export async function ncc_postcss_modules_extract_imports(task, opts) {
  await task
    .source(
      relative(__dirname, require.resolve('postcss-modules-extract-imports'))
    )
    .ncc({
      packageName: 'postcss-modules-extract-imports',
      externals: {
        'postcss/lib/parser': 'postcss/lib/parser',
        ...externals,
      },
    })
    .target('src/compiled/postcss-modules-extract-imports')
}
// eslint-disable-next-line camelcase
externals['postcss-modules-local-by-default'] =
  'next/dist/compiled/postcss-modules-local-by-default'
export async function ncc_postcss_modules_local_by_default(task, opts) {
  await task
    .source(
      relative(__dirname, require.resolve('postcss-modules-local-by-default'))
    )
    .ncc({
      packageName: 'postcss-modules-local-by-default',
      externals: {
        'postcss/lib/parser': 'postcss/lib/parser',
        ...externals,
      },
    })
    .target('src/compiled/postcss-modules-local-by-default')
}
// eslint-disable-next-line camelcase
externals['postcss-modules-scope'] = 'next/dist/compiled/postcss-modules-scope'
export async function ncc_postcss_modules_scope(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('postcss-modules-scope')))
    .ncc({
      packageName: 'postcss-modules-scope',
      externals: {
        'postcss/lib/parser': 'postcss/lib/parser',
        ...externals,
      },
    })
    .target('src/compiled/postcss-modules-scope')
}
// eslint-disable-next-line camelcase
externals['postcss-modules-values'] =
  'next/dist/compiled/postcss-modules-values'
export async function ncc_postcss_modules_values(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('postcss-modules-values')))
    .ncc({
      packageName: 'postcss-modules-values',
      externals: {
        'postcss/lib/parser': 'postcss/lib/parser',
        ...externals,
      },
    })
    .target('src/compiled/postcss-modules-values')
}
// eslint-disable-next-line camelcase
externals['postcss-value-parser'] = 'next/dist/compiled/postcss-value-parser'
export async function ncc_postcss_value_parser(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('postcss-value-parser')))
    .ncc({
      packageName: 'postcss-value-parser',
      externals: {
        'postcss/lib/parser': 'postcss/lib/parser',
        ...externals,
      },
    })
    .target('src/compiled/postcss-value-parser')
}
// eslint-disable-next-line camelcase
externals['icss-utils'] = 'next/dist/compiled/icss-utils'
export async function ncc_icss_utils(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('icss-utils')))
    .ncc({
      packageName: 'icss-utils',
      externals: {
        'postcss/lib/parser': 'postcss/lib/parser',
        ...externals,
      },
    })
    .target('src/compiled/icss-utils')
}

externals['scheduler'] = 'next/dist/compiled/scheduler-experimental'
externals['scheduler'] = 'next/dist/compiled/scheduler'
export async function copy_vendor_react(task_) {
  function* copy_vendor_react_impl(task, opts) {
    const channel = opts.experimental ? `experimental-builtin` : `builtin`
    const packageSuffix = opts.experimental ? `-experimental` : ``

    // Override the `react`, `react-dom` and `scheduler`'s package names to avoid
    // "The name `react` was looked up in the Haste module map" warnings.
    // TODO-APP: remove unused fields from package.json and unused files
    function overridePackageName(source) {
      const json = JSON.parse(source)
      json.name = json.name + '-' + channel
      return JSON.stringify(
        {
          name: json.name,
          main: json.main,
          exports: json.exports,
          dependencies: json.dependencies,
          peerDependencies: json.peerDependencies,
          browser: json.browser,
        },
        null,
        2
      )
    }

    function aliasVendoredReactPackages(source) {
      return source
        .replace(
          /require\(["']react["']\)/g,
          `require("next/dist/compiled/react${packageSuffix}")`
        )
        .replace(
          /require\(["']react-dom["']\)/g,
          `require("next/dist/compiled/react-dom${packageSuffix}")`
        )
        .replace(
          /require\(["']scheduler["']\)/g,
          `require("next/dist/compiled/scheduler${packageSuffix}")`
        )
    }

    const schedulerDir = dirname(
      relative(__dirname, require.resolve(`scheduler-${channel}/package.json`))
    )
    yield task
      .source(join(schedulerDir, '*.{json,js}'))
      // eslint-disable-next-line require-yield
      .run({ every: true }, function* (file) {
        if (file.base === 'package.json') {
          file.data = overridePackageName(file.data.toString())
        }
      })
      .target(`src/compiled/scheduler${packageSuffix}`)
    yield task
      .source(join(schedulerDir, 'cjs/**/*.{js,map}'))
      .target(`src/compiled/scheduler${packageSuffix}/cjs`)
    yield task
      .source(join(schedulerDir, 'LICENSE'))
      .target(`src/compiled/scheduler${packageSuffix}`)

    const reactDir = dirname(
      relative(__dirname, require.resolve(`react-${channel}/package.json`))
    )
    const reactDomDir = dirname(
      relative(__dirname, require.resolve(`react-dom-${channel}/package.json`))
    )

    yield task
      .source(join(reactDir, '*.{json,js}'))
      // eslint-disable-next-line require-yield
      .run({ every: true }, function* (file) {
        if (file.base === 'package.json') {
          file.data = overridePackageName(file.data.toString())
        }
      })
      .target(`src/compiled/react${packageSuffix}`)
    yield task
      .source(join(reactDir, 'LICENSE'))
      .target(`src/compiled/react${packageSuffix}`)
    yield task
      .source(join(reactDir, 'cjs/**/*.{js,map}'))
      // eslint-disable-next-line require-yield
      .run({ every: true }, function* (file) {
        const source = file.data.toString()
        // We replace the module/chunk loading code with our own implementation in Next.js.
        file.data = aliasVendoredReactPackages(source)
      })
      .target(`src/compiled/react${packageSuffix}/cjs`)

    yield task
      .source(join(reactDomDir, '*.{json,js}'))
      // eslint-disable-next-line require-yield
      .run({ every: true }, function* (file) {
        if (file.base === 'package.json') {
          file.data = overridePackageName(file.data.toString())
        }
      })
      .target(`src/compiled/react-dom${packageSuffix}`)
    yield task
      .source(join(reactDomDir, 'LICENSE'))
      .target(`src/compiled/react-dom${packageSuffix}`)
    yield task
      .source(join(reactDomDir, 'cjs/**/*.{js,map}'))
      // eslint-disable-next-line require-yield
      .run({ every: true }, function* (file) {
        const source = file.data.toString()
        // We replace the module/chunk loading code with our own implementation in Next.js.
        let newSource = aliasVendoredReactPackages(source)

        file.data = newSource

        // Note that we don't replace `react-dom` with `next/dist/compiled/react-dom`
        // as it mighe be aliased to the server rendering stub.
      })
      .target(`src/compiled/react-dom${packageSuffix}/cjs`)

    function replaceIdentifiersInAst(
      /** @type {recast.types.namedTypes.File} */ ast,
      /** @type {Map<string, ExpressionKind>} */ replacements
    ) {
      recast.types.namedTypes.File.assert(ast)
      recast.visit(ast, {
        visitIdentifier(path) {
          const replacement = replacements.get(path.node.name)
          if (replacement !== undefined) {
            path.replace(replacement)
          }
          this.traverse(path)
        },
      })
    }

    function parseFile(
      /** @type {string} */ code,
      /** @type {recast.Options} */ opts
    ) {
      /** @type {recast.types.namedTypes.File} */
      const file = recast.parse(code, {
        parser: {
          parse(source, options) {
            return require('recast/parsers/acorn').parse(source, {
              ...options,
              // allow `import()` in `react-server-dom-{webpack,turbopack}-client.node.unbundled.development.js`
              ecmaVersion: 'latest',
              sourceType: 'script',
            })
          },
        },
        ...opts,
      })
      return file
    }

    /** @typedef {ReturnType<typeof parseExpression>} ExpressionKind */

    function parseExpression(/** @type {string} */ exprCode) {
      /** @type {recast.types.namedTypes.File} */
      const ast = recast.parse(`(${exprCode});`)
      const statement =
        /** @type {recast.types.namedTypes.ExpressionStatement} */ (
          ast.program.body[0]
        )
      return statement.expression
    }

    // Remove unused files
    const reactDomCompiledDir = join(
      __dirname,
      `src/compiled/react-dom${packageSuffix}`
    )
    const itemsToRemove = [
      'static.js',
      'static.browser.js',
      'unstable_testing.js',
      'test-utils.js',
      'server.bun.js',
      'cjs/react-dom-server.bun.development.js',
      'cjs/react-dom-server.bun.production.min.js',
      'cjs/react-dom-test-utils.development.js',
      'cjs/react-dom-test-utils.production.min.js',
      'unstable_server-external-runtime.js',
    ]
    for (const item of itemsToRemove) {
      yield rmrf(join(reactDomCompiledDir, item))
    }

    // react-server-dom-webpack
    // Currently, this `next` and `experimental` channels are always in sync so
    // we can use the same version for both.
    const reactServerDomWebpackDir = dirname(
      relative(
        __dirname,
        require.resolve(`react-server-dom-webpack${packageSuffix}/package.json`)
      )
    )
    yield task
      .source(join(reactServerDomWebpackDir, 'LICENSE'))
      .target(`src/compiled/react-server-dom-webpack${packageSuffix}`)
    yield task
      .source(
        join(reactServerDomWebpackDir, '{package.json,*.js,cjs/**/*.{js,map}}')
      )
      // eslint-disable-next-line require-yield
      .run({ every: true }, function* (file) {
        // We replace the module/chunk loading code with our own implementation in Next.js.
        // NOTE: We only replace module/chunk loading for server builds because the server
        // bundles have unique constraints like a runtime bundle. For browser builds this
        // package will be bundled alongside user code and we don't need to introduce the extra
        // indirection
        if (
          (file.base.startsWith('react-server-dom-webpack-client') &&
            !file.base.startsWith('react-server-dom-webpack-client.browser')) ||
          (file.base.startsWith('react-server-dom-webpack-server') &&
            !file.base.startsWith('react-server-dom-webpack-server.browser'))
        ) {
          const filepath = file.dir + '/' + file.base
          const source = file.data.toString()
          const ast = parseFile(source, { sourceFileName: filepath })
          replaceIdentifiersInAst(
            ast,
            new Map([
              [
                '__webpack_require__',
                parseExpression('globalThis.__next_require__'),
              ],
            ])
          )

          file.data = recast.print(ast).code
        } else if (file.base === 'package.json') {
          file.data = overridePackageName(file.data)
        }
      })
      .target(`src/compiled/react-server-dom-webpack${packageSuffix}`)

    // react-server-dom-turbopack
    // Currently, this `next` and `experimental` channels are always in sync so
    // we can use the same version for both.
    const reactServerDomTurbopackDir = dirname(
      relative(
        __dirname,
        require.resolve(
          `react-server-dom-turbopack${packageSuffix}/package.json`
        )
      )
    )
    yield task
      .source(join(reactServerDomTurbopackDir, 'LICENSE'))
      .target(`src/compiled/react-server-dom-turbopack${packageSuffix}`)
    yield task
      .source(
        join(
          reactServerDomTurbopackDir,
          '{package.json,*.js,cjs/**/*.{js,map}}'
        )
      )
      // eslint-disable-next-line require-yield
      .run({ every: true }, function* (file) {
        // We replace the module loading code with our own implementation in Next.js.
        // NOTE: We only replace module loading for server builds because the server
        // bundles have unique constraints like a runtime bundle. For browser builds this
        // package will be bundled alongside user code and we don't need to introduce the extra
        // indirection

        if (
          (file.base.startsWith('react-server-dom-turbopack-client') ||
            file.base.startsWith('react-server-dom-turbopack-server')) &&
          !file.base.includes('.browser.')
        ) {
          const source = file.data.toString()
          const filepath = file.dir + '/' + file.base
          const ast = parseFile(source, { sourceFileName: filepath })

          replaceIdentifiersInAst(
            ast,
            new Map([
              [
                '__turbopack_load_by_url__',
                parseExpression('globalThis.__next_chunk_load__'),
              ],
              [
                '__turbopack_require__',
                parseExpression('globalThis.__next_require__'),
              ],
            ])
          )

          file.data = recast.print(ast).code
        } else if (file.base === 'package.json') {
          file.data = overridePackageName(file.data)
        }
      })
      .target(`src/compiled/react-server-dom-turbopack${packageSuffix}`)
  }

  // As taskr transpiles async functions into generators, to reuse the same logic
  // we need to directly write this iteration logic here.
  for (const res of copy_vendor_react_impl(task_, { experimental: false })) {
    await res
  }
  for (const res of copy_vendor_react_impl(task_, { experimental: true })) {
    await res
  }

  // TODO: Support react-is experimental channel. We currently assume Canary and Experimental are equal.
  await task_
    .source(
      join(dirname(require.resolve('react-is-builtin/package.json')), '**/*')
    )
    .target('src/compiled/react-is')
}

// eslint-disable-next-line camelcase
export async function ncc_rsc_poison_packages(task, opts) {
  await task
    .source(join(dirname(require.resolve('server-only')), '*'))
    .target('src/compiled/server-only')
  await task
    .source(join(dirname(require.resolve('client-only')), '*'))
    .target('src/compiled/client-only')
}

externals['sass-loader'] = 'next/dist/compiled/sass-loader'
// eslint-disable-next-line camelcase
export async function ncc_sass_loader(task, opts) {
  const sassLoaderPath = require.resolve('sass-loader')
  const utilsPath = join(dirname(sassLoaderPath), 'utils.js')
  const originalContent = await fs.readFile(utilsPath, 'utf8')

  await fs.writeFile(
    utilsPath,
    originalContent.replace(
      /require\.resolve\(["'](sass|node-sass)["']\)/g,
      'eval("require").resolve("$1")'
    )
  )

  await task
    .source(relative(__dirname, sassLoaderPath))
    .ncc({
      packageName: 'sass-loader',
      externals: {
        ...externals,
        'schema-utils': externals['schema-utils3'],
        'loader-utils': externals['loader-utils2'],
      },
      target: 'es5',
    })
    .target('src/compiled/sass-loader')
}
// eslint-disable-next-line camelcase
externals['schema-utils'] = 'MISSING_VERSION schema-utils version not specified'
externals['schema-utils2'] = 'next/dist/compiled/schema-utils2'
export async function ncc_schema_utils2(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('schema-utils2')))
    .ncc({
      packageName: 'schema-utils',
      bundleName: 'schema-utils2',
      externals,
    })
    .target('src/compiled/schema-utils2')
}
// eslint-disable-next-line camelcase
externals['schema-utils3'] = 'next/dist/compiled/schema-utils3'
export async function ncc_schema_utils3(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('schema-utils3')))
    .ncc({
      packageName: 'schema-utils',
      bundleName: 'schema-utils3',
      externals,
    })
    .target('src/compiled/schema-utils3')
}
externals['semver'] = 'next/dist/compiled/semver'
export async function ncc_semver(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('semver')))
    .ncc({ packageName: 'semver', externals })
    .target('src/compiled/semver')
}
// eslint-disable-next-line camelcase
externals['send'] = 'next/dist/compiled/send'
export async function ncc_send(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('send')))
    .ncc({ packageName: 'send', externals })
    .target('src/compiled/send')
}
// eslint-disable-next-line camelcase
// NB: Used by other dependencies, but Vercel version is a duplicate
// version so can be inlined anyway (although may change in future)
externals['source-map'] = 'next/dist/compiled/source-map'
export async function ncc_source_map(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('source-map')))
    .ncc({ packageName: 'source-map', externals })
    .target('src/compiled/source-map')
}
// eslint-disable-next-line camelcase
// NB: Used by other dependencies, but Vercel version is a duplicate
// version so can be inlined anyway (although may change in future)
externals['source-map08'] = 'next/dist/compiled/source-map08'
externals['next/dist/compiled/source-map08'] = 'next/dist/compiled/source-map08'
export async function ncc_source_map08(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('source-map08')))
    .ncc({
      packageName: 'source-map08',
      packageJsonName: 'source-map08',
      externals,
      minify: false,
    })
    .target('src/compiled/source-map08')
}
// eslint-disable-next-line camelcase
externals['string-hash'] = 'next/dist/compiled/string-hash'
export async function ncc_string_hash(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('string-hash')))
    .ncc({ packageName: 'string-hash', externals })
    .target('src/compiled/string-hash')
}
// eslint-disable-next-line camelcase
externals['strip-ansi'] = 'next/dist/compiled/strip-ansi'
externals['next/dist/compiled/strip-ansi'] = 'next/dist/compiled/strip-ansi'
export async function ncc_strip_ansi(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('strip-ansi')))
    .ncc({ packageName: 'strip-ansi', externals })
    .target('src/compiled/strip-ansi')
}
// eslint-disable-next-line camelcase
externals['@vercel/nft'] = 'next/dist/compiled/@vercel/nft'
export async function ncc_nft(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('@vercel/nft')))
    .ncc({ packageName: '@vercel/nft', externals })
    .target('src/compiled/@vercel/nft')
}

// eslint-disable-next-line camelcase
externals['tar'] = 'next/dist/compiled/tar'
export async function ncc_tar(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('tar')))
    .ncc({ packageName: 'tar', externals })
    .target('src/compiled/tar')
}

// eslint-disable-next-line camelcase
externals['terser'] = 'next/dist/compiled/terser'
export async function ncc_terser(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('terser')))
    .ncc({ packageName: 'terser', externals })
    .target('src/compiled/terser')
}
// eslint-disable-next-line camelcase
externals['text-table'] = 'next/dist/compiled/text-table'
export async function ncc_text_table(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('text-table')))
    .ncc({ packageName: 'text-table', externals })
    .target('src/compiled/text-table')
}
// eslint-disable-next-line camelcase
externals['unistore'] = 'next/dist/compiled/unistore'
export async function ncc_unistore(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('unistore')))
    .ncc({ packageName: 'unistore', externals })
    .target('src/compiled/unistore')
}

// eslint-disable-next-line camelcase
externals['superstruct'] = 'next/dist/compiled/superstruct'
export async function ncc_superstruct(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('superstruct')))
    .ncc({ packageName: 'superstruct', externals })
    .target('src/compiled/superstruct')
}

externals['zod'] = 'next/dist/compiled/zod'
export async function ncc_zod(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('zod')))
    .ncc({ packageName: 'zod', externals })
    .target('src/compiled/zod')
}

externals['zod-validation-error'] = 'next/dist/compiled/zod-validation-error'
export async function ncc_zod_validation_error(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('zod-validation-error')))
    .ncc({ packageName: 'zod-validation-error', externals })
    .target('src/compiled/zod-validation-error')
}

// eslint-disable-next-line camelcase
externals['web-vitals'] = 'next/dist/compiled/web-vitals'
export async function ncc_web_vitals(task, opts) {
  await task
    .source(
      relative(
        __dirname,
        resolve(resolveFrom(__dirname, 'web-vitals'), '../web-vitals.js')
      )
    )
    // web-vitals@3.0.0 is pure ESM, compile to CJS for pre-compiled
    .ncc({ packageName: 'web-vitals', externals, target: 'es5', esm: false })
    .target('src/compiled/web-vitals')
}
// eslint-disable-next-line camelcase
externals['web-vitals-attribution'] =
  'next/dist/compiled/web-vitals-attribution'
export async function ncc_web_vitals_attribution(task, opts) {
  await task
    .source(
      relative(
        __dirname,
        resolve(require.resolve('web-vitals'), '../web-vitals.attribution.js')
      )
    )
    .ncc({
      packageName: 'web-vitals',
      bundleName: 'web-vitals-attribution',
      externals,
      target: 'es5',
      esm: false,
    })
    .target('src/compiled/web-vitals-attribution')
}
// eslint-disable-next-line camelcase
externals['webpack-sources'] = 'error webpack-sources version not specified'
externals['webpack-sources1'] = 'next/dist/compiled/webpack-sources1'
export async function ncc_webpack_sources1(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('webpack-sources1')))
    .ncc({ packageName: 'webpack-sources1', externals, target: 'es5' })
    .target('src/compiled/webpack-sources1')
}
// eslint-disable-next-line camelcase
externals['webpack-sources3'] = 'next/dist/compiled/webpack-sources3'
export async function ncc_webpack_sources3(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('webpack-sources3')))
    .ncc({ packageName: 'webpack-sources3', externals, target: 'es5' })
    .target('src/compiled/webpack-sources3')
}

// eslint-disable-next-line camelcase
externals['picomatch'] = 'next/dist/compiled/picomatch'
export async function ncc_minimatch(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('picomatch')))
    .ncc({ packageName: 'picomatch', externals })
    .target('src/compiled/picomatch')
}

// eslint-disable-next-line camelcase
externals['mini-css-extract-plugin'] =
  'next/dist/compiled/mini-css-extract-plugin'

export async function ncc_mini_css_extract_plugin(task, opts) {
  await task
    .source(
      relative(
        __dirname,
        resolve(require.resolve('mini-css-extract-plugin'), '../index.js')
      )
    )
    .ncc({
      externals: {
        ...externals,
        './index': './index.js',
        'schema-utils': externals['schema-utils3'],
        'webpack-sources': externals['webpack-sources1'],
      },
    })
    .target('src/compiled/mini-css-extract-plugin')
  await task
    .source(
      relative(
        __dirname,
        resolve(
          require.resolve('mini-css-extract-plugin'),
          '../hmr/hotModuleReplacement.js'
        )
      )
    )
    .ncc({
      externals: {
        ...externals,
        './hmr': './hmr',
        'schema-utils': 'next/dist/compiled/schema-utils3',
      },
    })
    .target('src/compiled/mini-css-extract-plugin/hmr')
  await task
    .source(relative(__dirname, require.resolve('mini-css-extract-plugin')))
    .ncc({
      packageName: 'mini-css-extract-plugin',
      externals: {
        ...externals,
        './index': './index.js',
        'schema-utils': externals['schema-utils3'],
      },
    })
    .target('src/compiled/mini-css-extract-plugin')
}

// eslint-disable-next-line camelcase
externals['ua-parser-js'] = 'next/dist/compiled/ua-parser-js'
export async function ncc_ua_parser_js(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('ua-parser-js')))
    .ncc({ packageName: 'ua-parser-js', externals })
    .target('src/compiled/ua-parser-js')
}
// eslint-disable-next-line camelcase
export async function ncc_webpack_bundle5(task, opts) {
  const bundleExternals = {
    ...externals,
    'schema-utils': externals['schema-utils3'],
    'webpack-sources': externals['webpack-sources3'],
  }
  for (const pkg of Object.keys(webpackBundlePackages)) {
    delete bundleExternals[pkg]
  }
  await task
    .source('src/bundles/webpack/bundle5.js')
    .ncc({
      packageName: 'webpack',
      bundleName: 'webpack',
      customEmit(path) {
        if (path.endsWith('.runtime.js')) return `'./${basename(path)}'`
      },
      externals: bundleExternals,
      target: 'es5',
    })
    .target('src/compiled/webpack')
}

const webpackBundlePackages = {
  webpack: 'next/dist/compiled/webpack/webpack-lib',
  'webpack/lib/NormalModule': 'next/dist/compiled/webpack/NormalModule',
  'webpack/lib/node/NodeTargetPlugin':
    'next/dist/compiled/webpack/NodeTargetPlugin',
}

Object.assign(externals, webpackBundlePackages)

export async function ncc_webpack_bundle_packages(task, opts) {
  await task
    .source('src/bundles/webpack/packages/*')
    .target('src/compiled/webpack/')
}

// eslint-disable-next-line camelcase
externals['ws'] = 'next/dist/compiled/ws'
export async function ncc_ws(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('ws')))
    .ncc({ packageName: 'ws', externals })
    .target('src/compiled/ws')
}

externals['path-to-regexp'] = 'next/dist/compiled/path-to-regexp'
export async function ncc_path_to_regexp(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('path-to-regexp')))
    .ncc({ packageName: 'path-to-regexp', externals })
    .target('src/compiled/path-to-regexp')
}

// eslint-disable-next-line camelcase
externals['@opentelemetry/api'] = 'next/dist/compiled/@opentelemetry/api'
export async function ncc_opentelemetry_api(task, opts) {
  await task
    .source(
      opts.src || relative(__dirname, require.resolve('@opentelemetry/api'))
    )
    .ncc({ packageName: '@opentelemetry/api', externals })
    .target('src/compiled/@opentelemetry/api')
}

// eslint-disable-next-line camelcase
externals['http-proxy-agent'] = 'next/dist/compiled/http-proxy-agent'
export async function ncc_http_proxy_agent(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('http-proxy-agent')))
    .ncc({ packageName: 'http-proxy-agent', externals })
    .target('src/compiled/http-proxy-agent')
}

// eslint-disable-next-line camelcase
externals['https-proxy-agent'] = 'next/dist/compiled/https-proxy-agent'
export async function ncc_https_proxy_agent(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('https-proxy-agent')))
    .ncc({ packageName: 'https-proxy-agent', externals })
    .target('src/compiled/https-proxy-agent')
}

externals['safe-stable-stringify'] = 'next/dist/compiled/safe-stable-stringify'
export async function ncc_safe_stable_stringify(task, opts) {
  await task
    .source(relative(__dirname, require.resolve('safe-stable-stringify')))
    .ncc({
      packageName: 'safe-stable-stringify',
      externals,
      target: 'es5',
    })
    .target('src/compiled/safe-stable-stringify')
}

export async function precompile(task, opts) {
  await task.parallel(
    ['browser_polyfills', 'copy_ncced', 'copy_styled_jsx_assets'],
    opts
  )
}

// eslint-disable-next-line camelcase
export async function copy_ncced(task) {
  // we don't ncc every time we build since these won't change
  // that often and can be committed to the repo saving build time
  await task.source('src/compiled/**/*').target('dist/compiled')
}

export async function ncc(task, opts) {
  await task
    .clear('src/compiled')
    .parallel(
      [
        'ncc_safe_stable_stringify',
        'ncc_amp_optimizer',
        'ncc_node_html_parser',
        'ncc_napirs_triples',
        'ncc_p_limit',
        'ncc_p_queue',
        'ncc_raw_body',
        'ncc_image_size',
        'ncc_hapi_accept',
        'ncc_commander',
        'ncc_node_anser',
        'ncc_node_stacktrace_parser',
        'ncc_node_data_uri_to_buffer',
        'ncc_node_cssescape',
        'ncc_node_shell_quote',
        'ncc_acorn',
        'ncc_amphtml_validator',
        'ncc_async_retry',
        'ncc_async_sema',
        'ncc_postcss_plugin_stub_for_cssnano_simple',
        'ncc_assert',
        'ncc_browser_zlib',
        'ncc_buffer',
        'ncc_crypto_browserify',
        'ncc_domain_browser',
        'ncc_events',
        'ncc_stream_browserify',
        'ncc_stream_http',
        'ncc_https_browserify',
        'ncc_os_browserify',
        'ncc_path_browserify',
        'ncc_process',
        'ncc_querystring_es3',
        'ncc_string_decoder',
        'ncc_util',
        'ncc_punycode',
        'ncc_set_immediate',
        'ncc_timers_browserify',
        'ncc_tty_browserify',
        'ncc_vm_browserify',
        'ncc_babel_bundle',
        'ncc_bytes',
        'ncc_ci_info',
        'ncc_cli_select',
        'ncc_comment_json',
        'ncc_compression',
        'ncc_conf',
        'ncc_content_disposition',
        'ncc_content_type',
        'ncc_cookie',
        'ncc_cross_spawn',
        'ncc_debug',
        'ncc_devalue',
        'ncc_find_up',
        'ncc_fresh',
        'ncc_glob',
        'ncc_gzip_size',
        'ncc_http_proxy',
        'ncc_ignore_loader',
        'ncc_is_animated',
        'ncc_is_docker',
        'ncc_is_wsl',
        'ncc_json5',
        'ncc_jsonwebtoken',
        'ncc_loader_runner',
        'ncc_loader_utils2',
        'ncc_loader_utils3',
        'ncc_lodash_curry',
        'ncc_lru_cache',
        'ncc_nanoid',
        'ncc_native_url',
        'ncc_neo_async',
        'ncc_ora',
        'ncc_path_to_regexp',
        'ncc_postcss_safe_parser',
        'ncc_postcss_flexbugs_fixes',
        'ncc_postcss_preset_env',
        'ncc_postcss_scss',
        'ncc_postcss_modules_extract_imports',
        'ncc_postcss_modules_local_by_default',
        'ncc_postcss_modules_scope',
        'ncc_postcss_modules_values',
        'ncc_postcss_value_parser',
        'ncc_icss_utils',
        'ncc_schema_utils2',
        'ncc_schema_utils3',
        'ncc_semver',
        'ncc_send',
        'ncc_source_map',
        'ncc_source_map08',
        'ncc_string_hash',
        'ncc_strip_ansi',
        'ncc_superstruct',
        'ncc_zod',
        'ncc_zod_validation_error',
        'ncc_nft',
        'ncc_tar',
        'ncc_terser',
        'ncc_text_table',
        'ncc_unistore',
        'ncc_watchpack',
        'ncc_web_vitals',
        'ncc_web_vitals_attribution',
        'ncc_webpack_bundle5',
        'ncc_webpack_sources1',
        'ncc_webpack_sources3',
        'ncc_ws',
        'ncc_ua_parser_js',
        'ncc_minimatch',
        'ncc_opentelemetry_api',
        'ncc_http_proxy_agent',
        'ncc_https_proxy_agent',
        'ncc_mini_css_extract_plugin',
      ],
      opts
    )
  await task.parallel(['ncc_webpack_bundle_packages'], opts)
  await task.parallel(['ncc_babel_bundle_packages'], opts)
  await task.serial(
    [
      'ncc_browserslist',
      'ncc_cssnano_simple_bundle',
      'copy_regenerator_runtime',
      'copy_babel_runtime',
      'copy_vercel_og',
      'copy_constants_browserify',
      'copy_vendor_react',
      'ncc_sass_loader',
      'ncc_jest_worker',
      'ncc_edge_runtime_cookies',
      'ncc_edge_runtime_primitives',
      'ncc_edge_runtime_ponyfill',
      'ncc_edge_runtime',
      'ncc_busboy',
      'ncc_mswjs_interceptors',
      'ncc_rsc_poison_packages',
    ],
    opts
  )
}

export async function next_compile(task, opts) {
  await task.parallel(
    [
      'cli',
      'bin',
      'server',
      'server_esm',
      'api_esm',
      'nextbuild',
      'nextbuildjest',
      'nextbuildstatic',
      'nextbuildstatic_esm',
      'nextbuild_esm',
      'next_devtools_entrypoint',
      'next_devtools_server',
      'next_devtools_server_esm',
      'next_devtools_shared',
      'next_devtools_shared_esm',
      'next_devtools_userspace',
      'next_devtools_userspace_esm',
      'pages',
      'pages_esm',
      'lib',
      'lib_esm',
      'client',
      'client_esm',
      'diagnostics',
      'telemetry',
      'trace',
      'shared',
      'shared_esm',
      'shared_re_exported',
      'shared_re_exported_esm',
      'server_wasm',
      'experimental_testing',
      'experimental_testmode',
    ],
    opts
  )
}

export async function compile(task, opts) {
  await task.serial(['next_compile', 'next_bundle'], opts)

  await task.serial([
    'ncc_react_refresh_utils',
    'ncc_next_font',
    'capsize_metrics',
  ])
}

export async function bin(task, opts) {
  await task
    .source('src/bin/*')
    .swc('server', { stripExtension: true, dev: opts.dev })
    .target('dist/bin', { mode: '0755' })
}

export async function cli(task, opts) {
  await task
    .source('src/cli/**/*.+(js|ts|tsx)')
    .swc('server', { dev: opts.dev })
    .target('dist/cli')
}

export async function lib(task, opts) {
  await task
    .source('src/lib/**/!(*.test).+(js|ts|tsx|json)')
    .swc('server', { dev: opts.dev })
    .target('dist/lib')
}

export async function lib_esm(task, opts) {
  await task
    .source('src/lib/**/!(*.test).+(js|ts|tsx|json)')
    .swc('server', { dev: opts.dev, esm: true })
    .target('dist/esm/lib')
}

export async function server(task, opts) {
  await task
    .source('src/server/**/!(*.test).+(js|ts|tsx)')
    .swc('server', { dev: opts.dev })
    .target('dist/server')
}

export async function server_esm(task, opts) {
  await task
    .source('src/server/**/!(*.test).+(js|mts|ts|tsx)')
    .swc('server', { dev: opts.dev, esm: true })
    .target('dist/esm/server')
}

// Provide ESM entry files for Next.js apis,
// Remain in ESM both for dist/ and dist/esm
export async function api_esm(task, opts) {
  await task
    .source('src/api/**/*.+(js|mts|ts|tsx)')
    .swc('server', { dev: opts.dev, esm: true })
    .target('dist/api')
    .target('dist/esm/api')
}

export async function nextbuild(task, opts) {
  await task
    .source('src/build/**/*.+(js|ts|tsx)', {
      ignore: [
        '**/fixture/**',
        '**/tests/**',
        '**/jest/**',
        '**/*.test.d.ts',
        '**/*.test.+(js|ts|tsx)',
      ],
    })
    .swc('server', { dev: opts.dev })
    .target('dist/build')
}

export async function nextbuild_esm(task, opts) {
  await task
    .source('src/build/**/*.+(js|ts|tsx)', {
      ignore: [
        '**/fixture/**',
        '**/tests/**',
        '**/jest/**',
        '**/*.test.d.ts',
        '**/*.test.+(js|ts|tsx)',
      ],
    })
    .swc('server', { dev: opts.dev, esm: true })
    .target('dist/esm/build')
}

export async function nextbuildjest(task, opts) {
  await task
    .source('src/build/jest/**/*.+(js|ts|tsx)', {
      ignore: [
        '**/fixture/**',
        '**/tests/**',
        '**/*.test.d.ts',
        '**/*.test.+(js|ts|tsx)',
      ],
    })
    .swc('server', { dev: opts.dev, interopClientDefaultExport: true })
    .target('dist/build/jest')
}

export async function client(task, opts) {
  await task
    .source('src/client/**/!(*.test|*.stories).+(js|ts|tsx|woff2)')
    .swc('client', { dev: opts.dev, interopClientDefaultExport: true })
    .target('dist/client')
}

export async function client_esm(task, opts) {
  await task
    .source('src/client/**/!(*.test|*.stories).+(js|ts|tsx|woff2)')
    .swc('client', { dev: opts.dev, esm: true })
    .target('dist/esm/client')
}

export async function next_devtools_entrypoint(task, opts) {
  await task
    .source('src/next-devtools/dev-overlay.shim.ts')
    .swc('client', { dev: opts.dev, interopClientDefaultExport: true })
    .target('dist/next-devtools')
}

export async function next_devtools_server(task, opts) {
  await task
    .source(
      'src/next-devtools/server/**/!(*.test|*.stories).+(js|ts|tsx|woff2)'
    )
    .swc('client', { dev: opts.dev, interopClientDefaultExport: true })
    .target('dist/next-devtools/server')
}

export async function next_devtools_server_esm(task, opts) {
  await task
    .source(
      'src/next-devtools/server/**/!(*.test|*.stories).+(js|ts|tsx|woff2)'
    )
    .swc('client', { dev: opts.dev, esm: true })
    .target('dist/esm/next-devtools/server')
}

export async function next_devtools_shared(task, opts) {
  await task
    .source(
      'src/next-devtools/shared/**/!(*.test|*.stories).+(js|ts|tsx|woff2)'
    )
    .swc('client', { dev: opts.dev, interopClientDefaultExport: true })
    .target('dist/next-devtools/shared')
}

export async function next_devtools_shared_esm(task, opts) {
  await task
    .source(
      'src/next-devtools/shared/**/!(*.test|*.stories).+(js|ts|tsx|woff2)'
    )
    .swc('client', { dev: opts.dev, esm: true })
    .target('dist/esm/next-devtools/shared')
}

export async function next_devtools_userspace(task, opts) {
  await task
    .source(
      'src/next-devtools/userspace/**/!(*.test|*.stories).+(js|ts|tsx|woff2)'
    )
    .swc('client', { dev: opts.dev, interopClientDefaultExport: true })
    .target('dist/next-devtools/userspace')
}

export async function next_devtools_userspace_esm(task, opts) {
  await task
    .source(
      'src/next-devtools/userspace/**/!(*.test|*.stories).+(js|ts|tsx|woff2)'
    )
    .swc('client', { dev: opts.dev, esm: true })
    .target('dist/esm/next-devtools/userspace')
}

// export is a reserved keyword for functions
export async function nextbuildstatic(task, opts) {
  await task
    .source('src/export/**/!(*.test).+(js|ts|tsx)')
    .swc('server', { dev: opts.dev })
    .target('dist/export')
}

// export is a reserved keyword for functions
export async function nextbuildstatic_esm(task, opts) {
  await task
    .source('src/export/**/!(*.test).+(js|ts|tsx)')
    .swc('server', { dev: opts.dev, esm: true })
    .target('dist/esm/export')
}

export async function pages_app(task, opts) {
  await task
    .source('src/pages/_app.tsx')
    .swc('client', {
      dev: opts.dev,
      interopClientDefaultExport: true,
    })
    .target('dist/pages')
}

export async function pages_error(task, opts) {
  await task
    .source('src/pages/_error.tsx')
    .swc('client', {
      dev: opts.dev,
      interopClientDefaultExport: true,
    })
    .target('dist/pages')
}

export async function pages_document(task, opts) {
  await task
    .source('src/pages/_document.tsx')
    .swc('server', {
      dev: opts.dev,
    })
    .target('dist/pages')
}

export async function pages_app_esm(task, opts) {
  await task
    .source('src/pages/_app.tsx')
    .swc('client', {
      dev: opts.dev,
      esm: true,
    })
    .target('dist/esm/pages')
}

export async function pages_error_esm(task, opts) {
  await task
    .source('src/pages/_error.tsx')
    .swc('client', {
      dev: opts.dev,
      esm: true,
    })
    .target('dist/esm/pages')
}

export async function pages_document_esm(task, opts) {
  await task
    .source('src/pages/_document.tsx')
    .swc('server', {
      dev: opts.dev,
      esm: true,
    })
    .target('dist/esm/pages')
}

export async function pages(task, opts) {
  await task.parallel(['pages_app', 'pages_error', 'pages_document'], opts)
}

export async function pages_esm(task, opts) {
  await task.parallel(
    ['pages_app_esm', 'pages_error_esm', 'pages_document_esm'],
    opts
  )
}

export async function telemetry(task, opts) {
  await task
    .source('src/telemetry/**/*.+(js|ts|tsx)')
    .swc('server', { dev: opts.dev })
    .target('dist/telemetry')
}

export async function trace(task, opts) {
  await task
    .source('src/trace/**/*.+(js|ts|tsx)')
    .swc('server', { dev: opts.dev })
    .target('dist/trace')
}

export async function diagnostics(task, opts) {
  await task
    .source('src/diagnostics/**/*.+(js|ts|tsx)')
    .swc('server', { dev: opts.dev })
    .target('dist/diagnostics')
}

export async function build(task, opts) {
  await task.serial(
    ['precompile', 'compile', 'check_error_codes', 'generate_types'],
    opts
  )
}

export async function generate_types(task, opts) {
  const watchmode = opts.dev
  const typesPromise = execa(
    'pnpm',
    [
      'run',
      'types',
      ...(watchmode ? ['--watch', '--preserveWatchOutput'] : []),
    ],
    { stdio: 'inherit' }
  )
  // In watch-mode the process never completes i.e. the Promise never resolve.
  // But taskr needs to know that it can start watching the files for the task it has to manually restart.
  if (!watchmode) {
    await typesPromise
  }
}

export async function check_error_codes(task, opts) {
  try {
    await execa.command('pnpm -w run check-error-codes', {
      stdio: 'inherit',
    })
  } catch (err) {
    if (process.env.CI) {
      await execa.command(
        'echo check_error_codes FAILED: There are new errors introduced but no corresponding error codes are found in errors.json file, so make sure you run `pnpm build` or `pnpm update-error-codes` and then commit the change in errors.json.',
        {
          stdio: 'inherit',
        }
      )
      process.exit(1)
    }
    await task.start('compile', opts)
  }
}

export default async function (task) {
  const opts = { dev: true }
  await task.clear('dist')
  await task.start('build', opts)
  await task.watch('src/bin', 'bin', opts)
  await task.watch('src/pages', 'pages', opts)
  await task.watch('src/server', ['server', 'server_esm', 'server_wasm'], opts)
  await task.watch('src/api', 'api_esm', opts)
  await task.watch(
    'src/build',
    ['nextbuild', 'nextbuild_esm', 'nextbuildjest'],
    opts
  )
  await task.watch(
    'src/next-devtools',
    [
      'next_devtools_entrypoint',
      'next_devtools_server',
      'next_devtools_server_esm',
      'next_devtools_shared',
      'next_devtools_shared_esm',
      'next_devtools_userspace',
      'next_devtools_userspace_esm',
    ],
    opts
  )
  await task.watch('src/experimental/testing', 'experimental_testing', opts)
  await task.watch('src/experimental/testmode', 'experimental_testmode', opts)
  await task.watch('src/export', 'nextbuildstatic', opts)
  await task.watch('src/export', 'nextbuildstatic_esm', opts)
  await task.watch('src/client', 'client', opts)
  await task.watch('src/client', 'client_esm', opts)
  await task.watch('src/diagnostics', 'diagnostics', opts)
  await task.watch('src/lib', 'lib', opts)
  await task.watch('src/lib', 'lib_esm', opts)
  await task.watch('src/cli', 'cli', opts)
  await task.watch('src/telemetry', 'telemetry', opts)
  await task.watch('src/trace', 'trace', opts)
  await task.watch(
    'src/shared',
    ['shared_re_exported', 'shared_re_exported_esm', 'shared', 'shared_esm'],
    opts
  )
}

export async function shared(task, opts) {
  await task
    .source('src/shared/**/*.+(js|ts|tsx)', {
      ignore: [
        'src/shared/**/{amp,config,constants,dynamic,app-dynamic,head,runtime-config}.+(js|ts|tsx)',
        '**/*.test.d.ts',
        '**/*.test.+(js|ts|tsx)',
      ],
    })
    .swc('client', { dev: opts.dev })
    .target('dist/shared')
}

export async function shared_esm(task, opts) {
  await task
    .source('src/shared/**/*.+(js|ts|tsx)', {
      ignore: [
        'src/shared/**/{amp,config,constants,dynamic,app-dynamic,head,runtime-config}.+(js|ts|tsx)',
        '**/*.test.d.ts',
        '**/*.test.+(js|ts|tsx)',
      ],
    })
    .swc('client', { dev: opts.dev, esm: true })
    .target('dist/esm/shared')
}

export async function shared_re_exported(task, opts) {
  await task
    .source(
      'src/shared/**/{amp,config,constants,dynamic,app-dynamic,head,runtime-config}.+(js|ts|tsx)',
      {
        ignore: ['**/*.test.d.ts', '**/*.test.+(js|ts|tsx)'],
      }
    )
    .swc('client', { dev: opts.dev, interopClientDefaultExport: true })
    .target('dist/shared')
}

export async function shared_re_exported_esm(task, opts) {
  await task
    .source(
      'src/shared/**/{amp,config,constants,app-dynamic,dynamic,head}.+(js|ts|tsx)',
      {
        ignore: ['**/*.test.d.ts', '**/*.test.+(js|ts|tsx)'],
      }
    )
    .swc('client', {
      dev: opts.dev,
      esm: true,
    })
    .target('dist/esm/shared')
}

export async function server_wasm(task, opts) {
  await task.source('src/server/**/*.+(wasm)').target('dist/server')
}

export async function experimental_testing(task, opts) {
  await task
    .source('src/experimental/testing/**/!(*.test).+(js|ts|tsx)')
    .swc('server', {
      dev: opts.dev,
    })
    .target('dist/experimental/testing')
}

export async function experimental_testmode(task, opts) {
  await task
    .source('src/experimental/testmode/**/!(*.test).+(js|ts|tsx)')
    .swc('server', {
      dev: opts.dev,
    })
    .target('dist/experimental/testmode')
}

export async function release(task) {
  await task.clear('dist').start('build')
}

export async function next_bundle_app_prod_turbo(task, opts) {
  await task.source('dist').webpack({
    watch: opts.dev,
    config: require('./next-runtime.webpack-config')({
      turbo: true,
      bundleType: 'app',
    }),
    name: 'next-bundle-app-prod-turbo',
  })
}

export async function next_bundle_app_prod(task, opts) {
  await task.source('dist').webpack({
    watch: opts.dev,
    config: require('./next-runtime.webpack-config')({
      dev: false,
      bundleType: 'app',
    }),
    name: 'next-bundle-app-prod',
  })
}

export async function next_bundle_app_dev_turbo(task, opts) {
  await task.source('dist').webpack({
    watch: opts.dev,
    config: require('./next-runtime.webpack-config')({
      turbo: true,
      dev: true,
      bundleType: 'app',
    }),
    name: 'next-bundle-app-dev-turbo',
  })
}

export async function next_bundle_app_dev(task, opts) {
  await task.source('dist').webpack({
    watch: opts.dev,
    config: require('./next-runtime.webpack-config')({
      dev: true,
      bundleType: 'app',
    }),
    name: 'next-bundle-app-dev',
  })
}

export async function next_bundle_app_prod_turbo_experimental(task, opts) {
  await task.source('dist').webpack({
    watch: opts.dev,
    config: require('./next-runtime.webpack-config')({
      turbo: true,
      bundleType: 'app',
      experimental: true,
    }),
    name: 'next-bundle-app-prod-turbo-experimental',
  })
}

export async function next_bundle_app_prod_experimental(task, opts) {
  await task.source('dist').webpack({
    watch: opts.dev,
    config: require('./next-runtime.webpack-config')({
      dev: false,
      bundleType: 'app',
      experimental: true,
    }),
    name: 'next-bundle-app-prod-experimental',
  })
}

export async function next_bundle_app_dev_turbo_experimental(task, opts) {
  await task.source('dist').webpack({
    watch: opts.dev,
    config: require('./next-runtime.webpack-config')({
      turbo: true,
      dev: true,
      bundleType: 'app',
      experimental: true,
    }),
    name: 'next-bundle-app-dev-turbo-experimental',
  })
}

export async function next_bundle_app_dev_experimental(task, opts) {
  await task.source('dist').webpack({
    watch: opts.dev,
    config: require('./next-runtime.webpack-config')({
      dev: true,
      bundleType: 'app',
      experimental: true,
    }),
    name: 'next-bundle-app-dev-experimental',
  })
}

export async function next_bundle_pages_prod(task, opts) {
  await task.source('dist').webpack({
    watch: opts.dev,
    config: require('./next-runtime.webpack-config')({
      dev: false,
      bundleType: 'pages',
    }),
    name: 'next-bundle-pages-prod',
  })
}

export async function next_bundle_pages_dev(task, opts) {
  await task.source('dist').webpack({
    watch: opts.dev,
    config: require('./next-runtime.webpack-config')({
      dev: true,
      bundleType: 'pages',
    }),
    name: 'next-bundle-pages-dev',
  })
}

export async function next_bundle_pages_prod_turbo(task, opts) {
  await task.source('dist').webpack({
    watch: opts.dev,
    config: require('./next-runtime.webpack-config')({
      turbo: true,
      bundleType: 'pages',
    }),
    name: 'next-bundle-pages-prod-turbo',
  })
}

export async function next_bundle_pages_dev_turbo(task, opts) {
  await task.source('dist').webpack({
    watch: opts.dev,
    config: require('./next-runtime.webpack-config')({
      turbo: true,
      dev: true,
      bundleType: 'pages',
    }),
    name: 'next-bundle-pages-dev-turbo',
  })
}

export async function next_bundle_server(task, opts) {
  await task.source('dist').webpack({
    watch: opts.dev,
    config: require('./next-runtime.webpack-config')({
      dev: false,
      bundleType: 'server',
    }),
    name: 'next-bundle-server',
  })
}

export async function next_bundle_devtools(task, opts) {
  await task.source('dist').webpack({
    watch: opts.dev,
    config: require('./next-devtools.webpack-config')({
      dev: opts.dev,
    }),
    name: 'next-bundle-devtools-dev',
  })
}

export async function next_bundle(task, opts) {
  await task.parallel(
    [
      // builds the app (route/page) bundles
      'next_bundle_app_prod_turbo',
      'next_bundle_app_prod',
      'next_bundle_app_dev_turbo',
      'next_bundle_app_dev',
      // builds the app (route/page) bundles with react experimental
      'next_bundle_app_prod_turbo_experimental',
      'next_bundle_app_prod_experimental',
      'next_bundle_app_dev_turbo_experimental',
      'next_bundle_app_dev_experimental',
      // builds the pages (page/api) bundles
      'next_bundle_pages_prod',
      'next_bundle_pages_dev',
      'next_bundle_pages_prod_turbo',
      'next_bundle_pages_dev_turbo',
      // builds the minimal server
      'next_bundle_server',
      // devtools
      'next_bundle_devtools',
    ],
    opts
  )
}

function writeJson(file, obj, { spaces = 0 } = {}) {
  return fs.writeFile(
    file,
    JSON.stringify(obj, null, spaces) + (spaces === 0 ? '\n' : '')
  )
}

function rmrf(path, options) {
  return fs.rm(path, { recursive: true, force: true, ...options })
}

function readJson(path) {
  return fs.readFile(path, 'utf8').then((content) => JSON.parse(content))
}