-
Notifications
You must be signed in to change notification settings - Fork 11
/
asyncLogic.js
214 lines (188 loc) · 8.76 KB
/
asyncLogic.js
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
// @ts-check
'use strict'
import defaultMethods from './defaultMethods.js'
import LogicEngine from './logic.js'
import { isSync } from './constants.js'
import declareSync from './utilities/declareSync.js'
import { buildAsync } from './compiler.js'
import omitUndefined from './utilities/omitUndefined.js'
import { optimize } from './async_optimizer.js'
import { applyPatches } from './compatibility.js'
import { coerceArray } from './utilities/coerceArray.js'
/**
* An engine capable of running asynchronous JSON Logic.
*/
class AsyncLogicEngine {
/**
* Creates a new instance of the Logic Engine.
*
* "compatible" applies a few patches to make it compatible with the preferences of mainline JSON Logic.
* The main changes are:
* - In mainline: "all" will return false if the array is empty; by default, we return true.
* - In mainline: empty arrays are falsey; in our implementation, they are truthy.
*
* @param {Object} methods An object that stores key-value pairs between the names of the commands & the functions they execute.
* @param {{ disableInline?: Boolean, disableInterpretedOptimization?: boolean, permissive?: boolean, compatible?: boolean }} options
*/
constructor (
methods = defaultMethods,
options = { disableInline: false, disableInterpretedOptimization: false, permissive: false }
) {
this.methods = { ...methods }
/** @type {{disableInline?: Boolean, disableInterpretedOptimization?: Boolean }} */
this.options = { disableInline: options.disableInline, disableInterpretedOptimization: options.disableInterpretedOptimization }
this.disableInline = options.disableInline
this.disableInterpretedOptimization = options.disableInterpretedOptimization
this.async = true
this.fallback = new LogicEngine(methods, options)
if (options.compatible) applyPatches(this)
this.optimizedMap = new WeakMap()
this.missesSinceSeen = 0
if (!this.isData) {
if (!options.permissive) this.isData = () => false
else this.isData = (data, key) => !(key in this.methods)
}
this.fallback.isData = this.isData
}
/**
* Determines the truthiness of a value.
* You can override this method to change the way truthiness is determined.
* @param {*} value
* @returns
*/
truthy (value) {
return value
}
/**
* An internal method used to parse through the JSON Logic at a lower level.
* @param {*} logic The logic being executed.
* @param {*} context The context of the logic being run (input to the function.)
* @param {*} above The context above (can be used for handlebars-style data traversal.)
* @returns {Promise<*>}
*/
async _parse (logic, context, above) {
const [func] = Object.keys(logic)
const data = logic[func]
if (this.isData(logic, func)) return logic
if (!this.methods[func]) throw new Error(`Method '${func}' was not found in the Logic Engine.`)
if (typeof this.methods[func] === 'function') {
const input = (!data || typeof data !== 'object') ? [data] : await this.run(data, context, { above })
const result = await this.methods[func](coerceArray(input), context, above, this)
return Array.isArray(result) ? Promise.all(result) : result
}
if (typeof this.methods[func] === 'object') {
const { asyncMethod, method, traverse } = this.methods[func]
const shouldTraverse = typeof traverse === 'undefined' ? true : traverse
const parsedData = shouldTraverse ? ((!data || typeof data !== 'object') ? [data] : coerceArray(await this.run(data, context, { above }))) : data
const result = await (asyncMethod || method)(parsedData, context, above, this)
return Array.isArray(result) ? Promise.all(result) : result
}
throw new Error(`Method '${func}' is not set up properly.`)
}
/**
*
* @param {String} name The name of the method being added.
* @param {((args: any, context: any, above: any[], engine: AsyncLogicEngine) => any) | { traverse?: Boolean, method?: (args: any, context: any, above: any[], engine: AsyncLogicEngine) => any, asyncMethod?: (args: any, context: any, above: any[], engine: AsyncLogicEngine) => Promise<any>, deterministic?: Function | Boolean }} method
* @param {{ deterministic?: Boolean, async?: Boolean, sync?: Boolean, optimizeUnary?: boolean }} annotations This is used by the compiler to help determine if it can optimize the function being generated.
*/
addMethod (
name,
method,
{ deterministic, async, sync, optimizeUnary } = {}
) {
if (typeof async === 'undefined' && typeof sync === 'undefined') sync = false
if (typeof sync !== 'undefined') async = !sync
if (typeof async !== 'undefined') sync = !async
if (typeof method === 'function') {
if (async) method = { asyncMethod: method, traverse: true }
else method = { method, traverse: true }
} else method = { ...method }
Object.assign(method, omitUndefined({ deterministic, optimizeUnary }))
// @ts-ignore
this.fallback.addMethod(name, method, { deterministic })
this.methods[name] = declareSync(method, sync)
}
/**
* Adds a batch of functions to the engine
* @param {String} name
* @param {Object} obj
* @param {{ deterministic?: Boolean, async?: Boolean, sync?: Boolean }} annotations Not recommended unless you're sure every function from the module will match these annotations.
*/
addModule (name, obj, annotations = {}) {
Object.getOwnPropertyNames(obj).forEach((key) => {
if (typeof obj[key] === 'function' || typeof obj[key] === 'object') this.addMethod(`${name}${name ? '.' : ''}${key}`, obj[key], annotations)
})
}
/**
* Runs the logic against the data.
*
* NOTE: With interpreted optimizations enabled, it will cache the execution plan for the logic for
* future invocations; if you plan to modify the logic, you should disable this feature, by passing
* `disableInterpretedOptimization: true` in the constructor.
*
* If it detects that a bunch of dynamic objects are being passed in, and it doesn't see the same object,
* it will disable the interpreted optimization.
*
* @param {*} logic The logic to be executed
* @param {*} data The data being passed in to the logic to be executed against.
* @param {{ above?: any }} options Options for the invocation
* @returns {Promise}
*/
async run (logic, data = {}, options = {}) {
const { above = [] } = options
// OPTIMIZER BLOCK //
if (this.missesSinceSeen > 500) {
this.disableInterpretedOptimization = true
this.missesSinceSeen = 0
}
if (!this.disableInterpretedOptimization && typeof logic === 'object' && logic && !this.optimizedMap.has(logic)) {
this.optimizedMap.set(logic, optimize(logic, this, above))
this.missesSinceSeen++
return typeof this.optimizedMap.get(logic) === 'function' ? this.optimizedMap.get(logic)(data, above) : this.optimizedMap.get(logic)
}
if (!this.disableInterpretedOptimization && logic && typeof logic === 'object' && this.optimizedMap.get(logic)) {
this.missesSinceSeen = 0
return typeof this.optimizedMap.get(logic) === 'function' ? this.optimizedMap.get(logic)(data, above) : this.optimizedMap.get(logic)
}
// END OPTIMIZER BLOCK //
if (Array.isArray(logic)) {
const res = []
// Note: In the past, it used .map and Promise.all; this can be changed in the future
// if we want it to run concurrently.
for (let i = 0; i < logic.length; i++) res.push(await this.run(logic[i], data, { above }))
return res
}
if (logic && typeof logic === 'object' && Object.keys(logic).length > 0) return this._parse(logic, data, above)
return logic
}
/**
*
* @param {*} logic The logic to be built.
* @param {{ top?: Boolean, above?: any }} options
* @returns {Promise<Function>}
*/
async build (logic, options = {}) {
const { above = [], top = true } = options
this.fallback.truthy = this.truthy
// @ts-ignore
this.fallback.allowFunctions = this.allowFunctions
if (top) {
const constructedFunction = await buildAsync(logic, { engine: this, above, async: true, state: {} })
const result = declareSync((...args) => {
if (top === true) {
try {
const result = typeof constructedFunction === 'function' ? constructedFunction(...args) : constructedFunction
return Promise.resolve(result)
} catch (err) {
return Promise.reject(err)
}
}
return typeof constructedFunction === 'function' ? constructedFunction(...args) : constructedFunction
}, top !== true && isSync(constructedFunction))
return typeof constructedFunction === 'function' || top === true ? result : constructedFunction
}
return logic
}
}
Object.assign(AsyncLogicEngine.prototype.truthy, { IDENTITY: true })
export default AsyncLogicEngine