-
Notifications
You must be signed in to change notification settings - Fork 230
/
Copy pathindex.ts
324 lines (282 loc) · 9.45 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
import * as path from 'path'
import * as fs from 'fs-extra'
import * as _ from 'lodash'
import * as globby from 'globby'
import * as typescript from './typescript'
import { watchFiles } from './watchFiles'
const SERVERLESS_FOLDER = '.serverless'
const BUILD_FOLDER = '.build'
export class TypeScriptPlugin {
private originalServicePath: string
private isWatching: boolean
serverless: Serverless.Instance
options: Serverless.Options
hooks: { [key: string]: Function }
commands: Serverless.CommandsDefinition
constructor(serverless: Serverless.Instance, options: Serverless.Options) {
this.serverless = serverless
this.options = options
this.commands = {
invoke: {
commands: {
local: {
options: {
watch: {
type: 'boolean',
usage: 'Watch file changes and re-invoke automatically the function'
}
}
}
}
}
}
this.hooks = {
'before:run:run': async () => {
await this.compileTs()
await this.copyExtras()
await this.copyDependencies()
},
'before:offline:start': async () => {
await this.compileTs()
await this.copyExtras()
await this.copyDependencies()
this.watchAll()
},
'before:offline:start:init': async () => {
await this.compileTs()
await this.copyExtras()
await this.copyDependencies()
this.watchAll()
},
'before:package:createDeploymentArtifacts': async () => {
await this.compileTs()
await this.copyExtras()
await this.copyDependencies(true)
},
'after:package:createDeploymentArtifacts': async () => {
await this.cleanup()
},
'before:deploy:function:packageFunction': async () => {
await this.compileTs()
await this.copyExtras()
await this.copyDependencies(true)
},
'after:deploy:function:packageFunction': async () => {
await this.cleanup()
},
'before:invoke:local:invoke': async () => {
const emitedFiles = await this.compileTs()
await this.copyExtras()
await this.copyDependencies()
if (this.isWatching) {
emitedFiles.forEach(filename => {
const module = require.resolve(path.resolve(this.originalServicePath, filename))
delete require.cache[module]
})
}
},
'after:invoke:local:invoke': async () => {
if (this.options.watch) {
await this.watchFunction()
}
}
}
}
get functions() {
const { options } = this
const { service } = this.serverless
const functions = service.functions || {}
const nodeFunctions = {}
for (const [name, functionObject] of Object.entries(functions)) {
const runtime = functions[name].runtime || service.provider.runtime
if (runtime.includes('nodejs')) {
nodeFunctions[name] = functionObject
}
}
if (options.function && nodeFunctions[options.function]) {
return {
[options.function]: nodeFunctions[options.function]
}
}
return nodeFunctions
}
get rootFileNames() {
return typescript.extractFileNames(
this.originalServicePath,
this.serverless.service.provider.name,
this.functions
)
}
prepare() {
// exclude serverless-plugin-typescript
for (const fnName in this.functions) {
const fn = this.functions[fnName]
fn.package = fn.package || {
exclude: [],
include: [],
patterns: []
}
// Add plugin to excluded packages or an empty array if exclude is undefined
fn.package.exclude = _.uniq([...fn.package.exclude || [], 'node_modules/serverless-plugin-typescript'])
}
}
async watchFunction(): Promise<void> {
if (this.isWatching) {
return
}
this.serverless.cli.log(`Watch function ${this.options.function}...`)
this.serverless.cli.log('Waiting for changes...')
this.isWatching = true
await new Promise((resolve, reject) => {
watchFiles(this.rootFileNames, this.originalServicePath, () => {
this.serverless.pluginManager.spawn('invoke:local').catch(reject)
})
})
}
async watchAll(): Promise<void> {
if (this.isWatching) {
return
}
this.serverless.cli.log(`Watching typescript files...`)
this.isWatching = true
watchFiles(this.rootFileNames, this.originalServicePath, this.compileTs.bind(this))
}
async compileTs(): Promise<string[]> {
this.prepare()
this.serverless.cli.log('Compiling with Typescript...')
if (!this.originalServicePath) {
// Save original service path and functions
this.originalServicePath = this.serverless.config.servicePath
// Fake service path so that serverless will know what to zip
this.serverless.config.servicePath = path.join(this.originalServicePath, BUILD_FOLDER)
}
let tsConfigFileLocation: string | undefined
if (
this.serverless.service.custom !== undefined
&& this.serverless.service.custom.serverlessPluginTypescript !== undefined
) {
tsConfigFileLocation = this.serverless.service.custom.serverlessPluginTypescript.tsConfigFileLocation
}
const tsconfig = typescript.getTypescriptConfig(
this.originalServicePath,
tsConfigFileLocation,
this.isWatching ? null : this.serverless.cli
)
tsconfig.outDir = BUILD_FOLDER
const emitedFiles = await typescript.run(this.rootFileNames, tsconfig)
this.serverless.cli.log('Typescript compiled.')
return emitedFiles
}
/** Link or copy extras such as node_modules or package.patterns definitions */
async copyExtras() {
const { service } = this.serverless
const patterns = [...(service.package.include || []), ...(service.package.patterns || [])]
// include any "extras" from the "include" section
if (patterns.length > 0) {
const files = await globby(patterns)
for (const filename of files) {
const destFileName = path.resolve(path.join(BUILD_FOLDER, filename))
const dirname = path.dirname(destFileName)
if (!fs.existsSync(dirname)) {
fs.mkdirpSync(dirname)
}
if (!fs.existsSync(destFileName)) {
fs.copySync(path.resolve(filename), path.resolve(path.join(BUILD_FOLDER, filename)), { dereference: true })
}
}
}
}
/**
* Copy the `node_modules` folder and `package.json` files to the output
* directory.
* @param isPackaging Provided if serverless is packaging the service for deployment
*/
async copyDependencies(isPackaging = false) {
const outPkgPath = path.resolve(path.join(BUILD_FOLDER, 'package.json'))
const outModulesPath = path.resolve(path.join(BUILD_FOLDER, 'node_modules'))
// copy development dependencies during packaging
if (isPackaging) {
if (fs.existsSync(outModulesPath)) {
fs.removeSync(outModulesPath)
}
fs.copySync(
path.resolve('node_modules'),
path.resolve(path.join(BUILD_FOLDER, 'node_modules')),
{ dereference: true }
)
} else {
if (!fs.existsSync(outModulesPath)) {
await this.linkOrCopy(path.resolve('node_modules'), outModulesPath, 'junction')
}
}
// copy/link package.json
if (!fs.existsSync(outPkgPath)) {
await this.linkOrCopy(path.resolve('package.json'), outPkgPath, 'file')
}
}
/**
* 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.originalServicePath, BUILD_FOLDER, SERVERLESS_FOLDER),
path.join(this.originalServicePath, SERVERLESS_FOLDER)
)
const layerNames = service.getAllLayers()
layerNames.forEach(name => {
service.layers[name].package.artifact = path.join(
this.originalServicePath,
SERVERLESS_FOLDER,
path.basename(service.layers[name].package.artifact)
)
})
if (this.options.function) {
const fn = service.functions[this.options.function]
fn.package.artifact = path.join(
this.originalServicePath,
SERVERLESS_FOLDER,
path.basename(fn.package.artifact)
)
return
}
if (service.package.individually) {
const functionNames = service.getAllFunctions()
functionNames.forEach(name => {
service.functions[name].package.artifact = path.join(
this.originalServicePath,
SERVERLESS_FOLDER,
path.basename(service.functions[name].package.artifact)
)
})
return
}
service.package.artifact = path.join(
this.originalServicePath,
SERVERLESS_FOLDER,
path.basename(service.package.artifact)
)
}
async cleanup(): Promise<void> {
await this.moveArtifacts()
// Restore service path
this.serverless.config.servicePath = this.originalServicePath
// Remove temp build folder
fs.removeSync(path.join(this.originalServicePath, BUILD_FOLDER))
}
/**
* Attempt to symlink a given path or directory and copy if it fails with an
* `EPERM` error.
*/
private async linkOrCopy(srcPath: string, dstPath: string, type?: fs.FsSymlinkType): Promise<void> {
return fs.symlink(srcPath, dstPath, type)
.catch(error => {
if (error.code === 'EPERM' && error.errno === -4048) {
return fs.copy(srcPath, dstPath)
}
throw error
})
}
}
module.exports = TypeScriptPlugin