-
Notifications
You must be signed in to change notification settings - Fork 27k
/
config.ts
1286 lines (1155 loc) · 39.2 KB
/
config.ts
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
import { existsSync } from 'fs'
import { basename, extname, join, relative, isAbsolute, resolve } from 'path'
import { pathToFileURL } from 'url'
import findUp from 'next/dist/compiled/find-up'
import * as Log from '../build/output/log'
import { CONFIG_FILES, PHASE_DEVELOPMENT_SERVER } from '../shared/lib/constants'
import { defaultConfig, normalizeConfig } from './config-shared'
import type {
ExperimentalConfig,
NextConfigComplete,
NextConfig,
TurboLoaderItem,
} from './config-shared'
import { loadWebpackHook } from './config-utils'
import { imageConfigDefault } from '../shared/lib/image-config'
import type { ImageConfig } from '../shared/lib/image-config'
import { loadEnvConfig, updateInitialEnv } from '@next/env'
import { flushAndExit } from '../telemetry/flush-and-exit'
import { findRootDir } from '../lib/find-root'
import { setHttpClientAndAgentOptions } from './setup-http-agent-env'
import { pathHasPrefix } from '../shared/lib/router/utils/path-has-prefix'
import { matchRemotePattern } from '../shared/lib/match-remote-pattern'
import type { ZodError } from 'next/dist/compiled/zod'
import { hasNextSupport } from '../server/ci-info'
import { transpileConfig } from '../build/next-config-ts/transpile-config'
import { dset } from '../shared/lib/dset'
import { normalizeZodErrors } from '../shared/lib/zod'
export { normalizeConfig } from './config-shared'
export type { DomainLocale, NextConfig } from './config-shared'
function normalizeNextConfigZodErrors(
error: ZodError<NextConfig>
): [errorMessages: string[], shouldExit: boolean] {
let shouldExit = false
const issues = normalizeZodErrors(error)
return [
issues.flatMap(({ issue, message }) => {
if (issue.path[0] === 'images') {
// We exit the build when encountering an error in the images config
shouldExit = true
}
return message
}),
shouldExit,
]
}
export function warnOptionHasBeenDeprecated(
config: NextConfig,
nestedPropertyKey: string,
reason: string,
silent: boolean
) {
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.warn(reason)
}
}
}
export function warnOptionHasBeenMovedOutOfExperimental(
config: NextConfig,
oldExperimentalKey: string,
newKey: string,
configFileName: string,
silent: boolean
) {
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 as any)[oldExperimentalKey]
}
return config
}
function warnCustomizedOption(
config: NextConfig,
key: string,
defaultValue: any,
customMessage: string,
configFileName: string,
silent: boolean
) {
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}.`
)
}
}
function assignDefaults(
dir: string,
userConfig: { [key: string]: any },
silent: boolean
) {
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<{ [key: string]: any }>(
(currentConfig, key) => {
const value = userConfig[key]
if (value === undefined || value === null) {
return currentConfig
}
if (key === 'distDir') {
if (typeof value !== 'string') {
throw new Error(
`Specified distDir is not a string, found type "${typeof value}"`
)
}
const userDistDir = value.trim()
// don't allow public as the distDir as this is a reserved folder for
// public files
if (userDistDir === 'public') {
throw 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`
)
}
// 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 new Error(
`Invalid distDir provided, distDir can not be an empty string. Please remove this config or set it to undefined`
)
}
}
if (key === 'pageExtensions') {
if (!Array.isArray(value)) {
throw new Error(
`Specified pageExtensions is not an array of strings, found "${value}". Please update this config or remove it.`
)
}
if (!value.length) {
throw new Error(
`Specified pageExtensions is an empty array. Please update it with the relevant extensions or remove it.`
)
}
value.forEach((ext) => {
if (typeof ext !== 'string') {
throw new Error(
`Specified pageExtensions is not an array of strings, found "${ext}" of type "${typeof ext}". Please update this config or remove it.`
)
}
})
}
if (!!value && value.constructor === Object) {
currentConfig[key] = {
...defaultConfig[key],
...Object.keys(value).reduce<any>((c, k) => {
const v = value[k]
if (v !== undefined && v !== null) {
c[k] = v
}
return c
}, {}),
}
} else {
currentConfig[key] = value
}
return currentConfig
},
{}
)
// TODO: remove these once we've made PPR default
// If this was defaulted to true, it implies that the configuration was
// overridden for testing to be defaulted on.
if (defaultConfig.experimental?.ppr) {
Log.warn(
`\`experimental.ppr\` has been defaulted to \`true\` because \`__NEXT_EXPERIMENTAL_PPR\` was set to \`true\` during testing.`
)
}
const result = { ...defaultConfig, ...config }
if (
result.experimental?.allowDevelopmentBuild &&
process.env.NODE_ENV !== 'development'
) {
throw new Error(
`The experimental.allowDevelopmentBuild option requires NODE_ENV to be explicitly set to 'development'.`
)
}
if (
!process.env.__NEXT_VERSION?.includes('canary') &&
!process.env.__NEXT_TEST_MODE
) {
// Prevents usage of certain experimental features outside of canary
if (result.experimental?.ppr) {
throw new CanaryOnlyError('experimental.ppr')
} else if (result.experimental?.dynamicIO) {
throw new CanaryOnlyError('experimental.dynamicIO')
} else if (result.experimental?.turbo?.unstablePersistentCaching) {
throw new CanaryOnlyError('experimental.turbo.unstablePersistentCaching')
}
}
if (result.output === 'export') {
if (result.i18n) {
throw new Error(
'Specified "i18n" cannot be used with "output: export". See more info here: https://nextjs.org/docs/messages/export-no-i18n'
)
}
if (!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 new Error(
`Specified assetPrefix is not a string, found type "${typeof result.assetPrefix}" https://nextjs.org/docs/messages/invalid-assetprefix`
)
}
if (typeof result.basePath !== 'string') {
throw new Error(
`Specified basePath is not a string, found type "${typeof result.basePath}"`
)
}
if (result.basePath !== '') {
if (result.basePath === '/') {
throw new Error(
`Specified basePath /. basePath has to be either an empty string or a path prefix"`
)
}
if (!result.basePath.startsWith('/')) {
throw new Error(
`Specified basePath has to start with a /, found "${result.basePath}"`
)
}
if (result.basePath !== '/') {
if (result.basePath.endsWith('/')) {
throw new Error(
`Specified basePath should not end with /, found "${result.basePath}"`
)
}
if (result.assetPrefix === '') {
result.assetPrefix = result.basePath
}
if (result.amp?.canonicalBase === '') {
result.amp.canonicalBase = result.basePath
}
}
}
if (result?.images) {
const images: ImageConfig = result.images
if (typeof images !== 'object') {
throw new Error(
`Specified images should be an object received ${typeof images}.\nSee more info here: https://nextjs.org/docs/messages/invalid-images-config`
)
}
if (images.localPatterns) {
if (!Array.isArray(images.localPatterns)) {
throw 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`
)
}
// 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: '',
})
}
}
if (images.remotePatterns) {
if (!Array.isArray(images.remotePatterns)) {
throw 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`
)
}
// static images are automatically prefixed with assetPrefix
// so we need to ensure _next/image allows downloading from
// this resource
if (config.assetPrefix?.startsWith('http')) {
try {
const url = new URL(config.assetPrefix)
const hasMatchForAssetPrefix = images.remotePatterns.some((pattern) =>
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(/:$/, '') as 'http' | 'https',
port: url.port,
})
}
} catch (error) {
throw new Error(
`Invalid assetPrefix provided. Original error: ${error}`
)
}
}
}
if (images.domains) {
if (!Array.isArray(images.domains)) {
throw 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`
)
}
}
if (!images.loader) {
images.loader = 'default'
}
if (
images.loader !== 'default' &&
images.loader !== 'custom' &&
images.path === imageConfigDefault.path
) {
throw 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`
)
}
if (
images.path === imageConfigDefault.path &&
result.basePath &&
!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 new Error(
`Specified images.loader property (${images.loader}) cannot be used with images.loaderFile property. Please set images.loader to "custom".`
)
}
const absolutePath = join(dir, images.loaderFile)
if (!existsSync(absolutePath)) {
throw new Error(
`Specified images.loaderFile does not exist at "${absolutePath}".`
)
}
images.loaderFile = absolutePath
}
}
warnCustomizedOption(
result,
'experimental.esmExternals',
true,
'experimental.esmExternals is not recommended to be modified as it may disrupt module resolution',
configFileName,
silent
)
warnOptionHasBeenDeprecated(
result,
'experimental.instrumentationHook',
'`experimental.instrumentationHook` is no longer needed to be configured in Next.js',
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,
'outputFileTracingRoot',
'outputFileTracingRoot',
configFileName,
silent
)
warnOptionHasBeenMovedOutOfExperimental(
result,
'outputFileTracingIncludes',
'outputFileTracingIncludes',
configFileName,
silent
)
warnOptionHasBeenMovedOutOfExperimental(
result,
'outputFileTracingExcludes',
'outputFileTracingExcludes',
configFileName,
silent
)
if ((result.experimental as any).outputStandalone) {
if (!silent) {
Log.warn(
`experimental.outputStandalone has been renamed to "output: 'standalone'", please move the config.`
)
}
result.output = 'standalone'
}
if (
typeof result.experimental?.serverActions?.bodySizeLimit !== 'undefined'
) {
const value = parseInt(
result.experimental.serverActions?.bodySizeLimit.toString()
)
if (isNaN(value) || value < 1) {
throw 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'
)
}
}
warnOptionHasBeenMovedOutOfExperimental(
result,
'transpilePackages',
'transpilePackages',
configFileName,
silent
)
warnOptionHasBeenMovedOutOfExperimental(
result,
'skipMiddlewareUrlNormalize',
'skipMiddlewareUrlNormalize',
configFileName,
silent
)
warnOptionHasBeenMovedOutOfExperimental(
result,
'skipTrailingSlashRedirect',
'skipTrailingSlashRedirect',
configFileName,
silent
)
if (
result?.outputFileTracingRoot &&
!isAbsolute(result.outputFileTracingRoot)
) {
result.outputFileTracingRoot = resolve(result.outputFileTracingRoot)
if (!silent) {
Log.warn(
`outputFileTracingRoot should be absolute, using: ${result.outputFileTracingRoot}`
)
}
}
if (
result?.experimental?.turbo?.root &&
!isAbsolute(result.experimental.turbo.root)
) {
result.experimental.turbo.root = resolve(result.experimental.turbo.root)
if (!silent) {
Log.warn(
`experimental.turbo.root should be absolute, using: ${result.experimental.turbo.root}`
)
}
}
// only leverage deploymentId
if (process.env.NEXT_DEPLOYMENT_ID) {
result.deploymentId = process.env.NEXT_DEPLOYMENT_ID
}
if (result?.outputFileTracingRoot && !result?.experimental?.turbo?.root) {
dset(
result,
['experimental', 'turbo', 'root'],
result.outputFileTracingRoot
)
}
// use the closest lockfile as tracing root
if (!result?.outputFileTracingRoot || !result?.experimental?.turbo?.root) {
let rootDir = findRootDir(dir)
if (rootDir) {
if (!result?.outputFileTracingRoot) {
result.outputFileTracingRoot = rootDir
defaultConfig.outputFileTracingRoot = result.outputFileTracingRoot
}
if (!result?.experimental?.turbo?.root) {
dset(result, ['experimental', 'turbo', 'root'], rootDir)
dset(defaultConfig, ['experimental', 'turbo', 'root'], rootDir)
}
}
}
setHttpClientAndAgentOptions(result || defaultConfig)
if (result.i18n) {
const { i18n } = result
const i18nType = typeof i18n
if (i18nType !== 'object') {
throw new Error(
`Specified i18n should be an object received ${i18nType}.\nSee more info here: https://nextjs.org/docs/messages/invalid-i18n-config`
)
}
if (!Array.isArray(i18n.locales)) {
throw 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`
)
}
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 new Error(
`Specified i18n.defaultLocale should be a string.\nSee more info here: https://nextjs.org/docs/messages/invalid-i18n-config`
)
}
if (typeof i18n.domains !== 'undefined' && !Array.isArray(i18n.domains)) {
throw 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`
)
}
if (i18n.domains) {
const invalidDomainItems = i18n.domains.filter((item) => {
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?.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 new Error(
`Invalid i18n.domains values:\n${invalidDomainItems
.map((item: any) => 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`
)
}
}
if (!Array.isArray(i18n.locales)) {
throw 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`
)
}
const invalidLocales = i18n.locales.filter(
(locale: any) => typeof locale !== 'string'
)
if (invalidLocales.length > 0) {
throw 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`
)
}
if (!i18n.locales.includes(i18n.defaultLocale)) {
throw new Error(
`Specified i18n.defaultLocale should be included in i18n.locales.\nSee more info here: https://nextjs.org/docs/messages/invalid-i18n-config`
)
}
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 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`
)
}
// 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 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`
)
}
}
if (result.devIndicators?.buildActivityPosition) {
const { buildActivityPosition } = result.devIndicators
const allowedValues = [
'top-left',
'top-right',
'bottom-left',
'bottom-right',
]
if (!allowedValues.includes(buildActivityPosition)) {
throw new Error(
`Invalid "devIndicator.buildActivityPosition" provided, expected one of ${allowedValues.join(
', '
)}, received ${buildActivityPosition}`
)
}
}
if (result.experimental) {
result.experimental.cacheLife = {
...defaultConfig.experimental?.cacheLife,
...result.experimental.cacheLife,
}
const defaultDefault = defaultConfig.experimental?.cacheLife?.['default']
if (
!defaultDefault ||
defaultDefault.revalidate === undefined ||
defaultDefault.expire === undefined ||
!defaultConfig.experimental?.staleTimes?.static
) {
throw new Error('No default cacheLife profile.')
}
const defaultCacheLifeProfile = result.experimental.cacheLife['default']
if (!defaultCacheLifeProfile) {
result.experimental.cacheLife['default'] = defaultDefault
} else {
if (defaultCacheLifeProfile.stale === undefined) {
const staticStaleTime = result.experimental.staleTimes?.static
defaultCacheLifeProfile.stale =
staticStaleTime ?? defaultConfig.experimental?.staleTimes?.static
}
if (defaultCacheLifeProfile.revalidate === undefined) {
defaultCacheLifeProfile.revalidate = defaultDefault.revalidate
}
if (defaultCacheLifeProfile.expire === undefined) {
defaultCacheLifeProfile.expire =
result.expireTime ?? defaultDefault.expire
}
}
// This is the most dynamic cache life profile.
const secondsCacheLifeProfile = result.experimental.cacheLife['seconds']
if (
secondsCacheLifeProfile &&
secondsCacheLifeProfile.stale === undefined
) {
// We default this to whatever stale time you had configured for dynamic content.
// Since this is basically a dynamic cache life profile.
const dynamicStaleTime = result.experimental.staleTimes?.dynamic
secondsCacheLifeProfile.stale =
dynamicStaleTime ?? defaultConfig.experimental?.staleTimes?.dynamic
}
}
if (result.experimental?.cacheHandlers) {
const allowedHandlerNameRegex = /[a-z-]/
if (typeof result.experimental.cacheHandlers !== 'object') {
throw new Error(
`Invalid "experimental.cacheHandlers" provided, expected an object e.g. { default: '/my-handler.js' }, received ${JSON.stringify(result.experimental.cacheHandlers)}`
)
}
const handlerKeys = Object.keys(result.experimental.cacheHandlers)
const invalidHandlerItems: Array<{ key: string; reason: string }> = []
for (const key of handlerKeys) {
if (!allowedHandlerNameRegex.test(key)) {
invalidHandlerItems.push({
key,
reason: 'key must only use characters a-z and -',
})
} else {
const handlerPath = result.experimental.cacheHandlers[key]
if (handlerPath && !existsSync(handlerPath)) {
invalidHandlerItems.push({
key,
reason: `cache handler path provided does not exist, received ${handlerPath}`,
})
}
}
if (invalidHandlerItems.length) {
throw new Error(
`Invalid handler fields configured for "experimental.cacheHandler":\n${invalidHandlerItems.map((item) => `${key}: ${item.reason}`).join('\n')}`
)
}
}
}
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.experimental?.optimizePackageImports || []
if (!result.experimental) {
result.experimental = {}
}
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-squlite-node',
'@effect/sql-squlite-bun',
'@effect/sql-squlite-wasm',
'@effect/sql-squlite-react-native',
'@effect/sql-squlite-wasm',
'@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',
]),
]
return result
}