-
Notifications
You must be signed in to change notification settings - Fork 31.5k
Expand file tree
/
Copy pathindex.ts
More file actions
3447 lines (3094 loc) · 118 KB
/
Copy pathindex.ts
File metadata and controls
3447 lines (3094 loc) · 118 KB
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 type { AppBuildManifest } from './webpack/plugins/app-build-manifest-plugin'
import type { PagesManifest } from './webpack/plugins/pages-manifest-plugin'
import type { ExportPathMap, NextConfigComplete } from '../server/config-shared'
import type { MiddlewareManifest } from './webpack/plugins/middleware-plugin'
import type { ActionManifest } from './webpack/plugins/flight-client-entry-plugin'
import type { ExportAppOptions } from '../export/types'
import type { Revalidate } from '../server/lib/revalidate'
import '../lib/setup-exception-listeners'
import { loadEnvConfig, type LoadedEnvFiles } from '@next/env'
import { bold, yellow } from '../lib/picocolors'
import crypto from 'crypto'
import { makeRe } from 'next/dist/compiled/picomatch'
import { existsSync, promises as fs } from 'fs'
import os from 'os'
import { Worker } from '../lib/worker'
import { defaultConfig } from '../server/config-shared'
import devalue from 'next/dist/compiled/devalue'
import findUp from 'next/dist/compiled/find-up'
import { nanoid } from 'next/dist/compiled/nanoid/index.cjs'
import { Sema } from 'next/dist/compiled/async-sema'
import path from 'path'
import {
STATIC_STATUS_PAGE_GET_INITIAL_PROPS_ERROR,
PUBLIC_DIR_MIDDLEWARE_CONFLICT,
MIDDLEWARE_FILENAME,
PAGES_DIR_ALIAS,
INSTRUMENTATION_HOOK_FILENAME,
RSC_PREFETCH_SUFFIX,
RSC_SUFFIX,
} from '../lib/constants'
import { FileType, fileExists } from '../lib/file-exists'
import { findPagesDir } from '../lib/find-pages-dir'
import loadCustomRoutes, {
normalizeRouteRegex,
} from '../lib/load-custom-routes'
import type {
CustomRoutes,
Header,
Redirect,
Rewrite,
RouteHas,
} from '../lib/load-custom-routes'
import { nonNullable } from '../lib/non-nullable'
import { recursiveDelete } from '../lib/recursive-delete'
import { verifyPartytownSetup } from '../lib/verify-partytown-setup'
import { validateTurboNextConfig } from '../lib/turbopack-warning'
import {
BUILD_ID_FILE,
BUILD_MANIFEST,
CLIENT_STATIC_FILES_PATH,
EXPORT_DETAIL,
EXPORT_MARKER,
AUTOMATIC_FONT_OPTIMIZATION_MANIFEST,
IMAGES_MANIFEST,
PAGES_MANIFEST,
PHASE_PRODUCTION_BUILD,
PRERENDER_MANIFEST,
REACT_LOADABLE_MANIFEST,
ROUTES_MANIFEST,
SERVER_DIRECTORY,
SERVER_FILES_MANIFEST,
STATIC_STATUS_PAGES,
MIDDLEWARE_MANIFEST,
APP_PATHS_MANIFEST,
APP_PATH_ROUTES_MANIFEST,
APP_BUILD_MANIFEST,
RSC_MODULE_TYPES,
NEXT_FONT_MANIFEST,
SUBRESOURCE_INTEGRITY_MANIFEST,
MIDDLEWARE_BUILD_MANIFEST,
MIDDLEWARE_REACT_LOADABLE_MANIFEST,
SERVER_REFERENCE_MANIFEST,
FUNCTIONS_CONFIG_MANIFEST,
UNDERSCORE_NOT_FOUND_ROUTE_ENTRY,
UNDERSCORE_NOT_FOUND_ROUTE,
} from '../shared/lib/constants'
import { getSortedRoutes, isDynamicRoute } from '../shared/lib/router/utils'
import type { __ApiPreviewProps } from '../server/api-utils'
import loadConfig from '../server/config'
import type { BuildManifest } from '../server/get-page-files'
import { normalizePagePath } from '../shared/lib/page-path/normalize-page-path'
import { getPagePath } from '../server/require'
import * as ciEnvironment from '../telemetry/ci-info'
import {
turborepoTraceAccess,
TurborepoAccessTraceResult,
writeTurborepoAccessTraceResult,
} from './turborepo-access-trace'
import {
eventBuildOptimize,
eventCliSession,
eventBuildFeatureUsage,
eventNextPlugins,
EVENT_BUILD_FEATURE_USAGE,
eventPackageUsedInGetServerSideProps,
eventBuildCompleted,
} from '../telemetry/events'
import type { EventBuildFeatureUsage } from '../telemetry/events'
import { Telemetry } from '../telemetry/storage'
import {
isDynamicMetadataRoute,
getPageStaticInfo,
} from './analysis/get-page-static-info'
import { createPagesMapping, getPageFilePath, sortByPageExts } from './entries'
import { PAGE_TYPES } from '../lib/page-types'
import { generateBuildId } from './generate-build-id'
import { isWriteable } from './is-writeable'
import * as Log from './output/log'
import createSpinner from './spinner'
import { trace, flushAllTraces, setGlobal, type Span } from '../trace'
import {
detectConflictingPaths,
computeFromManifest,
getJsPageSizeInKb,
printCustomRoutes,
printTreeView,
copyTracedFiles,
isReservedPage,
isAppBuiltinNotFoundPage,
serializePageInfos,
} from './utils'
import type { PageInfo, PageInfos, AppConfig } from './utils'
import { writeBuildId } from './write-build-id'
import { normalizeLocalePath } from '../shared/lib/i18n/normalize-locale-path'
import isError from '../lib/is-error'
import type { NextError } from '../lib/is-error'
import { isEdgeRuntime } from '../lib/is-edge-runtime'
import { recursiveCopy } from '../lib/recursive-copy'
import { recursiveReadDir } from '../lib/recursive-readdir'
import {
loadBindings,
lockfilePatchPromise,
teardownTraceSubscriber,
teardownHeapProfiler,
createDefineEnv,
} from './swc'
import { getNamedRouteRegex } from '../shared/lib/router/utils/route-regex'
import { getFilesInDir } from '../lib/get-files-in-dir'
import { eventSwcPlugins } from '../telemetry/events/swc-plugins'
import { normalizeAppPath } from '../shared/lib/router/utils/app-paths'
import {
ACTION,
NEXT_ROUTER_PREFETCH_HEADER,
RSC_HEADER,
RSC_CONTENT_TYPE_HEADER,
NEXT_ROUTER_STATE_TREE,
NEXT_DID_POSTPONE_HEADER,
} from '../client/components/app-router-headers'
import { webpackBuild } from './webpack-build'
import { NextBuildContext, type MappedPages } from './build-context'
import { normalizePathSep } from '../shared/lib/page-path/normalize-path-sep'
import { isAppRouteRoute } from '../lib/is-app-route-route'
import { createClientRouterFilter } from '../lib/create-client-router-filter'
import { createValidFileMatcher } from '../server/lib/find-page-file'
import { startTypeChecking } from './type-check'
import { generateInterceptionRoutesRewrites } from '../lib/generate-interception-routes-rewrites'
import { buildDataRoute } from '../server/lib/router-utils/build-data-route'
import { initialize as initializeIncrementalCache } from '../server/lib/incremental-cache-server'
import { nodeFs } from '../server/lib/node-fs-methods'
import { collectBuildTraces } from './collect-build-traces'
import type { BuildTraceContext } from './webpack/plugins/next-trace-entrypoints-plugin'
import { formatManifest } from './manifests/formatter/format-manifest'
import { getStartServerInfo, logStartInfo } from '../server/lib/app-info-log'
import type { NextEnabledDirectories } from '../server/base-server'
import { hasCustomExportOutput } from '../export/utils'
import { interopDefault } from '../lib/interop-default'
import { formatDynamicImportPath } from '../lib/format-dynamic-import-path'
import { isInterceptionRouteAppPath } from '../server/future/helpers/interception-routes'
import {
getTurbopackJsConfig,
handleEntrypoints,
type EntryIssuesMap,
handleRouteType,
handlePagesErrorRoute,
formatIssue,
isRelevantWarning,
} from '../server/dev/turbopack-utils'
import { TurbopackManifestLoader } from '../server/dev/turbopack/manifest-loader'
import type { Entrypoints } from '../server/dev/turbopack/types'
import { buildCustomRoute } from '../lib/build-custom-route'
import { createProgress } from './progress'
import { traceMemoryUsage } from '../lib/memory/trace'
import { generateEncryptionKeyBase64 } from '../server/app-render/encryption-utils'
import type { DeepReadonly } from '../shared/lib/deep-readonly'
import { getNodeOptionsWithoutInspect } from '../server/lib/utils'
interface ExperimentalBypassForInfo {
experimentalBypassFor?: RouteHas[]
}
interface ExperimentalPPRInfo {
experimentalPPR: boolean | undefined
}
interface DataRouteRouteInfo {
dataRoute: string | null
prefetchDataRoute: string | null | undefined
}
export interface SsgRoute
extends ExperimentalBypassForInfo,
DataRouteRouteInfo,
ExperimentalPPRInfo {
initialRevalidateSeconds: Revalidate
srcRoute: string | null
initialStatus?: number
initialHeaders?: Record<string, string>
}
export interface DynamicSsgRoute
extends ExperimentalBypassForInfo,
DataRouteRouteInfo,
ExperimentalPPRInfo {
fallback: string | null | false
routeRegex: string
dataRouteRegex: string | null
prefetchDataRouteRegex: string | null | undefined
}
export type PrerenderManifest = {
version: 4
routes: { [route: string]: SsgRoute }
dynamicRoutes: { [route: string]: DynamicSsgRoute }
notFoundRoutes: string[]
preview: __ApiPreviewProps
}
type ManifestBuiltRoute = {
/**
* The route pattern used to match requests for this route.
*/
regex: string
}
export type ManifestRewriteRoute = ManifestBuiltRoute & Rewrite
export type ManifestRedirectRoute = ManifestBuiltRoute & Redirect
export type ManifestHeaderRoute = ManifestBuiltRoute & Header
export type ManifestRoute = ManifestBuiltRoute & {
page: string
namedRegex?: string
routeKeys?: { [key: string]: string }
}
export type ManifestDataRoute = {
page: string
routeKeys?: { [key: string]: string }
dataRouteRegex: string
namedDataRouteRegex?: string
}
export type RoutesManifest = {
version: number
pages404: boolean
basePath: string
redirects: Array<Redirect>
rewrites?:
| Array<ManifestRewriteRoute>
| {
beforeFiles: Array<ManifestRewriteRoute>
afterFiles: Array<ManifestRewriteRoute>
fallback: Array<ManifestRewriteRoute>
}
headers: Array<ManifestHeaderRoute>
staticRoutes: Array<ManifestRoute>
dynamicRoutes: Array<ManifestRoute>
dataRoutes: Array<ManifestDataRoute>
i18n?: {
domains?: Array<{
http?: true
domain: string
locales?: string[]
defaultLocale: string
}>
locales: string[]
defaultLocale: string
localeDetection?: false
}
rsc: {
header: typeof RSC_HEADER
didPostponeHeader: typeof NEXT_DID_POSTPONE_HEADER
varyHeader: string
prefetchHeader: typeof NEXT_ROUTER_PREFETCH_HEADER
suffix: typeof RSC_SUFFIX
prefetchSuffix: typeof RSC_PREFETCH_SUFFIX
}
skipMiddlewareUrlNormalize?: boolean
caseSensitive?: boolean
}
function pageToRoute(page: string) {
const routeRegex = getNamedRouteRegex(page, true)
return {
page,
regex: normalizeRouteRegex(routeRegex.re.source),
routeKeys: routeRegex.routeKeys,
namedRegex: routeRegex.namedRegex,
}
}
function getCacheDir(distDir: string): string {
const cacheDir = path.join(distDir, 'cache')
if (ciEnvironment.isCI && !ciEnvironment.hasNextSupport) {
const hasCache = existsSync(cacheDir)
if (!hasCache) {
// Intentionally not piping to stderr which is what `Log.warn` does in case people fail in CI when
// stderr is detected.
console.log(
`${Log.prefixes.warn} No build cache found. Please configure build caching for faster rebuilds. Read more: https://nextjs.org/docs/messages/no-cache`
)
}
}
return cacheDir
}
async function writeFileUtf8(filePath: string, content: string): Promise<void> {
await fs.writeFile(filePath, content, 'utf-8')
}
function readFileUtf8(filePath: string): Promise<string> {
return fs.readFile(filePath, 'utf8')
}
async function writeManifest<T extends object>(
filePath: string,
manifest: T
): Promise<void> {
await writeFileUtf8(filePath, formatManifest(manifest))
}
async function readManifest<T extends object>(filePath: string): Promise<T> {
return JSON.parse(await readFileUtf8(filePath))
}
async function writePrerenderManifest(
distDir: string,
manifest: DeepReadonly<PrerenderManifest>
): Promise<void> {
await writeManifest(path.join(distDir, PRERENDER_MANIFEST), manifest)
}
async function writeClientSsgManifest(
prerenderManifest: DeepReadonly<PrerenderManifest>,
{
buildId,
distDir,
locales,
}: { buildId: string; distDir: string; locales: string[] }
) {
const ssgPages = new Set<string>(
[
...Object.entries(prerenderManifest.routes)
// Filter out dynamic routes
.filter(([, { srcRoute }]) => srcRoute == null)
.map(([route]) => normalizeLocalePath(route, locales).pathname),
...Object.keys(prerenderManifest.dynamicRoutes),
].sort()
)
const clientSsgManifestContent = `self.__SSG_MANIFEST=${devalue(
ssgPages
)};self.__SSG_MANIFEST_CB&&self.__SSG_MANIFEST_CB()`
await writeFileUtf8(
path.join(distDir, CLIENT_STATIC_FILES_PATH, buildId, '_ssgManifest.js'),
clientSsgManifestContent
)
}
interface FunctionsConfigManifest {
version: number
functions: Record<string, Record<string, string | number>>
}
async function writeFunctionsConfigManifest(
distDir: string,
manifest: FunctionsConfigManifest
): Promise<void> {
await writeManifest(
path.join(distDir, SERVER_DIRECTORY, FUNCTIONS_CONFIG_MANIFEST),
manifest
)
}
interface RequiredServerFilesManifest {
version: number
config: NextConfigComplete
appDir: string
relativeAppDir: string
files: string[]
ignore: string[]
}
async function writeRequiredServerFilesManifest(
distDir: string,
requiredServerFiles: RequiredServerFilesManifest
) {
await writeManifest(
path.join(distDir, SERVER_FILES_MANIFEST),
requiredServerFiles
)
}
async function writeImagesManifest(
distDir: string,
config: NextConfigComplete
): Promise<void> {
const images = { ...config.images }
const { deviceSizes, imageSizes } = images
;(images as any).sizes = [...deviceSizes, ...imageSizes]
// By default, remotePatterns will allow no remote images ([])
images.remotePatterns = (config?.images?.remotePatterns || []).map((p) => ({
// Modifying the manifest should also modify matchRemotePattern()
protocol: p.protocol,
hostname: makeRe(p.hostname).source,
port: p.port,
pathname: makeRe(p.pathname ?? '**', { dot: true }).source,
search: p.search,
}))
// By default, localPatterns will allow all local images (undefined)
if (config?.images?.localPatterns) {
images.localPatterns = config.images.localPatterns.map((p) => ({
// Modifying the manifest should also modify matchLocalPattern()
pathname: makeRe(p.pathname ?? '**', { dot: true }).source,
search: p.search,
}))
}
await writeManifest(path.join(distDir, IMAGES_MANIFEST), {
version: 1,
images,
})
}
const STANDALONE_DIRECTORY = 'standalone' as const
async function writeStandaloneDirectory(
nextBuildSpan: Span,
distDir: string,
pageKeys: { pages: string[]; app: string[] | undefined },
denormalizedAppPages: string[] | undefined,
outputFileTracingRoot: string,
requiredServerFiles: RequiredServerFilesManifest,
middlewareManifest: MiddlewareManifest,
hasInstrumentationHook: boolean,
staticPages: Set<string>,
loadedEnvFiles: LoadedEnvFiles,
appDir: string | undefined
) {
await nextBuildSpan
.traceChild('write-standalone-directory')
.traceAsyncFn(async () => {
await copyTracedFiles(
// requiredServerFiles.appDir Refers to the application directory, not App Router.
requiredServerFiles.appDir,
distDir,
pageKeys.pages,
denormalizedAppPages,
outputFileTracingRoot,
requiredServerFiles.config,
middlewareManifest,
hasInstrumentationHook,
staticPages
)
for (const file of [
...requiredServerFiles.files,
path.join(requiredServerFiles.config.distDir, SERVER_FILES_MANIFEST),
...loadedEnvFiles.reduce<string[]>((acc, envFile) => {
if (['.env', '.env.production'].includes(envFile.path)) {
acc.push(envFile.path)
}
return acc
}, []),
]) {
// requiredServerFiles.appDir Refers to the application directory, not App Router.
const filePath = path.join(requiredServerFiles.appDir, file)
const outputPath = path.join(
distDir,
STANDALONE_DIRECTORY,
path.relative(outputFileTracingRoot, filePath)
)
await fs.mkdir(path.dirname(outputPath), {
recursive: true,
})
await fs.copyFile(filePath, outputPath)
}
await recursiveCopy(
path.join(distDir, SERVER_DIRECTORY, 'pages'),
path.join(
distDir,
STANDALONE_DIRECTORY,
path.relative(outputFileTracingRoot, distDir),
SERVER_DIRECTORY,
'pages'
),
{ overwrite: true }
)
if (appDir) {
const originalServerApp = path.join(distDir, SERVER_DIRECTORY, 'app')
if (existsSync(originalServerApp)) {
await recursiveCopy(
originalServerApp,
path.join(
distDir,
STANDALONE_DIRECTORY,
path.relative(outputFileTracingRoot, distDir),
SERVER_DIRECTORY,
'app'
),
{ overwrite: true }
)
}
}
})
}
function getNumberOfWorkers(config: NextConfigComplete) {
if (
config.experimental.cpus &&
config.experimental.cpus !== defaultConfig.experimental!.cpus
) {
return config.experimental.cpus
}
if (config.experimental.memoryBasedWorkersCount) {
return Math.max(
Math.min(config.experimental.cpus || 1, Math.floor(os.freemem() / 1e9)),
// enforce a minimum of 4 workers
4
)
}
if (config.experimental.cpus) {
return config.experimental.cpus
}
// Fall back to 4 workers if a count is not specified
return 4
}
const staticWorkerPath = require.resolve('./worker')
const staticWorkerExposedMethods = [
'hasCustomGetInitialProps',
'isPageStatic',
'getDefinedNamedExports',
'exportPage',
] as const
type StaticWorker = typeof import('./worker') & Worker
type PageDataCollectionKeys = Exclude<
(typeof staticWorkerExposedMethods)[number],
'exportPage'
>
function createStaticWorker(
config: NextConfigComplete,
incrementalCacheIpcPort?: number,
incrementalCacheIpcValidationKey?: string
): StaticWorker {
let infoPrinted = false
const timeout = config.staticPageGenerationTimeout || 0
return new Worker(staticWorkerPath, {
timeout: timeout * 1000,
logger: Log,
onRestart: (method, args, attempts) => {
if (method === 'exportPage') {
const [arg] = args as Parameters<StaticWorker['exportPage']>
const pagePath = arg.path
if (attempts >= 3) {
throw new Error(
`Static page generation for ${pagePath} is still timing out after 3 attempts. See more info here https://nextjs.org/docs/messages/static-page-generation-timeout`
)
}
Log.warn(
`Restarted static page generation for ${pagePath} because it took more than ${timeout} seconds`
)
} else {
const [arg] = args as Parameters<StaticWorker[PageDataCollectionKeys]>
const pagePath = arg.page
if (attempts >= 2) {
throw new Error(
`Collecting page data for ${pagePath} is still timing out after 2 attempts. See more info here https://nextjs.org/docs/messages/page-data-collection-timeout`
)
}
Log.warn(
`Restarted collecting page data for ${pagePath} because it took more than ${timeout} seconds`
)
}
if (!infoPrinted) {
Log.warn(
'See more info here https://nextjs.org/docs/messages/static-page-generation-timeout'
)
infoPrinted = true
}
},
numWorkers: getNumberOfWorkers(config),
forkOptions: {
env: {
...process.env,
__NEXT_INCREMENTAL_CACHE_IPC_PORT: incrementalCacheIpcPort
? incrementalCacheIpcPort + ''
: undefined,
__NEXT_INCREMENTAL_CACHE_IPC_KEY: incrementalCacheIpcValidationKey,
// we don't pass down NODE_OPTIONS as it can
// extra memory usage
NODE_OPTIONS: getNodeOptionsWithoutInspect()
.replace(/--max-old-space-size=[\d]{1,}/, '')
.trim(),
},
},
enableWorkerThreads: config.experimental.workerThreads,
exposedMethods: staticWorkerExposedMethods,
}) as StaticWorker
}
async function writeFullyStaticExport(
config: NextConfigComplete,
incrementalCacheIpcPort: number | undefined,
incrementalCacheIpcValidationKey: string | undefined,
dir: string,
enabledDirectories: NextEnabledDirectories,
configOutDir: string,
nextBuildSpan: Span
): Promise<void> {
const exportApp = require('../export')
.default as typeof import('../export').default
const pagesWorker = createStaticWorker(
config,
incrementalCacheIpcPort,
incrementalCacheIpcValidationKey
)
const appWorker = createStaticWorker(
config,
incrementalCacheIpcPort,
incrementalCacheIpcValidationKey
)
await exportApp(
dir,
{
buildExport: false,
nextConfig: config,
enabledDirectories,
silent: true,
threads: config.experimental.cpus,
outdir: path.join(dir, configOutDir),
// The worker already explicitly binds `this` to each of the
// exposed methods.
exportAppPageWorker: appWorker?.exportPage,
exportPageWorker: pagesWorker?.exportPage,
endWorker: async () => {
await pagesWorker.end()
await appWorker.end()
},
},
nextBuildSpan
)
// ensure the worker is not left hanging
pagesWorker.close()
appWorker.close()
}
async function getBuildId(
isGenerateMode: boolean,
distDir: string,
nextBuildSpan: Span,
config: NextConfigComplete
) {
if (isGenerateMode) {
return await fs.readFile(path.join(distDir, 'BUILD_ID'), 'utf8')
}
return await nextBuildSpan
.traceChild('generate-buildid')
.traceAsyncFn(() => generateBuildId(config.generateBuildId, nanoid))
}
const IS_TURBOPACK_BUILD = process.env.TURBOPACK && process.env.TURBOPACK_BUILD
export default async function build(
dir: string,
reactProductionProfiling = false,
debugOutput = false,
runLint = true,
noMangling = false,
appDirOnly = false,
turboNextBuild = false,
experimentalBuildMode: 'default' | 'compile' | 'generate'
): Promise<void> {
const isCompileMode = experimentalBuildMode === 'compile'
const isGenerateMode = experimentalBuildMode === 'generate'
try {
const nextBuildSpan = trace('next-build', undefined, {
buildMode: experimentalBuildMode,
isTurboBuild: String(turboNextBuild),
version: process.env.__NEXT_VERSION as string,
})
NextBuildContext.nextBuildSpan = nextBuildSpan
NextBuildContext.dir = dir
NextBuildContext.appDirOnly = appDirOnly
NextBuildContext.reactProductionProfiling = reactProductionProfiling
NextBuildContext.noMangling = noMangling
await nextBuildSpan.traceAsyncFn(async () => {
// attempt to load global env values so they are available in next.config.js
const { loadedEnvFiles } = nextBuildSpan
.traceChild('load-dotenv')
.traceFn(() => loadEnvConfig(dir, false, Log))
NextBuildContext.loadedEnvFiles = loadedEnvFiles
const turborepoAccessTraceResult = new TurborepoAccessTraceResult()
const config: NextConfigComplete = await nextBuildSpan
.traceChild('load-next-config')
.traceAsyncFn(() =>
turborepoTraceAccess(
() =>
loadConfig(PHASE_PRODUCTION_BUILD, dir, {
// Log for next.config loading process
silent: false,
}),
turborepoAccessTraceResult
)
)
process.env.NEXT_DEPLOYMENT_ID = config.deploymentId || ''
NextBuildContext.config = config
let configOutDir = 'out'
if (hasCustomExportOutput(config)) {
configOutDir = config.distDir
config.distDir = '.next'
}
const distDir = path.join(dir, config.distDir)
setGlobal('phase', PHASE_PRODUCTION_BUILD)
setGlobal('distDir', distDir)
const buildId = await getBuildId(
isGenerateMode,
distDir,
nextBuildSpan,
config
)
NextBuildContext.buildId = buildId
const customRoutes: CustomRoutes = await nextBuildSpan
.traceChild('load-custom-routes')
.traceAsyncFn(() => loadCustomRoutes(config))
const { headers, rewrites, redirects } = customRoutes
const combinedRewrites: Rewrite[] = [
...rewrites.beforeFiles,
...rewrites.afterFiles,
...rewrites.fallback,
]
const hasRewrites = combinedRewrites.length > 0
NextBuildContext.originalRewrites = config._originalRewrites
NextBuildContext.originalRedirects = config._originalRedirects
const cacheDir = getCacheDir(distDir)
const telemetry = new Telemetry({ distDir })
setGlobal('telemetry', telemetry)
const publicDir = path.join(dir, 'public')
const { pagesDir, appDir } = findPagesDir(dir)
NextBuildContext.pagesDir = pagesDir
NextBuildContext.appDir = appDir
const enabledDirectories: NextEnabledDirectories = {
app: typeof appDir === 'string',
pages: typeof pagesDir === 'string',
}
// Generate a random encryption key for this build.
// This key is used to encrypt cross boundary values and can be used to generate hashes.
const encryptionKey = await generateEncryptionKeyBase64()
NextBuildContext.encryptionKey = encryptionKey
const isSrcDir = path
.relative(dir, pagesDir || appDir || '')
.startsWith('src')
const hasPublicDir = existsSync(publicDir)
telemetry.record(
eventCliSession(dir, config, {
webpackVersion: 5,
cliCommand: 'build',
isSrcDir,
hasNowJson: !!(await findUp('now.json', { cwd: dir })),
isCustomServer: null,
turboFlag: false,
pagesDir: !!pagesDir,
appDir: !!appDir,
})
)
eventNextPlugins(path.resolve(dir)).then((events) =>
telemetry.record(events)
)
eventSwcPlugins(path.resolve(dir), config).then((events) =>
telemetry.record(events)
)
// Always log next version first then start rest jobs
const { envInfo, expFeatureInfo } = await getStartServerInfo(dir, false)
logStartInfo({
networkUrl: null,
appUrl: null,
envInfo,
expFeatureInfo,
})
const ignoreESLint = Boolean(config.eslint.ignoreDuringBuilds)
const shouldLint = !ignoreESLint && runLint
const typeCheckingOptions: Parameters<typeof startTypeChecking>[0] = {
dir,
appDir,
pagesDir,
runLint,
shouldLint,
ignoreESLint,
telemetry,
nextBuildSpan,
config,
cacheDir,
}
// For app directory, we run type checking after build. That's because
// we dynamically generate types for each layout and page in the app
// directory.
if (!appDir && !isCompileMode)
await startTypeChecking(typeCheckingOptions)
if (appDir && 'exportPathMap' in config) {
Log.error(
'The "exportPathMap" configuration cannot be used with the "app" directory. Please use generateStaticParams() instead.'
)
await telemetry.flush()
process.exit(1)
}
const buildLintEvent: EventBuildFeatureUsage = {
featureName: 'build-lint',
invocationCount: shouldLint ? 1 : 0,
}
telemetry.record({
eventName: EVENT_BUILD_FEATURE_USAGE,
payload: buildLintEvent,
})
const validFileMatcher = createValidFileMatcher(
config.pageExtensions,
appDir
)
const pagesPaths =
!appDirOnly && pagesDir
? await nextBuildSpan.traceChild('collect-pages').traceAsyncFn(() =>
recursiveReadDir(pagesDir, {
pathnameFilter: validFileMatcher.isPageFile,
})
)
: []
const middlewareDetectionRegExp = new RegExp(
`^${MIDDLEWARE_FILENAME}\\.(?:${config.pageExtensions.join('|')})$`
)
const instrumentationHookDetectionRegExp = new RegExp(
`^${INSTRUMENTATION_HOOK_FILENAME}\\.(?:${config.pageExtensions.join(
'|'
)})$`
)
const rootDir = path.join((pagesDir || appDir)!, '..')
const instrumentationHookEnabled = Boolean(
config.experimental.instrumentationHook
)
const includes = [
middlewareDetectionRegExp,
...(instrumentationHookEnabled
? [instrumentationHookDetectionRegExp]
: []),
]
const rootPaths = (await getFilesInDir(rootDir))
.filter((file) => includes.some((include) => include.test(file)))
.sort(sortByPageExts(config.pageExtensions))
.map((file) => path.join(rootDir, file).replace(dir, ''))
const hasInstrumentationHook = rootPaths.some((p) =>
p.includes(INSTRUMENTATION_HOOK_FILENAME)
)
const hasMiddlewareFile = rootPaths.some((p) =>
p.includes(MIDDLEWARE_FILENAME)
)
NextBuildContext.hasInstrumentationHook = hasInstrumentationHook
const previewProps: __ApiPreviewProps = {
previewModeId: crypto.randomBytes(16).toString('hex'),
previewModeSigningKey: crypto.randomBytes(32).toString('hex'),
previewModeEncryptionKey: crypto.randomBytes(32).toString('hex'),
}
NextBuildContext.previewProps = previewProps
const mappedPages = nextBuildSpan
.traceChild('create-pages-mapping')
.traceFn(() =>
createPagesMapping({
isDev: false,
pageExtensions: config.pageExtensions,
pagesType: PAGE_TYPES.PAGES,
pagePaths: pagesPaths,
pagesDir,
})
)
NextBuildContext.mappedPages = mappedPages
let mappedAppPages: MappedPages | undefined
let denormalizedAppPages: string[] | undefined
if (appDir) {
const appPaths = await nextBuildSpan
.traceChild('collect-app-paths')
.traceAsyncFn(() =>
recursiveReadDir(appDir, {
pathnameFilter: (absolutePath) =>
validFileMatcher.isAppRouterPage(absolutePath) ||
// For now we only collect the root /not-found page in the app
// directory as the 404 fallback
validFileMatcher.isRootNotFound(absolutePath),
ignorePartFilter: (part) => part.startsWith('_'),
})
)
mappedAppPages = nextBuildSpan
.traceChild('create-app-mapping')
.traceFn(() =>
createPagesMapping({
pagePaths: appPaths,
isDev: false,
pagesType: PAGE_TYPES.APP,
pageExtensions: config.pageExtensions,
pagesDir: pagesDir,
})
)
// If the metadata route doesn't contain generating dynamic exports,
// we can replace the dynamic catch-all route and use the static route instead.
for (const [pageKey, pagePath] of Object.entries(mappedAppPages)) {
if (pageKey.includes('[[...__metadata_id__]]')) {
const pageFilePath = getPageFilePath({
absolutePagePath: pagePath,
pagesDir,
appDir,
rootDir,
})
const isDynamic = await isDynamicMetadataRoute(pageFilePath)
if (!isDynamic) {
delete mappedAppPages[pageKey]
mappedAppPages[pageKey.replace('[[...__metadata_id__]]/', '')] =
pagePath
}
if (
pageKey.includes('sitemap.xml/[[...__metadata_id__]]') &&
isDynamic
) {
delete mappedAppPages[pageKey]
mappedAppPages[
pageKey.replace(
'sitemap.xml/[[...__metadata_id__]]',
'sitemap/[__metadata_id__]'
)
] = pagePath
}
}
}
NextBuildContext.mappedAppPages = mappedAppPages
}
const mappedRootPaths = createPagesMapping({
isDev: false,