File size: 78,374 Bytes
979bf48
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
0 && (module.exports = {
    default: null,
    normalizeConfig: null,
    warnOptionHasBeenDeprecated: null,
    warnOptionHasBeenMovedOutOfExperimental: null
});
function _export(target, all) {
    for(var name in all)Object.defineProperty(target, name, {
        enumerable: true,
        get: all[name]
    });
}
_export(exports, {
    default: function() {
        return loadConfig;
    },
    normalizeConfig: function() {
        return _configshared.normalizeConfig;
    },
    warnOptionHasBeenDeprecated: function() {
        return warnOptionHasBeenDeprecated;
    },
    warnOptionHasBeenMovedOutOfExperimental: function() {
        return warnOptionHasBeenMovedOutOfExperimental;
    }
});
const _fs = require("fs");
const _path = require("path");
const _url = require("url");
const _findup = /*#__PURE__*/ _interop_require_default(require("next/dist/compiled/find-up"));
const _log = /*#__PURE__*/ _interop_require_wildcard(require("../build/output/log"));
const _ciinfo = /*#__PURE__*/ _interop_require_wildcard(require("../server/ci-info"));
const _constants = require("../shared/lib/constants");
const _configshared = require("./config-shared");
const _configutils = require("./config-utils");
const _imageconfig = require("../shared/lib/image-config");
const _env = require("@next/env");
const _flushtelemetry = require("../telemetry/flush-telemetry");
const _findroot = require("../lib/find-root");
const _setuphttpagentenv = require("./setup-http-agent-env");
const _pathhasprefix = require("../shared/lib/router/utils/path-has-prefix");
const _matchremotepattern = require("../shared/lib/match-remote-pattern");
const _transpileconfig = require("../build/next-config-ts/transpile-config");
const _dset = require("../shared/lib/dset");
const _zod = require("../shared/lib/zod");
const _isbot = require("../shared/lib/router/utils/is-bot");
const _findpagesdir = require("../lib/find-pages-dir");
const _interopdefault = require("../lib/interop-default");
const _hash = require("../shared/lib/hash");
const _harddeprecatedconfigerror = require("../shared/lib/errors/hard-deprecated-config-error");
const _nextinstanceerrorstate = require("./mcp/tools/next-instance-error-state");
function _interop_require_default(obj) {
    return obj && obj.__esModule ? obj : {
        default: obj
    };
}
function _getRequireWildcardCache(nodeInterop) {
    if (typeof WeakMap !== "function") return null;
    var cacheBabelInterop = new WeakMap();
    var cacheNodeInterop = new WeakMap();
    return (_getRequireWildcardCache = function(nodeInterop) {
        return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
    })(nodeInterop);
}
function _interop_require_wildcard(obj, nodeInterop) {
    if (!nodeInterop && obj && obj.__esModule) {
        return obj;
    }
    if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
        return {
            default: obj
        };
    }
    var cache = _getRequireWildcardCache(nodeInterop);
    if (cache && cache.has(obj)) {
        return cache.get(obj);
    }
    var newObj = {
        __proto__: null
    };
    var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
    for(var key in obj){
        if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
            var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
            if (desc && (desc.get || desc.set)) {
                Object.defineProperty(newObj, key, desc);
            } else {
                newObj[key] = obj[key];
            }
        }
    }
    newObj.default = obj;
    if (cache) {
        cache.set(obj, newObj);
    }
    return newObj;
}
function normalizeNextConfigZodErrors(error) {
    const warnings = [];
    const fatalErrors = [];
    const issues = (0, _zod.normalizeZodErrors)(error);
    for (const { issue, message: originalMessage } of issues){
        let message = originalMessage;
        let shouldExit = false;
        if (issue.path[0] === 'images') {
            // We exit the build when encountering an error in the images config
            shouldExit = true;
        }
        if (issue.code === 'unrecognized_keys' && issue.path[0] === 'experimental') {
            if (message.includes('turbopackPersistentCachingForBuild')) {
                // We exit the build when encountering an error in the turbopackPersistentCaching config
                shouldExit = true;
                message += "\nUse 'experimental.turbopackFileSystemCacheForBuild' instead.";
                message += '\nLearn more: https://nextjs.org/docs/app/api-reference/config/next-config-js/turbopackFileSystemCache';
            } else if (message.includes('turbopackPersistentCaching')) {
                // We exit the build when encountering an error in the turbopackPersistentCaching config
                shouldExit = true;
                message += "\nUse 'experimental.turbopackFileSystemCacheForDev' instead.";
                message += '\nLearn more: https://nextjs.org/docs/app/api-reference/config/next-config-js/turbopackFileSystemCache';
            }
        }
        if (shouldExit) {
            fatalErrors.push(message);
        } else {
            warnings.push(message);
        }
    }
    return [
        warnings,
        fatalErrors
    ];
}
function warnOptionHasBeenDeprecated(config, nestedPropertyKey, reason, silent) {
    let hasWarned = false;
    if (!silent) {
        let current = config;
        let found = true;
        const nestedPropertyKeys = nestedPropertyKey.split('.');
        for (const key of nestedPropertyKeys){
            if (current[key] !== undefined) {
                current = current[key];
            } else {
                found = false;
                break;
            }
        }
        if (found) {
            _log.warnOnce(reason);
            hasWarned = true;
        }
    }
    return hasWarned;
}
function checkDeprecations(userConfig, configFileName, silent, dir) {
    var _userConfig_images_domains, _userConfig_images;
    warnOptionHasBeenDeprecated(userConfig, 'experimental.middlewarePrefetch', `\`experimental.middlewarePrefetch\` is deprecated. Please use \`experimental.proxyPrefetch\` instead in ${configFileName}.`, silent);
    warnOptionHasBeenDeprecated(userConfig, 'experimental.middlewareClientMaxBodySize', `\`experimental.middlewareClientMaxBodySize\` is deprecated. Please use \`experimental.proxyClientMaxBodySize\` instead in ${configFileName}.`, silent);
    warnOptionHasBeenDeprecated(userConfig, 'experimental.externalMiddlewareRewritesResolve', `\`experimental.externalMiddlewareRewritesResolve\` is deprecated. Please use \`experimental.externalProxyRewritesResolve\` instead in ${configFileName}.`, silent);
    warnOptionHasBeenDeprecated(userConfig, 'skipMiddlewareUrlNormalize', `\`skipMiddlewareUrlNormalize\` is deprecated. Please use \`skipProxyUrlNormalize\` instead in ${configFileName}.`, silent);
    warnOptionHasBeenDeprecated(userConfig, 'experimental.instrumentationHook', `\`experimental.instrumentationHook\` is no longer needed, because \`instrumentation.js\` is available by default. You can remove it from ${configFileName}.`, silent);
    warnOptionHasBeenDeprecated(userConfig, 'experimental.after', `\`experimental.after\` is no longer needed, because \`after\` is available by default. You can remove it from ${configFileName}.`, silent);
    warnOptionHasBeenDeprecated(userConfig, 'eslint', `\`eslint\` configuration in ${configFileName} is no longer supported. See more info here: https://nextjs.org/docs/app/api-reference/cli/next#next-lint-options`, silent);
    if ((_userConfig_images = userConfig.images) == null ? void 0 : (_userConfig_images_domains = _userConfig_images.domains) == null ? void 0 : _userConfig_images_domains.length) {
        warnOptionHasBeenDeprecated(userConfig, 'images.domains', `\`images.domains\` is deprecated in favor of \`images.remotePatterns\`. Please update ${configFileName} to protect your application from malicious users.`, silent);
    }
    // i18n deprecation for App Router
    if (userConfig.i18n) {
        const hasAppDir = Boolean((0, _findpagesdir.findDir)(dir, 'app'));
        if (hasAppDir) {
            warnOptionHasBeenDeprecated(userConfig, 'i18n', `i18n configuration in ${configFileName} is unsupported in App Router.\nLearn more about internationalization in App Router: https://nextjs.org/docs/app/building-your-application/routing/internationalization`, silent);
        }
    }
}
function warnOptionHasBeenMovedOutOfExperimental(config, oldExperimentalKey, newKey, configFileName, silent) {
    if (config.experimental && oldExperimentalKey in config.experimental) {
        if (!silent) {
            _log.warn(`\`experimental.${oldExperimentalKey}\` has been moved to \`${newKey}\`. ` + `Please update your ${configFileName} file accordingly.`);
        }
        let current = config;
        const newKeys = newKey.split('.');
        while(newKeys.length > 1){
            const key = newKeys.shift();
            current[key] = current[key] || {};
            current = current[key];
        }
        ;
        current[newKeys.shift()] = config.experimental[oldExperimentalKey];
    }
    return config;
}
function warnCustomizedOption(config, key, defaultValue, customMessage, configFileName, silent) {
    const segs = key.split('.');
    let current = config;
    while(segs.length >= 1){
        const seg = segs.shift();
        if (!(seg in current)) {
            return;
        }
        current = current[seg];
    }
    if (!silent && current !== defaultValue) {
        _log.warn(`The "${key}" option has been modified. ${customMessage ? customMessage + '. ' : ''}It should be removed from your ${configFileName}.`);
    }
}
/**
 * Assigns defaults to the user config and validates the config.
 *
 * @param dir - The directory of the project.
 * @param userConfig - The user config.
 * @param silent - Whether to suppress warnings.
 * @returns The complete config.
 */ function assignDefaultsAndValidate(dir, userConfig, silent, phase) {
    var _result_experimental, _result_experimental_serverActions, _result_experimental1, _userConfig_experimental, _userConfig_experimental1, _userConfig_experimental2, _userConfig_experimental3, _userConfig_experimental4, _userConfig_experimental5, _userConfig_experimental6, _userConfig_experimental7, _userConfig_experimental8, _userConfig_experimental9, _userConfig_experimental10, _userConfig_experimental11, _userConfig_experimental12, _userConfig_experimental13, _userConfig_experimental14, _userConfig_experimental15, _result_experimental2, _result_turbopack, _result_turbopack1, _result_devIndicators, _result_experimental3;
    const configFileName = userConfig.configFileName;
    if (typeof userConfig.exportTrailingSlash !== 'undefined') {
        if (!silent) {
            _log.warn(`The "exportTrailingSlash" option has been renamed to "trailingSlash". Please update your ${configFileName}.`);
        }
        if (typeof userConfig.trailingSlash === 'undefined') {
            userConfig.trailingSlash = userConfig.exportTrailingSlash;
        }
        delete userConfig.exportTrailingSlash;
    }
    const config = Object.keys(userConfig).reduce((currentConfig, key)=>{
        const value = userConfig[key];
        if (value === undefined || value === null) {
            return currentConfig;
        }
        if (key === 'distDir') {
            if (typeof value !== 'string') {
                throw Object.defineProperty(new Error(`Specified distDir is not a string, found type "${typeof value}"`), "__NEXT_ERROR_CODE", {
                    value: "E206",
                    enumerable: false,
                    configurable: true
                });
            }
            const userDistDir = value.trim();
            // don't allow public as the distDir as this is a reserved folder for
            // public files
            if (userDistDir === 'public') {
                throw Object.defineProperty(new Error(`The 'public' directory is reserved in Next.js and can not be set as the 'distDir'. https://nextjs.org/docs/messages/can-not-output-to-public`), "__NEXT_ERROR_CODE", {
                    value: "E221",
                    enumerable: false,
                    configurable: true
                });
            }
            // make sure distDir isn't an empty string as it can result in the provided
            // directory being deleted in development mode
            if (userDistDir.length === 0) {
                throw Object.defineProperty(new Error(`Invalid distDir provided, distDir can not be an empty string. Please remove this config or set it to undefined`), "__NEXT_ERROR_CODE", {
                    value: "E391",
                    enumerable: false,
                    configurable: true
                });
            }
        }
        if (key === 'pageExtensions') {
            if (!Array.isArray(value)) {
                throw Object.defineProperty(new Error(`Specified pageExtensions is not an array of strings, found "${value}". Please update this config or remove it.`), "__NEXT_ERROR_CODE", {
                    value: "E140",
                    enumerable: false,
                    configurable: true
                });
            }
            if (!value.length) {
                throw Object.defineProperty(new Error(`Specified pageExtensions is an empty array. Please update it with the relevant extensions or remove it.`), "__NEXT_ERROR_CODE", {
                    value: "E43",
                    enumerable: false,
                    configurable: true
                });
            }
            value.forEach((ext)=>{
                if (typeof ext !== 'string') {
                    throw Object.defineProperty(new Error(`Specified pageExtensions is not an array of strings, found "${ext}" of type "${typeof ext}". Please update this config or remove it.`), "__NEXT_ERROR_CODE", {
                        value: "E108",
                        enumerable: false,
                        configurable: true
                    });
                }
            });
        }
        const defaultValue = _configshared.defaultConfig[key];
        if (!!value && value.constructor === Object && typeof defaultValue === 'object') {
            currentConfig[key] = {
                ...defaultValue,
                ...Object.keys(value).reduce((c, k)=>{
                    const v = value[k];
                    if (v !== undefined && v !== null) {
                        c[k] = v;
                    }
                    return c;
                }, {})
            };
        } else {
            currentConfig[key] = value;
        }
        return currentConfig;
    }, {});
    const result = {
        ..._configshared.defaultConfig,
        ...config,
        experimental: {
            ..._configshared.defaultConfig.experimental,
            ...config.experimental
        }
    };
    // ensure correct default is set for api-resolver revalidate handling
    if (!result.experimental.trustHostHeader && _ciinfo.hasNextSupport) {
        result.experimental.trustHostHeader = true;
    }
    if (((_result_experimental = result.experimental) == null ? void 0 : _result_experimental.allowDevelopmentBuild) && process.env.NODE_ENV !== 'development') {
        throw Object.defineProperty(new Error(`The experimental.allowDevelopmentBuild option requires NODE_ENV to be explicitly set to 'development'.`), "__NEXT_ERROR_CODE", {
            value: "E195",
            enumerable: false,
            configurable: true
        });
    }
    // Validate sassOptions.functions is not used with Turbopack
    if (process.env.TURBOPACK && result.sassOptions && 'functions' in result.sassOptions) {
        throw Object.defineProperty(new Error(`The "sassOptions.functions" option is not supported when using Turbopack. ` + `Custom Sass functions are only available with webpack. ` + `Please remove the "functions" property from your sassOptions in ${configFileName}.`), "__NEXT_ERROR_CODE", {
            value: "E893",
            enumerable: false,
            configurable: true
        });
    }
    if (result.experimental.ppr) {
        throw new _harddeprecatedconfigerror.HardDeprecatedConfigError(`\`experimental.ppr\` has been merged into \`cacheComponents\`. The Partial Prerendering feature is still available, but is now enabled via \`cacheComponents\`. Please update your ${configFileName} accordingly.`);
    }
    if (result.output === 'export') {
        if (result.i18n) {
            throw Object.defineProperty(new Error('Specified "i18n" cannot be used with "output: export". See more info here: https://nextjs.org/docs/messages/export-no-i18n'), "__NEXT_ERROR_CODE", {
                value: "E493",
                enumerable: false,
                configurable: true
            });
        }
        if (!_ciinfo.hasNextSupport) {
            if (result.rewrites) {
                _log.warn('Specified "rewrites" will not automatically work with "output: export". See more info here: https://nextjs.org/docs/messages/export-no-custom-routes');
            }
            if (result.redirects) {
                _log.warn('Specified "redirects" will not automatically work with "output: export". See more info here: https://nextjs.org/docs/messages/export-no-custom-routes');
            }
            if (result.headers) {
                _log.warn('Specified "headers" will not automatically work with "output: export". See more info here: https://nextjs.org/docs/messages/export-no-custom-routes');
            }
        }
    }
    if (typeof result.assetPrefix !== 'string') {
        throw Object.defineProperty(new Error(`Specified assetPrefix is not a string, found type "${typeof result.assetPrefix}" https://nextjs.org/docs/messages/invalid-assetprefix`), "__NEXT_ERROR_CODE", {
            value: "E68",
            enumerable: false,
            configurable: true
        });
    }
    if (typeof result.basePath !== 'string') {
        throw Object.defineProperty(new Error(`Specified basePath is not a string, found type "${typeof result.basePath}"`), "__NEXT_ERROR_CODE", {
            value: "E326",
            enumerable: false,
            configurable: true
        });
    }
    if (result.basePath !== '') {
        if (result.basePath === '/') {
            throw Object.defineProperty(new Error(`Specified basePath /. basePath has to be either an empty string or a path prefix"`), "__NEXT_ERROR_CODE", {
                value: "E95",
                enumerable: false,
                configurable: true
            });
        }
        if (!result.basePath.startsWith('/')) {
            throw Object.defineProperty(new Error(`Specified basePath has to start with a /, found "${result.basePath}"`), "__NEXT_ERROR_CODE", {
                value: "E105",
                enumerable: false,
                configurable: true
            });
        }
        if (result.basePath !== '/') {
            if (result.basePath.endsWith('/')) {
                throw Object.defineProperty(new Error(`Specified basePath should not end with /, found "${result.basePath}"`), "__NEXT_ERROR_CODE", {
                    value: "E39",
                    enumerable: false,
                    configurable: true
                });
            }
            if (result.assetPrefix === '') {
                result.assetPrefix = result.basePath;
            }
        }
    }
    if (result == null ? void 0 : result.images) {
        const images = result.images;
        if (typeof images !== 'object') {
            throw Object.defineProperty(new Error(`Specified images should be an object received ${typeof images}.\nSee more info here: https://nextjs.org/docs/messages/invalid-images-config`), "__NEXT_ERROR_CODE", {
                value: "E171",
                enumerable: false,
                configurable: true
            });
        }
        if (images.localPatterns) {
            if (!Array.isArray(images.localPatterns)) {
                throw Object.defineProperty(new Error(`Specified images.localPatterns should be an Array received ${typeof images.localPatterns}.\nSee more info here: https://nextjs.org/docs/messages/invalid-images-config`), "__NEXT_ERROR_CODE", {
                    value: "E118",
                    enumerable: false,
                    configurable: true
                });
            }
            // avoid double-pushing the same pattern if it already exists
            const hasMatch = images.localPatterns.some((pattern)=>pattern.pathname === '/_next/static/media/**' && pattern.search === '');
            if (!hasMatch) {
                // static import images are automatically allowed
                images.localPatterns.push({
                    pathname: '/_next/static/media/**',
                    search: ''
                });
            }
        } else {
            // All paths are not allowed for a search query by default.
            images.localPatterns = [
                {
                    pathname: '**',
                    search: ''
                }
            ];
        }
        if (images.remotePatterns) {
            var _config_assetPrefix;
            if (!Array.isArray(images.remotePatterns)) {
                throw Object.defineProperty(new Error(`Specified images.remotePatterns should be an Array received ${typeof images.remotePatterns}.\nSee more info here: https://nextjs.org/docs/messages/invalid-images-config`), "__NEXT_ERROR_CODE", {
                    value: "E27",
                    enumerable: false,
                    configurable: true
                });
            }
            // We must convert URL to RemotePattern since URL has a colon in the protocol
            // and also has additional properties we want to filter out. Also, new URL()
            // accepts any protocol so we need manual validation here.
            images.remotePatterns = images.remotePatterns.map(({ protocol, hostname, port, pathname, search })=>{
                const proto = protocol == null ? void 0 : protocol.replace(/:$/, '');
                if (![
                    'http',
                    'https',
                    undefined
                ].includes(proto)) {
                    throw Object.defineProperty(new Error(`Specified images.remotePatterns must have protocol "http" or "https" received "${proto}".`), "__NEXT_ERROR_CODE", {
                        value: "E671",
                        enumerable: false,
                        configurable: true
                    });
                }
                return {
                    protocol: proto,
                    hostname,
                    port,
                    pathname,
                    search
                };
            });
            // static images are automatically prefixed with assetPrefix
            // so we need to ensure _next/image allows downloading from
            // this resource
            if ((_config_assetPrefix = config.assetPrefix) == null ? void 0 : _config_assetPrefix.startsWith('http')) {
                try {
                    const url = new URL(config.assetPrefix);
                    const hasMatchForAssetPrefix = images.remotePatterns.some((pattern)=>(0, _matchremotepattern.matchRemotePattern)(pattern, url));
                    // avoid double-pushing the same pattern if it already can be matched
                    if (!hasMatchForAssetPrefix) {
                        images.remotePatterns.push({
                            hostname: url.hostname,
                            protocol: url.protocol.replace(/:$/, ''),
                            port: url.port
                        });
                    }
                } catch (error) {
                    throw Object.defineProperty(new Error(`Invalid assetPrefix provided. Original error: ${error}`), "__NEXT_ERROR_CODE", {
                        value: "E343",
                        enumerable: false,
                        configurable: true
                    });
                }
            }
        }
        if (images.domains) {
            if (!Array.isArray(images.domains)) {
                throw Object.defineProperty(new Error(`Specified images.domains should be an Array received ${typeof images.domains}.\nSee more info here: https://nextjs.org/docs/messages/invalid-images-config`), "__NEXT_ERROR_CODE", {
                    value: "E402",
                    enumerable: false,
                    configurable: true
                });
            }
        }
        if (!images.loader) {
            images.loader = 'default';
        }
        if (images.loader !== 'default' && images.loader !== 'custom' && images.path === _imageconfig.imageConfigDefault.path) {
            throw Object.defineProperty(new Error(`Specified images.loader property (${images.loader}) also requires images.path property to be assigned to a URL prefix.\nSee more info here: https://nextjs.org/docs/api-reference/next/legacy/image#loader-configuration`), "__NEXT_ERROR_CODE", {
                value: "E228",
                enumerable: false,
                configurable: true
            });
        }
        if (images.path === _imageconfig.imageConfigDefault.path && result.basePath && !(0, _pathhasprefix.pathHasPrefix)(images.path, result.basePath)) {
            images.path = `${result.basePath}${images.path}`;
        }
        // Append trailing slash for non-default loaders and when trailingSlash is set
        if (images.path && !images.path.endsWith('/') && (images.loader !== 'default' || result.trailingSlash)) {
            images.path += '/';
        }
        if (images.loaderFile) {
            if (images.loader !== 'default' && images.loader !== 'custom') {
                throw Object.defineProperty(new Error(`Specified images.loader property (${images.loader}) cannot be used with images.loaderFile property. Please set images.loader to "custom".`), "__NEXT_ERROR_CODE", {
                    value: "E449",
                    enumerable: false,
                    configurable: true
                });
            }
            const absolutePath = (0, _path.join)(dir, images.loaderFile);
            if (!(0, _fs.existsSync)(absolutePath)) {
                throw Object.defineProperty(new Error(`Specified images.loaderFile does not exist at "${absolutePath}".`), "__NEXT_ERROR_CODE", {
                    value: "E461",
                    enumerable: false,
                    configurable: true
                });
            }
            images.loaderFile = absolutePath;
        }
    }
    warnCustomizedOption(result, 'experimental.esmExternals', true, 'experimental.esmExternals is not recommended to be modified as it may disrupt module resolution', configFileName, silent);
    warnOptionHasBeenMovedOutOfExperimental(result, 'bundlePagesExternals', 'bundlePagesRouterDependencies', configFileName, silent);
    warnOptionHasBeenMovedOutOfExperimental(result, 'serverComponentsExternalPackages', 'serverExternalPackages', configFileName, silent);
    warnOptionHasBeenMovedOutOfExperimental(result, 'relay', 'compiler.relay', configFileName, silent);
    warnOptionHasBeenMovedOutOfExperimental(result, 'styledComponents', 'compiler.styledComponents', configFileName, silent);
    warnOptionHasBeenMovedOutOfExperimental(result, 'emotion', 'compiler.emotion', configFileName, silent);
    warnOptionHasBeenMovedOutOfExperimental(result, 'reactRemoveProperties', 'compiler.reactRemoveProperties', configFileName, silent);
    warnOptionHasBeenMovedOutOfExperimental(result, 'removeConsole', 'compiler.removeConsole', configFileName, silent);
    warnOptionHasBeenMovedOutOfExperimental(result, 'swrDelta', 'expireTime', configFileName, silent);
    warnOptionHasBeenMovedOutOfExperimental(result, 'typedRoutes', 'typedRoutes', configFileName, silent);
    warnOptionHasBeenMovedOutOfExperimental(result, 'outputFileTracingRoot', 'outputFileTracingRoot', configFileName, silent);
    warnOptionHasBeenMovedOutOfExperimental(result, 'outputFileTracingIncludes', 'outputFileTracingIncludes', configFileName, silent);
    warnOptionHasBeenMovedOutOfExperimental(result, 'outputFileTracingExcludes', 'outputFileTracingExcludes', configFileName, silent);
    warnOptionHasBeenMovedOutOfExperimental(result, 'reactCompiler', 'reactCompiler', configFileName, silent);
    warnOptionHasBeenMovedOutOfExperimental(result, 'enablePrerenderSourceMaps', 'enablePrerenderSourceMaps', configFileName, silent);
    warnOptionHasBeenMovedOutOfExperimental(result, 'cacheComponents', 'cacheComponents', configFileName, silent);
    warnOptionHasBeenMovedOutOfExperimental(result, 'cacheLife', 'cacheLife', configFileName, silent);
    warnOptionHasBeenMovedOutOfExperimental(result, 'cacheHandlers', 'cacheHandlers', configFileName, silent);
    if (result.experimental.outputStandalone) {
        if (!silent) {
            _log.warn(`experimental.outputStandalone has been renamed to "output: 'standalone'", please move the config.`);
        }
        result.output = 'standalone';
    }
    if (typeof ((_result_experimental1 = result.experimental) == null ? void 0 : (_result_experimental_serverActions = _result_experimental1.serverActions) == null ? void 0 : _result_experimental_serverActions.bodySizeLimit) !== 'undefined') {
        const bytes = require('next/dist/compiled/bytes');
        const bodySizeLimit = result.experimental.serverActions.bodySizeLimit;
        let value;
        if (typeof bodySizeLimit === 'number') {
            value = bodySizeLimit;
        } else {
            value = bytes.parse(bodySizeLimit);
        }
        if (value === null || isNaN(value) || value < 1) {
            throw Object.defineProperty(new Error('Server Actions Size Limit must be a valid number or filesize format larger than 1MB: https://nextjs.org/docs/app/api-reference/next-config-js/serverActions#bodysizelimit'), "__NEXT_ERROR_CODE", {
                value: "E100",
                enumerable: false,
                configurable: true
            });
        }
    }
    // Throw if both Middleware and Proxy config are set.
    if (((_userConfig_experimental = userConfig.experimental) == null ? void 0 : _userConfig_experimental.proxyClientMaxBodySize) !== undefined && ((_userConfig_experimental1 = userConfig.experimental) == null ? void 0 : _userConfig_experimental1.middlewareClientMaxBodySize) !== undefined) {
        throw Object.defineProperty(new Error('Config options `experimental.proxyClientMaxBodySize` and `experimental.middlewareClientMaxBodySize` cannot be set at the same time. Please use `experimental.proxyClientMaxBodySize` instead.'), "__NEXT_ERROR_CODE", {
            value: "E879",
            enumerable: false,
            configurable: true
        });
    }
    if (((_userConfig_experimental2 = userConfig.experimental) == null ? void 0 : _userConfig_experimental2.proxyPrefetch) !== undefined && ((_userConfig_experimental3 = userConfig.experimental) == null ? void 0 : _userConfig_experimental3.middlewarePrefetch) !== undefined) {
        throw Object.defineProperty(new Error('Config options `experimental.proxyPrefetch` and `experimental.middlewarePrefetch` cannot be set at the same time. Please use `experimental.proxyPrefetch` instead.'), "__NEXT_ERROR_CODE", {
            value: "E880",
            enumerable: false,
            configurable: true
        });
    }
    if (((_userConfig_experimental4 = userConfig.experimental) == null ? void 0 : _userConfig_experimental4.externalProxyRewritesResolve) !== undefined && ((_userConfig_experimental5 = userConfig.experimental) == null ? void 0 : _userConfig_experimental5.externalMiddlewareRewritesResolve) !== undefined) {
        throw Object.defineProperty(new Error('Config options `experimental.externalProxyRewritesResolve` and `experimental.externalMiddlewareRewritesResolve` cannot be set at the same time. Please use `experimental.externalProxyRewritesResolve` instead.'), "__NEXT_ERROR_CODE", {
            value: "E877",
            enumerable: false,
            configurable: true
        });
    }
    if (userConfig.skipProxyUrlNormalize !== undefined && userConfig.skipMiddlewareUrlNormalize !== undefined) {
        throw Object.defineProperty(new Error('Config options `skipProxyUrlNormalize` and `skipMiddlewareUrlNormalize` cannot be set at the same time. Please use `skipProxyUrlNormalize` instead.'), "__NEXT_ERROR_CODE", {
            value: "E878",
            enumerable: false,
            configurable: true
        });
    }
    // Map Proxy config to Middleware config as it is currently an alias.
    if (((_userConfig_experimental6 = userConfig.experimental) == null ? void 0 : _userConfig_experimental6.proxyClientMaxBodySize) === undefined && ((_userConfig_experimental7 = userConfig.experimental) == null ? void 0 : _userConfig_experimental7.middlewareClientMaxBodySize) !== undefined) {
        result.experimental.proxyClientMaxBodySize = userConfig.experimental.middlewareClientMaxBodySize;
    }
    if (((_userConfig_experimental8 = userConfig.experimental) == null ? void 0 : _userConfig_experimental8.proxyPrefetch) === undefined && ((_userConfig_experimental9 = userConfig.experimental) == null ? void 0 : _userConfig_experimental9.middlewarePrefetch) !== undefined) {
        result.experimental.proxyPrefetch = userConfig.experimental.middlewarePrefetch;
    }
    if (((_userConfig_experimental10 = userConfig.experimental) == null ? void 0 : _userConfig_experimental10.externalProxyRewritesResolve) === undefined && ((_userConfig_experimental11 = userConfig.experimental) == null ? void 0 : _userConfig_experimental11.externalMiddlewareRewritesResolve) !== undefined) {
        result.experimental.externalProxyRewritesResolve = userConfig.experimental.externalMiddlewareRewritesResolve;
    }
    if (userConfig.skipProxyUrlNormalize === undefined && userConfig.skipMiddlewareUrlNormalize !== undefined) {
        result.skipProxyUrlNormalize = userConfig.skipMiddlewareUrlNormalize;
    }
    // Inverse case: when new name is set but not the old name, copy the value to the old name
    // to avoid breaking change on resolved config object written to `.next/`
    if (((_userConfig_experimental12 = userConfig.experimental) == null ? void 0 : _userConfig_experimental12.proxyPrefetch) !== undefined && ((_userConfig_experimental13 = userConfig.experimental) == null ? void 0 : _userConfig_experimental13.middlewarePrefetch) === undefined) {
        result.experimental.middlewarePrefetch = userConfig.experimental.proxyPrefetch;
    }
    if (((_userConfig_experimental14 = userConfig.experimental) == null ? void 0 : _userConfig_experimental14.externalProxyRewritesResolve) !== undefined && ((_userConfig_experimental15 = userConfig.experimental) == null ? void 0 : _userConfig_experimental15.externalMiddlewareRewritesResolve) === undefined) {
        result.experimental.externalMiddlewareRewritesResolve = userConfig.experimental.externalProxyRewritesResolve;
    }
    if (userConfig.skipProxyUrlNormalize !== undefined && userConfig.skipMiddlewareUrlNormalize === undefined) {
        result.skipMiddlewareUrlNormalize = userConfig.skipProxyUrlNormalize;
    }
    // Normalize & validate experimental.proxyClientMaxBodySize
    if (typeof ((_result_experimental2 = result.experimental) == null ? void 0 : _result_experimental2.proxyClientMaxBodySize) !== 'undefined') {
        const proxyClientMaxBodySize = result.experimental.proxyClientMaxBodySize;
        let normalizedValue;
        if (typeof proxyClientMaxBodySize === 'string') {
            const bytes = require('next/dist/compiled/bytes');
            normalizedValue = bytes.parse(proxyClientMaxBodySize);
        } else if (typeof proxyClientMaxBodySize === 'number') {
            normalizedValue = proxyClientMaxBodySize;
        } else {
            throw Object.defineProperty(new Error('Client Max Body Size must be a valid number (bytes) or filesize format string (e.g., "5mb")'), "__NEXT_ERROR_CODE", {
                value: "E860",
                enumerable: false,
                configurable: true
            });
        }
        if (isNaN(normalizedValue) || normalizedValue < 1) {
            throw Object.defineProperty(new Error('Client Max Body Size must be larger than 0 bytes'), "__NEXT_ERROR_CODE", {
                value: "E861",
                enumerable: false,
                configurable: true
            });
        }
        // Store the normalized value as a number
        result.experimental.proxyClientMaxBodySize = normalizedValue;
    }
    warnOptionHasBeenMovedOutOfExperimental(result, 'transpilePackages', 'transpilePackages', configFileName, silent);
    warnOptionHasBeenMovedOutOfExperimental(result, 'skipMiddlewareUrlNormalize', 'skipMiddlewareUrlNormalize', configFileName, silent);
    warnOptionHasBeenMovedOutOfExperimental(result, 'skipTrailingSlashRedirect', 'skipTrailingSlashRedirect', configFileName, silent);
    if ((result == null ? void 0 : result.outputFileTracingRoot) && !(0, _path.isAbsolute)(result.outputFileTracingRoot)) {
        result.outputFileTracingRoot = (0, _path.resolve)(result.outputFileTracingRoot);
        if (!silent) {
            _log.warn(`outputFileTracingRoot should be absolute, using: ${result.outputFileTracingRoot}`);
        }
    }
    if ((result == null ? void 0 : (_result_turbopack = result.turbopack) == null ? void 0 : _result_turbopack.root) && !(0, _path.isAbsolute)(result.turbopack.root)) {
        result.turbopack.root = (0, _path.resolve)(result.turbopack.root);
        if (!silent) {
            _log.warn(`turbopack.root should be absolute, using: ${result.turbopack.root}`);
        }
    }
    if (result.experimental.runtimeServerDeploymentId == null && phase === _constants.PHASE_PRODUCTION_BUILD && _ciinfo.hasNextSupport && process.env.NEXT_DEPLOYMENT_ID) {
        if (result.deploymentId != null && result.deploymentId !== process.env.NEXT_DEPLOYMENT_ID) {
            throw Object.defineProperty(new Error(`The NEXT_DEPLOYMENT_ID environment variable value "${process.env.NEXT_DEPLOYMENT_ID}" does not match the provided deploymentId "${result.deploymentId}" in the config.`), "__NEXT_ERROR_CODE", {
                value: "E971",
                enumerable: false,
                configurable: true
            });
        }
        result.experimental.runtimeServerDeploymentId = true;
    }
    // only leverage deploymentId
    if (process.env.NEXT_DEPLOYMENT_ID) {
        result.deploymentId = process.env.NEXT_DEPLOYMENT_ID;
    }
    const tracingRoot = result == null ? void 0 : result.outputFileTracingRoot;
    const turbopackRoot = result == null ? void 0 : (_result_turbopack1 = result.turbopack) == null ? void 0 : _result_turbopack1.root;
    // If both provided, validate they match. If not, use outputFileTracingRoot.
    if (tracingRoot && turbopackRoot && tracingRoot !== turbopackRoot) {
        _log.warn(`Both \`outputFileTracingRoot\` and \`turbopack.root\` are set, but they must have the same value.\n` + `Using \`outputFileTracingRoot\` value: ${tracingRoot}.`);
    }
    let rootDir = tracingRoot || turbopackRoot;
    if (!rootDir) {
        const { rootDir: foundRootDir, lockFiles } = (0, _findroot.findRootDirAndLockFiles)(dir);
        rootDir = foundRootDir;
        if (!silent) {
            (0, _findroot.warnDuplicatedLockFiles)(lockFiles);
        }
    }
    if (!rootDir) {
        throw Object.defineProperty(new Error('Failed to find the root directory of the project. This is a bug in Next.js.'), "__NEXT_ERROR_CODE", {
            value: "E782",
            enumerable: false,
            configurable: true
        });
    }
    // Ensure both properties are set to the same value
    result.outputFileTracingRoot = rootDir;
    (0, _dset.dset)(result, [
        'turbopack',
        'root'
    ], rootDir);
    (0, _setuphttpagentenv.setHttpClientAndAgentOptions)(result || _configshared.defaultConfig);
    if (result.i18n) {
        const { i18n } = result;
        const i18nType = typeof i18n;
        if (i18nType !== 'object') {
            throw Object.defineProperty(new Error(`Specified i18n should be an object received ${i18nType}.\nSee more info here: https://nextjs.org/docs/messages/invalid-i18n-config`), "__NEXT_ERROR_CODE", {
                value: "E148",
                enumerable: false,
                configurable: true
            });
        }
        if (!Array.isArray(i18n.locales)) {
            throw Object.defineProperty(new Error(`Specified i18n.locales should be an Array received ${typeof i18n.locales}.\nSee more info here: https://nextjs.org/docs/messages/invalid-i18n-config`), "__NEXT_ERROR_CODE", {
                value: "E227",
                enumerable: false,
                configurable: true
            });
        }
        if (i18n.locales.length > 100 && !silent) {
            _log.warn(`Received ${i18n.locales.length} i18n.locales items which exceeds the recommended max of 100.\nSee more info here: https://nextjs.org/docs/advanced-features/i18n-routing#how-does-this-work-with-static-generation`);
        }
        const defaultLocaleType = typeof i18n.defaultLocale;
        if (!i18n.defaultLocale || defaultLocaleType !== 'string') {
            throw Object.defineProperty(new Error(`Specified i18n.defaultLocale should be a string.\nSee more info here: https://nextjs.org/docs/messages/invalid-i18n-config`), "__NEXT_ERROR_CODE", {
                value: "E441",
                enumerable: false,
                configurable: true
            });
        }
        if (typeof i18n.domains !== 'undefined' && !Array.isArray(i18n.domains)) {
            throw Object.defineProperty(new Error(`Specified i18n.domains must be an array of domain objects e.g. [ { domain: 'example.fr', defaultLocale: 'fr', locales: ['fr'] } ] received ${typeof i18n.domains}.\nSee more info here: https://nextjs.org/docs/messages/invalid-i18n-config`), "__NEXT_ERROR_CODE", {
                value: "E456",
                enumerable: false,
                configurable: true
            });
        }
        if (i18n.domains) {
            const invalidDomainItems = i18n.domains.filter((item)=>{
                var _i18n_domains;
                if (!item || typeof item !== 'object') return true;
                if (!item.defaultLocale) return true;
                if (!item.domain || typeof item.domain !== 'string') return true;
                if (item.domain.includes(':')) {
                    console.warn(`i18n domain: "${item.domain}" is invalid it should be a valid domain without protocol (https://) or port (:3000) e.g. example.vercel.sh`);
                    return true;
                }
                const defaultLocaleDuplicate = (_i18n_domains = i18n.domains) == null ? void 0 : _i18n_domains.find((altItem)=>altItem.defaultLocale === item.defaultLocale && altItem.domain !== item.domain);
                if (!silent && defaultLocaleDuplicate) {
                    console.warn(`Both ${item.domain} and ${defaultLocaleDuplicate.domain} configured the defaultLocale ${item.defaultLocale} but only one can. Change one item's default locale to continue`);
                    return true;
                }
                let hasInvalidLocale = false;
                if (Array.isArray(item.locales)) {
                    for (const locale of item.locales){
                        if (typeof locale !== 'string') hasInvalidLocale = true;
                        for (const domainItem of i18n.domains || []){
                            if (domainItem === item) continue;
                            if (domainItem.locales && domainItem.locales.includes(locale)) {
                                console.warn(`Both ${item.domain} and ${domainItem.domain} configured the locale (${locale}) but only one can. Remove it from one i18n.domains config to continue`);
                                hasInvalidLocale = true;
                                break;
                            }
                        }
                    }
                }
                return hasInvalidLocale;
            });
            if (invalidDomainItems.length > 0) {
                throw Object.defineProperty(new Error(`Invalid i18n.domains values:\n${invalidDomainItems.map((item)=>JSON.stringify(item)).join('\n')}\n\ndomains value must follow format { domain: 'example.fr', defaultLocale: 'fr', locales: ['fr'] }.\nSee more info here: https://nextjs.org/docs/messages/invalid-i18n-config`), "__NEXT_ERROR_CODE", {
                    value: "E413",
                    enumerable: false,
                    configurable: true
                });
            }
        }
        if (!Array.isArray(i18n.locales)) {
            throw Object.defineProperty(new Error(`Specified i18n.locales must be an array of locale strings e.g. ["en-US", "nl-NL"] received ${typeof i18n.locales}.\nSee more info here: https://nextjs.org/docs/messages/invalid-i18n-config`), "__NEXT_ERROR_CODE", {
                value: "E432",
                enumerable: false,
                configurable: true
            });
        }
        const invalidLocales = i18n.locales.filter((locale)=>typeof locale !== 'string');
        if (invalidLocales.length > 0) {
            throw Object.defineProperty(new Error(`Specified i18n.locales contains invalid values (${invalidLocales.map(String).join(', ')}), locales must be valid locale tags provided as strings e.g. "en-US".\n` + `See here for list of valid language sub-tags: http://www.iana.org/assignments/language-subtag-registry/language-subtag-registry`), "__NEXT_ERROR_CODE", {
                value: "E71",
                enumerable: false,
                configurable: true
            });
        }
        if (!i18n.locales.includes(i18n.defaultLocale)) {
            throw Object.defineProperty(new Error(`Specified i18n.defaultLocale should be included in i18n.locales.\nSee more info here: https://nextjs.org/docs/messages/invalid-i18n-config`), "__NEXT_ERROR_CODE", {
                value: "E515",
                enumerable: false,
                configurable: true
            });
        }
        const normalizedLocales = new Set();
        const duplicateLocales = new Set();
        i18n.locales.forEach((locale)=>{
            const localeLower = locale.toLowerCase();
            if (normalizedLocales.has(localeLower)) {
                duplicateLocales.add(locale);
            }
            normalizedLocales.add(localeLower);
        });
        if (duplicateLocales.size > 0) {
            throw Object.defineProperty(new Error(`Specified i18n.locales contains the following duplicate locales:\n` + `${[
                ...duplicateLocales
            ].join(', ')}\n` + `Each locale should be listed only once.\n` + `See more info here: https://nextjs.org/docs/messages/invalid-i18n-config`), "__NEXT_ERROR_CODE", {
                value: "E471",
                enumerable: false,
                configurable: true
            });
        }
        // make sure default Locale is at the front
        i18n.locales = [
            i18n.defaultLocale,
            ...i18n.locales.filter((locale)=>locale !== i18n.defaultLocale)
        ];
        const localeDetectionType = typeof i18n.localeDetection;
        if (localeDetectionType !== 'boolean' && localeDetectionType !== 'undefined') {
            throw Object.defineProperty(new Error(`Specified i18n.localeDetection should be undefined or a boolean received ${localeDetectionType}.\nSee more info here: https://nextjs.org/docs/messages/invalid-i18n-config`), "__NEXT_ERROR_CODE", {
                value: "E439",
                enumerable: false,
                configurable: true
            });
        }
    }
    if (result.devIndicators !== false && ((_result_devIndicators = result.devIndicators) == null ? void 0 : _result_devIndicators.position)) {
        const { position } = result.devIndicators;
        const allowedValues = [
            'top-left',
            'top-right',
            'bottom-left',
            'bottom-right'
        ];
        if (!allowedValues.includes(position)) {
            throw Object.defineProperty(new Error(`Invalid "devIndicator.position" provided, expected one of ${allowedValues.join(', ')}, received ${position}`), "__NEXT_ERROR_CODE", {
                value: "E643",
                enumerable: false,
                configurable: true
            });
        }
    }
    if (result.cacheLife) {
        var _defaultConfig_cacheLife, _defaultConfig_experimental_staleTimes, _defaultConfig_experimental;
        result.cacheLife = {
            ..._configshared.defaultConfig.cacheLife,
            ...result.cacheLife
        };
        const defaultDefault = (_defaultConfig_cacheLife = _configshared.defaultConfig.cacheLife) == null ? void 0 : _defaultConfig_cacheLife['default'];
        if (!defaultDefault || defaultDefault.revalidate === undefined || defaultDefault.expire === undefined || !((_defaultConfig_experimental = _configshared.defaultConfig.experimental) == null ? void 0 : (_defaultConfig_experimental_staleTimes = _defaultConfig_experimental.staleTimes) == null ? void 0 : _defaultConfig_experimental_staleTimes.static)) {
            throw Object.defineProperty(new Error('No default cacheLife profile.'), "__NEXT_ERROR_CODE", {
                value: "E350",
                enumerable: false,
                configurable: true
            });
        }
        const defaultCacheLifeProfile = result.cacheLife['default'];
        if (!defaultCacheLifeProfile) {
            result.cacheLife['default'] = defaultDefault;
        } else {
            if (defaultCacheLifeProfile.stale === undefined) {
                var _result_experimental_staleTimes, _defaultConfig_experimental_staleTimes1, _defaultConfig_experimental1;
                const staticStaleTime = (_result_experimental_staleTimes = result.experimental.staleTimes) == null ? void 0 : _result_experimental_staleTimes.static;
                defaultCacheLifeProfile.stale = staticStaleTime ?? ((_defaultConfig_experimental1 = _configshared.defaultConfig.experimental) == null ? void 0 : (_defaultConfig_experimental_staleTimes1 = _defaultConfig_experimental1.staleTimes) == null ? void 0 : _defaultConfig_experimental_staleTimes1.static);
            }
            if (defaultCacheLifeProfile.revalidate === undefined) {
                defaultCacheLifeProfile.revalidate = defaultDefault.revalidate;
            }
            if (defaultCacheLifeProfile.expire === undefined) {
                defaultCacheLifeProfile.expire = result.expireTime ?? defaultDefault.expire;
            }
        }
    }
    if (result.cacheHandlers) {
        const allowedHandlerNameRegex = /[a-z-]/;
        if (typeof result.cacheHandlers !== 'object') {
            throw Object.defineProperty(new Error(`Invalid "cacheHandlers" provided, expected an object e.g. { default: '/my-handler.js' }, received ${JSON.stringify(result.cacheHandlers)}`), "__NEXT_ERROR_CODE", {
                value: "E901",
                enumerable: false,
                configurable: true
            });
        }
        const handlerKeys = Object.keys(result.cacheHandlers);
        const invalidHandlerItems = [];
        for (const key of handlerKeys){
            if (key === 'private') {
                invalidHandlerItems.push({
                    key,
                    reason: 'The cache handler for "use cache: private" cannot be customized.'
                });
            } else if (!allowedHandlerNameRegex.test(key)) {
                invalidHandlerItems.push({
                    key,
                    reason: 'key must only use characters a-z and -'
                });
            } else {
                const handlerPath = result.cacheHandlers[key];
                if (handlerPath && !(0, _fs.existsSync)(handlerPath)) {
                    invalidHandlerItems.push({
                        key,
                        reason: `cache handler path provided does not exist, received ${handlerPath}`
                    });
                }
            }
            if (invalidHandlerItems.length) {
                throw Object.defineProperty(new Error(`Invalid handler fields configured for "cacheHandlers":\n${invalidHandlerItems.map((item)=>`${key}: ${item.reason}`).join('\n')}`), "__NEXT_ERROR_CODE", {
                    value: "E902",
                    enumerable: false,
                    configurable: true
                });
            }
        }
    }
    const userProvidedModularizeImports = result.modularizeImports;
    // Unfortunately these packages end up re-exporting 10600 modules, for example: https://unpkg.com/browse/@mui/icons-material@5.11.16/esm/index.js.
    // Leveraging modularizeImports tremendously reduces compile times for these.
    result.modularizeImports = {
        ...userProvidedModularizeImports || {},
        // This is intentionally added after the user-provided modularizeImports config.
        '@mui/icons-material': {
            transform: '@mui/icons-material/{{member}}'
        },
        lodash: {
            transform: 'lodash/{{member}}'
        }
    };
    const userProvidedOptimizePackageImports = ((_result_experimental3 = result.experimental) == null ? void 0 : _result_experimental3.optimizePackageImports) || [];
    result.experimental.optimizePackageImports = [
        ...new Set([
            ...userProvidedOptimizePackageImports,
            'lucide-react',
            'date-fns',
            'lodash-es',
            'ramda',
            'antd',
            'react-bootstrap',
            'ahooks',
            '@ant-design/icons',
            '@headlessui/react',
            '@headlessui-float/react',
            '@heroicons/react/20/solid',
            '@heroicons/react/24/solid',
            '@heroicons/react/24/outline',
            '@visx/visx',
            '@tremor/react',
            'rxjs',
            '@mui/material',
            '@mui/icons-material',
            'recharts',
            'react-use',
            'effect',
            '@effect/schema',
            '@effect/platform',
            '@effect/platform-node',
            '@effect/platform-browser',
            '@effect/platform-bun',
            '@effect/sql',
            '@effect/sql-mssql',
            '@effect/sql-mysql2',
            '@effect/sql-pg',
            '@effect/sql-sqlite-node',
            '@effect/sql-sqlite-bun',
            '@effect/sql-sqlite-wasm',
            '@effect/sql-sqlite-react-native',
            '@effect/rpc',
            '@effect/rpc-http',
            '@effect/typeclass',
            '@effect/experimental',
            '@effect/opentelemetry',
            '@material-ui/core',
            '@material-ui/icons',
            '@tabler/icons-react',
            'mui-core',
            // We don't support wildcard imports for these configs, e.g. `react-icons/*`
            // so we need to add them manually.
            // In the future, we should consider automatically detecting packages that
            // need to be optimized.
            'react-icons/ai',
            'react-icons/bi',
            'react-icons/bs',
            'react-icons/cg',
            'react-icons/ci',
            'react-icons/di',
            'react-icons/fa',
            'react-icons/fa6',
            'react-icons/fc',
            'react-icons/fi',
            'react-icons/gi',
            'react-icons/go',
            'react-icons/gr',
            'react-icons/hi',
            'react-icons/hi2',
            'react-icons/im',
            'react-icons/io',
            'react-icons/io5',
            'react-icons/lia',
            'react-icons/lib',
            'react-icons/lu',
            'react-icons/md',
            'react-icons/pi',
            'react-icons/ri',
            'react-icons/rx',
            'react-icons/si',
            'react-icons/sl',
            'react-icons/tb',
            'react-icons/tfi',
            'react-icons/ti',
            'react-icons/vsc',
            'react-icons/wi'
        ])
    ];
    if (!result.htmlLimitedBots) {
        // @ts-expect-error: override the htmlLimitedBots with default string, type covert: RegExp -> string
        result.htmlLimitedBots = _isbot.HTML_LIMITED_BOT_UA_RE_STRING;
    }
    if (typeof result.experimental.mcpServer === 'undefined' && process.env.__NEXT_EXPERIMENTAL_MCP_SERVER === 'true') {
        result.experimental.mcpServer = true;
    }
    if (result.cacheComponents) {
        // TODO: remove once we've finished migrating internally to cacheComponents.
        result.experimental.ppr = true;
        // Prerender sourcemaps are enabled by default when using cacheComponents, unless explicitly disabled.
        if (result.enablePrerenderSourceMaps === undefined) {
            result.enablePrerenderSourceMaps = true;
        }
    }
    // "use cache" was originally implicitly enabled with the cacheComponents flag, so
    // we transfer the value for cacheComponents to the explicit useCache flag to ensure
    // backwards compatibility.
    if (result.experimental.useCache === undefined) {
        result.experimental.useCache = result.cacheComponents;
    }
    // Store the distDirRoot in the config before it is modified by the isolatedDevBuild flag
    ;
    result.distDirRoot = result.distDir;
    if (phase === _constants.PHASE_DEVELOPMENT_SERVER && result.experimental.isolatedDevBuild) {
        result.distDir = (0, _path.join)(result.distDir, 'dev');
    }
    return result;
}
async function applyModifyConfig(config, phase, silent) {
    var _config_experimental;
    // we always call modify config  and phase can be used to only
    // modify for specific times
    if ((_config_experimental = config.experimental) == null ? void 0 : _config_experimental.adapterPath) {
        const adapterMod = (0, _interopdefault.interopDefault)(await import((0, _url.pathToFileURL)(require.resolve(config.experimental.adapterPath)).href));
        if (typeof adapterMod.modifyConfig === 'function') {
            if (!silent) {
                _log.info(`Applying modifyConfig from ${adapterMod.name}`);
            }
            config = await adapterMod.modifyConfig(config, {
                phase
            });
        }
    }
    return config;
}
// Cache config with keys to handle multiple configurations (e.g., multi-zone)
const configCache = new Map();
// Generate cache key based on parameters that affect config output
// We need a unique key for cache because there can be multiple values
function getCacheKey(phase, dir, customConfig, reactProductionProfiling, debugPrerender, pid) {
    // The next.config.js is unique per project, so we can use the dir as the major key
    // to generate the unique config key. Include PID to invalidate on server restart.
    const keyData = JSON.stringify({
        dir,
        phase,
        hasCustomConfig: Boolean(customConfig),
        reactProductionProfiling: Boolean(reactProductionProfiling),
        debugPrerender: Boolean(debugPrerender),
        pid: pid || 0
    });
    return (0, _hash.djb2Hash)(keyData).toString(36);
}
async function loadConfig(phase, dir, { customConfig, rawConfig, silent = true, reportExperimentalFeatures, reactProductionProfiling, debugPrerender } = {}) {
    // Generate cache key based on parameters that affect config output
    // Include process.pid to invalidate cache on server restart
    const cacheKey = getCacheKey(phase, dir, customConfig, reactProductionProfiling, debugPrerender, process.pid);
    // Check if we have a cached result
    const cachedResult = configCache.get(cacheKey);
    if (cachedResult) {
        // Call the experimental features callback if provided
        if (reportExperimentalFeatures) {
            reportExperimentalFeatures(cachedResult.configuredExperimentalFeatures);
        }
        // Return raw config if requested and available
        if (rawConfig && cachedResult.rawConfig) {
            return cachedResult.rawConfig;
        }
        return cachedResult.config;
    } else {
        // Reset next.config errors before loading config
        // This happens on every config load to ensure fresh validation
        _nextinstanceerrorstate.NextInstanceErrorState.nextConfig = [];
    }
    // Original implementation continues below...
    if (!process.env.__NEXT_PRIVATE_RENDER_WORKER) {
        try {
            (0, _configutils.loadWebpackHook)();
        } catch (err) {
            // this can fail in standalone mode as the files
            // aren't traced/included
            if (!process.env.__NEXT_PRIVATE_STANDALONE_CONFIG) {
                throw err;
            }
        }
    }
    if (process.env.__NEXT_PRIVATE_STANDALONE_CONFIG) {
        // we don't apply assignDefaults or modifyConfig here as it
        // has already been applied
        const standaloneConfig = JSON.parse(process.env.__NEXT_PRIVATE_STANDALONE_CONFIG);
        // Cache the standalone config
        configCache.set(cacheKey, {
            config: standaloneConfig,
            rawConfig: standaloneConfig,
            configuredExperimentalFeatures: []
        });
        return standaloneConfig;
    }
    const curLog = silent ? {
        warn: ()=>{},
        info: ()=>{},
        error: ()=>{}
    } : _log;
    (0, _env.loadEnvConfig)(dir, phase === _constants.PHASE_DEVELOPMENT_SERVER, curLog);
    let configFileName = 'next.config.js';
    const configuredExperimentalFeatures = [];
    if (customConfig) {
        // Check deprecation warnings on the custom config before merging with defaults
        checkDeprecations(customConfig, configFileName, silent, dir);
        const config = await applyModifyConfig(assignDefaultsAndValidate(dir, {
            configOrigin: 'server',
            configFileName,
            ...customConfig
        }, silent, phase), phase, silent);
        // Cache the custom config result
        configCache.set(cacheKey, {
            config,
            rawConfig: customConfig,
            configuredExperimentalFeatures
        });
        reportExperimentalFeatures == null ? void 0 : reportExperimentalFeatures(configuredExperimentalFeatures);
        return config;
    }
    const path = await (0, _findup.default)(_constants.CONFIG_FILES, {
        cwd: dir
    });
    // If config file was found
    if (path == null ? void 0 : path.length) {
        var _userConfig_experimental;
        configFileName = (0, _path.basename)(path);
        let userConfigModule;
        try {
            const envBefore = Object.assign({}, process.env);
            // `import()` expects url-encoded strings, so the path must be properly
            // escaped and (especially on Windows) absolute paths must pe prefixed
            // with the `file://` protocol
            if (process.env.__NEXT_TEST_MODE === 'jest') {
                // dynamic import does not currently work inside of vm which
                // jest relies on so we fall back to require for this case
                // https://github.com/nodejs/node/issues/35889
                userConfigModule = require(path);
            } else if (configFileName === 'next.config.ts') {
                userConfigModule = await (0, _transpileconfig.transpileConfig)({
                    nextConfigPath: path,
                    configFileName,
                    cwd: dir
                });
            } else {
                userConfigModule = await import((0, _url.pathToFileURL)(path).href);
            }
            const newEnv = {};
            for (const key of Object.keys(process.env)){
                if (envBefore[key] !== process.env[key]) {
                    newEnv[key] = process.env[key];
                }
            }
            (0, _env.updateInitialEnv)(newEnv);
            if (rawConfig) {
                // Cache the raw config
                configCache.set(cacheKey, {
                    config: userConfigModule,
                    rawConfig: userConfigModule,
                    configuredExperimentalFeatures
                });
                reportExperimentalFeatures == null ? void 0 : reportExperimentalFeatures(configuredExperimentalFeatures);
                return userConfigModule;
            }
        } catch (err) {
            // Capture the error for MCP tool reporting
            _nextinstanceerrorstate.NextInstanceErrorState.nextConfig.push(err);
            // TODO: Modify docs to add cases of failing next.config.ts transformation
            curLog.error(`Failed to load ${configFileName}, see more info here https://nextjs.org/docs/messages/next-config-error`);
            throw err;
        }
        const loadedConfig = Object.freeze(await (0, _configshared.normalizeConfig)(phase, (0, _interopdefault.interopDefault)(userConfigModule)));
        if (loadedConfig.experimental) {
            for (const name of Object.keys(loadedConfig.experimental)){
                const value = loadedConfig.experimental[name];
                if (name.startsWith('turbopack') && !process.env.TURBOPACK) {
                    continue;
                }
                addConfiguredExperimentalFeature(configuredExperimentalFeatures, name, value);
            }
        }
        // Clone a new userConfig each time to avoid mutating the original
        const userConfig = cloneObject(loadedConfig);
        // Check deprecation warnings on the actual user config before merging with defaults
        checkDeprecations(userConfig, configFileName, silent, dir);
        // Always validate the config against schema in non minimal mode
        if (!process.env.NEXT_MINIMAL && !silent) {
            await validateConfigSchema(userConfig, configFileName, curLog.warn, (messages)=>{
                // Capture validation messages for MCP error reporting
                if (messages.length > 0) {
                    const fullMessage = messages.join('\n');
                    _nextinstanceerrorstate.NextInstanceErrorState.nextConfig.push(Object.defineProperty(new Error(fullMessage), "__NEXT_ERROR_CODE", {
                        value: "E394",
                        enumerable: false,
                        configurable: true
                    }));
                }
            });
        }
        if (userConfig.target && userConfig.target !== 'server') {
            throw Object.defineProperty(new Error(`The "target" property is no longer supported in ${configFileName}.\n` + 'See more info here https://nextjs.org/docs/messages/deprecated-target-config'), "__NEXT_ERROR_CODE", {
                value: "E478",
                enumerable: false,
                configurable: true
            });
        }
        if (reactProductionProfiling) {
            userConfig.reactProductionProfiling = reactProductionProfiling;
        }
        if ((_userConfig_experimental = userConfig.experimental) == null ? void 0 : _userConfig_experimental.useLightningcss) {
            var _css, _this, _userConfig_experimental1;
            const { loadBindings } = require('../build/swc');
            const isLightningSupported = (_this = await loadBindings((_userConfig_experimental1 = userConfig.experimental) == null ? void 0 : _userConfig_experimental1.useWasmBinary)) == null ? void 0 : (_css = _this.css) == null ? void 0 : _css.lightning;
            if (!isLightningSupported) {
                curLog.warn(`experimental.useLightningcss is set, but the setting is disabled because next-swc/wasm does not support it yet.`);
                userConfig.experimental.useLightningcss = false;
            }
        }
        // serialize the regex config into string
        if ((userConfig == null ? void 0 : userConfig.htmlLimitedBots) instanceof RegExp) {
            // @ts-expect-error: override the htmlLimitedBots with default string, type covert: RegExp -> string
            userConfig.htmlLimitedBots = userConfig.htmlLimitedBots.source;
        }
        enforceExperimentalFeatures(userConfig, {
            isDefaultConfig: false,
            configuredExperimentalFeatures,
            debugPrerender,
            phase
        });
        const completeConfig = assignDefaultsAndValidate(dir, {
            configOrigin: (0, _path.relative)(dir, path),
            configFile: path,
            configFileName,
            ...userConfig
        }, silent, phase);
        const finalConfig = await applyModifyConfig(completeConfig, phase, silent);
        // Cache the final result
        configCache.set(cacheKey, {
            config: finalConfig,
            rawConfig: userConfigModule,
            configuredExperimentalFeatures
        });
        if (reportExperimentalFeatures) {
            reportExperimentalFeatures(configuredExperimentalFeatures);
        }
        return finalConfig;
    } else {
        const configBaseName = (0, _path.basename)(_constants.CONFIG_FILES[0], (0, _path.extname)(_constants.CONFIG_FILES[0]));
        const unsupportedConfig = _findup.default.sync([
            `${configBaseName}.cjs`,
            `${configBaseName}.cts`,
            // TODO: Remove `as any` once we bump @types/node to v22.10.0+
            ...process.features.typescript ? [] : [
                'next.config.mts'
            ],
            `${configBaseName}.json`,
            `${configBaseName}.jsx`,
            `${configBaseName}.tsx`
        ], {
            cwd: dir
        });
        if (unsupportedConfig == null ? void 0 : unsupportedConfig.length) {
            throw Object.defineProperty(new Error(`Configuring Next.js via '${(0, _path.basename)(unsupportedConfig)}' is not supported. Please replace the file with 'next.config.js', 'next.config.mjs', or 'next.config.ts'.`), "__NEXT_ERROR_CODE", {
                value: "E203",
                enumerable: false,
                configurable: true
            });
        }
    }
    const clonedDefaultConfig = cloneObject(_configshared.defaultConfig);
    enforceExperimentalFeatures(clonedDefaultConfig, {
        isDefaultConfig: true,
        configuredExperimentalFeatures,
        debugPrerender,
        phase
    });
    // always call assignDefaults to ensure settings like
    // reactRoot can be updated correctly even with no next.config.js
    const completeConfig = assignDefaultsAndValidate(dir, {
        ...clonedDefaultConfig,
        configFileName
    }, silent, phase);
    (0, _setuphttpagentenv.setHttpClientAndAgentOptions)(completeConfig);
    const finalConfig = await applyModifyConfig(completeConfig, phase, silent);
    // Cache the default config result
    configCache.set(cacheKey, {
        config: finalConfig,
        rawConfig: clonedDefaultConfig,
        configuredExperimentalFeatures
    });
    if (reportExperimentalFeatures) {
        reportExperimentalFeatures(configuredExperimentalFeatures);
    }
    return finalConfig;
}
function enforceExperimentalFeatures(config, options) {
    const { configuredExperimentalFeatures, debugPrerender, isDefaultConfig, phase } = options;
    config.experimental ??= {};
    if (debugPrerender && (phase === _constants.PHASE_PRODUCTION_BUILD || phase === _constants.PHASE_EXPORT)) {
        // TODO: This is not an experimental feature, but should be enabled alongside other prerender debugging features.
        config.enablePrerenderSourceMaps = true;
        setExperimentalFeatureForDebugPrerender(config.experimental, 'serverSourceMaps', true, configuredExperimentalFeatures);
        setExperimentalFeatureForDebugPrerender(config.experimental, process.env.TURBOPACK ? 'turbopackMinify' : 'serverMinification', false, configuredExperimentalFeatures);
        setExperimentalFeatureForDebugPrerender(config.experimental, 'prerenderEarlyExit', false, configuredExperimentalFeatures);
    }
    // TODO: Remove this once we've made Cache Components the default.
    if (process.env.__NEXT_CACHE_COMPONENTS === 'true' && // We do respect an explicit value in the user config.
    (config.cacheComponents === undefined || isDefaultConfig && !config.cacheComponents)) {
        config.cacheComponents = true;
    }
    // TODO: Remove this once using the debug channel is the default.
    if (process.env.__NEXT_EXPERIMENTAL_DEBUG_CHANNEL === 'true' && // We do respect an explicit value in the user config.
    (config.experimental.reactDebugChannel === undefined || isDefaultConfig && !config.experimental.reactDebugChannel)) {
        config.experimental.reactDebugChannel = true;
        if (configuredExperimentalFeatures) {
            addConfiguredExperimentalFeature(configuredExperimentalFeatures, 'reactDebugChannel', true, 'enabled by `__NEXT_EXPERIMENTAL_DEBUG_CHANNEL`');
        }
    }
    if (process.env.__NEXT_EXPERIMENTAL_TRANSITION_INDICATOR === 'true' && // We do respect an explicit value in the user config.
    (config.experimental.transitionIndicator === undefined || isDefaultConfig && !config.experimental.transitionIndicator)) {
        config.experimental.transitionIndicator = true;
        if (configuredExperimentalFeatures) {
            addConfiguredExperimentalFeature(configuredExperimentalFeatures, 'transitionIndicator', true, 'enabled by `__NEXT_EXPERIMENTAL_TRANSITION_INDICATOR`');
        }
    }
    if (process.env.__NEXT_ENABLE_REACT_COMPILER === 'true' && // We do respect an explicit value in the user config.
    (config.reactCompiler === undefined || isDefaultConfig && !config.reactCompiler)) {
        config.reactCompiler = true;
    // TODO: Report if we enable non-experimental features via env
    }
}
function addConfiguredExperimentalFeature(configuredExperimentalFeatures, key, value, reason) {
    if (value !== _configshared.defaultConfig.experimental[key]) {
        configuredExperimentalFeatures.push({
            key,
            value,
            reason
        });
    }
}
function setExperimentalFeatureForDebugPrerender(experimentalConfig, key, value, configuredExperimentalFeatures) {
    if (experimentalConfig[key] !== value) {
        experimentalConfig[key] = value;
        if (configuredExperimentalFeatures) {
            const action = value === true ? 'enabled' : value === false ? 'disabled' : 'set';
            const reason = `${action} by \`--debug-prerender\``;
            addConfiguredExperimentalFeature(configuredExperimentalFeatures, key, value, reason);
        }
    }
}
function cloneObject(obj) {
    // Primitives & null
    if (obj === null || typeof obj !== 'object') {
        return obj;
    }
    // RegExp → clone via constructor
    if (obj instanceof RegExp) {
        return new RegExp(obj.source, obj.flags);
    }
    // Function → just reuse the function reference
    if (typeof obj === 'function') {
        return obj;
    }
    // Arrays → map each element
    if (Array.isArray(obj)) {
        return obj.map(cloneObject);
    }
    // Detect non‑plain objects (class instances)
    const proto = Object.getPrototypeOf(obj);
    const isPlainObject = proto === Object.prototype || proto === null;
    // If it's not a plain object, just return the original
    if (!isPlainObject) {
        return obj;
    }
    // Plain object → create a new object with the same prototype
    // and copy all properties, cloning data properties and keeping
    // accessor properties (getters/setters) as‑is.
    const result = Object.create(proto);
    for (const key of Reflect.ownKeys(obj)){
        const descriptor = Object.getOwnPropertyDescriptor(obj, key);
        if (descriptor && (descriptor.get || descriptor.set)) {
            // Accessor property → copy descriptor as‑is (get/set functions)
            Object.defineProperty(result, key, descriptor);
        } else {
            // Data property → clone the value
            result[key] = cloneObject(obj[key]);
        }
    }
    return result;
}
async function validateConfigSchema(userConfig, configFileName, warn, onValidationMessages) {
    // We only validate the config against schema in non minimal mode
    const { configSchema } = require('./config-schema');
    const state = configSchema.safeParse(userConfig);
    if (!state.success) {
        const [warnings, fatalErrors] = normalizeNextConfigZodErrors(state.error);
        const hasFatalErrors = fatalErrors.length > 0;
        // Group warnings first
        if (warnings.length > 0) {
            const warningMessages = [
                `Invalid ${configFileName} options detected: `
            ];
            for (const error of warnings){
                warningMessages.push(`    ${error.split('\n').join('\n    ')}`);
            }
            warningMessages.push('See more info here: https://nextjs.org/docs/messages/invalid-next-config');
            // Call the callback with validation messages if provided
            if (onValidationMessages) {
                onValidationMessages(warningMessages);
            }
            for (const message of warningMessages){
                warn(message);
            }
        }
        // Then throw hard errors
        if (hasFatalErrors) {
            await (0, _flushtelemetry.flushTelemetry)();
            const errorMessages = [
                `Fatal next config errors found in ${configFileName} that must be fixed:`
            ];
            for (const error of fatalErrors){
                errorMessages.push(`    ${error.split('\n').join('\n    ')}`);
            }
            errorMessages.push('These configuration options are required or have been migrated. Please update your configuration.');
            errorMessages.push('See more info here: https://nextjs.org/docs/messages/invalid-next-config');
            // Call the callback with validation messages if provided
            if (onValidationMessages) {
                onValidationMessages(errorMessages);
            }
            const fullErrorMessage = errorMessages.join('\n');
            throw Object.defineProperty(new Error(fullErrorMessage), "__NEXT_ERROR_CODE", {
                value: "E394",
                enumerable: false,
                configurable: true
            });
        }
    }
}

//# sourceMappingURL=config.js.map