-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
utils.ts
2668 lines (2372 loc) · 73 KB
/
utils.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 {
FileFsRef,
Files,
Config,
debug,
FileBlob,
glob,
Lambda,
Prerender,
getLambdaOptionsFromFunction,
getPlatformEnv,
streamToBuffer,
NowBuildError,
isSymbolicLink,
NodejsLambda,
EdgeFunction,
Images,
} from '@vercel/build-utils';
import { NodeFileTraceReasons } from '@vercel/nft';
import type {
HasField,
Header,
Rewrite,
Route,
RouteWithSrc,
} from '@vercel/routing-utils';
import { Sema } from 'async-sema';
import crc32 from 'buffer-crc32';
import fs, { lstat, stat } from 'fs-extra';
import path from 'path';
import resolveFrom from 'resolve-from';
import semver from 'semver';
import zlib from 'zlib';
import url from 'url';
import escapeStringRegexp from 'escape-string-regexp';
import { htmlContentType } from '.';
import textTable from 'text-table';
import { getNextjsEdgeFunctionSource } from './edge-function-source/get-edge-function-source';
import type { LambdaOptionsWithFiles } from '@vercel/build-utils/dist/lambda';
import { stringifySourceMap } from './sourcemapped';
import type { RawSourceMap } from 'source-map';
import bytes from 'bytes';
type stringMap = { [key: string]: string };
export const KIB = 1024;
export const MIB = 1024 * KIB;
export const prettyBytes = (n: number) => bytes(n, { unitSeparator: ' ' });
// Identify /[param]/ in route string
// eslint-disable-next-line no-useless-escape
const TEST_DYNAMIC_ROUTE = /\/\[[^\/]+?\](?=\/|$)/;
function isDynamicRoute(route: string): boolean {
route = route.startsWith('/') ? route : `/${route}`;
return TEST_DYNAMIC_ROUTE.test(route);
}
/**
* Validate if the entrypoint is allowed to be used
*/
function validateEntrypoint(entrypoint: string) {
if (
!/package\.json$/.exec(entrypoint) &&
!/next\.config\.js$/.exec(entrypoint)
) {
throw new NowBuildError({
message:
'Specified "src" for "@vercel/next" has to be "package.json" or "next.config.js"',
code: 'NEXT_INCORRECT_SRC',
});
}
}
/**
* Exclude certain files from the files object
*/
function excludeFiles(
files: Files,
matcher: (filePath: string) => boolean
): Files {
return Object.keys(files).reduce((newFiles, filePath) => {
if (matcher(filePath)) {
return newFiles;
}
return {
...newFiles,
[filePath]: files[filePath],
};
}, {});
}
/**
* Enforce specific package.json configuration for smallest possible lambda
*/
function normalizePackageJson(
defaultPackageJson: {
dependencies?: stringMap;
devDependencies?: stringMap;
scripts?: stringMap;
} = {}
) {
const dependencies: stringMap = {};
const devDependencies: stringMap = {
...defaultPackageJson.dependencies,
...defaultPackageJson.devDependencies,
};
if (devDependencies.react) {
dependencies.react = devDependencies.react;
delete devDependencies.react;
}
if (devDependencies['react-dom']) {
dependencies['react-dom'] = devDependencies['react-dom'];
delete devDependencies['react-dom'];
}
delete devDependencies['next-server'];
return {
...defaultPackageJson,
dependencies: {
// react and react-dom can be overwritten
react: 'latest',
'react-dom': 'latest',
...dependencies, // override react if user provided it
// next-server is forced to canary
'next-server': 'v7.0.2-canary.49',
},
devDependencies: {
...devDependencies,
// next is forced to canary
next: 'v7.0.2-canary.49',
},
scripts: {
...defaultPackageJson.scripts,
'now-build':
'NODE_OPTIONS=--max_old_space_size=3000 next build --lambdas',
},
};
}
async function getNextConfig(workPath: string, entryPath: string) {
const entryConfig = path.join(entryPath, './next.config.js');
if (await fs.pathExists(entryConfig)) {
return fs.readFile(entryConfig, 'utf8');
}
const workConfig = path.join(workPath, './next.config.js');
if (await fs.pathExists(workConfig)) {
return fs.readFile(workConfig, 'utf8');
}
return null;
}
function getImagesConfig(
imagesManifest: NextImagesManifest | undefined
): Images | undefined {
return imagesManifest?.images?.loader === 'default' &&
imagesManifest.images?.unoptimized !== true
? {
domains: imagesManifest.images.domains,
sizes: imagesManifest.images.sizes,
remotePatterns: imagesManifest.images.remotePatterns,
minimumCacheTTL: imagesManifest.images.minimumCacheTTL,
formats: imagesManifest.images.formats,
dangerouslyAllowSVG: imagesManifest.images.dangerouslyAllowSVG,
contentSecurityPolicy: imagesManifest.images.contentSecurityPolicy,
}
: undefined;
}
function normalizePage(page: string): string {
// Resolve on anything that doesn't start with `/`
if (!page.startsWith('/')) {
page = `/${page}`;
}
// remove '/index' from the end
page = page.replace(/\/index$/, '/');
return page;
}
export type Redirect = Rewrite & {
statusCode?: number;
permanent?: boolean;
};
type RoutesManifestRegex = {
regex: string;
regexKeys: string[];
};
type RoutesManifestRoute = {
page: string;
regex: string;
namedRegex?: string;
routeKeys?: { [named: string]: string };
};
type RoutesManifestOld = {
pages404: boolean;
basePath: string | undefined;
redirects: (Redirect & RoutesManifestRegex)[];
rewrites:
| (Rewrite & RoutesManifestRegex)[]
| {
beforeFiles: (Rewrite & RoutesManifestRegex)[];
afterFiles: (Rewrite & RoutesManifestRegex)[];
fallback: (Rewrite & RoutesManifestRegex)[];
};
headers?: (Header & RoutesManifestRegex)[];
dynamicRoutes: RoutesManifestRoute[];
staticRoutes: RoutesManifestRoute[];
version: 1 | 2 | 3;
dataRoutes?: Array<{
page: string;
dataRouteRegex: string;
namedDataRouteRegex?: string;
routeKeys?: { [named: string]: string };
}>;
i18n?: {
localeDetection?: boolean;
defaultLocale: string;
locales: string[];
domains?: Array<{
http?: boolean;
domain: string;
locales?: string[];
defaultLocale: string;
}>;
};
rsc?: {
header: string;
varyHeader: string;
};
skipMiddlewareUrlNormalize?: boolean;
};
type RoutesManifestV4 = Omit<RoutesManifestOld, 'dynamicRoutes' | 'version'> & {
version: 4;
dynamicRoutes: (RoutesManifestRoute | { page: string; isMiddleware: true })[];
};
export type RoutesManifest = RoutesManifestV4 | RoutesManifestOld;
export async function getRoutesManifest(
entryPath: string,
outputDirectory: string,
nextVersion?: string
): Promise<RoutesManifest | undefined> {
const shouldHaveManifest =
nextVersion && semver.gte(nextVersion, '9.1.4-canary.0');
if (!shouldHaveManifest) return;
const pathRoutesManifest = path.join(
entryPath,
outputDirectory,
'routes-manifest.json'
);
const hasRoutesManifest = await fs
.access(pathRoutesManifest)
.then(() => true)
.catch(() => false);
if (shouldHaveManifest && !hasRoutesManifest) {
throw new NowBuildError({
message:
`The file "${pathRoutesManifest}" couldn't be found. This is normally caused by a misconfiguration in your project.\n` +
'Please check the following, and reach out to support if you cannot resolve the problem:\n' +
' 1. If present, be sure your `build` script in "package.json" calls `next build`.' +
' 2. Navigate to your project\'s settings in the Vercel dashboard, and verify that the "Build Command" is not overridden, or that it calls `next build`.' +
' 3. Navigate to your project\'s settings in the Vercel dashboard, and verify that the "Output Directory" is not overridden. Note that `next export` does **not** require you change this setting, even if you customize the `next export` output directory.',
link: 'https://err.sh/vercel/vercel/now-next-routes-manifest',
code: 'NEXT_NO_ROUTES_MANIFEST',
});
}
const routesManifest: RoutesManifest = await fs.readJSON(pathRoutesManifest);
// remove temporary array based routeKeys from v1/v2 of routes
// manifest since it can result in invalid routes
for (const route of routesManifest.dataRoutes || []) {
if (Array.isArray(route.routeKeys)) {
delete route.routeKeys;
delete route.namedDataRouteRegex;
}
}
for (const route of routesManifest.dynamicRoutes || []) {
if ('routeKeys' in route && Array.isArray(route.routeKeys)) {
delete route.routeKeys;
delete route.namedRegex;
}
}
return routesManifest;
}
export async function getDynamicRoutes(
entryPath: string,
entryDirectory: string,
dynamicPages: string[],
isDev?: boolean,
routesManifest?: RoutesManifest,
omittedRoutes?: Set<string>,
canUsePreviewMode?: boolean,
bypassToken?: string,
isServerMode?: boolean,
dynamicMiddlewareRouteMap?: Map<string, RouteWithSrc>
): Promise<RouteWithSrc[]> {
if (routesManifest) {
switch (routesManifest.version) {
case 1:
case 2: {
return routesManifest.dynamicRoutes
.filter(({ page }) => canUsePreviewMode || !omittedRoutes?.has(page))
.map(({ page, regex }: { page: string; regex: string }) => {
return {
src: regex,
dest: !isDev ? path.posix.join('/', entryDirectory, page) : page,
check: true,
status:
canUsePreviewMode && omittedRoutes?.has(page) ? 404 : undefined,
};
});
}
case 3:
case 4: {
return routesManifest.dynamicRoutes
.filter(({ page }) => canUsePreviewMode || !omittedRoutes?.has(page))
.map(params => {
if ('isMiddleware' in params) {
const route = dynamicMiddlewareRouteMap?.get(params.page);
if (!route) {
throw new Error(
`Could not find dynamic middleware route for ${params.page}`
);
}
return route;
}
const { page, namedRegex, regex, routeKeys } = params;
const route: RouteWithSrc = {
src: namedRegex || regex,
dest: `${
!isDev ? path.posix.join('/', entryDirectory, page) : page
}${
routeKeys
? `?${Object.keys(routeKeys)
.map(key => `${routeKeys[key]}=$${key}`)
.join('&')}`
: ''
}`,
};
if (!isServerMode) {
route.check = true;
}
if (isServerMode && canUsePreviewMode && omittedRoutes?.has(page)) {
// only match this route when in preview mode so
// preview works for non-prerender fallback: false pages
route.has = [
{
type: 'cookie',
key: '__prerender_bypass',
value: bypassToken || undefined,
},
{
type: 'cookie',
key: '__next_preview_data',
},
];
}
return route;
});
}
default: {
// update MIN_ROUTES_MANIFEST_VERSION
throw new NowBuildError({
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.',
code: 'NEXT_VERSION_UPGRADE',
});
}
}
}
// FALLBACK:
// When `routes-manifest.json` does not exist (old Next.js versions), we'll try to
// require the methods we need from Next.js' internals.
if (!dynamicPages.length) {
return [];
}
let getRouteRegex: ((pageName: string) => { re: RegExp }) | undefined =
undefined;
let getSortedRoutes: ((normalizedPages: string[]) => string[]) | undefined;
try {
// NOTE: `eval('require')` is necessary to avoid bad transpilation to `__webpack_require__`
({ getRouteRegex, getSortedRoutes } = eval('require')(
resolveFrom(entryPath, 'next-server/dist/lib/router/utils')
));
if (typeof getRouteRegex !== 'function') {
getRouteRegex = undefined;
}
} catch (_) {} // eslint-disable-line no-empty
if (!getRouteRegex || !getSortedRoutes) {
try {
// NOTE: `eval('require')` is necessary to avoid bad transpilation to `__webpack_require__`
({ getRouteRegex, getSortedRoutes } = eval('require')(
resolveFrom(entryPath, 'next/dist/next-server/lib/router/utils')
));
if (typeof getRouteRegex !== 'function') {
getRouteRegex = undefined;
}
} catch (_) {} // eslint-disable-line no-empty
}
if (!getRouteRegex || !getSortedRoutes) {
throw new NowBuildError({
message:
'Found usage of dynamic routes but not on a new enough version of Next.js.',
code: 'NEXT_DYNAMIC_ROUTES_OUTDATED',
});
}
const pageMatchers = getSortedRoutes(dynamicPages).map(pageName => ({
pageName,
matcher: getRouteRegex && getRouteRegex(pageName).re,
}));
const routes: RouteWithSrc[] = [];
pageMatchers.forEach(pageMatcher => {
// in `vercel dev` we don't need to prefix the destination
const dest = !isDev
? path.posix.join('/', entryDirectory, pageMatcher.pageName)
: pageMatcher.pageName;
if (pageMatcher && pageMatcher.matcher) {
routes.push({
src: pageMatcher.matcher.source,
dest,
check: !isDev,
});
}
});
return routes;
}
export function localizeDynamicRoutes(
dynamicRoutes: RouteWithSrc[],
dynamicPrefix: string,
entryDirectory: string,
staticPages: Files,
prerenderManifest: NextPrerenderedRoutes,
routesManifest?: RoutesManifest,
isServerMode?: boolean,
isCorrectLocaleAPIRoutes?: boolean
): RouteWithSrc[] {
return dynamicRoutes.map((route: RouteWithSrc) => {
// i18n is already handled for middleware
if (route.middleware !== undefined || route.middlewarePath !== undefined)
return route;
const { i18n } = routesManifest || {};
if (i18n) {
const { pathname } = url.parse(route.dest!);
const pathnameNoPrefix = pathname?.replace(dynamicPrefix, '');
const isFallback = prerenderManifest.fallbackRoutes[pathname!];
const isBlocking = prerenderManifest.blockingFallbackRoutes[pathname!];
const isApiRoute =
pathnameNoPrefix === '/api' || pathnameNoPrefix?.startsWith('/api/');
const isAutoExport =
staticPages[addLocaleOrDefault(pathname!, routesManifest).substring(1)];
const isLocalePrefixed =
isFallback || isBlocking || isAutoExport || isServerMode;
route.src = route.src.replace(
'^',
`^${dynamicPrefix ? `${dynamicPrefix}[/]?` : '[/]?'}(?${
isLocalePrefixed ? '<nextLocale>' : ':'
}${i18n.locales.map(locale => escapeStringRegexp(locale)).join('|')})?`
);
if (isLocalePrefixed && !(isCorrectLocaleAPIRoutes && isApiRoute)) {
// ensure destination has locale prefix to match prerender output
// path so that the prerender object is used
route.dest = route.dest!.replace(
`${path.posix.join('/', entryDirectory, '/')}`,
`${path.posix.join('/', entryDirectory, '$nextLocale', '/')}`
);
}
} else {
route.src = route.src.replace('^', `^${dynamicPrefix}`);
}
return route;
});
}
type LoaderKey = 'imgix' | 'cloudinary' | 'akamai' | 'default';
export type NextImagesManifest = {
version: number;
images: {
loader: LoaderKey;
sizes: number[];
domains: string[];
remotePatterns: RemotePattern[];
minimumCacheTTL?: number;
formats?: ImageFormat[];
unoptimized?: boolean;
dangerouslyAllowSVG?: boolean;
contentSecurityPolicy?: string;
};
};
export type RemotePattern = {
/**
* Must be `http` or `https`.
*/
protocol?: 'http' | 'https';
/**
* Can be literal or wildcard.
* Single `*` matches a single subdomain.
* Double `**` matches any number of subdomains.
*/
hostname: string;
/**
* Can be literal port such as `8080` or empty string
* meaning no port.
*/
port?: string;
/**
* Can be literal or wildcard.
* Single `*` matches a single path segment.
* Double `**` matches any number of path segments.
*/
pathname?: string;
};
type ImageFormat = 'image/avif' | 'image/webp';
export async function getImagesManifest(
entryPath: string,
outputDirectory: string
): Promise<NextImagesManifest | undefined> {
const pathImagesManifest = path.join(
entryPath,
outputDirectory,
'images-manifest.json'
);
const hasImagesManifest = await fs
.access(pathImagesManifest)
.then(() => true)
.catch(() => false);
if (!hasImagesManifest) {
return undefined;
}
return fs.readJson(pathImagesManifest);
}
type FileMap = { [page: string]: FileFsRef };
export function filterStaticPages(
staticPageFiles: FileMap,
dynamicPages: string[],
entryDirectory: string,
htmlContentType: string,
prerenderManifest: NextPrerenderedRoutes,
routesManifest?: RoutesManifest
) {
const staticPages: FileMap = {};
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] ||
prerenderManifest.staticRoutes[normalizePage(pathname)] ||
prerenderManifest.fallbackRoutes[normalizePage(pathname)]
) {
return;
}
const staticRoute = path.posix.join(entryDirectory, pathname);
staticPages[staticRoute] = staticPageFiles[page];
staticPages[staticRoute].contentType = htmlContentType;
if (isDynamicRoute(pathname)) {
dynamicPages.push(routeName);
return;
}
});
return staticPages;
}
export function getFilesMapFromReasons(
fileList: Set<string>,
reasons: NodeFileTraceReasons,
ignoreFn?: (file: string, parent?: string) => boolean
) {
// this uses the reasons tree to collect files specific to a
// certain parent allowing us to not have to trace each parent
// separately
const parentFilesMap = new Map<string, Set<string>>();
function propagateToParents(
parents: Set<string>,
file: string,
seen = new Set<string>()
) {
for (const parent of parents || []) {
if (!seen.has(parent)) {
seen.add(parent);
let parentFiles = parentFilesMap.get(parent);
if (!parentFiles) {
parentFiles = new Set();
parentFilesMap.set(parent, parentFiles);
}
if (!ignoreFn?.(file, parent)) {
parentFiles.add(file);
}
const parentReason = reasons.get(parent);
if (parentReason?.parents) {
propagateToParents(parentReason.parents, file, seen);
}
}
}
}
for (const file of fileList!) {
const reason = reasons!.get(file);
const isInitial =
reason?.type.length === 1 && reason.type.includes('initial');
if (
!reason ||
!reason.parents ||
(isInitial && reason.parents.size === 0)
) {
continue;
}
propagateToParents(reason.parents, file);
}
return parentFilesMap;
}
export const collectTracedFiles =
(
baseDir: string,
lstatResults: { [key: string]: ReturnType<typeof lstat> },
lstatSema: Sema,
reasons: NodeFileTraceReasons,
files: { [filePath: string]: FileFsRef }
) =>
async (file: string) => {
const reason = reasons.get(file);
if (reason && reason.type.includes('initial')) {
// Initial files are manually added to the lambda later
return;
}
const filePath = path.join(baseDir, file);
if (!lstatResults[filePath]) {
lstatResults[filePath] = lstatSema
.acquire()
.then(() => lstat(filePath))
.finally(() => lstatSema.release());
}
const { mode } = await lstatResults[filePath];
files[file] = new FileFsRef({
fsPath: path.join(baseDir, file),
mode,
});
};
export const ExperimentalTraceVersion = `9.0.4-canary.1`;
export type PseudoLayer = {
[fileName: string]: PseudoFile | PseudoSymbolicLink;
};
export type PseudoFile = {
file: FileFsRef;
isSymlink: false;
crc32: number;
compBuffer: Buffer;
uncompressedSize: number;
};
export type PseudoSymbolicLink = {
file: FileFsRef;
isSymlink: true;
symlinkTarget: string;
};
const compressBuffer = (buf: Buffer): Promise<Buffer> => {
return new Promise((resolve, reject) => {
zlib.deflateRaw(
buf,
{ level: zlib.constants.Z_BEST_COMPRESSION },
(err, compBuf) => {
if (err) return reject(err);
resolve(compBuf);
}
);
});
};
export type PseudoLayerResult = {
pseudoLayer: PseudoLayer;
pseudoLayerBytes: number;
};
export async function createPseudoLayer(files: {
[fileName: string]: FileFsRef;
}): Promise<PseudoLayerResult> {
const pseudoLayer: PseudoLayer = {};
let pseudoLayerBytes = 0;
for (const fileName of Object.keys(files)) {
const file = files[fileName];
if (isSymbolicLink(file.mode)) {
const symlinkTarget = await fs.readlink(file.fsPath);
pseudoLayer[fileName] = {
file,
isSymlink: true,
symlinkTarget,
};
} else {
const origBuffer = await streamToBuffer(file.toStream());
const compBuffer = await compressBuffer(origBuffer);
pseudoLayerBytes += compBuffer.byteLength;
pseudoLayer[fileName] = {
file,
compBuffer,
isSymlink: false,
crc32: crc32.unsigned(origBuffer),
uncompressedSize: origBuffer.byteLength,
};
}
}
return { pseudoLayer, pseudoLayerBytes };
}
interface CreateLambdaFromPseudoLayersOptions extends LambdaOptionsWithFiles {
layers: PseudoLayer[];
isStreaming?: boolean;
}
// measured with 1, 2, 5, 10, and `os.cpus().length || 5`
// and sema(1) produced the best results
const createLambdaSema = new Sema(1);
export async function createLambdaFromPseudoLayers({
files: baseFiles,
layers,
isStreaming,
...lambdaOptions
}: CreateLambdaFromPseudoLayersOptions) {
await createLambdaSema.acquire();
const files: Files = {};
const addedFiles = new Set();
// Add files from pseudo layers
for (const layer of layers) {
for (const seedKey of Object.keys(layer)) {
if (addedFiles.has(seedKey)) {
// File was already added in a previous pseudo layer
continue;
}
const item = layer[seedKey];
files[seedKey] = item.file;
addedFiles.add(seedKey);
}
}
for (const fileName of Object.keys(baseFiles)) {
if (addedFiles.has(fileName)) {
// File was already added in a previous pseudo layer
continue;
}
const file = baseFiles[fileName];
files[fileName] = file;
addedFiles.add(fileName);
}
createLambdaSema.release();
return new NodejsLambda({
...lambdaOptions,
...(isStreaming
? {
experimentalResponseStreaming: true,
}
: {}),
files,
shouldAddHelpers: false,
shouldAddSourcemapSupport: false,
supportsMultiPayloads: !!process.env.NEXT_PRIVATE_MULTI_PAYLOAD,
});
}
export type NextRequiredServerFilesManifest = {
appDir?: string;
files: string[];
ignore: string[];
config: Record<string, any>;
};
export type NextPrerenderedRoutes = {
bypassToken: string | null;
staticRoutes: {
[route: string]: {
initialRevalidate: number | false;
dataRoute: string;
srcRoute: string | null;
};
};
blockingFallbackRoutes: {
[route: string]: {
routeRegex: string;
dataRoute: string;
dataRouteRegex: string;
};
};
fallbackRoutes: {
[route: string]: {
fallback: string;
routeRegex: string;
dataRoute: string;
dataRouteRegex: string;
};
};
omittedRoutes: {
[route: string]: {
routeRegex: string;
dataRoute: string;
dataRouteRegex: string;
};
};
notFoundRoutes: string[];
isLocalePrefixed: boolean;
};
export async function getExportIntent(
entryPath: string
): Promise<false | { trailingSlash: boolean }> {
const pathExportMarker = path.join(entryPath, '.next', 'export-marker.json');
const hasExportMarker: boolean = await fs
.access(pathExportMarker, fs.constants.F_OK)
.then(() => true)
.catch(() => false);
if (!hasExportMarker) {
return false;
}
const manifest: {
version: 1;
exportTrailingSlash: boolean;
hasExportPathMap: boolean;
} = JSON.parse(await fs.readFile(pathExportMarker, 'utf8'));
switch (manifest.version) {
case 1: {
if (manifest.hasExportPathMap !== true) {
return false;
}
return { trailingSlash: manifest.exportTrailingSlash };
}
default: {
return false;
}
}
}
export async function getExportStatus(
entryPath: string
): Promise<false | { success: boolean; outDirectory: string }> {
const pathExportDetail = path.join(entryPath, '.next', 'export-detail.json');
const hasExportDetail: boolean = await fs
.access(pathExportDetail, fs.constants.F_OK)
.then(() => true)
.catch(() => false);
if (!hasExportDetail) {
return false;
}
const manifest: {
version: 1;
success: boolean;
outDirectory: string;
} = JSON.parse(await fs.readFile(pathExportDetail, 'utf8'));
switch (manifest.version) {
case 1: {
return {
success: !!manifest.success,
outDirectory: manifest.outDirectory,
};
}
default: {
return false;
}
}
}
export async function getRequiredServerFilesManifest(
entryPath: string,
outputDirectory: string
): Promise<NextRequiredServerFilesManifest | false> {
const pathRequiredServerFilesManifest = path.join(
entryPath,
outputDirectory,
'required-server-files.json'
);
const hasManifest: boolean = await fs
.access(pathRequiredServerFilesManifest, fs.constants.F_OK)
.then(() => true)
.catch(() => false);
if (!hasManifest) {
return false;
}
const manifestData = JSON.parse(
await fs.readFile(pathRequiredServerFilesManifest, 'utf8')
);
const requiredServerFiles = {
files: [],
ignore: [],
config: {},
appDir: manifestData.appDir,
};
switch (manifestData.version) {
case 1: {
requiredServerFiles.files = manifestData.files;
requiredServerFiles.ignore = manifestData.ignore;
requiredServerFiles.config = manifestData.config;
requiredServerFiles.appDir = manifestData.appDir;
break;
}
default: {
throw new Error(
`Invalid required-server-files manifest version ${manifestData.version}, please contact support if this error persists`
);
}
}
return requiredServerFiles;
}
export async function getPrerenderManifest(
entryPath: string,