-
Notifications
You must be signed in to change notification settings - Fork 172
/
Copy pathscript.ts
69 lines (59 loc) · 1.54 KB
/
script.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
/**
* @file Script
* @author Alexander Rose <[email protected]>
* @private
*/
import { Signal } from 'signals'
import { Log } from './globals'
import Stage from './stage/stage'
export interface ScriptSignals {
elementAdded: Signal
elementRemoved: Signal
nameChanged: Signal
}
/**
* Script class
*/
class Script {
readonly signals: ScriptSignals = {
elementAdded: new Signal(),
elementRemoved: new Signal(),
nameChanged: new Signal()
}
readonly dir: string
readonly fn: Function
readonly type = 'Script'
/**
* Create a script instance
* @param {String} functionBody - the function source
* @param {String} name - name of the script
* @param {String} path - path of the script
*/
constructor (functionBody: string, readonly name: string, readonly path: string) {
this.dir = path.substring(0, path.lastIndexOf('/') + 1)
try {
/* eslint-disable no-new-func */
this.fn = new Function('stage', '__name', '__path', '__dir', functionBody)
} catch (e) {
Log.error('Script compilation failed', e)
this.fn = function () {}
}
}
/**
* Execute the script
* @param {Stage} stage - the stage context
* @return {Promise} - resolve when script finished running
*/
run (stage: Stage): Promise<void> {
return new Promise((resolve, reject) => {
try {
this.fn.apply(null, [ stage, this.name, this.path, this.dir ])
resolve()
} catch (e) {
Log.error('Script.fn', e)
reject(e)
}
})
}
}
export default Script