-
Notifications
You must be signed in to change notification settings - Fork 26.2k
/
index.ts
685 lines (603 loc) · 20.2 KB
/
index.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
import chalk from 'chalk'
import fs from 'fs'
import Worker from 'jest-worker'
import mkdirpOrig from 'mkdirp'
import nanoid from 'next/dist/compiled/nanoid/index.js'
import path from 'path'
import { promisify } from 'util'
import formatWebpackMessages from '../client/dev/error-overlay/format-webpack-messages'
import { PUBLIC_DIR_MIDDLEWARE_CONFLICT } from '../lib/constants'
import { findPagesDir } from '../lib/find-pages-dir'
import { recursiveDelete } from '../lib/recursive-delete'
import { recursiveReadDir } from '../lib/recursive-readdir'
import { verifyTypeScriptSetup } from '../lib/verifyTypeScriptSetup'
import {
BUILD_MANIFEST,
PAGES_MANIFEST,
PHASE_PRODUCTION_BUILD,
PRERENDER_MANIFEST,
SERVER_DIRECTORY,
SERVERLESS_DIRECTORY,
} from '../next-server/lib/constants'
import { getRouteRegex, isDynamicRoute } from '../next-server/lib/router/utils'
import loadConfig, {
isTargetLikeServerless,
} from '../next-server/server/config'
import {
eventBuildDuration,
eventBuildOptimize,
eventNextPlugins,
eventVersion,
} from '../telemetry/events'
import { Telemetry } from '../telemetry/storage'
import { CompilerResult, runCompiler } from './compiler'
import { createEntrypoints, createPagesMapping } from './entries'
import { generateBuildId } from './generate-build-id'
import { isWriteable } from './is-writeable'
import createSpinner from './spinner'
import {
collectPages,
getPageSizeInKb,
hasCustomAppGetInitialProps,
PageInfo,
printTreeView,
} from './utils'
import getBaseWebpackConfig from './webpack-config'
import { getPageChunks } from './webpack/plugins/chunk-graph-plugin'
import { writeBuildId } from './write-build-id'
const fsUnlink = promisify(fs.unlink)
const fsRmdir = promisify(fs.rmdir)
const fsStat = promisify(fs.stat)
const fsMove = promisify(fs.rename)
const fsReadFile = promisify(fs.readFile)
const fsWriteFile = promisify(fs.writeFile)
const mkdirp = promisify(mkdirpOrig)
const staticCheckWorker = require.resolve('./utils')
export type SprRoute = {
initialRevalidateSeconds: number | false
srcRoute: string | null
dataRoute: string
}
export type DynamicSprRoute = {
routeRegex: string
dataRoute: string
dataRouteRegex: string
}
export type PrerenderManifest = {
version: number
routes: { [route: string]: SprRoute }
dynamicRoutes: { [route: string]: DynamicSprRoute }
}
export default async function build(dir: string, conf = null): Promise<void> {
if (!(await isWriteable(dir))) {
throw new Error(
'> Build directory is not writeable. https://err.sh/zeit/next.js/build-dir-not-writeable'
)
}
const buildSpinner = createSpinner({
prefixText: 'Creating an optimized production build',
})
const config = loadConfig(PHASE_PRODUCTION_BUILD, dir, conf)
const { target } = config
const buildId = await generateBuildId(config.generateBuildId, nanoid)
const distDir = path.join(dir, config.distDir)
const telemetry = new Telemetry({ distDir })
const publicDir = path.join(dir, 'public')
const pagesDir = findPagesDir(dir)
let publicFiles: string[] = []
let hasPublicDir = false
let backgroundWork: (Promise<any> | undefined)[] = []
backgroundWork.push(
telemetry.record(eventVersion({ cliCommand: 'build' })),
eventNextPlugins(path.resolve(dir)).then(events => telemetry.record(events))
)
await verifyTypeScriptSetup(dir, pagesDir)
try {
await fsStat(publicDir)
hasPublicDir = true
} catch (_) {}
if (hasPublicDir) {
publicFiles = await recursiveReadDir(publicDir, /.*/)
}
let tracer: any = null
if (config.experimental.profiling) {
const { createTrace } = require('./profiler/profiler.js')
tracer = createTrace(path.join(distDir, `profile-events.json`))
tracer.profiler.startProfiling()
}
const isLikeServerless = isTargetLikeServerless(target)
const pagePaths: string[] = await collectPages(
pagesDir,
config.pageExtensions
)
// needed for static exporting since we want to replace with HTML
// files
const allStaticPages = new Set<string>()
let allPageInfos = new Map<string, PageInfo>()
const mappedPages = createPagesMapping(pagePaths, config.pageExtensions)
const entrypoints = createEntrypoints(mappedPages, target, buildId, config)
const conflictingPublicFiles: string[] = []
if (hasPublicDir) {
try {
await fsStat(path.join(publicDir, '_next'))
throw new Error(PUBLIC_DIR_MIDDLEWARE_CONFLICT)
} catch (err) {}
}
for (let file of publicFiles) {
file = file
.replace(/\\/g, '/')
.replace(/\/index$/, '')
.split(publicDir)
.pop()!
if (mappedPages[file]) {
conflictingPublicFiles.push(file)
}
}
const numConflicting = conflictingPublicFiles.length
if (numConflicting) {
throw new Error(
`Conflicting public and page file${
numConflicting === 1 ? ' was' : 's were'
} found. https://err.sh/zeit/next.js/conflicting-public-file-page\n${conflictingPublicFiles.join(
'\n'
)}`
)
}
const configs = await Promise.all([
getBaseWebpackConfig(dir, {
tracer,
buildId,
isServer: false,
config,
target,
pagesDir,
entrypoints: entrypoints.client,
}),
getBaseWebpackConfig(dir, {
tracer,
buildId,
isServer: true,
config,
target,
pagesDir,
entrypoints: entrypoints.server,
}),
])
const clientConfig = configs[0]
if (
clientConfig.optimization &&
(clientConfig.optimization.minimize !== true ||
(clientConfig.optimization.minimizer &&
clientConfig.optimization.minimizer.length === 0))
) {
console.warn(
chalk.bold.yellow(`Warning: `) +
chalk.bold(
`Production code optimization has been disabled in your project. Read more: https://err.sh/zeit/next.js/minification-disabled`
)
)
}
const webpackBuildStart = process.hrtime()
let result: CompilerResult = { warnings: [], errors: [] }
// TODO: why do we need this?? https://github.com/zeit/next.js/issues/8253
if (isLikeServerless) {
const clientResult = await runCompiler(clientConfig)
// Fail build if clientResult contains errors
if (clientResult.errors.length > 0) {
result = {
warnings: [...clientResult.warnings],
errors: [...clientResult.errors],
}
} else {
const serverResult = await runCompiler(configs[1])
result = {
warnings: [...clientResult.warnings, ...serverResult.warnings],
errors: [...clientResult.errors, ...serverResult.errors],
}
}
} else {
result = await runCompiler(configs)
}
const webpackBuildEnd = process.hrtime(webpackBuildStart)
if (buildSpinner) {
buildSpinner.stopAndPersist()
}
console.log()
result = formatWebpackMessages(result)
if (result.errors.length > 0) {
// Only keep the first error. Others are often indicative
// of the same problem, but confuse the reader with noise.
if (result.errors.length > 1) {
result.errors.length = 1
}
const error = result.errors.join('\n\n')
console.error(chalk.red('Failed to compile.\n'))
if (
error.indexOf('private-next-pages') > -1 &&
error.indexOf('does not contain a default export') > -1
) {
const page_name_regex = /\'private-next-pages\/(?<page_name>[^\']*)\'/
const parsed = page_name_regex.exec(error)
const page_name = parsed && parsed.groups && parsed.groups.page_name
throw new Error(
`webpack build failed: found page without a React Component as default export in pages/${page_name}\n\nSee https://err.sh/zeit/next.js/page-without-valid-component for more info.`
)
}
console.error(error)
console.error()
if (error.indexOf('private-next-pages') > -1) {
throw new Error(
'> webpack config.resolve.alias was incorrectly overriden. https://err.sh/zeit/next.js/invalid-resolve-alias'
)
}
throw new Error('> Build failed because of webpack errors')
} else if (result.warnings.length > 0) {
console.warn(chalk.yellow('Compiled with warnings.\n'))
console.warn(result.warnings.join('\n\n'))
console.warn()
} else {
console.log(chalk.green('Compiled successfully.\n'))
backgroundWork.push(
telemetry.record(
eventBuildDuration({
totalPageCount: pagePaths.length,
durationInSeconds: webpackBuildEnd[0],
})
)
)
}
const postBuildSpinner = createSpinner({
prefixText: 'Automatically optimizing pages',
})
const pageKeys = Object.keys(mappedPages)
const manifestPath = path.join(
distDir,
isLikeServerless ? SERVERLESS_DIRECTORY : SERVER_DIRECTORY,
PAGES_MANIFEST
)
const buildManifestPath = path.join(distDir, BUILD_MANIFEST)
const sprPages = new Set<string>()
const staticPages = new Set<string>()
const invalidPages = new Set<string>()
const hybridAmpPages = new Set<string>()
const additionalSprPaths = new Map<string, Array<string>>()
const pageInfos = new Map<string, PageInfo>()
const pagesManifest = JSON.parse(await fsReadFile(manifestPath, 'utf8'))
const buildManifest = JSON.parse(await fsReadFile(buildManifestPath, 'utf8'))
let customAppGetInitialProps: boolean | undefined
process.env.NEXT_PHASE = PHASE_PRODUCTION_BUILD
const staticCheckWorkers = new Worker(staticCheckWorker, {
numWorkers: config.experimental.cpus,
enableWorkerThreads: true,
})
const analysisBegin = process.hrtime()
await Promise.all(
pageKeys.map(async page => {
const chunks = getPageChunks(page)
const actualPage = page === '/' ? '/index' : page
const size = await getPageSizeInKb(
actualPage,
distDir,
buildId,
buildManifest,
config.experimental.modern
)
const bundleRelative = path.join(
isLikeServerless ? 'pages' : `static/${buildId}/pages`,
actualPage + '.js'
)
const serverBundle = path.join(
distDir,
isLikeServerless ? SERVERLESS_DIRECTORY : SERVER_DIRECTORY,
bundleRelative
)
let isStatic = false
pagesManifest[page] = bundleRelative.replace(/\\/g, '/')
const runtimeEnvConfig = {
publicRuntimeConfig: config.publicRuntimeConfig,
serverRuntimeConfig: config.serverRuntimeConfig,
}
const nonReservedPage = !page.match(/^\/(_app|_error|_document|api)/)
if (nonReservedPage && customAppGetInitialProps === undefined) {
customAppGetInitialProps = hasCustomAppGetInitialProps(
isLikeServerless
? serverBundle
: path.join(
distDir,
SERVER_DIRECTORY,
`/static/${buildId}/pages/_app.js`
),
runtimeEnvConfig
)
if (customAppGetInitialProps) {
console.warn(
chalk.bold.yellow(`Warning: `) +
chalk.yellow(
`You have opted-out of Automatic Static Optimization due to \`getInitialProps\` in \`pages/_app\`.`
)
)
console.warn(
'Read more: https://err.sh/next.js/opt-out-auto-static-optimization\n'
)
}
}
if (nonReservedPage) {
try {
let result: any = await (staticCheckWorkers as any).isPageStatic(
page,
serverBundle,
runtimeEnvConfig
)
if (result.isHybridAmp) {
hybridAmpPages.add(page)
}
if (result.prerender) {
sprPages.add(page)
if (result.prerenderRoutes) {
additionalSprPaths.set(page, result.prerenderRoutes)
}
}
if (result.static && customAppGetInitialProps === false) {
staticPages.add(page)
isStatic = true
} else if (result.prerender) {
sprPages.add(page)
}
} catch (err) {
if (err.message !== 'INVALID_DEFAULT_EXPORT') throw err
invalidPages.add(page)
}
}
pageInfos.set(page, { size, chunks, serverBundle, static: isStatic })
})
)
staticCheckWorkers.end()
if (invalidPages.size > 0) {
throw new Error(
`Build optimization failed: found page${
invalidPages.size === 1 ? '' : 's'
} without a React Component as default export in \n${[...invalidPages]
.map(pg => `pages${pg}`)
.join(
'\n'
)}\n\nSee https://err.sh/zeit/next.js/page-without-valid-component for more info.\n`
)
}
if (Array.isArray(configs[0].plugins)) {
configs[0].plugins.some((plugin: any) => {
if (!plugin.ampPages) {
return false
}
plugin.ampPages.forEach((pg: any) => {
pageInfos.get(pg)!.isAmp = true
})
return true
})
}
await writeBuildId(distDir, buildId)
const finalPrerenderRoutes: { [route: string]: SprRoute } = {}
const tbdPrerenderRoutes: string[] = []
if (staticPages.size > 0 || sprPages.size > 0) {
const combinedPages = [...staticPages, ...sprPages]
const exportApp = require('../export').default
const exportOptions = {
sprPages,
silent: true,
buildExport: true,
pages: combinedPages,
outdir: path.join(distDir, 'export'),
}
const exportConfig: any = {
...config,
initialPageRevalidationMap: {},
// Default map will be the collection of automatic statically exported
// pages and SPR pages.
// n.b. we cannot handle this above in combinedPages because the dynamic
// page must be in the `pages` array, but not in the mapping.
exportPathMap: (defaultMap: any) => {
// Remove dynamically routed pages from the default path map. These
// pages cannot be prerendered because we don't have enough information
// to do so.
//
// Note: prerendering disables automatic static optimization.
sprPages.forEach(page => {
if (isDynamicRoute(page)) {
tbdPrerenderRoutes.push(page)
delete defaultMap[page]
}
})
// Append the "well-known" routes we should prerender for, e.g. blog
// post slugs.
additionalSprPaths.forEach((routes, page) => {
routes.forEach(route => {
defaultMap[route] = { page }
})
})
return defaultMap
},
exportTrailingSlash: false,
}
await exportApp(dir, exportOptions, exportConfig)
// remove server bundles that were exported
for (const page of staticPages) {
const { serverBundle } = pageInfos.get(page)!
await fsUnlink(serverBundle)
}
const moveExportedPage = async (
page: string,
file: string,
isSpr: boolean,
ext: 'html' | 'json'
) => {
file = `${file}.${ext}`
const orig = path.join(exportOptions.outdir, file)
const relativeDest = (isLikeServerless
? path.join('pages', file)
: path.join('static', buildId, 'pages', file)
).replace(/\\/g, '/')
const dest = path.join(
distDir,
isLikeServerless ? SERVERLESS_DIRECTORY : SERVER_DIRECTORY,
relativeDest
)
if (!isSpr) {
pagesManifest[page] = relativeDest
if (page === '/') pagesManifest['/index'] = relativeDest
if (page === '/.amp') pagesManifest['/index.amp'] = relativeDest
}
await mkdirp(path.dirname(dest))
await fsMove(orig, dest)
}
for (const page of combinedPages) {
const isSpr = sprPages.has(page)
const isDynamic = isDynamicRoute(page)
let file = page === '/' ? '/index' : page
// The dynamic version of SPR pages are not prerendered. Below, we handle
// the specific prerenders of these.
if (!(isSpr && isDynamic)) {
await moveExportedPage(page, file, isSpr, 'html')
}
const hasAmp = hybridAmpPages.has(page)
if (hasAmp) {
await moveExportedPage(`${page}.amp`, `${file}.amp`, isSpr, 'html')
}
if (isSpr) {
// For a non-dynamic SPR page, we must copy its data file from export.
if (!isDynamic) {
await moveExportedPage(page, file, true, 'json')
finalPrerenderRoutes[page] = {
initialRevalidateSeconds:
exportConfig.initialPageRevalidationMap[page],
srcRoute: null,
dataRoute: path.posix.join(
'/_next/data',
buildId,
`${page === '/' ? '/index' : page}.json`
),
}
} else {
// For a dynamic SPR page, we did not copy its html nor data exports.
// Instead, we must copy specific versions of this page as defined by
// `unstable_getStaticParams` (additionalSprPaths).
const extraRoutes = additionalSprPaths.get(page) || []
for (const route of extraRoutes) {
await moveExportedPage(route, route, true, 'html')
await moveExportedPage(route, route, true, 'json')
finalPrerenderRoutes[route] = {
initialRevalidateSeconds:
exportConfig.initialPageRevalidationMap[route],
srcRoute: page,
dataRoute: path.posix.join(
'/_next/data',
buildId,
`${route === '/' ? '/index' : route}.json`
),
}
}
}
}
}
// remove temporary export folder
await recursiveDelete(exportOptions.outdir)
await fsRmdir(exportOptions.outdir)
await fsWriteFile(manifestPath, JSON.stringify(pagesManifest), 'utf8')
}
if (postBuildSpinner) postBuildSpinner.stopAndPersist()
console.log()
const analysisEnd = process.hrtime(analysisBegin)
backgroundWork.push(
telemetry.record(
eventBuildOptimize({
durationInSeconds: analysisEnd[0],
totalPageCount: pagePaths.length,
staticPageCount: staticPages.size,
ssrPageCount: pagePaths.length - staticPages.size,
})
)
)
if (sprPages.size > 0) {
const finalDynamicRoutes: PrerenderManifest['dynamicRoutes'] = {}
tbdPrerenderRoutes.forEach(tbdRoute => {
const dataRoute = path.posix.join(
'/_next/data',
buildId,
`${tbdRoute === '/' ? '/index' : tbdRoute}.json`
)
finalDynamicRoutes[tbdRoute] = {
routeRegex: getRouteRegex(tbdRoute).re.source,
dataRoute,
dataRouteRegex: getRouteRegex(
dataRoute.replace(/\.json$/, '')
).re.source.replace(/\(\?:\\\/\)\?\$$/, '\\.json$'),
}
})
const prerenderManifest: PrerenderManifest = {
version: 1,
routes: finalPrerenderRoutes,
dynamicRoutes: finalDynamicRoutes,
}
await fsWriteFile(
path.join(distDir, PRERENDER_MANIFEST),
JSON.stringify(prerenderManifest),
'utf8'
)
}
staticPages.forEach(pg => allStaticPages.add(pg))
pageInfos.forEach((info: PageInfo, key: string) => {
allPageInfos.set(key, info)
})
printTreeView(Object.keys(mappedPages), allPageInfos, isLikeServerless)
if (tracer) {
const parsedResults = await tracer.profiler.stopProfiling()
await new Promise(resolve => {
if (parsedResults === undefined) {
tracer.profiler.destroy()
tracer.trace.flush()
tracer.end(resolve)
return
}
const cpuStartTime = parsedResults.profile.startTime
const cpuEndTime = parsedResults.profile.endTime
tracer.trace.completeEvent({
name: 'TaskQueueManager::ProcessTaskFromWorkQueue',
id: ++tracer.counter,
cat: ['toplevel'],
ts: cpuStartTime,
args: {
src_file: '../../ipc/ipc_moji_bootstrap.cc',
src_func: 'Accept',
},
})
tracer.trace.completeEvent({
name: 'EvaluateScript',
id: ++tracer.counter,
cat: ['devtools.timeline'],
ts: cpuStartTime,
dur: cpuEndTime - cpuStartTime,
args: {
data: {
url: 'webpack',
lineNumber: 1,
columnNumber: 1,
frame: '0xFFF',
},
},
})
tracer.trace.instantEvent({
name: 'CpuProfile',
id: ++tracer.counter,
cat: ['disabled-by-default-devtools.timeline'],
ts: cpuEndTime,
args: {
data: {
cpuProfile: parsedResults.profile,
},
},
})
tracer.profiler.destroy()
tracer.trace.flush()
tracer.end(resolve)
})
}
await Promise.all(backgroundWork).catch(() => {})
}