-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
index.ts
2613 lines (2335 loc) · 82.7 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 {
FileBlob,
FileFsRef,
Files,
Lambda,
NowBuildError,
PackageJson,
Prerender,
debug,
download,
getLambdaOptionsFromFunction,
getNodeVersion,
getSpawnOptions,
getScriptName,
glob,
runNpmInstall,
runPackageJsonScript,
execCommand,
getEnvForPackageManager,
getNodeBinPath,
scanParentDirs,
BuildV2,
PrepareCache,
NodejsLambda,
BuildResultV2Typical as BuildResult,
} from '@vercel/build-utils';
import { Handler, Route, Source } from '@vercel/routing-utils';
import {
convertHeaders,
convertRedirects,
convertRewrites,
} from '@vercel/routing-utils/dist/superstatic';
import { nodeFileTrace } from '@vercel/nft';
import { Sema } from 'async-sema';
// 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 createServerlessConfig from './create-serverless-config';
import nextLegacyVersions from './legacy-versions';
import { serverBuild } from './server-build';
import {
collectTracedFiles,
createLambdaFromPseudoLayers,
createPseudoLayer,
detectLambdaLimitExceeding,
excludeFiles,
ExperimentalTraceVersion,
filterStaticPages,
getDynamicRoutes,
getExportIntent,
getExportStatus,
getFilesMapFromReasons,
getImagesManifest,
getMiddlewareManifest,
getNextConfig,
getPageLambdaGroups,
getPrerenderManifest,
getPrivateOutputs,
getRequiredServerFilesManifest,
getRoutesManifest,
getSourceFilePathFromPage,
getStaticFiles,
isDynamicRoute,
localizeDynamicRoutes,
normalizeIndexOutput,
normalizePackageJson,
normalizePage,
onPrerenderRoute,
onPrerenderRouteInitial,
PseudoFile,
PseudoLayer,
PseudoLayerResult,
updateRouteSrc,
validateEntrypoint,
} from './utils';
export const version = 2;
export const htmlContentType = 'text/html; charset=utf-8';
const SERVER_BUILD_MINIMUM_NEXT_VERSION = 'v10.0.9-canary.4';
// related PR: https://github.com/vercel/next.js/pull/25418
const BEFORE_FILES_CONTINUE_NEXT_VERSION = 'v10.2.3-canary.1';
// related PR: https://github.com/vercel/next.js/pull/27143
const REDIRECTS_NO_STATIC_NEXT_VERSION = 'v11.0.2-canary.15';
export 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
// NOTE: `eval('require')` is necessary to avoid bad transpilation to `__webpack_require__`
const nextVersion: string = eval('require')(
resolveFrom(entryPath, 'next/package.json')
).version;
console.log(`Detected Next.js version: ${nextVersion}`);
return nextVersion;
} catch (_ignored) {
console.log(
`Warning: Could not identify 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;
}
export const build: BuildV2 = async ({
files,
workPath,
repoRootPath,
entrypoint,
config = {},
meta = {},
}) => {
validateEntrypoint(entrypoint);
// Limit for max size each lambda can be, 50 MB if no custom limit
const lambdaCompressedByteLimit = (config.maxLambdaSize ||
50 * 1000 * 1000) as number;
let entryDirectory = path.dirname(entrypoint);
let entryPath = path.join(workPath, entryDirectory);
// allow testing root directory setting with vercel.json
if (config.rootDirectory) {
repoRootPath = entryPath;
entryPath = path.join(entryPath, config.rootDirectory as string);
}
const outputDirectory = config.outputDirectory || '.next';
const dotNextStatic = path.join(entryPath, outputDirectory, 'static');
// TODO: remove after testing used for simulating root directory monorepo
// setting that can't be triggered with vercel.json
const baseDir = repoRootPath || workPath;
debug(
JSON.stringify(
{
repoRootPath,
baseDir,
workPath,
entryPath,
entryDirectory,
outputDirectory,
},
null,
2
)
);
Object.keys(process.env)
.filter(key => key.startsWith('VERCEL_'))
.forEach(key => {
const newKey = `NEXT_PUBLIC_${key}`;
if (!(newKey in process.env)) {
process.env[newKey] = process.env[key];
}
});
await download(files, workPath, meta);
if (config.rootDirectory) {
// this must come after the download step since files outside
// the root directory will be excluded if we update workPath first.
// This should not be used when the actual root directory setting
// is being used since this is meant to simulate it while testing
workPath = path.join(workPath, config.rootDirectory as string);
}
let pkg = await readPackageJson(entryPath);
const nextVersionRange = await getNextVersionRange(entryPath);
const nodeVersion = await getNodeVersion(entryPath, undefined, config, meta);
const spawnOpts = getSpawnOptions(meta, nodeVersion);
const { cliType, lockfileVersion } = await scanParentDirs(entryPath);
spawnOpts.env = getEnvForPackageManager({
cliType,
lockfileVersion,
nodeVersion,
env: spawnOpts.env || {},
});
const nowJsonPath = await findUp(['now.json', 'vercel.json'], {
cwd: entryPath,
});
let hasLegacyRoutes = false;
const hasFunctionsConfig = !!config.functions;
if (await pathExists(dotNextStatic)) {
console.warn('WARNING: You should not upload the `.next` directory.');
}
const isLegacy = nextVersionRange && isLegacyNext(nextVersionRange);
debug(`MODE: ${isLegacy ? 'legacy' : 'server(less)'}`);
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 { installCommand, 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);
}
if (typeof installCommand === 'string') {
if (installCommand.trim()) {
console.log(`Running "install" command: \`${installCommand}\`...`);
await execCommand(installCommand, {
...spawnOpts,
cwd: entryPath,
});
} else {
console.log(`Skipping "install" command...`);
}
} else {
await runNpmInstall(entryPath, [], spawnOpts, meta, nodeVersion);
}
// 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"',
});
}
let isServerMode =
!(config.framework === 'blitzjs') &&
semver.gte(nextVersion, SERVER_BUILD_MINIMUM_NEXT_VERSION);
const beforeFilesShouldContinue = semver.gte(
nextVersion,
BEFORE_FILES_CONTINUE_NEXT_VERSION
);
const isCorrectLocaleAPIRoutes = semver.gte(nextVersion, 'v11.0.2-canary.3');
if (isServerMode) {
debug(
`Application is being built in server mode since ${nextVersion} meets minimum version of ${SERVER_BUILD_MINIMUM_NEXT_VERSION}`
);
} else {
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 =
!isServerMode &&
!hasLegacyRoutes &&
!hasFunctionsConfig &&
typeof config.sharedLambdas === 'undefined'
? true
: !!config.sharedLambdas;
let target: undefined | string;
if (isServerMode) {
// server mode eligible Next.js apps do not need
// the target forced via next.config.js wrapping since
// we can leverage the NEXT_PRIVATE_TARGET env variable
target = 'server';
} else if (!isLegacy) {
target = await createServerlessConfig(workPath, entryPath, nextVersion);
}
const env: typeof process.env = { ...spawnOpts.env };
const memoryToConsume = Math.floor(os.totalmem() / 1024 ** 2) - 128;
env.NODE_OPTIONS = `--max_old_space_size=${memoryToConsume}`;
env.NEXT_EDGE_RUNTIME_PROVIDER = 'vercel';
if (target) {
// Since version v10.0.8-canary.15 of Next.js the NEXT_PRIVATE_TARGET env
// value can be used to override the target set in next.config.js
// this helps us catch cases where we can't locate the next.config.js
// correctly
env.NEXT_PRIVATE_TARGET = target;
}
env.NEXT_PRIVATE_OUTPUT_TRACE_ROOT = baseDir;
if (isServerMode) {
// when testing with jest NODE_ENV will be set to test so ensure
// it is production when running the build command
env.NODE_ENV = 'production';
}
if (buildCommand) {
// Add `node_modules/.bin` to PATH
const nodeBinPath = await getNodeBinPath({ cwd: entryPath });
env.PATH = `${nodeBinPath}${path.delimiter}${env.PATH}`;
// Yarn v2 PnP mode may be activated, so force "node-modules" linker style
if (!env.YARN_NODE_LINKER) {
env.YARN_NODE_LINKER = 'node-modules';
}
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,
});
}
debug('build command exited');
let appMountPrefixNoTrailingSlash = path.posix
.join('/', entryDirectory)
.replace(/\/+$/, '');
const requiredServerFilesManifest = isServerMode
? await getRequiredServerFilesManifest(entryPath, outputDirectory)
: false;
isServerMode = !!requiredServerFilesManifest;
const routesManifest = await getRoutesManifest(
entryPath,
outputDirectory,
nextVersion
);
const imagesManifest = await getImagesManifest(entryPath, outputDirectory);
const prerenderManifest = await getPrerenderManifest(
entryPath,
outputDirectory
);
const omittedPrerenderRoutes = new Set(
Object.keys(prerenderManifest.omittedRoutes)
);
const hasIsr404Page =
typeof prerenderManifest.staticRoutes[
routesManifest?.i18n
? // eslint-disable-next-line @typescript-eslint/no-non-null-asserted-optional-chain
path.join('/', routesManifest?.i18n!.defaultLocale!, '/404')
: '/404'
]?.initialRevalidate === 'number';
const wildcardConfig: BuildResult['wildcard'] =
routesManifest?.i18n?.domains && routesManifest.i18n.domains.length > 0
? routesManifest.i18n.domains.map(item => {
return {
domain: item.domain,
value:
item.defaultLocale === routesManifest.i18n?.defaultLocale
? ''
: `/${item.defaultLocale}`,
};
})
: undefined;
const privateOutputs = await getPrivateOutputs(
path.join(entryPath, outputDirectory),
{
'next-stats.json': '_next/__private/stats.json',
trace: '_next/__private/trace',
}
);
const headers: Route[] = [];
const beforeFilesRewrites: Route[] = [];
const afterFilesRewrites: Route[] = [];
const fallbackRewrites: Route[] = [];
let 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 || isServerMode) {
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:
case 4: {
redirects.push(...convertRedirects(routesManifest.redirects));
if (Array.isArray(routesManifest.rewrites)) {
afterFilesRewrites.push(
...convertRewrites(
routesManifest.rewrites,
routesManifest.i18n ? ['nextInternalLocale'] : undefined
)
);
} else {
beforeFilesRewrites.push(
...convertRewrites(routesManifest.rewrites.beforeFiles).map(r => {
if ('check' in r) {
if (beforeFilesShouldContinue) {
delete r.check;
r.continue = true;
}
// override: true helps maintain order so that redirects don't
// come after beforeFiles rewrites
r.override = true;
}
return r;
})
);
afterFilesRewrites.push(
...convertRewrites(routesManifest.rewrites.afterFiles)
);
fallbackRewrites.push(
...convertRewrites(routesManifest.rewrites.fallback)
);
}
if (routesManifest.headers) {
headers.push(...convertHeaders(routesManifest.headers));
}
// This applies the _next match prevention for redirects and
// also allows matching the trailingSlash setting automatically
// for all custom routes
if (semver.gte(nextVersion, REDIRECTS_NO_STATIC_NEXT_VERSION)) {
redirects.forEach((r, i) =>
updateRouteSrc(r, i, routesManifest.redirects)
);
afterFilesRewrites.forEach((r, i) =>
updateRouteSrc(
r,
i,
Array.isArray(routesManifest.rewrites)
? routesManifest.rewrites
: routesManifest.rewrites.afterFiles
)
);
beforeFilesRewrites.forEach((r, i) =>
updateRouteSrc(
r,
i,
Array.isArray(routesManifest.rewrites)
? []
: routesManifest.rewrites.beforeFiles
)
);
fallbackRewrites.forEach((r, i) =>
updateRouteSrc(
r,
i,
Array.isArray(routesManifest.rewrites)
? []
: routesManifest.rewrites.fallback
)
);
headers.forEach((r, i) =>
updateRouteSrc(r, i, routesManifest.headers || [])
);
}
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.',
});
}
// if legacy builds are being used then it can cause conflict with
// basePath so we show an error
if (entryDirectory.length > 1) {
throw new NowBuildError({
code: 'NEXT_BASEPATH_LEGACY_BUILDS',
message:
'basePath can not be used with `builds` in vercel.json, use Project Settings to configure your monorepo instead',
link: 'https://vercel.com/docs/platform/projects#project-settings',
});
}
entryDirectory = path.join(entryDirectory, nextBasePath);
appMountPrefixNoTrailingSlash = path.posix
.join('/', entryDirectory)
.replace(/\/+$/, '');
}
if (routesManifest.pages404) {
hasPages404 = true;
}
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.',
});
}
}
}
let dynamicPrefix = path.join('/', entryDirectory);
dynamicPrefix = dynamicPrefix === '/' ? '' : dynamicPrefix;
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_SIZES',
message:
'image-manifest.json "images.sizes" must be an array. Contact support if this continues to happen.',
});
}
if (images.remotePatterns && !Array.isArray(images.remotePatterns)) {
throw new NowBuildError({
code: 'NEXT_IMAGES_REMOTEPATTERNS',
message:
'image-manifest.json "images.remotePatterns" must be an array. Contact support if this continues to happen',
});
}
if (
images.minimumCacheTTL &&
!Number.isInteger(images.minimumCacheTTL)
) {
throw new NowBuildError({
code: 'NEXT_IMAGES_MINIMUMCACHETTL',
message:
'image-manifest.json "images.minimumCacheTTL" must be an integer. Contact support if this continues to happen.',
});
}
if (
typeof images.dangerouslyAllowSVG !== 'undefined' &&
typeof images.dangerouslyAllowSVG !== 'boolean'
) {
throw new NowBuildError({
code: 'NEXT_IMAGES_DANGEROUSLYALLOWSVG',
message:
'image-manifest.json "images.dangerouslyAllowSVG" must be an boolean. Contact support if this continues to happen.',
});
}
if (
typeof images.contentSecurityPolicy !== 'undefined' &&
typeof images.contentSecurityPolicy !== 'string'
) {
throw new NowBuildError({
code: 'NEXT_IMAGES_CONTENTSECURITYPOLICY',
message:
'image-manifest.json "images.contentSecurityPolicy" must be an string. 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,
...privateOutputs.files,
};
// 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?.loader === 'default'
? {
domains: imagesManifest.images.domains,
sizes: imagesManifest.images.sizes,
remotePatterns: imagesManifest.images.remotePatterns,
minimumCacheTTL: imagesManifest.images.minimumCacheTTL,
dangerouslyAllowSVG: imagesManifest.images.dangerouslyAllowSVG,
contentSecurityPolicy:
imagesManifest.images.contentSecurityPolicy,
}
: undefined,
routes: [
...privateOutputs.routes,
...headers,
...redirects,
...beforeFilesRewrites,
// 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' },
// ensure the basePath prefixed _next/image is rewritten to the root
// _next/image path
...(routesManifest?.basePath
? [
{
src: path.join('/', entryDirectory, '_next/image/?'),
dest: '/_next/image',
check: true,
},
]
: []),
// No-op _next/data rewrite to trigger handle: 'rewrites' and then 404
// if no match to prevent rewriting _next/data unexpectedly
{
src: path.join('/', entryDirectory, '_next/data/(.*)'),
dest: path.join('/', entryDirectory, '_next/data/$1'),
check: true,
},
{
src: path.join('/', entryDirectory, '_next/data/(.*)'),
status: 404,
},
// These need to come before handle: miss or else they are grouped
// with that routing section
...afterFilesRewrites,
// make sure 404 page is used when a directory is matched without
// an index page
{ handle: 'resource' },
...fallbackRewrites,
{ src: path.join('/', entryDirectory, '.*'), status: 404 },
// 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|image|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|image|media|${escapedBuildId})/.+`
),
// 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,
important: 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'),
},
]
: []),
],
};
}
if (isLegacy) {
debug('Running npm install --production...');
await runNpmInstall(
entryPath,
['--production'],
spawnOpts,
meta,
nodeVersion
);
}
if (process.env.NPM_AUTH_TOKEN) {
await remove(path.join(entryPath, '.npmrc'));
}
const trailingSlashRedirects: Route[] = [];
let trailingSlash = false;
redirects = redirects.filter(_redir => {
const redir = _redir as Source;
// detect the trailing slash redirect and make sure it's
// kept above the wildcard mapping to prevent erroneous redirects
// since non-continue routes come after continue the $wildcard
// route will come before the redirect otherwise and if the
// redirect is triggered it breaks locale mapping
const location =
redir.headers && (redir.headers.location || redir.headers.Location);
if (redir.status === 308 && (location === '/$1' || location === '/$1/')) {
// we set continue here to prevent the redirect from
// moving underneath i18n routes
redir.continue = true;
trailingSlashRedirects.push(redir);
if (location === '/$1/') {
trailingSlash = true;
}
return false;
}
return true;
});
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 } = {};
let staticPages: { [key: string]: FileFsRef } = {};
const dynamicPages: string[] = [];
let static404Page: string | undefined;
let page404Path = '';
let hasStatic500: undefined | boolean;
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 nextFiles = {
...nodeModules,
...dotNextRootFiles,
...dotNextServerRootFiles,
};
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 getServerlessPages({
pagesDir,
entryPath,