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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
import React from 'react'
import ReactRefreshWebpackPlugin from 'next/dist/compiled/@next/react-refresh-utils/dist/ReactRefreshWebpackPlugin'
import { yellow, bold } from '../lib/picocolors'
import crypto from 'crypto'
import { webpack } from 'next/dist/compiled/webpack/webpack'
import path from 'path'

import { getDefineEnv } from './define-env'
import { escapeStringRegexp } from '../shared/lib/escape-regexp'
import { WEBPACK_LAYERS, WEBPACK_RESOURCE_QUERIES } from '../lib/constants'
import type { WebpackLayerName } from '../lib/constants'
import {
  isWebpackBundledLayer,
  isWebpackClientOnlyLayer,
  shouldUseReactServerCondition,
  isWebpackDefaultLayer,
  RSPACK_DEFAULT_LAYERS_REGEX,
} from './utils'
import type { CustomRoutes } from '../lib/load-custom-routes.js'
import {
  CLIENT_STATIC_FILES_RUNTIME_AMP,
  CLIENT_STATIC_FILES_RUNTIME_MAIN,
  CLIENT_STATIC_FILES_RUNTIME_MAIN_APP,
  CLIENT_STATIC_FILES_RUNTIME_POLYFILLS_SYMBOL,
  CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH,
  CLIENT_STATIC_FILES_RUNTIME_WEBPACK,
  MIDDLEWARE_REACT_LOADABLE_MANIFEST,
  REACT_LOADABLE_MANIFEST,
  SERVER_DIRECTORY,
  COMPILER_NAMES,
} from '../shared/lib/constants'
import type { CompilerNameValues } from '../shared/lib/constants'
import { execOnce } from '../shared/lib/utils'
import type { NextConfigComplete } from '../server/config-shared'
import { finalizeEntrypoint } from './entries'
import * as Log from './output/log'
import { buildConfiguration } from './webpack/config'
import MiddlewarePlugin, {
  getEdgePolyfilledModules,
  handleWebpackExternalForEdgeRuntime,
} from './webpack/plugins/middleware-plugin'
import BuildManifestPlugin from './webpack/plugins/build-manifest-plugin'
import { JsConfigPathsPlugin } from './webpack/plugins/jsconfig-paths-plugin'
import { DropClientPage } from './webpack/plugins/next-drop-client-page-plugin'
import PagesManifestPlugin from './webpack/plugins/pages-manifest-plugin'
import { ProfilingPlugin } from './webpack/plugins/profiling-plugin'
import { ReactLoadablePlugin } from './webpack/plugins/react-loadable-plugin'
import { WellKnownErrorsPlugin } from './webpack/plugins/wellknown-errors-plugin'
import { regexLikeCss } from './webpack/config/blocks/css'
import { CopyFilePlugin } from './webpack/plugins/copy-file-plugin'
import { ClientReferenceManifestPlugin } from './webpack/plugins/flight-manifest-plugin'
import { FlightClientEntryPlugin as NextFlightClientEntryPlugin } from './webpack/plugins/flight-client-entry-plugin'
import { RspackFlightClientEntryPlugin } from './webpack/plugins/rspack-flight-client-entry-plugin'
import { NextTypesPlugin } from './webpack/plugins/next-types-plugin'
import type {
  Feature,
  SWC_TARGET_TRIPLE,
} from './webpack/plugins/telemetry-plugin/telemetry-plugin'
import type { Span } from '../trace'
import type { MiddlewareMatcher } from './analysis/get-page-static-info'
import loadJsConfig, {
  type JsConfig,
  type ResolvedBaseUrl,
} from './load-jsconfig'
import { loadBindings } from './swc'
import { AppBuildManifestPlugin } from './webpack/plugins/app-build-manifest-plugin'
import { SubresourceIntegrityPlugin } from './webpack/plugins/subresource-integrity-plugin'
import { NextFontManifestPlugin } from './webpack/plugins/next-font-manifest-plugin'
import { getSupportedBrowsers } from './utils'
import { MemoryWithGcCachePlugin } from './webpack/plugins/memory-with-gc-cache-plugin'
import { getBabelConfigFile } from './get-babel-config-file'
import { needsExperimentalReact } from '../lib/needs-experimental-react'
import type { SWCLoaderOptions } from './webpack/loaders/next-swc-loader'
import { isResourceInPackages, makeExternalHandler } from './handle-externals'
import {
  getMainField,
  edgeConditionNames,
} from './webpack-config-rules/resolve'
import { OptionalPeerDependencyResolverPlugin } from './webpack/plugins/optional-peer-dependency-resolve-plugin'
import {
  createWebpackAliases,
  createServerOnlyClientOnlyAliases,
  createVendoredReactAliases,
  createNextApiEsmAliases,
  createAppRouterApiAliases,
} from './create-compiler-aliases'
import { hasCustomExportOutput } from '../export/utils'
import { CssChunkingPlugin } from './webpack/plugins/css-chunking-plugin'
import {
  getBabelLoader,
  getReactCompilerLoader,
} from './get-babel-loader-config'
import {
  NEXT_PROJECT_ROOT,
  NEXT_PROJECT_ROOT_DIST_CLIENT,
} from './next-dir-paths'
import { getRspackCore, getRspackReactRefresh } from '../shared/lib/get-rspack'
import { RspackProfilingPlugin } from './webpack/plugins/rspack-profiling-plugin'
import getWebpackBundler from '../shared/lib/get-webpack-bundler'
import type { NextBuildContext } from './build-context'

type ExcludesFalse = <T>(x: T | false) => x is T
type ClientEntries = {
  [key: string]: string | string[]
}

const EXTERNAL_PACKAGES =
  require('../lib/server-external-packages.json') as string[]

const DEFAULT_TRANSPILED_PACKAGES =
  require('../lib/default-transpiled-packages.json') as string[]

if (parseInt(React.version) < 18) {
  throw new Error('Next.js requires react >= 18.2.0 to be installed.')
}

export const babelIncludeRegexes: RegExp[] = [
  /next[\\/]dist[\\/](esm[\\/])?shared[\\/]lib/,
  /next[\\/]dist[\\/](esm[\\/])?client/,
  /next[\\/]dist[\\/](esm[\\/])?pages/,
  /[\\/](strip-ansi|ansi-regex|styled-jsx)[\\/]/,
]

const browserNonTranspileModules = [
  // Transpiling `process/browser` will trigger babel compilation error due to value replacement.
  // TypeError: Property left of AssignmentExpression expected node to be of a type ["LVal"] but instead got "BooleanLiteral"
  // e.g. `process.browser = true` will become `true = true`.
  /[\\/]node_modules[\\/]process[\\/]browser/,
  // Exclude precompiled react packages from browser compilation due to SWC helper insertion (#61791),
  // We fixed the issue but it's safer to exclude them from compilation since they don't need to be re-compiled.
  /[\\/]next[\\/]dist[\\/]compiled[\\/](react|react-dom|react-server-dom-webpack)(-experimental)?($|[\\/])/,
]
const precompileRegex = /[\\/]next[\\/]dist[\\/]compiled[\\/]/

const asyncStoragesRegex =
  /next[\\/]dist[\\/](esm[\\/])?server[\\/]app-render[\\/](work-async-storage|action-async-storage|dynamic-access-async-storage|work-unit-async-storage)/

// Support for NODE_PATH
const nodePathList = (process.env.NODE_PATH || '')
  .split(process.platform === 'win32' ? ';' : ':')
  .filter((p) => !!p)

const baseWatchOptions: webpack.Configuration['watchOptions'] = Object.freeze({
  aggregateTimeout: 5,
  ignored:
    // Matches **/node_modules/**, **/.git/** and **/.next/**
    /^((?:[^/]*(?:\/|$))*)(\.(git|next)|node_modules)(\/((?:[^/]*(?:\/|$))*)(?:$|\/))?/,
})

function isModuleCSS(module: { type: string }) {
  return (
    // mini-css-extract-plugin
    module.type === `css/mini-extract` ||
    // extract-css-chunks-webpack-plugin (old)
    module.type === `css/extract-chunks` ||
    // extract-css-chunks-webpack-plugin (new)
    module.type === `css/extract-css-chunks`
  )
}

const devtoolRevertWarning = execOnce(
  (devtool: webpack.Configuration['devtool']) => {
    console.warn(
      yellow(bold('Warning: ')) +
        bold(`Reverting webpack devtool to '${devtool}'.\n`) +
        'Changing the webpack devtool in development mode will cause severe performance regressions.\n' +
        'Read more: https://nextjs.org/docs/messages/improper-devtool'
    )
  }
)

let loggedSwcDisabled = false
let loggedIgnoredCompilerOptions = false
const reactRefreshLoaderName =
  'next/dist/compiled/@next/react-refresh-utils/dist/loader'

function getReactRefreshLoader() {
  return process.env.NEXT_RSPACK
    ? getRspackReactRefresh().loader
    : require.resolve(reactRefreshLoaderName)
}

export function attachReactRefresh(
  webpackConfig: webpack.Configuration,
  targetLoader: webpack.RuleSetUseItem
) {
  const reactRefreshLoader = getReactRefreshLoader()
  webpackConfig.module?.rules?.forEach((rule) => {
    if (rule && typeof rule === 'object' && 'use' in rule) {
      const curr = rule.use
      // When the user has configured `defaultLoaders.babel` for a input file:
      if (curr === targetLoader) {
        rule.use = [reactRefreshLoader, curr as webpack.RuleSetUseItem]
      } else if (
        Array.isArray(curr) &&
        curr.some((r) => r === targetLoader) &&
        // Check if loader already exists:
        !curr.some(
          (r) => r === reactRefreshLoader || r === reactRefreshLoaderName
        )
      ) {
        const idx = curr.findIndex((r) => r === targetLoader)
        // Clone to not mutate user input
        rule.use = [...curr]

        // inject / input: [other, babel] output: [other, refresh, babel]:
        rule.use.splice(idx, 0, reactRefreshLoader)
      }
    }
  })
}

export const NODE_RESOLVE_OPTIONS = {
  dependencyType: 'commonjs',
  modules: ['node_modules'],
  fallback: false,
  exportsFields: ['exports'],
  importsFields: ['imports'],
  conditionNames: ['node', 'require'],
  descriptionFiles: ['package.json'],
  extensions: ['.js', '.json', '.node'],
  enforceExtensions: false,
  symlinks: true,
  mainFields: ['main'],
  mainFiles: ['index'],
  roots: [],
  fullySpecified: false,
  preferRelative: false,
  preferAbsolute: false,
  restrictions: [],
}

export const NODE_BASE_RESOLVE_OPTIONS = {
  ...NODE_RESOLVE_OPTIONS,
  alias: false,
}

export const NODE_ESM_RESOLVE_OPTIONS = {
  ...NODE_RESOLVE_OPTIONS,
  alias: false,
  dependencyType: 'esm',
  conditionNames: ['node', 'import'],
  fullySpecified: true,
}

export const NODE_BASE_ESM_RESOLVE_OPTIONS = {
  ...NODE_ESM_RESOLVE_OPTIONS,
  alias: false,
}

export const nextImageLoaderRegex =
  /\.(png|jpg|jpeg|gif|webp|avif|ico|bmp|svg)$/i

export async function loadProjectInfo({
  dir,
  config,
  dev,
}: {
  dir: string
  config: NextConfigComplete
  dev: boolean
}): Promise<{
  jsConfig: JsConfig
  jsConfigPath?: string
  resolvedBaseUrl: ResolvedBaseUrl
  supportedBrowsers: string[] | undefined
}> {
  const { jsConfig, jsConfigPath, resolvedBaseUrl } = await loadJsConfig(
    dir,
    config
  )
  const supportedBrowsers = getSupportedBrowsers(dir, dev)
  return {
    jsConfig,
    jsConfigPath,
    resolvedBaseUrl,
    supportedBrowsers,
  }
}

export function hasExternalOtelApiPackage(): boolean {
  try {
    require('@opentelemetry/api') as typeof import('@opentelemetry/api')
    return true
  } catch {
    return false
  }
}

const UNSAFE_CACHE_REGEX = /[\\/]pages[\\/][^\\/]+(?:$|\?|#)/

export function getCacheDirectories(
  configs: webpack.Configuration[]
): Set<string> {
  return new Set(
    configs
      .map((cfg) => {
        if (typeof cfg.cache === 'object' && cfg.cache.type === 'filesystem') {
          return cfg.cache.cacheDirectory
        }
        return null
      })
      .filter((dir) => dir != null)
  )
}

export default async function getBaseWebpackConfig(
  dir: string,
  {
    buildId,
    encryptionKey,
    config,
    compilerType,
    dev = false,
    entrypoints,
    isDevFallback = false,
    pagesDir,
    reactProductionProfiling = false,
    rewrites,
    originalRewrites,
    originalRedirects,
    runWebpackSpan,
    appDir,
    middlewareMatchers,
    noMangling,
    jsConfig,
    jsConfigPath,
    resolvedBaseUrl,
    supportedBrowsers,
    clientRouterFilters,
    fetchCacheKeyPrefix,
    isCompileMode,
    previewProps,
  }: {
    previewProps: NonNullable<(typeof NextBuildContext)['previewProps']>
    isCompileMode?: boolean
    buildId: string
    encryptionKey: string
    config: NextConfigComplete
    compilerType: CompilerNameValues
    dev?: boolean
    entrypoints: webpack.EntryObject
    isDevFallback?: boolean
    pagesDir: string | undefined
    reactProductionProfiling?: boolean
    rewrites: CustomRoutes['rewrites']
    originalRewrites: CustomRoutes['rewrites'] | undefined
    originalRedirects: CustomRoutes['redirects'] | undefined
    runWebpackSpan: Span
    appDir: string | undefined
    middlewareMatchers?: MiddlewareMatcher[]
    noMangling?: boolean
    jsConfig: any
    jsConfigPath?: string
    resolvedBaseUrl: ResolvedBaseUrl
    supportedBrowsers: string[] | undefined
    clientRouterFilters?: {
      staticFilter: ReturnType<
        import('../shared/lib/bloom-filter').BloomFilter['export']
      >
      dynamicFilter: ReturnType<
        import('../shared/lib/bloom-filter').BloomFilter['export']
      >
    }
    fetchCacheKeyPrefix?: string
  }
): Promise<webpack.Configuration> {
  const bundler = getWebpackBundler()
  const isClient = compilerType === COMPILER_NAMES.client
  const isEdgeServer = compilerType === COMPILER_NAMES.edgeServer
  const isNodeServer = compilerType === COMPILER_NAMES.server

  const isRspack = Boolean(process.env.NEXT_RSPACK)

  const FlightClientEntryPlugin =
    isRspack && process.env.BUILTIN_FLIGHT_CLIENT_ENTRY_PLUGIN
      ? RspackFlightClientEntryPlugin
      : NextFlightClientEntryPlugin

  // If the current compilation is aimed at server-side code instead of client-side code.
  const isNodeOrEdgeCompilation = isNodeServer || isEdgeServer

  const hasRewrites =
    rewrites.beforeFiles.length > 0 ||
    rewrites.afterFiles.length > 0 ||
    rewrites.fallback.length > 0

  const hasAppDir = !!appDir
  const disableOptimizedLoading = true
  const enableTypedRoutes = !!config.experimental.typedRoutes && hasAppDir
  const bundledReactChannel = needsExperimentalReact(config)
    ? '-experimental'
    : ''

  const babelConfigFile = getBabelConfigFile(dir)

  if (!dev && hasCustomExportOutput(config)) {
    config.distDir = '.next'
  }
  const distDir = path.join(dir, config.distDir)

  let useSWCLoader = !babelConfigFile || config.experimental.forceSwcTransforms
  let SWCBinaryTarget: [Feature, boolean] | undefined = undefined
  if (useSWCLoader) {
    // TODO: we do not collect wasm target yet
    const binaryTarget = (
      require('./swc') as typeof import('./swc')
    )?.getBinaryMetadata?.()?.target as SWC_TARGET_TRIPLE
    SWCBinaryTarget = binaryTarget
      ? [`swc/target/${binaryTarget}` as const, true]
      : undefined
  }

  if (!loggedSwcDisabled && !useSWCLoader && babelConfigFile) {
    Log.info(
      `Disabled SWC as replacement for Babel because of custom Babel configuration "${path.relative(
        dir,
        babelConfigFile
      )}" https://nextjs.org/docs/messages/swc-disabled`
    )
    loggedSwcDisabled = true
  }

  // eagerly load swc bindings instead of waiting for transform calls
  if (!babelConfigFile && isClient) {
    await loadBindings(config.experimental.useWasmBinary)
  }

  // since `pages` doesn't always bundle by default we need to
  // auto-include optimizePackageImports in transpilePackages
  const finalTranspilePackages: string[] = (
    config.transpilePackages || []
  ).concat(DEFAULT_TRANSPILED_PACKAGES)

  for (const pkg of config.experimental.optimizePackageImports || []) {
    if (!finalTranspilePackages.includes(pkg)) {
      finalTranspilePackages.push(pkg)
    }
  }

  if (!loggedIgnoredCompilerOptions && !useSWCLoader && config.compiler) {
    Log.info(
      '`compiler` options in `next.config.js` will be ignored while using Babel https://nextjs.org/docs/messages/ignored-compiler-options'
    )
    loggedIgnoredCompilerOptions = true
  }

  const excludeCache: Record<string, boolean> = {}
  function exclude(excludePath: string): boolean {
    const cached = excludeCache[excludePath]
    if (cached !== undefined) {
      return cached
    }

    const shouldExclude =
      excludePath.includes('node_modules') &&
      !babelIncludeRegexes.some((r) => r.test(excludePath)) &&
      !isResourceInPackages(excludePath, finalTranspilePackages)

    excludeCache[excludePath] = shouldExclude
    return shouldExclude
  }

  const shouldIncludeExternalDirs =
    config.experimental.externalDir || !!config.transpilePackages
  const codeCondition = {
    test: { or: [/\.(tsx|ts|js|cjs|mjs|jsx)$/, /__barrel_optimize__/] },
    ...(shouldIncludeExternalDirs
      ? // Allowing importing TS/TSX files from outside of the root dir.
        {}
      : { include: [dir, ...babelIncludeRegexes] }),
    exclude,
  }

  const babelLoader = getBabelLoader(
    useSWCLoader,
    babelConfigFile,
    isNodeOrEdgeCompilation,
    distDir,
    pagesDir,
    dir,
    (appDir || pagesDir)!,
    dev,
    isClient,
    config.experimental?.reactCompiler,
    codeCondition.exclude
  )

  const reactCompilerLoader = babelLoader
    ? undefined
    : getReactCompilerLoader(
        config.experimental?.reactCompiler,
        dir,
        dev,
        isNodeOrEdgeCompilation,
        codeCondition.exclude
      )

  let swcTraceProfilingInitialized = false
  const getSwcLoader = (extraOptions: Partial<SWCLoaderOptions>) => {
    if (
      config?.experimental?.swcTraceProfiling &&
      !swcTraceProfilingInitialized
    ) {
      // This will init subscribers once only in a single process lifecycle,
      // even though it can be called multiple times.
      // Subscriber need to be initialized _before_ any actual swc's call (transform, etcs)
      // to collect correct trace spans when they are called.
      swcTraceProfilingInitialized = true
      ;(
        require('./swc') as typeof import('./swc')
      )?.initCustomTraceSubscriber?.(
        path.join(distDir, `swc-trace-profile-${Date.now()}.json`)
      )
    }

    const useBuiltinSwcLoader = process.env.BUILTIN_SWC_LOADER
    if (isRspack && useBuiltinSwcLoader) {
      return {
        loader: 'builtin:next-swc-loader',
        options: {
          isServer: isNodeOrEdgeCompilation,
          rootDir: dir,
          pagesDir,
          appDir,
          hasReactRefresh: dev && isClient,
          transpilePackages: finalTranspilePackages,
          supportedBrowsers,
          swcCacheDir: path.join(
            dir,
            config?.distDir ?? '.next',
            'cache',
            'swc'
          ),
          serverReferenceHashSalt: encryptionKey,

          // rspack specific options
          pnp: Boolean(process.versions.pnp),
          optimizeServerReact: Boolean(config.experimental.optimizeServerReact),
          modularizeImports: config.modularizeImports,
          decorators: Boolean(
            jsConfig?.compilerOptions?.experimentalDecorators
          ),
          emitDecoratorMetadata: Boolean(
            jsConfig?.compilerOptions?.emitDecoratorMetadata
          ),
          regeneratorRuntimePath: require.resolve(
            'next/dist/compiled/regenerator-runtime'
          ),

          ...extraOptions,
        },
      }
    }

    return {
      loader: 'next-swc-loader',
      options: {
        isServer: isNodeOrEdgeCompilation,
        compilerType,
        rootDir: dir,
        pagesDir,
        appDir,
        hasReactRefresh: dev && isClient,
        nextConfig: config,
        jsConfig,
        transpilePackages: finalTranspilePackages,
        supportedBrowsers,
        swcCacheDir: path.join(dir, config?.distDir ?? '.next', 'cache', 'swc'),
        serverReferenceHashSalt: encryptionKey,
        ...extraOptions,
      } satisfies SWCLoaderOptions,
    }
  }

  // RSC loaders, prefer ESM, set `esm` to true
  const swcServerLayerLoader = getSwcLoader({
    serverComponents: true,
    bundleLayer: WEBPACK_LAYERS.reactServerComponents,
    esm: true,
  })
  const swcSSRLayerLoader = getSwcLoader({
    serverComponents: true,
    bundleLayer: WEBPACK_LAYERS.serverSideRendering,
    esm: true,
  })
  const swcBrowserLayerLoader = getSwcLoader({
    serverComponents: true,
    bundleLayer: WEBPACK_LAYERS.appPagesBrowser,
    esm: true,
  })
  // Default swc loaders for pages doesn't prefer ESM.
  const swcDefaultLoader = getSwcLoader({
    serverComponents: true,
    esm: false,
  })

  const defaultLoaders = {
    babel: useSWCLoader ? swcDefaultLoader : babelLoader!,
  }

  const appServerLayerLoaders = hasAppDir
    ? [
        // When using Babel, we will have to add the SWC loader
        // as an additional pass to handle RSC correctly.
        // This will cause some performance overhead but
        // acceptable as Babel will not be recommended.
        swcServerLayerLoader,
        babelLoader,
        reactCompilerLoader,
      ].filter(Boolean)
    : []

  const instrumentLayerLoaders = [
    'next-flight-loader',
    // When using Babel, we will have to add the SWC loader
    // as an additional pass to handle RSC correctly.
    // This will cause some performance overhead but
    // acceptable as Babel will not be recommended.
    swcServerLayerLoader,
    babelLoader,
  ].filter(Boolean)

  const middlewareLayerLoaders = [
    'next-flight-loader',
    // When using Babel, we will have to use SWC to do the optimization
    // for middleware to tree shake the unused default optimized imports like "next/server".
    // This will cause some performance overhead but
    // acceptable as Babel will not be recommended.
    getSwcLoader({
      serverComponents: true,
      bundleLayer: WEBPACK_LAYERS.middleware,
    }),
    babelLoader,
  ].filter(Boolean)

  const reactRefreshLoaders = dev && isClient ? [getReactRefreshLoader()] : []

  // client components layers: SSR or browser
  const createClientLayerLoader = ({
    isBrowserLayer,
    reactRefresh,
  }: {
    isBrowserLayer: boolean
    reactRefresh: boolean
  }) => [
    ...(reactRefresh ? reactRefreshLoaders : []),
    {
      // This loader handles actions and client entries
      // in the client layer.
      loader: 'next-flight-client-module-loader',
    },
    ...(hasAppDir
      ? [
          // When using Babel, we will have to add the SWC loader
          // as an additional pass to handle RSC correctly.
          // This will cause some performance overhead but
          // acceptable as Babel will not be recommended.
          isBrowserLayer ? swcBrowserLayerLoader : swcSSRLayerLoader,
          babelLoader,
          reactCompilerLoader,
        ].filter(Boolean)
      : []),
  ]

  const appBrowserLayerLoaders = createClientLayerLoader({
    isBrowserLayer: true,
    // reactRefresh for browser layer is applied conditionally to user-land source
    reactRefresh: false,
  })
  const appSSRLayerLoaders = createClientLayerLoader({
    isBrowserLayer: false,
    reactRefresh: true,
  })

  // Loader for API routes needs to be differently configured as it shouldn't
  // have RSC transpiler enabled, so syntax checks such as invalid imports won't
  // be performed.
  const apiRoutesLayerLoaders = useSWCLoader
    ? getSwcLoader({
        serverComponents: false,
        bundleLayer: WEBPACK_LAYERS.apiNode,
      })
    : defaultLoaders.babel

  const pageExtensions = config.pageExtensions

  const outputPath = isNodeOrEdgeCompilation
    ? path.join(distDir, SERVER_DIRECTORY)
    : distDir

  const reactServerCondition = [
    'react-server',
    ...(isEdgeServer ? edgeConditionNames : []),
    // inherits the default conditions
    '...',
  ]

  const reactRefreshEntry = isRspack
    ? getRspackReactRefresh().entry
    : require.resolve(
        `next/dist/compiled/@next/react-refresh-utils/dist/runtime`
      )

  const clientEntries = isClient
    ? ({
        // Backwards compatibility
        'main.js': [],
        ...(dev
          ? {
              [CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH]: reactRefreshEntry,
              [CLIENT_STATIC_FILES_RUNTIME_AMP]:
                `./` +
                path
                  .relative(
                    dir,
                    path.join(NEXT_PROJECT_ROOT_DIST_CLIENT, 'dev', 'amp-dev')
                  )
                  .replace(/\\/g, '/'),
            }
          : {}),
        [CLIENT_STATIC_FILES_RUNTIME_MAIN]:
          `./` +
          path
            .relative(
              dir,
              path.join(
                NEXT_PROJECT_ROOT_DIST_CLIENT,
                dev ? `next-dev.js` : 'next.js'
              )
            )
            .replace(/\\/g, '/'),
        ...(hasAppDir
          ? {
              [CLIENT_STATIC_FILES_RUNTIME_MAIN_APP]: dev
                ? [
                    reactRefreshEntry,
                    `./` +
                      path
                        .relative(
                          dir,
                          path.join(
                            NEXT_PROJECT_ROOT_DIST_CLIENT,
                            'app-next-dev.js'
                          )
                        )
                        .replace(/\\/g, '/'),
                  ]
                : [
                    `./` +
                      path
                        .relative(
                          dir,
                          path.join(
                            NEXT_PROJECT_ROOT_DIST_CLIENT,
                            'app-next.js'
                          )
                        )
                        .replace(/\\/g, '/'),
                  ],
            }
          : {}),
      } satisfies ClientEntries)
    : undefined

  const resolveConfig: webpack.Configuration['resolve'] = {
    // Disable .mjs for node_modules bundling
    extensions: ['.js', '.mjs', '.tsx', '.ts', '.jsx', '.json', '.wasm'],
    extensionAlias: config.experimental.extensionAlias,
    modules: [
      'node_modules',
      ...nodePathList, // Support for NODE_PATH environment variable
    ],
    alias: createWebpackAliases({
      distDir,
      isClient,
      isEdgeServer,
      dev,
      config,
      pagesDir,
      appDir,
      dir,
      reactProductionProfiling,
    }),
    ...(isClient
      ? {
          fallback: {
            process: require.resolve('./polyfills/process'),
          },
        }
      : undefined),
    // default main fields use pages dir ones, and customize app router ones in loaders.
    mainFields: getMainField(compilerType, false),
    ...(isEdgeServer && {
      conditionNames: edgeConditionNames,
    }),
    plugins: [
      isNodeServer ? new OptionalPeerDependencyResolverPlugin() : undefined,
    ].filter(Boolean) as webpack.ResolvePluginInstance[],
    ...((isRspack && jsConfigPath
      ? {
          // Skip paths that are routed to a .d.ts file
          restrictions: [/^(?!.*\.d\.ts$).*$/],
          tsConfig: {
            configFile: jsConfigPath,
          },
        }
      : {}) as any),
  }

  // Packages which will be split into the 'framework' chunk.
  // Only top-level packages are included, e.g. nested copies like
  // 'node_modules/meow/node_modules/object-assign' are not included.
  const nextFrameworkPaths: string[] = []
  const topLevelFrameworkPaths: string[] = []
  const visitedFrameworkPackages = new Set<string>()
  // Adds package-paths of dependencies recursively
  const addPackagePath = (
    packageName: string,
    relativeToPath: string,
    paths: string[]
  ) => {
    try {
      if (visitedFrameworkPackages.has(packageName)) {
        return
      }
      visitedFrameworkPackages.add(packageName)

      const packageJsonPath = require.resolve(`${packageName}/package.json`, {
        paths: [relativeToPath],
      })

      // Include a trailing slash so that a `.startsWith(packagePath)` check avoids false positives
      // when one package name starts with the full name of a different package.
      // For example:
      //   "node_modules/react-slider".startsWith("node_modules/react")  // true
      //   "node_modules/react-slider".startsWith("node_modules/react/") // false
      const directory = path.join(packageJsonPath, '../')

      // Returning from the function in case the directory has already been added and traversed
      if (paths.includes(directory)) return
      paths.push(directory)
      const dependencies = require(packageJsonPath).dependencies || {}
      for (const name of Object.keys(dependencies)) {
        addPackagePath(name, directory, paths)
      }
    } catch (_) {
      // don't error on failing to resolve framework packages
    }
  }

  for (const packageName of [
    'react',
    'react-dom',
    ...(hasAppDir
      ? [
          `next/dist/compiled/react${bundledReactChannel}`,
          `next/dist/compiled/react-dom${bundledReactChannel}`,
        ]
      : []),
  ]) {
    addPackagePath(packageName, dir, topLevelFrameworkPaths)
  }
  addPackagePath('next', dir, nextFrameworkPaths)

  const crossOrigin = config.crossOrigin

  // The `serverExternalPackages` should not conflict with
  // the `transpilePackages`.
  if (config.serverExternalPackages && finalTranspilePackages) {
    const externalPackageConflicts = finalTranspilePackages.filter((pkg) =>
      config.serverExternalPackages?.includes(pkg)
    )
    if (externalPackageConflicts.length > 0) {
      throw new Error(
        `The packages specified in the 'transpilePackages' conflict with the 'serverExternalPackages': ${externalPackageConflicts.join(
          ', '
        )}`
      )
    }
  }

  // For original request, such as `package name`
  const optOutBundlingPackages = EXTERNAL_PACKAGES.concat(
    ...(config.serverExternalPackages || [])
  ).filter((pkg) => !finalTranspilePackages?.includes(pkg))
  // For resolved request, such as `absolute path/package name/foo/bar.js`
  const optOutBundlingPackageRegex = new RegExp(
    `[/\\\\]node_modules[/\\\\](${optOutBundlingPackages
      .map((p) => p.replace(/\//g, '[/\\\\]'))
      .join('|')})[/\\\\]`
  )

  const transpilePackagesRegex = new RegExp(
    `[/\\\\]node_modules[/\\\\](${finalTranspilePackages
      ?.map((p) => p.replace(/\//g, '[/\\\\]'))
      .join('|')})[/\\\\]`
  )

  const handleExternals = makeExternalHandler({
    config,
    optOutBundlingPackageRegex,
    transpiledPackages: finalTranspilePackages,
    dir,
  })

  const pageExtensionsRegex = new RegExp(`\\.(${pageExtensions.join('|')})$`)

  const aliasCodeConditionTest = [codeCondition.test, pageExtensionsRegex]

  const builtinModules = (require('module') as typeof import('module'))
    .builtinModules

  const shouldEnableSlowModuleDetection =
    !!config.experimental.slowModuleDetection && dev

  const getParallelism = () => {
    const override = Number(process.env.NEXT_WEBPACK_PARALLELISM)
    if (shouldEnableSlowModuleDetection) {
      if (override) {
        console.warn(
          'NEXT_WEBPACK_PARALLELISM is specified but will be ignored due to experimental.slowModuleDetection being enabled.'
        )
      }
      return 1
    }
    return override || undefined
  }

  const telemetryPlugin =
    !dev &&
    isClient &&
    new (
      require('./webpack/plugins/telemetry-plugin/telemetry-plugin') as typeof import('./webpack/plugins/telemetry-plugin/telemetry-plugin')
    ).TelemetryPlugin(
      new Map(
        [
          ['swcLoader', useSWCLoader],
          ['swcRelay', !!config.compiler?.relay],
          ['swcStyledComponents', !!config.compiler?.styledComponents],
          [
            'swcReactRemoveProperties',
            !!config.compiler?.reactRemoveProperties,
          ],
          [
            'swcExperimentalDecorators',
            !!jsConfig?.compilerOptions?.experimentalDecorators,
          ],
          ['swcRemoveConsole', !!config.compiler?.removeConsole],
          ['swcImportSource', !!jsConfig?.compilerOptions?.jsxImportSource],
          ['swcEmotion', !!config.compiler?.emotion],
          ['transpilePackages', !!config.transpilePackages],
          ['skipMiddlewareUrlNormalize', !!config.skipMiddlewareUrlNormalize],
          ['skipTrailingSlashRedirect', !!config.skipTrailingSlashRedirect],
          ['modularizeImports', !!config.modularizeImports],
          // If esmExternals is not same as default value, it represents customized usage
          ['esmExternals', config.experimental.esmExternals !== true],
          SWCBinaryTarget,
        ].filter<[Feature, boolean]>(Boolean as any)
      )
    )

  let webpackConfig: webpack.Configuration = {
    parallelism: getParallelism(),
    ...(isNodeServer ? { externalsPresets: { node: true } } : {}),
    // @ts-ignore
    externals:
      isClient || isEdgeServer
        ? // make sure importing "next" is handled gracefully for client
          // bundles in case a user imported types and it wasn't removed
          // TODO: should we warn/error for this instead?
          [
            'next',
            ...(isEdgeServer
              ? [
                  {
                    '@builder.io/partytown': '{}',
                    'next/dist/compiled/etag': '{}',
                  },
                  getEdgePolyfilledModules(),
                  handleWebpackExternalForEdgeRuntime,
                ]
              : []),
          ]
        : [
            ...builtinModules,
            ({
              context,
              request,
              dependencyType,
              contextInfo,
              getResolve,
            }: {
              context: string
              request: string
              dependencyType: string
              contextInfo: {
                issuer: string
                issuerLayer: string | null
                compiler: string
              }
              getResolve: (
                options: any
              ) => (
                resolveContext: string,
                resolveRequest: string,
                callback: (
                  err?: Error,
                  result?: string,
                  resolveData?: { descriptionFileData?: { type?: any } }
                ) => void
              ) => void
            }) =>
              handleExternals(
                context,
                request,
                dependencyType,
                contextInfo.issuerLayer as WebpackLayerName,
                (options) => {
                  const resolveFunction = getResolve(options)
                  return (resolveContext: string, requestToResolve: string) =>
                    new Promise((resolve, reject) => {
                      resolveFunction(
                        resolveContext,
                        requestToResolve,
                        (err, result, resolveData) => {
                          if (err) return reject(err)
                          if (!result) return resolve([null, false])
                          const isEsm = /\.js$/i.test(result)
                            ? resolveData?.descriptionFileData?.type ===
                              'module'
                            : /\.mjs$/i.test(result)
                          resolve([result, isEsm])
                        }
                      )
                    })
                }
              ),
          ],

    optimization: {
      emitOnErrors: !dev,
      checkWasmTypes: false,
      nodeEnv: false,

      splitChunks: (():
        | Required<webpack.Configuration>['optimization']['splitChunks']
        | false => {
        // server chunking
        if (dev) {
          if (isNodeServer) {
            /*
              In development, we want to split code that comes from `node_modules` into their own chunks.
              This is because in development, we often need to reload the user bundle due to changes in the code.
              To work around this, we put all the vendor code into separate chunks so that we don't need to reload them.
              This is safe because the vendor code doesn't change between reloads.
            */
            const extractRootNodeModule = (modulePath: string) => {
              // This regex is used to extract the root node module name to be used as the chunk group name.
              // example: ../../node_modules/.pnpm/next@10/foo/node_modules/bar -> next@10
              const regex =
                /node_modules(?:\/|\\)\.?(?:pnpm(?:\/|\\))?([^/\\]+)/
              const match = modulePath.match(regex)
              return match ? match[1] : null
            }
            return {
              cacheGroups: {
                // this chunk configuration gives us a separate chunk for each top level module in node_modules
                // or a hashed chunk if we can't extract the module name.
                vendor: {
                  chunks: 'all',
                  reuseExistingChunk: true,
                  test: /[\\/]node_modules[\\/]/,
                  minSize: 0,
                  minChunks: 1,
                  maxAsyncRequests: 300,
                  maxInitialRequests: 300,
                  name: (module: webpack.Module) => {
                    const moduleId = module.nameForCondition()!
                    const rootModule = extractRootNodeModule(moduleId)
                    if (rootModule) {
                      return `vendor-chunks/${rootModule}`
                    } else {
                      const hash = crypto.createHash('sha1').update(moduleId)
                      hash.update(moduleId)
                      return `vendor-chunks/${hash.digest('hex')}`
                    }
                  },
                },
                // disable the default chunk groups
                default: false,
                defaultVendors: false,
              },
            }
          }

          return false
        }

        if (isNodeServer || isEdgeServer) {
          return {
            filename: `${isEdgeServer ? `edge-chunks/` : ''}[name].js`,
            chunks: 'all',
            minChunks: 2,
          }
        }

        const frameworkCacheGroup = {
          chunks: 'all' as const,
          name: 'framework',
          // Ensures the framework chunk is not created for App Router.
          layer: isWebpackDefaultLayer,
          test(module: any) {
            const resource = module.nameForCondition?.()
            return resource
              ? topLevelFrameworkPaths.some((pkgPath) =>
                  resource.startsWith(pkgPath)
                )
              : false
          },
          priority: 40,
          // Don't let webpack eliminate this chunk (prevents this chunk from
          // becoming a part of the commons chunk)
          enforce: true,
        }

        const libCacheGroup = {
          test(module: {
            type: string
            size: Function
            nameForCondition: Function
          }): boolean {
            return (
              !module.type?.startsWith('css') &&
              module.size() > 160000 &&
              /node_modules[/\\]/.test(module.nameForCondition() || '')
            )
          },
          name(module: {
            layer: string | null | undefined
            type: string
            libIdent?: Function
            updateHash: (hash: crypto.Hash) => void
          }): string {
            const hash = crypto.createHash('sha1')
            if (isModuleCSS(module)) {
              module.updateHash(hash)
            } else {
              if (!module.libIdent) {
                throw new Error(
                  `Encountered unknown module type: ${module.type}. Please open an issue.`
                )
              }
              hash.update(module.libIdent({ context: dir }))
            }

            // Ensures the name of the chunk is not the same between two modules in different layers
            // E.g. if you import 'button-library' in App Router and Pages Router we don't want these to be bundled in the same chunk
            // as they're never used on the same page.
            if (module.layer) {
              hash.update(module.layer)
            }

            return hash.digest('hex').substring(0, 8)
          },
          priority: 30,
          minChunks: 1,
          reuseExistingChunk: true,
        }

        // client chunking
        return {
          // Keep main and _app chunks unsplitted in webpack 5
          // as we don't need a separate vendor chunk from that
          // and all other chunk depend on them so there is no
          // duplication that need to be pulled out.
          chunks: isRspack
            ? // using a function here causes noticable slowdown
              // in rspack
              /(?!polyfills|main|pages\/_app)/
            : (chunk: any) =>
                !/^(polyfills|main|pages\/_app)$/.test(chunk.name),

          cacheGroups: isRspack
            ? {
                framework: {
                  chunks: 'all' as const,
                  name: 'framework',
                  layer: RSPACK_DEFAULT_LAYERS_REGEX,
                  test: /[/]node_modules[/](react|react-dom|next[/]dist[/]compiled[/](react|react-dom)(-experimental)?)[/]/,
                  priority: 40,
                  enforce: true,
                },
                lib: {
                  test: /[/]node_modules[/](?!.*\.(css|scss|sass|less|styl)$)/,
                  name: 'lib',
                  chunks: 'all',
                  priority: 30,
                  minChunks: 1,
                  reuseExistingChunk: true,
                },
              }
            : {
                framework: frameworkCacheGroup,
                lib: libCacheGroup,
              },
          maxInitialRequests: 25,
          minSize: 20000,
        }
      })(),
      runtimeChunk: isClient
        ? { name: CLIENT_STATIC_FILES_RUNTIME_WEBPACK }
        : undefined,

      minimize:
        !dev &&
        (isClient ||
          isEdgeServer ||
          (isNodeServer && config.experimental.serverMinification)),
      minimizer: [
        // Minify JavaScript
        isRspack
          ? new (getRspackCore().SwcJsMinimizerRspackPlugin)({
              // JS minimizer configuration
              // options should align with crates/napi/src/minify.rs#patch_opts
              minimizerOptions: {
                compress: {
                  inline: 2,
                  global_defs: {
                    'process.env.__NEXT_PRIVATE_MINIMIZE_MACRO_FALSE': false,
                  },
                },
                mangle: !noMangling && {
                  reserved: ['AbortSignal'],
                  disableCharFreq: !isClient,
                },
              },
            })
          : (compiler: webpack.Compiler) => {
              // @ts-ignore No typings yet
              const { MinifyPlugin } =
                require('./webpack/plugins/minify-webpack-plugin/src') as typeof import('./webpack/plugins/minify-webpack-plugin/src')
              new MinifyPlugin({
                noMangling,
                disableCharFreq: !isClient,
              }).apply(compiler)
            },
        // Minify CSS
        // By default, Rspack uses LightningCSS for CSS minification.
        // Rspack uses css-minimizer-plugin by default for compatibility.
        isRspack &&
        (process.env.__NEXT_TEST_MODE
          ? config.experimental.useLightningcss
          : config.experimental?.useLightningcss === undefined ||
            config.experimental.useLightningcss)
          ? new (getRspackCore().LightningCssMinimizerRspackPlugin)({
              // CSS minimizer configuration
              minimizerOptions: {
                targets: supportedBrowsers,
              },
            })
          : (compiler: webpack.Compiler) => {
              const { CssMinimizerPlugin } =
                require('./webpack/plugins/css-minimizer-plugin') as typeof import('./webpack/plugins/css-minimizer-plugin')
              new CssMinimizerPlugin({
                postcssOptions: {
                  map: {
                    // `inline: false` generates the source map in a separate file.
                    // Otherwise, the CSS file is needlessly large.
                    inline: false,
                    // `annotation: false` skips appending the `sourceMappingURL`
                    // to the end of the CSS file. Webpack already handles this.
                    annotation: false,
                  },
                },
              }).apply(compiler)
            },
      ],
    },
    context: dir,
    // Kept as function to be backwards compatible
    entry: async () => {
      return {
        ...(clientEntries ? clientEntries : {}),
        ...entrypoints,
      }
    },
    watchOptions: Object.freeze({
      ...baseWatchOptions,
      poll: config.watchOptions?.pollIntervalMs,
    }),
    output: {
      // we must set publicPath to an empty value to override the default of
      // auto which doesn't work in IE11
      publicPath: `${
        config.assetPrefix
          ? config.assetPrefix.endsWith('/')
            ? config.assetPrefix.slice(0, -1)
            : config.assetPrefix
          : ''
      }/_next/`,
      path: !dev && isNodeServer ? path.join(outputPath, 'chunks') : outputPath,
      // On the server we don't use hashes
      filename: isNodeOrEdgeCompilation
        ? dev || isEdgeServer
          ? `[name].js`
          : `../[name].js`
        : `static/chunks/${isDevFallback ? 'fallback/' : ''}[name]${
            dev ? '' : '-[contenthash]'
          }.js`,
      library: isClient || isEdgeServer ? '_N_E' : undefined,
      libraryTarget: isClient || isEdgeServer ? 'assign' : 'commonjs2',
      hotUpdateChunkFilename: 'static/webpack/[id].[fullhash].hot-update.js',
      hotUpdateMainFilename:
        'static/webpack/[fullhash].[runtime].hot-update.json',
      // This saves chunks with the name given via `import()`
      chunkFilename: isNodeOrEdgeCompilation
        ? '[name].js'
        : `static/chunks/${isDevFallback ? 'fallback/' : ''}${
            dev ? '[name]' : '[name].[contenthash]'
          }.js`,
      strictModuleExceptionHandling: true,
      crossOriginLoading: crossOrigin,
      // if `sources[number]` is not an absolute path, it's is resolved
      // relative to the location of the source map file (https://tc39.es/source-map/#resolving-sources).
      // However, Webpack's `resource-path` is relative to the app dir.
      // TODO: Either `sourceRoot` should be populated with the root and then we can use `[resource-path]`
      // or we need a way to resolve return `path.relative(sourceMapLocation, info.resourcePath)`
      devtoolModuleFilenameTemplate: dev
        ? '[absolute-resource-path]'
        : undefined,
      webassemblyModuleFilename: 'static/wasm/[modulehash].wasm',
      hashFunction: 'xxhash64',
      hashDigestLength: 16,
    },
    performance: false,
    resolve: resolveConfig,
    resolveLoader: {
      // The loaders Next.js provides
      alias: [
        'error-loader',
        'next-swc-loader',
        'next-client-pages-loader',
        'next-image-loader',
        'next-metadata-image-loader',
        'next-style-loader',
        'next-flight-loader',
        'next-flight-client-entry-loader',
        'next-flight-action-entry-loader',
        'next-flight-client-module-loader',
        'next-flight-server-reference-proxy-loader',
        'empty-loader',
        'next-middleware-loader',
        'next-edge-function-loader',
        'next-edge-app-route-loader',
        'next-edge-ssr-loader',
        'next-middleware-asset-loader',
        'next-middleware-wasm-loader',
        'next-app-loader',
        'next-route-loader',
        'next-font-loader',
        'next-invalid-import-error-loader',
        'next-metadata-route-loader',
        'modularize-import-loader',
        'next-barrel-loader',
        'next-error-browser-binary-loader',
      ].reduce(
        (alias, loader) => {
          // using multiple aliases to replace `resolveLoader.modules`
          alias[loader] = path.join(__dirname, 'webpack', 'loaders', loader)

          return alias
        },
        {} as Record<string, string>
      ),
      modules: [
        'node_modules',
        ...nodePathList, // Support for NODE_PATH environment variable
      ],
      plugins: [],
    },
    module: {
      rules: [
        // Alias server-only and client-only to proper exports based on bundling layers
        {
          issuerLayer: {
            or: [
              ...WEBPACK_LAYERS.GROUP.serverOnly,
              ...WEBPACK_LAYERS.GROUP.neutralTarget,
            ],
          },
          resolve: {
            // Error on client-only but allow server-only
            alias: createServerOnlyClientOnlyAliases(true),
          },
        },
        {
          issuerLayer: {
            not: [
              ...WEBPACK_LAYERS.GROUP.serverOnly,
              ...WEBPACK_LAYERS.GROUP.neutralTarget,
            ],
          },
          resolve: {
            // Error on server-only but allow client-only
            alias: createServerOnlyClientOnlyAliases(false),
          },
        },
        // Detect server-only / client-only imports and error in build time
        {
          test: [
            /^client-only$/,
            /next[\\/]dist[\\/]compiled[\\/]client-only[\\/]error/,
          ],
          loader: 'next-invalid-import-error-loader',
          issuerLayer: {
            or: WEBPACK_LAYERS.GROUP.serverOnly,
          },
          options: {
            message:
              "'client-only' cannot be imported from a Server Component module. It should only be used from a Client Component.",
          },
        },
        {
          test: [
            /^server-only$/,
            /next[\\/]dist[\\/]compiled[\\/]server-only[\\/]index/,
          ],
          loader: 'next-invalid-import-error-loader',
          issuerLayer: {
            not: [
              ...WEBPACK_LAYERS.GROUP.serverOnly,
              ...WEBPACK_LAYERS.GROUP.neutralTarget,
            ],
          },
          options: {
            message:
              "'server-only' cannot be imported from a Client Component module. It should only be used from a Server Component.",
          },
        },
        // Potential the bundle introduced into middleware and api can be poisoned by client-only
        // but not being used, so we disabled the `client-only` erroring on these layers.
        // `server-only` is still available.
        {
          test: [
            /^client-only$/,
            /next[\\/]dist[\\/]compiled[\\/]client-only[\\/]error/,
          ],
          loader: 'empty-loader',
          issuerLayer: {
            or: WEBPACK_LAYERS.GROUP.neutralTarget,
          },
        },
        ...(isNodeServer
          ? []
          : [
              {
                test: /[\\/].*?\.node$/,
                loader: 'next-error-browser-binary-loader',
              },
            ]),
        ...(hasAppDir
          ? [
              {
                // Make sure that AsyncLocalStorage module instance is shared between server and client
                // layers.
                layer: WEBPACK_LAYERS.shared,
                test: asyncStoragesRegex,
              },
              // Convert metadata routes to separate layer
              {
                resourceQuery: new RegExp(
                  WEBPACK_RESOURCE_QUERIES.metadataRoute
                ),
                layer: WEBPACK_LAYERS.reactServerComponents,
              },
              {
                // Ensure that the app page module is in the client layers, this
                // enables React to work correctly for RSC.
                layer: WEBPACK_LAYERS.serverSideRendering,
                test: /next[\\/]dist[\\/](esm[\\/])?server[\\/]route-modules[\\/]app-page[\\/]module/,
              },
              {
                issuerLayer: isWebpackBundledLayer,
                resolve: {
                  alias: createNextApiEsmAliases(),
                },
              },
              {
                issuerLayer: shouldUseReactServerCondition,
                resolve: {
                  alias: createAppRouterApiAliases(true),
                },
              },
              {
                issuerLayer: isWebpackClientOnlyLayer,
                resolve: {
                  alias: createAppRouterApiAliases(false),
                },
              },
            ]
          : []),
        ...(hasAppDir && !isClient
          ? [
              {
                issuerLayer: shouldUseReactServerCondition,
                test: {
                  // Resolve it if it is a source code file, and it has NOT been
                  // opted out of bundling.
                  and: [
                    aliasCodeConditionTest,
                    {
                      not: [optOutBundlingPackageRegex, asyncStoragesRegex],
                    },
                  ],
                },
                resourceQuery: {
                  // Do not apply next-flight-loader to imports generated by the
                  // next-metadata-image-loader, to avoid generating unnecessary
                  // and conflicting entries in the flight client entry plugin.
                  // These are already covered by the next-metadata-route-loader
                  // entries.
                  not: [
                    new RegExp(WEBPACK_RESOURCE_QUERIES.metadata),
                    new RegExp(WEBPACK_RESOURCE_QUERIES.metadataImageMeta),
                  ],
                },
                resolve: {
                  mainFields: getMainField(compilerType, true),
                  conditionNames: reactServerCondition,
                  // If missing the alias override here, the default alias will be used which aliases
                  // react to the direct file path, not the package name. In that case the condition
                  // will be ignored completely.
                  alias: createVendoredReactAliases(bundledReactChannel, {
                    // No server components profiling
                    reactProductionProfiling,
                    layer: WEBPACK_LAYERS.reactServerComponents,
                    isBrowser: isClient,
                    isEdgeServer,
                  }),
                },
                use: 'next-flight-loader',
              },
            ]
          : []),
        // TODO: FIXME: do NOT webpack 5 support with this
        // x-ref: https://github.com/webpack/webpack/issues/11467
        ...(!config.experimental.fullySpecified
          ? [
              {
                test: /\.m?js/,
                resolve: {
                  fullySpecified: false,
                },
              } as any,
            ]
          : []),
        ...(hasAppDir && isEdgeServer
          ? [
              // The Edge bundle includes the server in its entrypoint, so it has to
              // be in the SSR layer — here we convert the actual page request to
              // the RSC layer via a webpack rule.
              {
                resourceQuery: new RegExp(
                  WEBPACK_RESOURCE_QUERIES.edgeSSREntry
                ),
                layer: WEBPACK_LAYERS.reactServerComponents,
              },
            ]
          : []),
        ...(hasAppDir
          ? [
              {
                // Alias react-dom for ReactDOM.preload usage.
                // Alias react for switching between default set and share subset.
                oneOf: [
                  {
                    issuerLayer: shouldUseReactServerCondition,
                    test: {
                      // Resolve it if it is a source code file, and it has NOT been
                      // opted out of bundling.
                      and: [
                        aliasCodeConditionTest,
                        {
                          not: [optOutBundlingPackageRegex, asyncStoragesRegex],
                        },
                      ],
                    },
                    resolve: {
                      // It needs `conditionNames` here to require the proper asset,
                      // when react is acting as dependency of compiled/react-dom.
                      alias: createVendoredReactAliases(bundledReactChannel, {
                        reactProductionProfiling,
                        layer: WEBPACK_LAYERS.reactServerComponents,
                        isBrowser: isClient,
                        isEdgeServer,
                      }),
                    },
                  },
                  {
                    test: aliasCodeConditionTest,
                    issuerLayer: WEBPACK_LAYERS.serverSideRendering,
                    resolve: {
                      alias: createVendoredReactAliases(bundledReactChannel, {
                        reactProductionProfiling,
                        layer: WEBPACK_LAYERS.serverSideRendering,
                        isBrowser: isClient,
                        isEdgeServer,
                      }),
                    },
                  },
                ],
              },
              {
                test: aliasCodeConditionTest,
                issuerLayer: WEBPACK_LAYERS.appPagesBrowser,
                resolve: {
                  alias: createVendoredReactAliases(bundledReactChannel, {
                    reactProductionProfiling,
                    layer: WEBPACK_LAYERS.appPagesBrowser,
                    isBrowser: isClient,
                    isEdgeServer,
                  }),
                },
              },
            ]
          : []),
        // Do not apply react-refresh-loader to node_modules for app router browser layer
        ...(hasAppDir && dev && isClient
          ? [
              {
                test: codeCondition.test,
                exclude: [
                  // exclude unchanged modules from react-refresh
                  codeCondition.exclude,
                  transpilePackagesRegex,
                  precompileRegex,
                ],
                issuerLayer: WEBPACK_LAYERS.appPagesBrowser,
                use: reactRefreshLoaders,
                resolve: {
                  mainFields: getMainField(compilerType, true),
                },
              },
            ]
          : []),
        {
          oneOf: [
            {
              ...codeCondition,
              issuerLayer: WEBPACK_LAYERS.apiNode,
              use: apiRoutesLayerLoaders,
              // In Node.js, switch back to normal URL handling.
              // We won't bundle `new URL()` cases in Node.js bundler layer.
              parser: {
                url: true,
              },
            },
            {
              ...codeCondition,
              issuerLayer: WEBPACK_LAYERS.apiEdge,
              use: apiRoutesLayerLoaders,
              // In Edge runtime, we leave the url handling by default.
              // The new URL assets will be converted into edge assets through assets loader.
            },
            {
              test: codeCondition.test,
              issuerLayer: WEBPACK_LAYERS.middleware,
              use: middlewareLayerLoaders,
              resolve: {
                mainFields: getMainField(compilerType, true),
                conditionNames: reactServerCondition,
                alias: createVendoredReactAliases(bundledReactChannel, {
                  reactProductionProfiling,
                  layer: WEBPACK_LAYERS.middleware,
                  isBrowser: isClient,
                  isEdgeServer,
                }),
              },
            },
            {
              test: codeCondition.test,
              issuerLayer: WEBPACK_LAYERS.instrument,
              use: instrumentLayerLoaders,
              resolve: {
                mainFields: getMainField(compilerType, true),
                conditionNames: reactServerCondition,
                alias: createVendoredReactAliases(bundledReactChannel, {
                  reactProductionProfiling,
                  layer: WEBPACK_LAYERS.instrument,
                  isBrowser: isClient,
                  isEdgeServer,
                }),
              },
            },
            ...(hasAppDir
              ? [
                  {
                    test: codeCondition.test,
                    issuerLayer: shouldUseReactServerCondition,
                    exclude: asyncStoragesRegex,
                    use: appServerLayerLoaders,
                  },
                  {
                    test: codeCondition.test,
                    resourceQuery: new RegExp(
                      WEBPACK_RESOURCE_QUERIES.edgeSSREntry
                    ),
                    use: appServerLayerLoaders,
                  },
                  {
                    test: codeCondition.test,
                    issuerLayer: WEBPACK_LAYERS.appPagesBrowser,
                    // Exclude the transpilation of the app layer due to compilation issues
                    exclude: browserNonTranspileModules,
                    use: appBrowserLayerLoaders,
                    resolve: {
                      mainFields: getMainField(compilerType, true),
                    },
                  },
                  {
                    test: codeCondition.test,
                    issuerLayer: WEBPACK_LAYERS.serverSideRendering,
                    exclude: asyncStoragesRegex,
                    use: appSSRLayerLoaders,
                    resolve: {
                      mainFields: getMainField(compilerType, true),
                    },
                  },
                ]
              : []),
            {
              ...codeCondition,
              use: [
                ...reactRefreshLoaders,
                defaultLoaders.babel,
                reactCompilerLoader,
              ].filter(Boolean),
            },
          ],
        },

        ...(!config.images.disableStaticImages
          ? [
              {
                test: nextImageLoaderRegex,
                loader: 'next-image-loader',
                issuer: { not: regexLikeCss },
                dependency: { not: ['url'] },
                resourceQuery: {
                  not: [
                    new RegExp(WEBPACK_RESOURCE_QUERIES.metadata),
                    new RegExp(WEBPACK_RESOURCE_QUERIES.metadataRoute),
                    new RegExp(WEBPACK_RESOURCE_QUERIES.metadataImageMeta),
                  ],
                },
                options: {
                  isDev: dev,
                  compilerType,
                  basePath: config.basePath,
                  assetPrefix: config.assetPrefix,
                },
              },
            ]
          : []),
        ...(isEdgeServer
          ? [
              {
                resolve: {
                  fallback: {
                    process: require.resolve('./polyfills/process'),
                  },
                },
              },
            ]
          : isClient
            ? [
                {
                  resolve: {
                    fallback:
                      config.experimental.fallbackNodePolyfills === false
                        ? {
                            assert: false,
                            buffer: false,
                            constants: false,
                            crypto: false,
                            domain: false,
                            http: false,
                            https: false,
                            os: false,
                            path: false,
                            punycode: false,
                            process: false,
                            querystring: false,
                            stream: false,
                            string_decoder: false,
                            sys: false,
                            timers: false,
                            tty: false,
                            util: false,
                            vm: false,
                            zlib: false,
                            events: false,
                            setImmediate: false,
                          }
                        : {
                            assert: require.resolve(
                              'next/dist/compiled/assert'
                            ),
                            buffer: require.resolve(
                              'next/dist/compiled/buffer'
                            ),
                            constants: require.resolve(
                              'next/dist/compiled/constants-browserify'
                            ),
                            crypto: require.resolve(
                              'next/dist/compiled/crypto-browserify'
                            ),
                            domain: require.resolve(
                              'next/dist/compiled/domain-browser'
                            ),
                            http: require.resolve(
                              'next/dist/compiled/stream-http'
                            ),
                            https: require.resolve(
                              'next/dist/compiled/https-browserify'
                            ),
                            os: require.resolve(
                              'next/dist/compiled/os-browserify'
                            ),
                            path: require.resolve(
                              'next/dist/compiled/path-browserify'
                            ),
                            punycode: require.resolve(
                              'next/dist/compiled/punycode'
                            ),
                            process: require.resolve('./polyfills/process'),
                            // Handled in separate alias
                            querystring: require.resolve(
                              'next/dist/compiled/querystring-es3'
                            ),
                            stream: require.resolve(
                              'next/dist/compiled/stream-browserify'
                            ),
                            string_decoder: require.resolve(
                              'next/dist/compiled/string_decoder'
                            ),
                            sys: require.resolve('next/dist/compiled/util'),
                            timers: require.resolve(
                              'next/dist/compiled/timers-browserify'
                            ),
                            tty: require.resolve(
                              'next/dist/compiled/tty-browserify'
                            ),
                            // Handled in separate alias
                            // url: require.resolve('url'),
                            util: require.resolve('next/dist/compiled/util'),
                            vm: require.resolve(
                              'next/dist/compiled/vm-browserify'
                            ),
                            zlib: require.resolve(
                              'next/dist/compiled/browserify-zlib'
                            ),
                            events: require.resolve(
                              'next/dist/compiled/events'
                            ),
                            setImmediate: require.resolve(
                              'next/dist/compiled/setimmediate'
                            ),
                          },
                  },
                },
              ]
            : []),
        {
          // Mark `image-response.js` as side-effects free to make sure we can
          // tree-shake it if not used.
          test: /[\\/]next[\\/]dist[\\/](esm[\\/])?server[\\/]og[\\/]image-response\.js/,
          sideEffects: false,
        },
        // Mark the action-client-wrapper module as side-effects free to make sure
        // the individual transformed module of client action can be tree-shaken.
        // This will make modules processed by `next-flight-server-reference-proxy-loader` become side-effects free,
        // then on client side the module ids will become tree-shakable.
        // e.g. the output of client action module will look like:
        // `export { a } from 'next-flight-server-reference-proxy-loader?id=idOfA&name=a!
        // `export { b } from 'next-flight-server-reference-proxy-loader?id=idOfB&name=b!
        {
          test: /[\\/]next[\\/]dist[\\/](esm[\\/])?build[\\/]webpack[\\/]loaders[\\/]next-flight-loader[\\/]action-client-wrapper\.js/,
          sideEffects: false,
        },
        {
          // This loader rule should be before other rules, as it can output code
          // that still contains `"use client"` or `"use server"` statements that
          // needs to be re-transformed by the RSC compilers.
          // This loader rule works like a bridge between user's import and
          // the target module behind a package's barrel file. It reads SWC's
          // analysis result from the previous loader, and directly returns the
          // code that only exports values that are asked by the user.
          test: /__barrel_optimize__/,
          use: ({ resourceQuery }: { resourceQuery: string }) => {
            const names = (
              resourceQuery.match(/\?names=([^&]+)/)?.[1] || ''
            ).split(',')

            return [
              {
                loader: 'next-barrel-loader',
                options: {
                  names,
                  swcCacheDir: path.join(
                    dir,
                    config?.distDir ?? '.next',
                    'cache',
                    'swc'
                  ),
                },
                // This is part of the request value to serve as the module key.
                // The barrel loader are no-op re-exported modules keyed by
                // export names.
                ident: 'next-barrel-loader:' + resourceQuery,
              },
            ]
          },
        },
        {
          resolve: {
            alias: {
              next: NEXT_PROJECT_ROOT,
            },
          },
        },
      ],
    },
    plugins: [
      isNodeServer &&
        new bundler.NormalModuleReplacementPlugin(
          /\.\/(.+)\.shared-runtime$/,
          function (resource) {
            const moduleName = path.basename(
              resource.request,
              '.shared-runtime'
            )
            const layer = resource.contextInfo.issuerLayer
            let runtime

            switch (layer) {
              case WEBPACK_LAYERS.serverSideRendering:
              case WEBPACK_LAYERS.reactServerComponents:
              case WEBPACK_LAYERS.appPagesBrowser:
              case WEBPACK_LAYERS.actionBrowser:
                runtime = 'app-page'
                break
              case null:
              case undefined:
              default:
                runtime = 'pages'
            }
            resource.request = `next/dist/server/route-modules/${runtime}/vendored/contexts/${moduleName}`
          }
        ),
      dev && new MemoryWithGcCachePlugin({ maxGenerations: 5 }),
      dev &&
        isClient &&
        (isRspack
          ? // eslint-disable-next-line
            new (getRspackReactRefresh() as any)({
              injectLoader: false,
              injectEntry: false,
              overlay: false,
            })
          : new ReactRefreshWebpackPlugin(webpack)),
      // Makes sure `Buffer` and `process` are polyfilled in client and flight bundles (same behavior as webpack 4)
      (isClient || isEdgeServer) &&
        new bundler.ProvidePlugin({
          // Buffer is used by getInlineScriptSource
          Buffer: [require.resolve('buffer'), 'Buffer'],
          // Avoid process being overridden when in web run time
          ...(isClient && { process: [require.resolve('process')] }),
        }),

      new (getWebpackBundler().DefinePlugin)(
        getDefineEnv({
          isTurbopack: false,
          config,
          dev,
          distDir,
          projectPath: dir,
          fetchCacheKeyPrefix,
          hasRewrites,
          isClient,
          isEdgeServer,
          isNodeServer,
          middlewareMatchers,
          omitNonDeterministic: isCompileMode,
          rewrites,
        })
      ),
      isClient &&
        new ReactLoadablePlugin({
          filename: REACT_LOADABLE_MANIFEST,
          pagesDir,
          appDir,
          runtimeAsset: `server/${MIDDLEWARE_REACT_LOADABLE_MANIFEST}.js`,
          dev,
        }),
      // rspack doesn't support the parser hooks used here
      !isRspack && (isClient || isEdgeServer) && new DropClientPage(),
      isNodeServer &&
        !dev &&
        new ((
          require('./webpack/plugins/next-trace-entrypoints-plugin') as typeof import('./webpack/plugins/next-trace-entrypoints-plugin')
        )
          .TraceEntryPointsPlugin as typeof import('./webpack/plugins/next-trace-entrypoints-plugin').TraceEntryPointsPlugin)(
          {
            rootDir: dir,
            appDir: appDir,
            pagesDir: pagesDir,
            esmExternals: config.experimental.esmExternals,
            outputFileTracingRoot: config.outputFileTracingRoot,
            appDirEnabled: hasAppDir,
            traceIgnores: [],
            compilerType,
            swcLoaderConfig: swcDefaultLoader,
          }
        ),
      // Moment.js is an extremely popular library that bundles large locale files
      // by default due to how Webpack interprets its code. This is a practical
      // solution that requires the user to opt into importing specific locales.
      // https://github.com/jmblog/how-to-optimize-momentjs-with-webpack
      config.excludeDefaultMomentLocales &&
        new bundler.IgnorePlugin({
          resourceRegExp: /^\.\/locale$/,
          contextRegExp: /moment$/,
        }),
      ...(dev
        ? (() => {
            // Even though require.cache is server only we have to clear assets from both compilations
            // This is because the client compilation generates the build manifest that's used on the server side
            const { NextJsRequireCacheHotReloader } =
              require('./webpack/plugins/nextjs-require-cache-hot-reloader') as typeof import('./webpack/plugins/nextjs-require-cache-hot-reloader')
            const devPlugins: any[] = [
              new NextJsRequireCacheHotReloader({
                serverComponents: hasAppDir,
              }),
            ]

            if (isClient || isEdgeServer) {
              devPlugins.push(new bundler.HotModuleReplacementPlugin())
            }

            return devPlugins
          })()
        : []),
      !dev &&
        new bundler.IgnorePlugin({
          resourceRegExp: /react-is/,
          contextRegExp: /next[\\/]dist[\\/]/,
        }),
      isNodeOrEdgeCompilation &&
        new PagesManifestPlugin({
          dev,
          appDirEnabled: hasAppDir,
          isEdgeRuntime: isEdgeServer,
          distDir: !dev ? distDir : undefined,
        }),
      // MiddlewarePlugin should be after DefinePlugin so NEXT_PUBLIC_*
      // replacement is done before its process.env.* handling
      isEdgeServer &&
        new MiddlewarePlugin({
          dev,
          sriEnabled: !dev && !!config.experimental.sri?.algorithm,
          rewrites,
          edgeEnvironments: {
            __NEXT_BUILD_ID: buildId,
            NEXT_SERVER_ACTIONS_ENCRYPTION_KEY: encryptionKey,
            __NEXT_PREVIEW_MODE_ID: previewProps.previewModeId,
            __NEXT_PREVIEW_MODE_SIGNING_KEY: previewProps.previewModeSigningKey,
            __NEXT_PREVIEW_MODE_ENCRYPTION_KEY:
              previewProps.previewModeEncryptionKey,
          },
        }),
      isClient &&
        new BuildManifestPlugin({
          buildId,
          rewrites,
          isDevFallback,
          appDirEnabled: hasAppDir,
          clientRouterFilters,
        }),
      isRspack
        ? new RspackProfilingPlugin({ runWebpackSpan })
        : new ProfilingPlugin({ runWebpackSpan, rootDir: dir }),
      new WellKnownErrorsPlugin(),
      isClient &&
        new CopyFilePlugin({
          // file path to build output of `@next/polyfill-nomodule`
          filePath: require.resolve('./polyfills/polyfill-nomodule'),
          cacheKey: process.env.__NEXT_VERSION as string,
          name: `static/chunks/polyfills${dev ? '' : '-[hash]'}.js`,
          minimize: false,
          info: {
            [CLIENT_STATIC_FILES_RUNTIME_POLYFILLS_SYMBOL]: 1,
            // This file is already minified
            minimized: true,
          },
        }),
      hasAppDir && isClient && new AppBuildManifestPlugin({ dev }),
      hasAppDir &&
        (isClient
          ? new ClientReferenceManifestPlugin({
              dev,
              appDir,
              experimentalInlineCss: !!config.experimental.inlineCss,
            })
          : new FlightClientEntryPlugin({
              appDir,
              dev,
              isEdgeServer,
              encryptionKey,
            })),
      hasAppDir &&
        !isClient &&
        new NextTypesPlugin({
          dir,
          distDir: config.distDir,
          appDir,
          dev,
          isEdgeServer,
          pageExtensions: config.pageExtensions,
          typedRoutes: enableTypedRoutes,
          cacheLifeConfig: config.experimental.cacheLife,
          originalRewrites,
          originalRedirects,
        }),
      !dev &&
        isClient &&
        !!config.experimental.sri?.algorithm &&
        new SubresourceIntegrityPlugin(config.experimental.sri.algorithm),
      isClient &&
        new NextFontManifestPlugin({
          appDir,
        }),
      !dev &&
        isClient &&
        config.experimental.cssChunking &&
        (isRspack
          ? new (getRspackCore().experiments.CssChunkingPlugin)({
              strict: config.experimental.cssChunking === 'strict',
              nextjs: true,
            })
          : new CssChunkingPlugin(
              config.experimental.cssChunking === 'strict'
            )),
      telemetryPlugin,
      !dev &&
        isNodeServer &&
        new (
          require('./webpack/plugins/telemetry-plugin/telemetry-plugin') as typeof import('./webpack/plugins/telemetry-plugin/telemetry-plugin')
        ).TelemetryPlugin(new Map()),
      shouldEnableSlowModuleDetection &&
        new (
          require('./webpack/plugins/slow-module-detection-plugin') as typeof import('./webpack/plugins/slow-module-detection-plugin')
        ).default({
          compilerType,
          ...config.experimental.slowModuleDetection!,
        }),
    ].filter(Boolean as any as ExcludesFalse),
  }

  // Support tsconfig and jsconfig baseUrl
  // Only add the baseUrl if it's explicitly set in tsconfig/jsconfig
  if (resolvedBaseUrl && !resolvedBaseUrl.isImplicit) {
    webpackConfig.resolve?.modules?.push(resolvedBaseUrl.baseUrl)
  }

  // always add JsConfigPathsPlugin to allow hot-reloading
  // if the config is added/removed
  webpackConfig.resolve?.plugins?.unshift(
    new JsConfigPathsPlugin(
      jsConfig?.compilerOptions?.paths || {},
      resolvedBaseUrl
    )
  )

  const webpack5Config = webpackConfig as webpack.Configuration

  if (isEdgeServer) {
    webpack5Config.module?.rules?.unshift({
      test: /\.wasm$/,
      loader: 'next-middleware-wasm-loader',
      type: 'javascript/auto',
      resourceQuery: /module/i,
    })
    webpack5Config.module?.rules?.unshift({
      dependency: 'url',
      loader: 'next-middleware-asset-loader',
      type: 'javascript/auto',
      layer: WEBPACK_LAYERS.edgeAsset,
    })
    webpack5Config.module?.rules?.unshift({
      issuerLayer: WEBPACK_LAYERS.edgeAsset,
      type: 'asset/source',
    })
  }

  webpack5Config.experiments = {
    layers: true,
    cacheUnaffected: true,
    buildHttp: Array.isArray(config.experimental.urlImports)
      ? {
          allowedUris: config.experimental.urlImports,
          cacheLocation: path.join(dir, 'next.lock/data'),
          lockfileLocation: path.join(dir, 'next.lock/lock.json'),
        }
      : config.experimental.urlImports
        ? {
            cacheLocation: path.join(dir, 'next.lock/data'),
            lockfileLocation: path.join(dir, 'next.lock/lock.json'),
            ...config.experimental.urlImports,
          }
        : undefined,
  }

  webpack5Config.module!.parser = {
    javascript: {
      url: 'relative',
    },
  }
  webpack5Config.module!.generator = {
    asset: {
      filename: 'static/media/[name].[hash:8][ext]',
    },
  }

  if (!webpack5Config.output) {
    webpack5Config.output = {}
  }
  if (isClient) {
    webpack5Config.output.trustedTypes = 'nextjs#bundler'
  }

  if (isClient || isEdgeServer) {
    webpack5Config.output.enabledLibraryTypes = ['assign']
  }

  // This enables managedPaths for all node_modules
  // and also for the unplugged folder when using yarn pnp
  // It also add the yarn cache to the immutable paths
  webpack5Config.snapshot = {}
  if (process.versions.pnp === '3') {
    webpack5Config.snapshot.managedPaths = [
      /^(.+?(?:[\\/]\.yarn[\\/]unplugged[\\/][^\\/]+)?[\\/]node_modules[\\/])/,
    ]
  } else {
    webpack5Config.snapshot.managedPaths = [/^(.+?[\\/]node_modules[\\/])/]
  }
  if (process.versions.pnp === '3') {
    webpack5Config.snapshot.immutablePaths = [
      /^(.+?[\\/]cache[\\/][^\\/]+\.zip[\\/]node_modules[\\/])/,
    ]
  }

  if (dev) {
    if (!webpack5Config.optimization) {
      webpack5Config.optimization = {}
    }

    // For Server Components, it's necessary to have provided exports collected
    // to generate the correct flight manifest.
    if (!hasAppDir) {
      webpack5Config.optimization.providedExports = false
    }
    webpack5Config.optimization.usedExports = false
  }

  const configVars = JSON.stringify({
    optimizePackageImports: config?.experimental?.optimizePackageImports,
    crossOrigin: config.crossOrigin,
    pageExtensions: pageExtensions,
    trailingSlash: config.trailingSlash,
    buildActivityPosition:
      config.devIndicators === false
        ? undefined
        : config.devIndicators.position,
    productionBrowserSourceMaps: !!config.productionBrowserSourceMaps,
    reactStrictMode: config.reactStrictMode,
    optimizeCss: config.experimental.optimizeCss,
    nextScriptWorkers: config.experimental.nextScriptWorkers,
    scrollRestoration: config.experimental.scrollRestoration,
    typedRoutes: config.experimental.typedRoutes,
    basePath: config.basePath,
    excludeDefaultMomentLocales: config.excludeDefaultMomentLocales,
    assetPrefix: config.assetPrefix,
    disableOptimizedLoading,
    isEdgeRuntime: isEdgeServer,
    reactProductionProfiling,
    webpack: !!config.webpack,
    hasRewrites,
    swcLoader: useSWCLoader,
    removeConsole: config.compiler?.removeConsole,
    reactRemoveProperties: config.compiler?.reactRemoveProperties,
    styledComponents: config.compiler?.styledComponents,
    relay: config.compiler?.relay,
    emotion: config.compiler?.emotion,
    modularizeImports: config.modularizeImports,
    imageLoaderFile: config.images.loaderFile,
    clientTraceMetadata: config.experimental.clientTraceMetadata,
    serverSourceMaps: config.experimental.serverSourceMaps,
    serverReferenceHashSalt: encryptionKey,
  })

  const cache: any = {
    type: 'filesystem',
    // Disable memory cache in development in favor of our own MemoryWithGcCachePlugin.
    maxMemoryGenerations: dev ? 0 : Infinity, // Infinity is default value for production in webpack currently.
    // Includes:
    //  - Next.js location on disk (some loaders use absolute paths and some resolve options depend on absolute paths)
    //  - Next.js version
    //  - next.config.js keys that affect compilation
    version: `${__dirname}|${process.env.__NEXT_VERSION}|${configVars}`,
    cacheDirectory: path.join(distDir, 'cache', 'webpack'),
    // For production builds, it's more efficient to compress all cache files together instead of compression each one individually.
    // So we disable compression here and allow the build runner to take care of compressing the cache as a whole.
    // For local development, we still want to compress the cache files individually to avoid I/O bottlenecks
    // as we are seeing 1~10 seconds of fs I/O time from user reports.
    compression: dev ? 'gzip' : false,
  }

  // Adds `next.config.js` as a buildDependency when custom webpack config is provided
  if (config.webpack && config.configFile) {
    cache.buildDependencies = {
      config: [config.configFile],
      // We don't want to use the webpack default buildDependencies as we already include the next.js version
      defaultWebpack: [],
    }
  } else {
    cache.buildDependencies = {
      // We don't want to use the webpack default buildDependencies as we already include the next.js version
      defaultWebpack: [],
    }
  }
  webpack5Config.plugins?.push((compiler) => {
    compiler.hooks.done.tap('next-build-dependencies', (stats) => {
      const buildDependencies = stats.compilation.buildDependencies
      const nextPackage = path.dirname(require.resolve('next/package.json'))
      // Remove all next.js build dependencies, they are already covered by the cacheVersion
      // and next.js also imports the output files which leads to broken caching.
      for (const dep of buildDependencies) {
        if (dep.startsWith(nextPackage)) {
          buildDependencies.delete(dep)
        }
      }
    })
  })

  webpack5Config.cache = cache

  if (process.env.NEXT_WEBPACK_LOGGING) {
    const infra = process.env.NEXT_WEBPACK_LOGGING.includes('infrastructure')
    const profileClient =
      process.env.NEXT_WEBPACK_LOGGING.includes('profile-client')
    const profileServer =
      process.env.NEXT_WEBPACK_LOGGING.includes('profile-server')
    const summaryClient =
      process.env.NEXT_WEBPACK_LOGGING.includes('summary-client')
    const summaryServer =
      process.env.NEXT_WEBPACK_LOGGING.includes('summary-server')

    const profile =
      (profileClient && isClient) || (profileServer && isNodeOrEdgeCompilation)
    const summary =
      (summaryClient && isClient) || (summaryServer && isNodeOrEdgeCompilation)

    const logDefault = !infra && !profile && !summary

    if (logDefault || infra) {
      webpack5Config.infrastructureLogging = {
        level: 'verbose',
        debug: /FileSystemInfo/,
      }
    }

    if (logDefault || profile) {
      webpack5Config.plugins!.push((compiler: webpack.Compiler) => {
        compiler.hooks.done.tap('next-webpack-logging', (stats) => {
          console.log(
            stats.toString({
              colors: true,
              logging: logDefault ? 'log' : 'verbose',
            })
          )
        })
      })
    } else if (summary) {
      webpack5Config.plugins!.push((compiler: webpack.Compiler) => {
        compiler.hooks.done.tap('next-webpack-logging', (stats) => {
          console.log(
            stats.toString({
              preset: 'summary',
              colors: true,
              timings: true,
            })
          )
        })
      })
    }

    if (profile) {
      const ProgressPlugin =
        webpack.ProgressPlugin as unknown as typeof webpack.ProgressPlugin
      webpack5Config.plugins!.push(
        new ProgressPlugin({
          profile: true,
        })
      )
      webpack5Config.profile = true
    }
  }

  webpackConfig = await buildConfiguration(webpackConfig, {
    supportedBrowsers,
    rootDirectory: dir,
    customAppFile: pagesDir
      ? new RegExp(escapeStringRegexp(path.join(pagesDir, `_app`)))
      : undefined,
    hasAppDir,
    isDevelopment: dev,
    isServer: isNodeOrEdgeCompilation,
    isEdgeRuntime: isEdgeServer,
    targetWeb: isClient || isEdgeServer,
    assetPrefix: config.assetPrefix || '',
    sassOptions: config.sassOptions,
    productionBrowserSourceMaps: config.productionBrowserSourceMaps,
    future: config.future,
    experimental: config.experimental,
    disableStaticImages: config.images.disableStaticImages,
    transpilePackages: config.transpilePackages,
    serverSourceMaps: config.experimental.serverSourceMaps,
  })

  // @ts-ignore Cache exists
  webpackConfig.cache.name = `${webpackConfig.name}-${webpackConfig.mode}${
    isDevFallback ? '-fallback' : ''
  }`

  if (dev) {
    if (webpackConfig.module) {
      webpackConfig.module.unsafeCache = (module: any) =>
        !UNSAFE_CACHE_REGEX.test(module.resource)
    } else {
      webpackConfig.module = {
        unsafeCache: (module: any) => !UNSAFE_CACHE_REGEX.test(module.resource),
      }
    }
  }

  let originalDevtool = webpackConfig.devtool
  if (typeof config.webpack === 'function') {
    const pluginCountBefore = webpackConfig.plugins?.length

    webpackConfig = config.webpack(webpackConfig, {
      dir,
      dev,
      isServer: isNodeOrEdgeCompilation,
      buildId,
      config,
      defaultLoaders,
      totalPages: Object.keys(entrypoints).length,
      webpack: bundler,
      ...(isNodeOrEdgeCompilation
        ? {
            nextRuntime: isEdgeServer ? 'edge' : 'nodejs',
          }
        : {}),
    })

    if (telemetryPlugin && pluginCountBefore) {
      const pluginCountAfter = webpackConfig.plugins?.length
      if (pluginCountAfter) {
        const pluginsChanged = pluginCountAfter !== pluginCountBefore
        telemetryPlugin.addUsage('webpackPlugins', pluginsChanged ? 1 : 0)
      }
    }

    if (!webpackConfig) {
      throw new Error(
        `Webpack config is undefined. You may have forgot to return properly from within the "webpack" method of your ${config.configFileName}.\n` +
          'See more info here https://nextjs.org/docs/messages/undefined-webpack-config'
      )
    }

    if (dev && originalDevtool !== webpackConfig.devtool) {
      webpackConfig.devtool = originalDevtool
      devtoolRevertWarning(originalDevtool)
    }

    // eslint-disable-next-line @typescript-eslint/no-shadow
    const webpack5Config = webpackConfig as webpack.Configuration

    // disable lazy compilation of entries as next.js has it's own method here
    if (webpack5Config.experiments?.lazyCompilation === true) {
      webpack5Config.experiments.lazyCompilation = {
        entries: false,
      }
    } else if (
      typeof webpack5Config.experiments?.lazyCompilation === 'object' &&
      webpack5Config.experiments.lazyCompilation.entries !== false
    ) {
      webpack5Config.experiments.lazyCompilation.entries = false
    }

    if (typeof (webpackConfig as any).then === 'function') {
      console.warn(
        '> Promise returned in next config. https://nextjs.org/docs/messages/promise-in-next-config'
      )
    }
  }
  const rules = webpackConfig.module?.rules || []

  const customSvgRule = rules.find(
    (rule): rule is webpack.RuleSetRule =>
      (rule &&
        typeof rule === 'object' &&
        rule.loader !== 'next-image-loader' &&
        'test' in rule &&
        rule.test instanceof RegExp &&
        rule.test.test('.svg')) ||
      false
  )

  if (customSvgRule && hasAppDir) {
    // Create React aliases for SVG components that were transformed using a
    // custom webpack config with e.g. the `@svgr/webpack` loader, or the
    // `babel-plugin-inline-react-svg` plugin.
    rules.push({
      test: customSvgRule.test,
      oneOf: [
        WEBPACK_LAYERS.reactServerComponents,
        WEBPACK_LAYERS.serverSideRendering,
        WEBPACK_LAYERS.appPagesBrowser,
      ].map((layer) => ({
        issuerLayer: layer,
        resolve: {
          alias: createVendoredReactAliases(bundledReactChannel, {
            reactProductionProfiling,
            layer,
            isBrowser: isClient,
            isEdgeServer,
          }),
        },
      })),
    })
  }

  if (!config.images.disableStaticImages) {
    const nextImageRule = rules.find(
      (rule) =>
        rule && typeof rule === 'object' && rule.loader === 'next-image-loader'
    )
    if (customSvgRule && nextImageRule && typeof nextImageRule === 'object') {
      // Exclude svg if the user already defined it in custom
      // webpack config such as the `@svgr/webpack` loader, or
      // the `babel-plugin-inline-react-svg` plugin.
      nextImageRule.test = /\.(png|jpg|jpeg|gif|webp|avif|ico|bmp)$/i
    }
  }

  if (
    config.experimental.craCompat &&
    webpackConfig.module?.rules &&
    webpackConfig.plugins
  ) {
    // CRA allows importing non-webpack handled files with file-loader
    // these need to be the last rule to prevent catching other items
    // https://github.com/facebook/create-react-app/blob/fddce8a9e21bf68f37054586deb0c8636a45f50b/packages/react-scripts/config/webpack.config.js#L594
    const fileLoaderExclude = [/\.(js|mjs|jsx|ts|tsx|json)$/]
    const fileLoader = {
      exclude: fileLoaderExclude,
      issuer: fileLoaderExclude,
      type: 'asset/resource',
    }

    const topRules = []
    const innerRules = []

    for (const rule of webpackConfig.module.rules) {
      if (!rule || typeof rule !== 'object') continue
      if (rule.resolve) {
        topRules.push(rule)
      } else {
        if (
          rule.oneOf &&
          !(rule.test || rule.exclude || rule.resource || rule.issuer)
        ) {
          rule.oneOf.forEach((r) => innerRules.push(r))
        } else {
          innerRules.push(rule)
        }
      }
    }

    webpackConfig.module.rules = [
      ...(topRules as any),
      {
        oneOf: [...innerRules, fileLoader],
      },
    ]
  }

  // Backwards compat with webpack-dev-middleware options object
  if (typeof config.webpackDevMiddleware === 'function') {
    const options = config.webpackDevMiddleware({
      watchOptions: webpackConfig.watchOptions,
    })
    if (options.watchOptions) {
      webpackConfig.watchOptions = options.watchOptions
    }
  }

  function canMatchCss(rule: webpack.RuleSetCondition | undefined): boolean {
    if (!rule) {
      return false
    }

    const fileNames = [
      '/tmp/NEXTJS_CSS_DETECTION_FILE.css',
      '/tmp/NEXTJS_CSS_DETECTION_FILE.scss',
      '/tmp/NEXTJS_CSS_DETECTION_FILE.sass',
      '/tmp/NEXTJS_CSS_DETECTION_FILE.less',
      '/tmp/NEXTJS_CSS_DETECTION_FILE.styl',
    ]

    if (rule instanceof RegExp && fileNames.some((input) => rule.test(input))) {
      return true
    }

    if (typeof rule === 'function') {
      if (
        fileNames.some((input) => {
          try {
            if (rule(input)) {
              return true
            }
          } catch {}
          return false
        })
      ) {
        return true
      }
    }

    if (Array.isArray(rule) && rule.some(canMatchCss)) {
      return true
    }

    return false
  }

  const hasUserCssConfig =
    webpackConfig.module?.rules?.some(
      (rule: any) => canMatchCss(rule.test) || canMatchCss(rule.include)
    ) ?? false

  if (hasUserCssConfig) {
    // only show warning for one build
    if (isNodeOrEdgeCompilation) {
      console.warn(
        yellow(bold('Warning: ')) +
          bold(
            'Built-in CSS support is being disabled due to custom CSS configuration being detected.\n'
          ) +
          'See here for more info: https://nextjs.org/docs/messages/built-in-css-disabled\n'
      )
    }

    if (webpackConfig.module?.rules?.length) {
      // Remove default CSS Loaders
      webpackConfig.module.rules.forEach((r) => {
        if (!r || typeof r !== 'object') return
        if (Array.isArray(r.oneOf)) {
          r.oneOf = r.oneOf.filter(
            (o) => (o as any)[Symbol.for('__next_css_remove')] !== true
          )
        }
      })
    }
    if (webpackConfig.plugins?.length) {
      // Disable CSS Extraction Plugin
      webpackConfig.plugins = webpackConfig.plugins.filter(
        (p) => (p as any).__next_css_remove !== true
      )
    }
    if (webpackConfig.optimization?.minimizer?.length) {
      // Disable CSS Minifier
      webpackConfig.optimization.minimizer =
        webpackConfig.optimization.minimizer.filter(
          (e) => (e as any).__next_css_remove !== true
        )
    }
  }

  // Inject missing React Refresh loaders so that development mode is fast:
  if (dev && isClient) {
    attachReactRefresh(webpackConfig, defaultLoaders.babel)
  }

  // Backwards compat for `main.js` entry key
  // and setup of dependencies between entries
  // we can't do that in the initial entry for
  // backward-compat reasons
  const originalEntry: any = webpackConfig.entry
  if (typeof originalEntry !== 'undefined') {
    const updatedEntry = async () => {
      const entry: webpack.EntryObject =
        typeof originalEntry === 'function'
          ? await originalEntry()
          : originalEntry
      // Server compilation doesn't have main.js
      if (
        clientEntries &&
        Array.isArray(entry['main.js']) &&
        entry['main.js'].length > 0
      ) {
        const originalFile = clientEntries[
          CLIENT_STATIC_FILES_RUNTIME_MAIN
        ] as string
        entry[CLIENT_STATIC_FILES_RUNTIME_MAIN] = [
          ...entry['main.js'],
          originalFile,
        ]
      }
      delete entry['main.js']

      for (const name of Object.keys(entry)) {
        entry[name] = finalizeEntrypoint({
          value: entry[name],
          compilerType,
          name,
          hasAppDir,
        })
      }

      return entry
    }
    // @ts-ignore webpack 5 typings needed
    webpackConfig.entry = updatedEntry
  }

  if (!dev && typeof webpackConfig.entry === 'function') {
    // entry is always a function
    webpackConfig.entry = await webpackConfig.entry()
  }

  return webpackConfig
}