-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
index.ts
2294 lines (2033 loc) · 71.6 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
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 {
BuildOptions,
Config,
FileBlob,
FileFsRef,
Files,
Lambda,
NowBuildError,
PackageJson,
PrepareCacheOptions,
Prerender,
} from '@vercel/build-utils';
import { Handler, Route, Source } from '@vercel/routing-utils';
import {
convertHeaders,
convertRedirects,
convertRewrites,
} from '@vercel/routing-utils/dist/superstatic';
import { nodeFileTrace, NodeFileTraceReasons } from '@vercel/nft';
import { Sema } from 'async-sema';
import { ChildProcess, fork } from 'child_process';
// escape-string-regexp version must match Next.js version
import escapeStringRegexp from 'escape-string-regexp';
import findUp from 'find-up';
import { lstat, pathExists, readFile, remove, writeFile } from 'fs-extra';
import os from 'os';
import path from 'path';
import resolveFrom from 'resolve-from';
import semver from 'semver';
import url from 'url';
import buildUtils from './build-utils';
import createServerlessConfig from './create-serverless-config';
import nextLegacyVersions from './legacy-versions';
import {
addLocaleOrDefault,
createLambdaFromPseudoLayers,
createPseudoLayer,
EnvConfig,
excludeFiles,
ExperimentalTraceVersion,
getDynamicRoutes,
getExportIntent,
getExportStatus,
getImagesManifest,
getNextConfig,
getPathsInside,
getPrerenderManifest,
getRoutes,
getRoutesManifest,
getSourceFilePathFromPage,
isDynamicRoute,
normalizeLocalePath,
normalizePackageJson,
normalizePage,
PseudoLayer,
stringMap,
syncEnvVars,
validateEntrypoint,
} from './utils';
const {
createLambda,
debug,
download,
getLambdaOptionsFromFunction,
getNodeVersion,
getSpawnOptions,
getScriptName,
glob,
runNpmInstall,
runPackageJsonScript,
execCommand,
getNodeBinPath,
} = buildUtils;
interface BuildParamsMeta {
isDev: boolean | undefined;
env?: EnvConfig;
buildEnv?: EnvConfig;
}
interface BuildParamsType extends BuildOptions {
files: Files;
entrypoint: string;
workPath: string;
meta: BuildParamsMeta;
}
export const version = 2;
const htmlContentType = 'text/html; charset=utf-8';
const nowDevChildProcesses = new Set<ChildProcess>();
['SIGINT', 'SIGTERM'].forEach(signal => {
process.once(signal as NodeJS.Signals, () => {
for (const child of nowDevChildProcesses) {
debug(
`Got ${signal}, killing dev server child process (pid=${child.pid})`
);
process.kill(child.pid, signal);
}
process.exit(0);
});
});
const MAX_AGE_ONE_YEAR = 31536000;
/**
* Read package.json from files
*/
async function readPackageJson(entryPath: string): Promise<PackageJson> {
const packagePath = path.join(entryPath, 'package.json');
try {
return JSON.parse(await readFile(packagePath, 'utf8'));
} catch (err) {
debug('package.json not found in entry');
return {};
}
}
/**
* Write package.json
*/
async function writePackageJson(workPath: string, packageJson: PackageJson) {
await writeFile(
path.join(workPath, 'package.json'),
JSON.stringify(packageJson, null, 2)
);
}
/**
* Write .npmrc with npm auth token
*/
async function writeNpmRc(workPath: string, token: string) {
await writeFile(
path.join(workPath, '.npmrc'),
`//registry.npmjs.org/:_authToken=${token}`
);
}
/**
* Get the installed Next version.
*/
function getRealNextVersion(entryPath: string): string | false {
try {
// First try to resolve the `next` dependency and get the real version from its
// package.json. This allows the builder to be used with frameworks like Blitz that
// bundle Next but where Next isn't in the project root's package.json
const nextVersion: string = require(resolveFrom(
entryPath,
'next/package.json'
)).version;
debug(`Detected Next.js version: ${nextVersion}`);
return nextVersion;
} catch (_ignored) {
debug(
`Could not identify real Next.js version, ensure it is defined as a project dependency.`
);
return false;
}
}
/**
* Get the package.json Next version.
*/
async function getNextVersionRange(entryPath: string): Promise<string | false> {
let nextVersion: string | false = false;
const pkg = await readPackageJson(entryPath);
if (pkg.dependencies && pkg.dependencies.next) {
nextVersion = pkg.dependencies.next;
} else if (pkg.devDependencies && pkg.devDependencies.next) {
nextVersion = pkg.devDependencies.next;
}
return nextVersion;
}
function isLegacyNext(nextVersion: string) {
// If version is using the dist-tag instead of a version range
if (nextVersion === 'canary' || nextVersion === 'latest') {
return false;
}
// If the version is an exact match with the legacy versions
if (nextLegacyVersions.indexOf(nextVersion) !== -1) {
return true;
}
const maxSatisfying = semver.maxSatisfying(nextLegacyVersions, nextVersion);
// When the version can't be matched with legacy versions, so it must be a newer version
if (maxSatisfying === null) {
return false;
}
return true;
}
const name = '[@vercel/next]';
const urls: stringMap = {};
function startDevServer(entryPath: string, runtimeEnv: EnvConfig) {
// `env` is omitted since that makes it default to `process.env`
const forked = fork(path.join(__dirname, 'dev-server.js'), [], {
cwd: entryPath,
execArgv: [],
});
const getUrl = () =>
new Promise<string>((resolve, reject) => {
forked.once('message', resolve);
forked.once('error', reject);
});
forked.send({ dir: entryPath, runtimeEnv });
return { forked, getUrl };
}
export const build = async ({
files,
workPath,
repoRootPath,
entrypoint,
config = {} as Config,
meta = {} as BuildParamsMeta,
}: BuildParamsType): Promise<{
routes: Route[];
images?: { domains: string[]; sizes: number[] };
output: Files;
wildcard?: Array<{
domain: string;
value: string;
}>;
watch?: string[];
childProcesses: ChildProcess[];
}> => {
validateEntrypoint(entrypoint);
// Limit for max size each lambda can be, 50 MB if no custom limit
const lambdaCompressedByteLimit = config.maxLambdaSize || 50 * 1000 * 1000;
let entryDirectory = path.dirname(entrypoint);
const entryPath = path.join(workPath, entryDirectory);
const outputDirectory = config.outputDirectory || '.next';
const dotNextStatic = path.join(entryPath, outputDirectory, 'static');
const baseDir = repoRootPath || workPath;
await download(files, workPath, meta);
let pkg = await readPackageJson(entryPath);
const nextVersionRange = await getNextVersionRange(entryPath);
const nodeVersion = await getNodeVersion(entryPath, undefined, config, meta);
const spawnOpts = getSpawnOptions(meta, nodeVersion);
const nowJsonPath = await findUp(['now.json', 'vercel.json'], {
cwd: entryPath,
});
let hasLegacyRoutes = false;
const hasFunctionsConfig = !!config.functions;
if (nowJsonPath) {
const nowJsonData = JSON.parse(await readFile(nowJsonPath, 'utf8'));
if (Array.isArray(nowJsonData.routes) && nowJsonData.routes.length > 0) {
hasLegacyRoutes = true;
console.warn(
`WARNING: your application is being opted out of @vercel/next's optimized lambdas mode due to legacy routes in ${path.basename(
nowJsonPath
)}. http://err.sh/vercel/vercel/next-legacy-routes-optimized-lambdas`
);
}
}
if (hasFunctionsConfig) {
console.warn(
`WARNING: Your application is being opted out of "@vercel/next" optimized lambdas mode due to \`functions\` config.\nMore info: http://err.sh/vercel/vercel/next-functions-config-optimized-lambdas`
);
}
// default to true but still allow opting out with the config
const isSharedLambdas =
!hasLegacyRoutes &&
!hasFunctionsConfig &&
typeof config.sharedLambdas === 'undefined'
? true
: !!config.sharedLambdas;
if (meta.isDev) {
let childProcess: ChildProcess | undefined;
// If this is the initial build, we want to start the server
if (!urls[entrypoint]) {
if (!process.env.NODE_ENV) {
process.env.NODE_ENV = 'development';
}
// The runtime env vars consist of the base `process.env` vars, but with the
// build env vars removed, and the runtime env vars mixed in afterwards
const runtimeEnv: EnvConfig = Object.assign({}, process.env);
syncEnvVars(runtimeEnv, meta.buildEnv || {}, meta.env || {});
const { forked, getUrl } = startDevServer(entryPath, runtimeEnv);
urls[entrypoint] = await getUrl();
childProcess = forked;
nowDevChildProcesses.add(forked);
debug(
`${name} Development server for ${entrypoint} running at ${urls[entrypoint]}`
);
}
const pathsInside = getPathsInside(entryDirectory, files);
return {
output: {},
images: undefined,
routes: await getRoutes(
entryPath,
entryDirectory,
pathsInside,
files,
urls[entrypoint]
),
watch: pathsInside,
childProcesses: childProcess ? [childProcess] : [],
};
}
if (await pathExists(dotNextStatic)) {
console.warn('WARNING: You should not upload the `.next` directory.');
}
const isLegacy = nextVersionRange && isLegacyNext(nextVersionRange);
debug(`MODE: ${isLegacy ? 'legacy' : 'serverless'}`);
if (isLegacy) {
console.warn(
"WARNING: your application is being deployed in @vercel/next's legacy mode. http://err.sh/vercel/vercel/now-next-legacy-mode"
);
await Promise.all([
remove(path.join(entryPath, 'yarn.lock')),
remove(path.join(entryPath, 'package-lock.json')),
]);
debug('Normalizing package.json');
pkg = normalizePackageJson(pkg);
debug('Normalized package.json result: ', pkg);
await writePackageJson(entryPath, pkg);
}
let buildScriptName = getScriptName(pkg, [
'vercel-build',
'now-build',
'build',
]);
const { buildCommand } = config;
if (!buildScriptName && !buildCommand) {
console.log(
'Your application is being built using `next build`. ' +
'If you need to define a different build step, please create a `vercel-build` script in your `package.json` ' +
'(e.g. `{ "scripts": { "vercel-build": "npm run prepare && next build" } }`).'
);
await writePackageJson(entryPath, {
...pkg,
scripts: {
'vercel-build': 'next build',
...pkg.scripts,
},
});
buildScriptName = 'vercel-build';
}
if (process.env.NPM_AUTH_TOKEN) {
debug('Found NPM_AUTH_TOKEN in environment, creating .npmrc');
await writeNpmRc(entryPath, process.env.NPM_AUTH_TOKEN);
}
console.log('Installing dependencies...');
await runNpmInstall(entryPath, [], spawnOpts, meta);
// Refetch Next version now that dependencies are installed.
// This will now resolve the actual installed Next version,
// even if Next isn't in the project package.json
const nextVersion = getRealNextVersion(entryPath);
if (!nextVersion) {
throw new NowBuildError({
code: 'NEXT_NO_VERSION',
message:
'No Next.js version could be detected in your project. Make sure `"next"` is installed in "dependencies" or "devDependencies"',
});
}
if (!isLegacy) {
await createServerlessConfig(workPath, entryPath, nextVersion);
}
const memoryToConsume = Math.floor(os.totalmem() / 1024 ** 2) - 128;
const env: { [key: string]: string | undefined } = { ...spawnOpts.env };
env.NODE_OPTIONS = `--max_old_space_size=${memoryToConsume}`;
if (buildCommand) {
// Add `node_modules/.bin` to PATH
const nodeBinPath = await getNodeBinPath({ cwd: entryPath });
env.PATH = `${nodeBinPath}${path.delimiter}${env.PATH}`;
debug(
`Added "${nodeBinPath}" to PATH env because a build command was used.`
);
console.log(`Running "${buildCommand}"`);
await execCommand(buildCommand, {
...spawnOpts,
cwd: entryPath,
env,
});
} else if (buildScriptName) {
await runPackageJsonScript(entryPath, buildScriptName, {
...spawnOpts,
env,
});
}
const appMountPrefixNoTrailingSlash = path.posix
.join('/', entryDirectory)
.replace(/\/+$/, '');
const routesManifest = await getRoutesManifest(
entryPath,
outputDirectory,
nextVersion
);
const imagesManifest = await getImagesManifest(entryPath, outputDirectory);
const prerenderManifest = await getPrerenderManifest(entryPath);
const headers: Route[] = [];
const rewrites: Route[] = [];
const redirects: Route[] = [];
const dataRoutes: Route[] = [];
let dynamicRoutes: Route[] = [];
// whether they have enabled pages/404.js as the custom 404 page
let hasPages404 = false;
let buildId = '';
let escapedBuildId = '';
if (isLegacy || isSharedLambdas) {
try {
buildId = await readFile(
path.join(entryPath, outputDirectory, 'BUILD_ID'),
'utf8'
);
escapedBuildId = escapeStringRegexp(buildId);
} catch (err) {
throw new NowBuildError({
code: 'NOW_NEXT_NO_BUILD_ID',
message:
'The BUILD_ID file was not found in the Output Directory. Did you forget to run "next build" in your Build Command?',
});
}
}
if (routesManifest) {
switch (routesManifest.version) {
case 1:
case 2:
case 3: {
redirects.push(...convertRedirects(routesManifest.redirects));
rewrites.push(...convertRewrites(routesManifest.rewrites));
if (routesManifest.headers) {
headers.push(...convertHeaders(routesManifest.headers));
}
if (routesManifest.dataRoutes) {
// Load the /_next/data routes for both dynamic SSG and SSP pages.
// These must be combined and sorted to prevent conflicts
for (const dataRoute of routesManifest.dataRoutes) {
const ssgDataRoute =
prerenderManifest.fallbackRoutes[dataRoute.page] ||
prerenderManifest.blockingFallbackRoutes[dataRoute.page];
// we don't need to add routes for non-lazy SSG routes since
// they have outputs which would override the routes anyways
if (
prerenderManifest.staticRoutes[dataRoute.page] ||
prerenderManifest.omittedRoutes.includes(dataRoute.page)
) {
continue;
}
const route = {
src: (
dataRoute.namedDataRouteRegex || dataRoute.dataRouteRegex
).replace(/^\^/, `^${appMountPrefixNoTrailingSlash}`),
dest: path.join(
'/',
entryDirectory,
// make sure to route SSG data route to the data prerender
// output, we don't do this for SSP routes since they don't
// have a separate data output
`${(ssgDataRoute && ssgDataRoute.dataRoute) || dataRoute.page}${
dataRoute.routeKeys
? `?${Object.keys(dataRoute.routeKeys)
.map(key => `${dataRoute.routeKeys![key]}=$${key}`)
.join('&')}`
: ''
}`
),
check: true,
};
const { i18n } = routesManifest;
if (i18n) {
route.src = route.src.replace(
// we need to double escape the build ID here
// to replace it properly
`/${escapedBuildId}/`,
`/${escapedBuildId}/(?${
ssgDataRoute ? '<nextLocale>' : ':'
}${i18n.locales
.map(locale => escapeStringRegexp(locale))
.join('|')})/`
);
// make sure to route to the correct prerender output
if (ssgDataRoute) {
route.dest = route.dest.replace(
`/${buildId}/`,
`/${buildId}/$nextLocale/`
);
}
}
dataRoutes.push(route);
}
}
if (routesManifest.pages404) {
hasPages404 = true;
}
if (routesManifest.basePath && routesManifest.basePath !== '/') {
const nextBasePath = routesManifest.basePath;
if (!nextBasePath.startsWith('/')) {
throw new NowBuildError({
code: 'NEXT_BASEPATH_STARTING_SLASH',
message:
'basePath must start with `/`. Please upgrade your `@vercel/next` builder and try again. Contact support if this continues to happen.',
});
}
if (nextBasePath.endsWith('/')) {
throw new NowBuildError({
code: 'NEXT_BASEPATH_TRAILING_SLASH',
message:
'basePath must not end with `/`. Please upgrade your `@vercel/next` builder and try again. Contact support if this continues to happen.',
});
}
entryDirectory = path.join(entryDirectory, nextBasePath);
}
break;
}
default: {
// update MIN_ROUTES_MANIFEST_VERSION in ./utils.ts
throw new NowBuildError({
code: 'NEXT_VERSION_OUTDATED',
message:
'This version of `@vercel/next` does not support the version of Next.js you are trying to deploy.\n' +
'Please upgrade your `@vercel/next` builder and try again. Contact support if this continues to happen.',
});
}
}
}
if (imagesManifest) {
switch (imagesManifest.version) {
case 1: {
if (!imagesManifest.images) {
throw new NowBuildError({
code: 'NEXT_IMAGES_MISSING',
message:
'image-manifest.json "images" is required. Contact support if this continues to happen.',
});
}
const { images } = imagesManifest;
if (!Array.isArray(images.domains)) {
throw new NowBuildError({
code: 'NEXT_IMAGES_DOMAINS',
message:
'image-manifest.json "images.domains" must be an array. Contact support if this continues to happen.',
});
}
if (!Array.isArray(images.sizes)) {
throw new NowBuildError({
code: 'NEXT_IMAGES_DOMAINS',
message:
'image-manifest.json "images.sizes" must be an array. Contact support if this continues to happen.',
});
}
break;
}
default: {
throw new NowBuildError({
code: 'NEXT_IMAGES_VERSION_UNKNOWN',
message:
'This version of `@vercel/next` does not support the version of Next.js you are trying to deploy.\n' +
'Please upgrade your `@vercel/next` builder and try again. Contact support if this continues to happen.',
});
}
}
}
const userExport = await getExportStatus(entryPath);
if (userExport) {
const exportIntent = await getExportIntent(entryPath);
const { trailingSlash = false } = exportIntent || {};
const resultingExport = await getExportStatus(entryPath);
if (!resultingExport) {
throw new NowBuildError({
code: 'NEXT_EXPORT_FAILED',
message:
'Exporting Next.js app failed. Please check your build logs and contact us if this continues.',
});
}
if (resultingExport.success !== true) {
throw new NowBuildError({
code: 'NEXT_EXPORT_FAILED',
message: 'Export of Next.js app failed. Please check your build logs.',
});
}
const outDirectory = resultingExport.outDirectory;
debug(`next export should use trailing slash: ${trailingSlash}`);
// This handles pages, `public/`, and `static/`.
const filesAfterBuild = await glob('**', outDirectory);
const output: Files = { ...filesAfterBuild };
// Strip `.html` extensions from build output
Object.entries(output)
.filter(([name]) => name.endsWith('.html'))
.forEach(([name, value]) => {
const cleanName = name.slice(0, -5);
delete output[name];
output[cleanName] = value;
if (value.type === 'FileBlob' || value.type === 'FileFsRef') {
value.contentType = value.contentType || 'text/html; charset=utf-8';
}
});
return {
output,
images: imagesManifest?.images
? {
domains: imagesManifest.images.domains,
sizes: imagesManifest.images.sizes,
}
: undefined,
routes: [
// User headers
...headers,
// User redirects
...redirects,
// Make sure to 404 for the /404 path itself
{
src: path.join('/', entryDirectory, '404'),
status: 404,
continue: true,
},
// Next.js pages, `static/` folder, reserved assets, and `public/`
// folder
{ handle: 'filesystem' },
// These need to come before handle: miss or else they are grouped
// with that routing section
...rewrites,
// We need to make sure to 404 for /_next after handle: miss since
// handle: miss is called before rewrites and to prevent rewriting
// /_next
{ handle: 'miss' },
{
src: path.join(
'/',
entryDirectory,
'_next/static/(?:[^/]+/pages|pages|chunks|runtime|css|media)/.+'
),
status: 404,
check: true,
dest: '$0',
},
// Dynamic routes
// TODO: do we want to do this?: ...dynamicRoutes,
// (if so make sure to add any dynamic routes after handle: 'rewrite' )
// routes to call after a file has been matched
{ handle: 'hit' },
// Before we handle static files we need to set proper caching headers
{
// This ensures we only match known emitted-by-Next.js files and not
// user-emitted files which may be missing a hash in their filename.
src: path.join(
'/',
entryDirectory,
'_next/static/(?:[^/]+/pages|pages|chunks|runtime|css|media)/.+'
),
// Next.js assets contain a hash or entropy in their filenames, so they
// are guaranteed to be unique and cacheable indefinitely.
headers: {
'cache-control': `public,max-age=${MAX_AGE_ONE_YEAR},immutable`,
},
continue: true,
},
// error handling
...(output[path.join('./', entryDirectory, '404')] ||
output[path.join('./', entryDirectory, '404/index')]
? [
{ handle: 'error' } as Handler,
{
status: 404,
src: path.join(entryDirectory, '.*'),
dest: path.join('/', entryDirectory, '404'),
},
]
: []),
],
watch: [],
childProcesses: [],
};
}
if (isLegacy) {
debug('Running npm install --production...');
await runNpmInstall(entryPath, ['--production'], spawnOpts, meta);
}
if (process.env.NPM_AUTH_TOKEN) {
await remove(path.join(entryPath, '.npmrc'));
}
const pageLambdaRoutes: Route[] = [];
const dynamicPageLambdaRoutes: Route[] = [];
const dynamicPageLambdaRoutesMap: { [page: string]: Route } = {};
const pageLambdaMap: { [page: string]: string } = {};
const lambdas: { [key: string]: Lambda } = {};
const prerenders: { [key: string]: Prerender | FileFsRef } = {};
const staticPages: { [key: string]: FileFsRef } = {};
const dynamicPages: string[] = [];
let static404Page: string | undefined;
let page404Path = '';
if (isLegacy) {
const filesAfterBuild = await glob('**', entryPath);
debug('Preparing serverless function files...');
const dotNextRootFiles = await glob(`${outputDirectory}/*`, entryPath);
const dotNextServerRootFiles = await glob(
`${outputDirectory}/server/*`,
entryPath
);
const nodeModules = excludeFiles(
await glob('node_modules/**', entryPath),
file => file.startsWith('node_modules/.cache')
);
const launcherFiles = {
'now__bridge.js': new FileFsRef({
fsPath: path.join(__dirname, 'now__bridge.js'),
}),
};
const nextFiles: { [key: string]: FileFsRef } = {
...nodeModules,
...dotNextRootFiles,
...dotNextServerRootFiles,
...launcherFiles,
};
if (filesAfterBuild['next.config.js']) {
nextFiles['next.config.js'] = filesAfterBuild['next.config.js'];
}
const pagesDir = path.join(
entryPath,
outputDirectory,
'server',
'static',
buildId,
'pages'
);
const pages = await glob('**/*.js', pagesDir);
const launcherPath = path.join(__dirname, 'legacy-launcher.js');
const launcherData = await readFile(launcherPath, 'utf8');
await Promise.all(
Object.keys(pages).map(async page => {
// These default pages don't have to be handled as they'd always 404
if (['_app.js', '_error.js', '_document.js'].includes(page)) {
return;
}
const pathname = page.replace(/\.js$/, '');
const launcher = launcherData.replace(
'PATHNAME_PLACEHOLDER',
`/${pathname.replace(/(^|\/)index$/, '')}`
);
const pageFiles = {
[`${outputDirectory}/server/static/${buildId}/pages/_document.js`]: filesAfterBuild[
`${outputDirectory}/server/static/${buildId}/pages/_document.js`
],
[`${outputDirectory}/server/static/${buildId}/pages/_app.js`]: filesAfterBuild[
`${outputDirectory}/server/static/${buildId}/pages/_app.js`
],
[`${outputDirectory}/server/static/${buildId}/pages/_error.js`]: filesAfterBuild[
`${outputDirectory}/server/static/${buildId}/pages/_error.js`
],
[`${outputDirectory}/server/static/${buildId}/pages/${page}`]: filesAfterBuild[
`${outputDirectory}/server/static/${buildId}/pages/${page}`
],
};
let lambdaOptions = {};
if (config && config.functions) {
lambdaOptions = await getLambdaOptionsFromFunction({
sourceFile: await getSourceFilePathFromPage({
workPath: entryPath,
page,
}),
config,
});
}
debug(`Creating serverless function for page: "${page}"...`);
lambdas[path.join(entryDirectory, pathname)] = await createLambda({
files: {
...nextFiles,
...pageFiles,
'now__launcher.js': new FileBlob({ data: launcher }),
},
handler: 'now__launcher.launcher',
runtime: nodeVersion.runtime,
...lambdaOptions,
});
debug(`Created serverless function for page: "${page}"`);
})
);
} else {
debug('Preparing serverless function files...');
const pagesDir = path.join(
entryPath,
outputDirectory,
'serverless',
'pages'
);
const pages = await glob('**/*.js', pagesDir);
const staticPageFiles = await glob('**/*.html', pagesDir);
Object.keys(staticPageFiles).forEach((page: string) => {
const pathname = page.replace(/\.html$/, '');
const routeName = normalizeLocalePath(
normalizePage(pathname),
routesManifest?.i18n?.locales
).pathname;
// Prerendered routes emit a `.html` file but should not be treated as a
// static page.
// Lazily prerendered routes have a fallback `.html` file on newer
// Next.js versions so we need to also not treat it as a static page here.
if (
prerenderManifest.staticRoutes[routeName] ||
prerenderManifest.fallbackRoutes[routeName]
) {
return;
}
const staticRoute = path.join(entryDirectory, pathname);
staticPages[staticRoute] = staticPageFiles[page];
staticPages[staticRoute].contentType = htmlContentType;
if (isDynamicRoute(pathname)) {
dynamicPages.push(routeName);
return;
}
});
// this can be either 404.html in latest versions
// or _errors/404.html versions while this was experimental
static404Page =
staticPages[path.join(entryDirectory, '404')] && hasPages404
? path.join(entryDirectory, '404')
: staticPages[path.join(entryDirectory, '_errors/404')]
? path.join(entryDirectory, '_errors/404')
: undefined;
// TODO: locale specific 404s
const { i18n } = routesManifest || {};
if (!static404Page && i18n) {
static404Page = staticPages[
path.join(entryDirectory, i18n.defaultLocale, '404')
]
? path.join(entryDirectory, i18n.defaultLocale, '404')
: undefined;
}
// > 1 because _error is a lambda but isn't used if a static 404 is available
const pageKeys = Object.keys(pages);
let hasLambdas = !static404Page || pageKeys.length > 1;
if (pageKeys.length === 0) {
const nextConfig = await getNextConfig(workPath, entryPath);
if (nextConfig != null) {
console.info('Found next.config.js:');
console.info(nextConfig);
console.info();
}
throw new NowBuildError({
code: 'NEXT_NO_SERVERLESS_PAGES',
message: 'No serverless pages were built',
link: 'https://err.sh/vercel/vercel/now-next-no-serverless-pages-built',
});
}
// Assume tracing to be safe, bail if we know we don't need it.
let requiresTracing = hasLambdas;
try {
if (nextVersion && semver.lt(nextVersion, ExperimentalTraceVersion)) {
debug(
'Next.js version is too old for us to trace the required dependencies.\n' +
'Assuming Next.js has handled it!'
);
requiresTracing = false;
}
} catch (err) {
console.log(
'Failed to check Next.js version for tracing compatibility: ' + err
);
}
let assets:
| undefined
| {
[filePath: string]: FileFsRef;
};
const isApiPage = (page: string) =>
page.replace(/\\/g, '/').match(/serverless\/pages\/api(\/|\.js$)/);
const canUsePreviewMode = Object.keys(pages).some(page =>
isApiPage(pages[page].fsPath)
);
let pseudoLayerBytes = 0;
let apiPseudoLayerBytes = 0;
const pseudoLayers: PseudoLayer[] = [];
const apiPseudoLayers: PseudoLayer[] = [];
const nonLambdaSsgPages = new Set<string>();
const onPrerenderRouteInitial = (routeKey: string) => {
// Get the route file as it'd be mounted in the builder output
const pr = prerenderManifest.staticRoutes[routeKey];
const { initialRevalidate, srcRoute } = pr;
const route = srcRoute || routeKey;
if (
initialRevalidate === false &&
!canUsePreviewMode &&
!prerenderManifest.fallbackRoutes[route] &&
!prerenderManifest.blockingFallbackRoutes[route]
) {
// if the 404 page used getStaticProps we need to update static404Page
// since it wasn't populated from the staticPages group
if (route === '/404') {
static404Page = path.join(entryDirectory, '404');
}
nonLambdaSsgPages.add(route === '/' ? '/index' : route);
}
};
Object.keys(prerenderManifest.staticRoutes).forEach(route =>
onPrerenderRouteInitial(route)
);
const tracedFiles: {
[filePath: string]: FileFsRef;