-
-
Notifications
You must be signed in to change notification settings - Fork 139
/
index.ts
335 lines (296 loc) · 9.96 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
import { build, BuildResult, BuildOptions } from 'esbuild';
import * as fs from 'fs-extra';
import * as globby from 'globby';
import * as path from 'path';
import { concat, mergeRight } from 'ramda';
import * as Serverless from 'serverless';
import * as Plugin from 'serverless/classes/Plugin';
import * as chokidar from 'chokidar';
import { extractFileNames } from './helper';
import { packExternalModules } from './pack-externals';
import { pack } from './pack';
import { preOffline } from './pre-offline';
import { preLocal } from './pre-local';
export const SERVERLESS_FOLDER = '.serverless';
export const BUILD_FOLDER = '.build';
export const WORK_FOLDER = '.esbuild';
interface OptionsExtended extends Serverless.Options {
verbose?: boolean;
}
export interface WatchConfiguration {
pattern?: string[] | string;
ignore?: string[] | string;
}
export interface Configuration extends Omit<BuildOptions, 'watch' | 'plugins'> {
packager: 'npm' | 'yarn';
packagePath: string;
exclude: string[];
watch: WatchConfiguration;
plugins?: string;
}
const DEFAULT_BUILD_OPTIONS: Partial<Configuration> = {
bundle: true,
target: 'es2017',
external: [],
exclude: ['aws-sdk'],
packager: 'npm',
watch: {
pattern: './**/*.(js|ts)',
ignore: [WORK_FOLDER, 'dist', 'node_modules', SERVERLESS_FOLDER],
},
};
export class EsbuildPlugin implements Plugin {
serviceDirPath: string;
workDirPath: string;
buildDirPath: string;
serverless: Serverless;
options: OptionsExtended;
hooks: Plugin.Hooks;
buildOptions: Configuration;
buildResults: {
result: BuildResult;
bundlePath: string;
func: any;
}[];
packExternalModules: () => Promise<void>;
pack: () => Promise<void>;
preOffline: () => Promise<void>;
preLocal: () => void;
constructor(serverless: Serverless, options: OptionsExtended) {
this.serverless = serverless;
this.options = options;
this.packExternalModules = packExternalModules.bind(this);
this.pack = pack.bind(this);
this.preOffline = preOffline.bind(this);
this.preLocal = preLocal.bind(this);
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore old verions use servicePath, new versions serviceDir. Types will use only one of them
this.serviceDirPath = this.serverless.config.serviceDir || this.serverless.config.servicePath;
this.workDirPath = path.join(this.serviceDirPath, WORK_FOLDER);
this.buildDirPath = path.join(this.workDirPath, BUILD_FOLDER);
const withDefaultOptions = mergeRight(DEFAULT_BUILD_OPTIONS);
this.buildOptions = withDefaultOptions<Configuration>(
this.serverless.service.custom?.esbuild ?? {}
);
this.hooks = {
'before:run:run': async () => {
await this.bundle();
await this.packExternalModules();
await this.copyExtras();
},
'before:offline:start': async () => {
await this.bundle();
await this.packExternalModules();
await this.copyExtras();
await this.preOffline();
this.watch();
},
'before:offline:start:init': async () => {
await this.bundle();
await this.packExternalModules();
await this.copyExtras();
await this.preOffline();
this.watch();
},
'before:package:createDeploymentArtifacts': async () => {
await this.bundle();
await this.packExternalModules();
await this.copyExtras();
await this.pack();
},
'after:package:createDeploymentArtifacts': async () => {
await this.cleanup();
},
'before:deploy:function:packageFunction': async () => {
await this.bundle();
await this.packExternalModules();
await this.copyExtras();
await this.pack();
},
'after:deploy:function:packageFunction': async () => {
await this.cleanup();
},
'before:invoke:local:invoke': async () => {
await this.bundle();
await this.packExternalModules();
await this.copyExtras();
await this.preLocal();
},
};
}
get functions(): Record<string, Serverless.FunctionDefinitionHandler> {
if (this.options.function) {
return {
[this.options.function]: this.serverless.service.getFunction(
this.options.function
) as Serverless.FunctionDefinitionHandler,
};
}
return this.serverless.service.functions as Record<
string,
Serverless.FunctionDefinitionHandler
>;
}
get rootFileNames() {
return extractFileNames(
this.serviceDirPath,
this.serverless.service.provider.name,
this.functions
);
}
async watch(): Promise<void> {
const options = {
ignored: this.buildOptions.watch.ignore,
awaitWriteFinish: true,
ignoreInitial: true,
};
chokidar.watch(this.buildOptions.watch.pattern, options).on('all', () =>
this.bundle(true)
.then(() => this.serverless.cli.log('Watching files for changes...'))
.catch(() =>
this.serverless.cli.log('Bundle error, waiting for a file change to reload...')
)
);
}
prepare() {
fs.mkdirpSync(this.buildDirPath);
fs.mkdirpSync(path.join(this.workDirPath, SERVERLESS_FOLDER));
// exclude serverless-esbuild
this.serverless.service.package = {
...(this.serverless.service.package || {}),
patterns: [
...new Set([
...(this.serverless.service.package?.include || []),
...(this.serverless.service.package?.exclude || []).map(concat('!')),
...(this.serverless.service.package?.patterns || []),
'!node_modules/serverless-esbuild',
]),
],
};
for (const fnName in this.functions) {
const fn = this.serverless.service.getFunction(fnName);
fn.package = {
...(fn.package || {}),
patterns: [
...new Set([
...(fn.package?.include || []),
...(fn.package?.exclude || []).map(concat('!')),
...(fn.package?.patterns || []),
]),
],
};
}
}
async bundle(incremental = false): Promise<BuildResult[]> {
this.prepare();
this.serverless.cli.log('Compiling with esbuild...');
return Promise.all(
this.rootFileNames.map(async ({ entry, func }) => {
const config: Omit<BuildOptions, 'watch'> = {
...this.buildOptions,
external: [...this.buildOptions.external, ...this.buildOptions.exclude],
entryPoints: [entry],
outdir: path.join(this.buildDirPath, path.dirname(entry)),
platform: 'node',
incremental,
plugins:
this.buildOptions.plugins &&
require(path.join(this.serviceDirPath, this.buildOptions.plugins)),
};
// esbuild v0.7.0 introduced config options validation, so I have to delete plugin specific options from esbuild config.
delete config['exclude'];
delete config['packager'];
delete config['packagePath'];
delete config['watch'];
delete config['pugins'];
const result = await build(config);
const bundlePath = entry.substr(0, entry.lastIndexOf('.')) + '.js';
return { result, bundlePath, func };
})
).then(results => {
this.serverless.cli.log('Compiling completed.');
this.buildResults = results;
return results.map(r => r.result);
});
}
/** Link or copy extras such as node_modules or package.patterns definitions */
async copyExtras() {
const { service } = this.serverless;
// include any "extras" from the "patterns" section
if (service.package.patterns.length > 0) {
const files = await globby(service.package.patterns);
for (const filename of files) {
const destFileName = path.resolve(path.join(this.buildDirPath, filename));
const dirname = path.dirname(destFileName);
if (!fs.existsSync(dirname)) {
fs.mkdirpSync(dirname);
}
if (!fs.existsSync(destFileName)) {
fs.copySync(path.resolve(filename), destFileName);
}
}
}
// include any "extras" from the individual function "patterns" section
for (const fnName in this.functions) {
const fn = this.serverless.service.getFunction(fnName);
if (fn.package.patterns.length === 0) {
continue;
}
const files = await globby(fn.package.patterns);
for (const filename of files) {
const destFileName = path.resolve(
path.join(this.buildDirPath, `__only_${fn.name}`, filename)
);
const dirname = path.dirname(destFileName);
if (!fs.existsSync(dirname)) {
fs.mkdirpSync(dirname);
}
if (!fs.existsSync(destFileName)) {
fs.copySync(path.resolve(filename), destFileName);
}
}
}
}
/**
* Move built code to the serverless folder, taking into account individual
* packaging preferences.
*/
async moveArtifacts(): Promise<void> {
const { service } = this.serverless;
await fs.copy(
path.join(this.workDirPath, SERVERLESS_FOLDER),
path.join(this.serviceDirPath, SERVERLESS_FOLDER)
);
if (this.options.function) {
const fn = service.getFunction(this.options.function);
fn.package.artifact = path.join(
this.serviceDirPath,
SERVERLESS_FOLDER,
path.basename(fn.package.artifact)
);
return;
}
if (service.package.individually) {
const functionNames = service.getAllFunctions();
functionNames.forEach(name => {
service.getFunction(name).package.artifact = path.join(
this.serviceDirPath,
SERVERLESS_FOLDER,
path.basename(service.getFunction(name).package.artifact)
);
});
return;
}
service.package.artifact = path.join(
this.serviceDirPath,
SERVERLESS_FOLDER,
path.basename(service.package.artifact)
);
}
async cleanup(): Promise<void> {
await this.moveArtifacts();
// Remove temp build folder
fs.removeSync(path.join(this.workDirPath));
}
}
module.exports = EsbuildPlugin;