vrpc 2.6.0 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,330 @@
1
+ /*
2
+ __/\\\________/\\\____/\\\\\\\\\______/\\\\\\\\\\\\\_________/\\\\\\\\\_
3
+ __\/\\\_______\/\\\__/\\\///////\\\___\/\\\/////////\\\____/\\\////////__
4
+ __\//\\\______/\\\__\/\\\_____\/\\\___\/\\\_______\/\\\__/\\\/___________
5
+ ___\//\\\____/\\\___\/\\\\\\\\\\\/____\/\\\\\\\\\\\\\/__/\\\_____________
6
+ ____\//\\\__/\\\____\/\\\//////\\\____\/\\\/////////___\/\\\_____________
7
+ _____\//\\\/\\\_____\/\\\____\//\\\___\/\\\____________\//\\\____________
8
+ ______\//\\\\\______\/\\\_____\//\\\__\/\\\_____________\///\\\__________
9
+ _______\//\\\_______\/\\\______\//\\\_\/\\\_______________\////\\\\\\\\\_
10
+ ________\///________\///________\///__\///___________________\/////////__
11
+
12
+
13
+ Non-intrusively adapts code and provides access in form of asynchronous remote
14
+ procedure calls (RPC).
15
+ Author: Dr. Burkhard C. Heisen (https://github.com/heisenware/vrpc)
16
+
17
+
18
+ Licensed under the MIT License <http://opensource.org/licenses/MIT>.
19
+ Copyright (c) 2018 - 2022 Dr. Burkhard C. Heisen <burkhard.heisen@heisenware.com>.
20
+
21
+ Permission is hereby granted, free of charge, to any person obtaining a copy
22
+ of this software and associated documentation files (the "Software"), to deal
23
+ in the Software without restriction, including without limitation the rights
24
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
25
+ copies of the Software, and to permit persons to whom the Software is
26
+ furnished to do so, subject to the following conditions:
27
+
28
+ The above copyright notice and this permission notice shall be included in all
29
+ copies or substantial portions of the Software.
30
+
31
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
32
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
33
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
34
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
35
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
36
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
37
+ SOFTWARE.
38
+ */
39
+
40
+ const EventEmitter = require('events')
41
+ const { nanoid } = require('nanoid')
42
+
43
+ /**
44
+ * Client capable of creating proxy classes and objects to locally call
45
+ * functions as provided through native addons.
46
+ */
47
+ class VrpcNative {
48
+ /**
49
+ * Constructs a local caller object, able to communicate to natively added C++
50
+ *
51
+ * @constructor
52
+ * @param {Object} adapter An adapter object, typically loaded as native addon
53
+ */
54
+ constructor (adapter) {
55
+ this._adapter = adapter
56
+ this._eventEmitter = new EventEmitter()
57
+
58
+ // register callback handler
59
+ this._adapter.onCallback(data => {
60
+ // when a javascript VrpcAdapter was used we will receive an object, in
61
+ // all other cases data will be a string (crossing language boundaries)
62
+ const json = typeof data === 'string' ? JSON.parse(data) : data
63
+ this._eventEmitter.emit(json.i, json.a)
64
+ })
65
+ }
66
+
67
+ /**
68
+ * Provides a proxy class to an existing one in the native addon
69
+ *
70
+ * You can use the returned class in the usual way. Static function calls
71
+ * are forwarded to the native addon, as are any instantiations and member
72
+ * function calls.
73
+ * @param {String} className The name of the class
74
+ * @returns Proxy Class
75
+ */
76
+ getClass (className) {
77
+ if (!this.getAvailableClasses().includes(className)) {
78
+ throw new Error(`Native addon does not provide class: ${className}`)
79
+ }
80
+ const eventEmitter = this._eventEmitter
81
+ const adapter = this._adapter
82
+
83
+ let invokeId = 0
84
+ let proxyId = 0
85
+ const classId = nanoid(4)
86
+
87
+ const memberFuncs = new Set(
88
+ JSON.parse(adapter.getMemberFunctions(className)).map(x => {
89
+ const pos = x.indexOf('-')
90
+ return pos > 0 ? x.substring(0, pos) : x
91
+ })
92
+ )
93
+
94
+ const staticFuncs = new Set(
95
+ JSON.parse(adapter.getStaticFunctions(className)).map(x => {
96
+ const pos = x.indexOf('-')
97
+ return pos > 0 ? x.substring(0, pos) : x
98
+ })
99
+ )
100
+
101
+ function wrapArguments (context, functionName, ...args) {
102
+ const wrapped = []
103
+ args.forEach((x, i) => {
104
+ // Check whether provided argument is a function
105
+ if (VrpcNative._isFunction(x)) {
106
+ if (functionName.startsWith('vrpcOn')) {
107
+ const id = `__f__${context}-${functionName}`
108
+ wrapped.push(id)
109
+ eventEmitter.on(id, a => x.apply(null, a))
110
+ } else {
111
+ const id = `__f__${context}-${functionName}-${i}-${invokeId++ %
112
+ Number.MAX_SAFE_INTEGER}`
113
+ wrapped.push(id)
114
+ eventEmitter.once(id, a => x.apply(null, a))
115
+ }
116
+ } else if (VrpcNative._isEmitter(x)) {
117
+ const { emitter, event } = x
118
+ const id = `__f__${context}-${functionName}-${i}-${event}`
119
+ wrapped.push(id)
120
+ eventEmitter.on(id, a => emitter.emit(event, ...a))
121
+ } else {
122
+ wrapped.push(x)
123
+ }
124
+ })
125
+ return wrapped
126
+ }
127
+
128
+ const Klass = class {
129
+ constructor (...args) {
130
+ // Create remote instance
131
+ // TODO Error handling while constructing
132
+ const instanceId = nanoid(8)
133
+ const { r } = JSON.parse(
134
+ adapter.call(
135
+ JSON.stringify({
136
+ c: className,
137
+ f: '__createIsolated__',
138
+ a: [instanceId, ...args]
139
+ })
140
+ )
141
+ )
142
+ this.vrpcInstanceId = r
143
+ this.vrpcProxyId = `${classId}-${proxyId++}`
144
+ memberFuncs.forEach(f => {
145
+ this[f] = (...args) => {
146
+ const { r, e } = JSON.parse(
147
+ adapter.call(
148
+ JSON.stringify({
149
+ f,
150
+ c: this.vrpcInstanceId,
151
+ a: wrapArguments(this.vrpcProxyId, f, ...args)
152
+ })
153
+ )
154
+ )
155
+ if (e) throw new Error(e)
156
+ // Handle functions returning a promise
157
+ if (typeof r === 'string' && r.substr(0, 5) === '__p__') {
158
+ return new Promise((resolve, reject) => {
159
+ eventEmitter.once(r, data => {
160
+ if (data.e) reject(new Error(data.e))
161
+ else resolve(data.r)
162
+ })
163
+ })
164
+ }
165
+ return r
166
+ }
167
+ })
168
+ if (!memberFuncs.has('vrpcOn') && !memberFuncs.has('vrpcOff')) {
169
+ this.vrpcOn = (functionName, ...args) => {
170
+ if (!memberFuncs.has(functionName)) throw new Error('Bad magic')
171
+ const { r, e } = JSON.parse(
172
+ adapter.call(
173
+ JSON.stringify({
174
+ f: functionName,
175
+ c: this.vrpcInstanceId,
176
+ a: wrapArguments(
177
+ this.vrpcProxyId,
178
+ `vrpcOn:${functionName}`,
179
+ ...args
180
+ )
181
+ })
182
+ )
183
+ )
184
+ if (e) throw new Error(e)
185
+ // Handle functions returning a promise
186
+ if (typeof r === 'string' && r.substr(0, 5) === '__p__') {
187
+ return new Promise((resolve, reject) => {
188
+ eventEmitter.once(r, data => {
189
+ if (data.e) reject(new Error(data.e))
190
+ else resolve(data.r)
191
+ })
192
+ })
193
+ }
194
+ return r
195
+ }
196
+ this.vrpcOff = functionName => {
197
+ const id = `__f__${this.vrpcProxyId}-vrpcOn:${functionName}`
198
+ eventEmitter.removeAllListeners(id)
199
+ }
200
+ }
201
+ }
202
+ } // Klass
203
+
204
+ // set the name of the class
205
+ Object.defineProperty(Klass, 'name', { value: className })
206
+
207
+ // inject static functions
208
+ staticFuncs.forEach(f => {
209
+ Klass[f] = (...args) => {
210
+ return JSON.parse(
211
+ adapter.call(
212
+ JSON.stringify({
213
+ f,
214
+ c: className,
215
+ a: wrapArguments(className, f, ...args)
216
+ })
217
+ )
218
+ ).r
219
+ }
220
+ })
221
+ if (!staticFuncs.has('vrpcOn')) {
222
+ Klass.vrpcOn = (functionName, ...args) => {
223
+ if (!staticFuncs.has(functionName)) throw new Error('Bad magic')
224
+ return JSON.parse(
225
+ adapter.call(
226
+ JSON.stringify({
227
+ f: functionName,
228
+ c: className,
229
+ a: wrapArguments(className, `vrpcOn:${functionName}`, ...args)
230
+ })
231
+ )
232
+ ).r
233
+ }
234
+ }
235
+ return Klass
236
+ }
237
+
238
+ /**
239
+ * Deletes a proxy object and its underlying instance
240
+ * @param {Object} proxy A proxy object
241
+ * @returns True in case of success, false otherwise
242
+ */
243
+ delete (proxy) {
244
+ if (!typeof proxy === 'object' || !proxy.vrpcProxyId) {
245
+ throw new Error('Provided argument seems not to be a VRPC proxy')
246
+ }
247
+ const json = {
248
+ c: proxy.constructor.name,
249
+ f: '__delete__',
250
+ a: [proxy.vrpcInstanceId]
251
+ }
252
+ return JSON.parse(this._adapter.call(JSON.stringify(json))).r
253
+ }
254
+
255
+ /**
256
+ * Secondary option to call a static function (when creation of a proxy class
257
+ * seems to be too much overhead)
258
+ *
259
+ * @param {String} className The class on which the static function should be called
260
+ * @param {String} functionName Name of the static function
261
+ * @param {...any} args The function arguments
262
+ * @returns The output of the underlying static function
263
+ */
264
+ callStatic (className, functionName, ...args) {
265
+ if (functionName === 'vrpcOff') {
266
+ const id = `__f__${className}-vrpcOn:${args[0]}`
267
+ this._eventEmitter.removeAllListeners(id)
268
+ }
269
+ const wrapped = []
270
+ args.forEach((x, i) => {
271
+ // Check whether provided argument is a function
272
+ if (VrpcNative._isFunction(x)) {
273
+ if (functionName.startsWith('vrpcOn')) {
274
+ const id = `__f__${className}-${functionName}:${args[0]}`
275
+ wrapped.push(id)
276
+ this._eventEmitter.on(id, a => x.apply(null, a))
277
+ } else {
278
+ const id = `__f__${className}-${functionName}-${i}-${invokeId++ %
279
+ Number.MAX_SAFE_INTEGER}`
280
+ wrapped.push(id)
281
+ this._eventEmitter.once(id, a => x.apply(null, a))
282
+ }
283
+ } else if (VrpcNative._isEmitter(x)) {
284
+ const { emitter, event } = x
285
+ const id = `__f__${className}-${functionName}-${i}-${event}`
286
+ wrapped.push(id)
287
+ this._eventEmitter.on(id, a => emitter.emit(event, ...a))
288
+ } else {
289
+ wrapped.push(x)
290
+ }
291
+ })
292
+ return JSON.parse(
293
+ this._adapter.call(
294
+ JSON.stringify({
295
+ c: className,
296
+ f: functionName === 'vrpcOn' ? args[0] : functionName,
297
+ a: wrapped
298
+ })
299
+ )
300
+ ).r
301
+ }
302
+
303
+ /**
304
+ * Retrieves an array of all available classes (names only)
305
+ *
306
+ * @return {Array.<String>} Array of class names
307
+ */
308
+ getAvailableClasses () {
309
+ return JSON.parse(this._adapter.getClasses())
310
+ }
311
+
312
+ // private:
313
+
314
+ static _isFunction (v) {
315
+ const getType = {}
316
+ return v && getType.toString.call(v) === '[object Function]'
317
+ }
318
+
319
+ static _isEmitter (v) {
320
+ return (
321
+ typeof v === 'object' &&
322
+ v.hasOwnProperty('emitter') &&
323
+ v.hasOwnProperty('event') &&
324
+ typeof v.emitter === 'object' &&
325
+ typeof v.emitter.emit === 'function'
326
+ )
327
+ }
328
+ }
329
+
330
+ module.exports = VrpcNative