-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
index.ts
322 lines (282 loc) · 9.46 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
import {
join,
dirname,
relative,
parse as parsePath,
sep,
basename,
} from 'path';
import { Project } from 'ts-morph';
import { getConfig } from '@vercel/static-config';
import { readFileSync, lstatSync, existsSync } from 'fs';
import { intersects, validRange } from 'semver';
import {
Lambda,
Files,
download,
glob,
debug,
getNodeVersion,
getPrefixedEnvVars,
getSpawnOptions,
runNpmInstall,
runPackageJsonScript,
execCommand,
File,
FileBlob,
FileFsRef,
PackageJson,
getEnvForPackageManager,
readConfigFile,
isSymbolicLink,
scanParentDirs,
NodejsLambda,
BuildV2,
PrepareCache,
} from '@vercel/build-utils';
import { nodeFileTrace } from '@vercel/nft';
import { getTransformedRoutes, Route } from '@vercel/routing-utils';
interface RedwoodToml {
web: { port?: number; apiProxyPath?: string };
api: { port?: number };
browser: { open?: boolean };
}
// Do not change this version for RW specific config,
// it refers to Vercels builder version
export const version = 2;
export const build: BuildV2 = async ({
workPath,
files,
entrypoint,
meta = {},
config = {},
}) => {
await download(files, workPath, meta);
const prefixedEnvs = getPrefixedEnvVars({
envPrefix: 'REDWOOD_ENV_',
envs: process.env,
});
for (const [key, value] of Object.entries(prefixedEnvs)) {
process.env[key] = value;
}
const { installCommand, buildCommand } = config;
const mountpoint = dirname(entrypoint);
const entrypointFsDirname = join(workPath, mountpoint);
const nodeVersion = await getNodeVersion(
entrypointFsDirname,
undefined,
config,
meta
);
const spawnOpts = getSpawnOptions(meta, nodeVersion);
if (!spawnOpts.env) {
spawnOpts.env = {};
}
const { cliType, lockfileVersion, packageJson } = await scanParentDirs(
entrypointFsDirname,
true
);
spawnOpts.env = getEnvForPackageManager({
cliType,
lockfileVersion,
packageJsonPackageManager: packageJson?.packageManager,
nodeVersion,
env: spawnOpts.env || {},
});
if (typeof installCommand === 'string') {
if (installCommand.trim()) {
console.log(`Running "install" command: \`${installCommand}\`...`);
await execCommand(installCommand, {
...spawnOpts,
cwd: entrypointFsDirname,
});
} else {
console.log(`Skipping "install" command...`);
}
} else {
await runNpmInstall(entrypointFsDirname, [], spawnOpts, meta, nodeVersion);
}
if (meta.isDev) {
throw new Error('Detected `@vercel/redwood` dev but this is not supported');
}
const pkg = await readConfigFile<PackageJson>(join(workPath, 'package.json'));
const toml = await readConfigFile<RedwoodToml>(
join(workPath, 'redwood.toml')
);
if (buildCommand) {
debug(`Executing build command "${buildCommand}"`);
await execCommand(buildCommand, {
...spawnOpts,
cwd: workPath,
});
} else if (hasScript('vercel-build', pkg)) {
debug(`Executing "yarn vercel-build"`);
await runPackageJsonScript(workPath, 'vercel-build', spawnOpts);
} else if (hasScript('build', pkg)) {
debug(`Executing "yarn build"`);
await runPackageJsonScript(workPath, 'build', spawnOpts);
} else {
const { devDependencies = {} } = pkg || {};
const versionRange = devDependencies['@redwoodjs/core'];
let cmd: string;
if (!versionRange || !validRange(versionRange)) {
console.log(
'WARNING: Unable to detect RedwoodJS version in package.json devDependencies'
);
cmd = 'yarn rw deploy vercel'; // Assume 0.25.0 and newer
} else if (intersects(versionRange, '<0.25.0')) {
// older than 0.25.0
cmd =
'yarn rw build && yarn rw db up --no-db-client --auto-approve && yarn rw dataMigrate up';
} else {
// 0.25.0 and newer
cmd = 'yarn rw deploy vercel';
}
await execCommand(cmd, {
...spawnOpts,
cwd: workPath,
});
}
const apiDir = toml?.web?.apiProxyPath?.replace(/^\//, '') ?? 'api';
const apiDistPath = join(workPath, 'api', 'dist', 'functions');
const webDistPath = join(workPath, 'web', 'dist');
const lambdaOutputs: { [filePath: string]: Lambda } = {};
// Strip out the .html extensions
// And populate staticOutputs map with updated paths and contentType
const webDistFiles = await glob('**', webDistPath);
const staticOutputs: Record<string, FileFsRef> = {};
for (const [fileName, fileFsRef] of Object.entries(webDistFiles)) {
const parsedPath = parsePath(fileFsRef.fsPath);
if (parsedPath.ext !== '.html') {
// No need to transform non-html files
staticOutputs[fileName] = fileFsRef;
} else {
const fileNameWithoutExtension = basename(fileName, '.html');
const pathWithoutHtmlExtension = join(
parsedPath.dir,
fileNameWithoutExtension
);
fileFsRef.contentType = 'text/html; charset=utf-8';
// @NOTE: Filename is relative to webDistPath
// e.g. {'./200': fsRef}
staticOutputs[relative(webDistPath, pathWithoutHtmlExtension)] =
fileFsRef;
}
}
// Each file in the `functions` dir will become a lambda
// Also supports nested functions like:
// ├── functions
// │ ├── bazinga
// │ │ ├── bazinga.js
// │ ├── graphql.js
const functionFiles = await glob('**/*.{js,ts}', apiDistPath);
const sourceCache = new Map<string, string | Buffer | null>();
const fsCache = new Map<string, File>();
const project = new Project();
for (const [funcName, fileFsRef] of Object.entries(functionFiles)) {
const outputName = join(apiDir, parsePath(funcName).name); // remove `.js` extension
const absEntrypoint = fileFsRef.fsPath;
const relativeEntrypoint = relative(workPath, absEntrypoint);
const awsLambdaHandler = getAWSLambdaHandler(relativeEntrypoint, 'handler');
let sourceFile = relativeEntrypoint.replace('/dist/', '/src/');
// Is this a TS file?
const sourceFileBase = basename(sourceFile, '.js');
const sourceFileDir = dirname(sourceFile);
if (existsSync(join(sourceFileDir, `${sourceFileBase}.ts`))) {
sourceFile = join(sourceFileDir, `${sourceFileBase}.ts`);
}
const { fileList, esmFileList, warnings } = await nodeFileTrace(
[absEntrypoint],
{
base: workPath,
processCwd: workPath,
ts: true,
mixedModules: true,
ignore: config.excludeFiles,
async readFile(fsPath: string): Promise<Buffer | string | null> {
const relPath = relative(workPath, fsPath);
const cached = sourceCache.get(relPath);
if (cached) return cached.toString();
// null represents a not found
if (cached === null) return null;
try {
const source = readFileSync(fsPath);
const { mode } = lstatSync(fsPath);
let entry: File;
if (isSymbolicLink(mode)) {
entry = new FileFsRef({ fsPath, mode });
} else {
entry = new FileBlob({ data: source, mode });
}
fsCache.set(relPath, entry);
sourceCache.set(relPath, source);
return source.toString();
} catch (e: any) {
if (e.code === 'ENOENT' || e.code === 'EISDIR') {
sourceCache.set(relPath, null);
return null;
}
throw e;
}
},
}
);
for (const warning of warnings) {
debug(`Warning from trace: ${warning.message}`);
}
const lambdaFiles: Files = {};
const allFiles = [...fileList, ...esmFileList];
for (const filePath of allFiles) {
lambdaFiles[filePath] = await FileFsRef.fromFsPath({
fsPath: join(workPath, filePath),
});
}
lambdaFiles[relative(workPath, fileFsRef.fsPath)] = fileFsRef;
const staticConfig = getConfig(project, sourceFile);
const regions = staticConfig?.regions;
if (regions && !Array.isArray(regions)) {
throw new Error('"regions" configuration must be an array');
}
const lambda = new NodejsLambda({
...staticConfig,
regions,
files: lambdaFiles,
handler: relativeEntrypoint,
runtime: nodeVersion.runtime,
shouldAddHelpers: false,
shouldAddSourcemapSupport: false,
awsLambdaHandler,
});
lambdaOutputs[outputName] = lambda;
}
// Older versions of redwood did not create 200.html automatically
// From v0.50.0+ 200.html is always generated as part of web build
// Note that in builder post-processing, we remove the .html extension
const fallbackHtmlPage = existsSync(join(webDistPath, '200.html'))
? '/200'
: '/index';
const defaultRoutesConfig = getTransformedRoutes({
// this makes sure we send back 200.html for unprerendered pages
rewrites: [{ source: '/(.*)', destination: fallbackHtmlPage }],
cleanUrls: true,
trailingSlash: false,
});
if (defaultRoutesConfig.error) {
throw new Error(defaultRoutesConfig.error.message);
}
return {
output: { ...staticOutputs, ...lambdaOutputs },
routes: defaultRoutesConfig.routes as Route[],
};
};
function getAWSLambdaHandler(filePath: string, handlerName: string) {
const { dir, name } = parsePath(filePath);
return `${dir}${dir ? sep : ''}${name}.${handlerName}`;
}
function hasScript(scriptName: string, pkg: PackageJson | null) {
const scripts = (pkg && pkg.scripts) || {};
return typeof scripts[scriptName] === 'string';
}
export const prepareCache: PrepareCache = ({ repoRootPath, workPath }) => {
return glob('**/node_modules/**', repoRootPath || workPath);
};