vrpc 2.5.0 → 3.0.0-alpha.2

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,307 @@
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 - 2021 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 objects and locally calling
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
+ getClass (className) {
68
+ if (!this.getAvailableClasses().includes(className)) {
69
+ throw new Error(`Native addon does not provide class: ${className}`)
70
+ }
71
+ const eventEmitter = this._eventEmitter
72
+ const adapter = this._adapter
73
+
74
+ let invokeId = 0
75
+ let proxyId = 0
76
+ const classId = nanoid(4)
77
+
78
+ const memberFuncs = new Set(
79
+ JSON.parse(adapter.getMemberFunctions(className)).map(x => {
80
+ const pos = x.indexOf('-')
81
+ return pos > 0 ? x.substring(0, pos) : x
82
+ })
83
+ )
84
+
85
+ const staticFuncs = new Set(
86
+ JSON.parse(adapter.getStaticFunctions(className)).map(x => {
87
+ const pos = x.indexOf('-')
88
+ return pos > 0 ? x.substring(0, pos) : x
89
+ })
90
+ )
91
+
92
+ function wrapArguments (context, functionName, ...args) {
93
+ const wrapped = []
94
+ args.forEach((x, i) => {
95
+ // Check whether provided argument is a function
96
+ if (VrpcNative._isFunction(x)) {
97
+ if (functionName.startsWith('vrpcOn')) {
98
+ const id = `__f__${context}-${functionName}`
99
+ wrapped.push(id)
100
+ eventEmitter.on(id, a => x.apply(null, a))
101
+ } else {
102
+ const id = `__f__${context}-${functionName}-${i}-${invokeId++ %
103
+ Number.MAX_SAFE_INTEGER}`
104
+ wrapped.push(id)
105
+ eventEmitter.once(id, a => x.apply(null, a))
106
+ }
107
+ } else if (VrpcNative._isEmitter(x)) {
108
+ const { emitter, event } = x
109
+ const id = `__f__${context}-${functionName}-${i}-${event}`
110
+ wrapped.push(id)
111
+ eventEmitter.on(id, a => emitter.emit(event, ...a))
112
+ } else {
113
+ wrapped.push(x)
114
+ }
115
+ })
116
+ return wrapped
117
+ }
118
+
119
+ const Klass = class {
120
+ constructor (...args) {
121
+ // Create remote instance
122
+ // TODO Error handling while constructing
123
+ const instanceId = nanoid(8)
124
+ const { r } = JSON.parse(
125
+ adapter.call(
126
+ JSON.stringify({
127
+ c: className,
128
+ f: '__createIsolated__',
129
+ a: [instanceId, ...args]
130
+ })
131
+ )
132
+ )
133
+ this.vrpcInstanceId = r
134
+ this.vrpcProxyId = `${classId}-${proxyId++}`
135
+ memberFuncs.forEach(f => {
136
+ this[f] = (...args) => {
137
+ const { r, e } = JSON.parse(
138
+ adapter.call(
139
+ JSON.stringify({
140
+ f,
141
+ c: this.vrpcInstanceId,
142
+ a: wrapArguments(this.vrpcProxyId, f, ...args)
143
+ })
144
+ )
145
+ )
146
+ if (e) throw new Error(e)
147
+ // Handle functions returning a promise
148
+ if (typeof r === 'string' && r.substr(0, 5) === '__p__') {
149
+ return new Promise((resolve, reject) => {
150
+ eventEmitter.once(r, data => {
151
+ if (data.e) reject(new Error(data.e))
152
+ else resolve(data.r)
153
+ })
154
+ })
155
+ }
156
+ return r
157
+ }
158
+ })
159
+ if (!memberFuncs.has('vrpcOn') && !memberFuncs.has('vrpcOff')) {
160
+ this.vrpcOn = (functionName, ...args) => {
161
+ if (!memberFuncs.has(functionName)) throw new Error('Bad magic')
162
+ const { r, e } = JSON.parse(
163
+ adapter.call(
164
+ JSON.stringify({
165
+ f: functionName,
166
+ c: this.vrpcInstanceId,
167
+ a: wrapArguments(
168
+ this.vrpcProxyId,
169
+ `vrpcOn:${functionName}`,
170
+ ...args
171
+ )
172
+ })
173
+ )
174
+ )
175
+ if (e) throw new Error(e)
176
+ // Handle functions returning a promise
177
+ if (typeof r === 'string' && r.substr(0, 5) === '__p__') {
178
+ return new Promise((resolve, reject) => {
179
+ eventEmitter.once(r, data => {
180
+ if (data.e) reject(new Error(data.e))
181
+ else resolve(data.r)
182
+ })
183
+ })
184
+ }
185
+ return r
186
+ }
187
+ this.vrpcOff = functionName => {
188
+ const id = `__f__${this.vrpcProxyId}-vrpcOn:${functionName}`
189
+ eventEmitter.removeAllListeners(id)
190
+ }
191
+ }
192
+ }
193
+ } // Klass
194
+
195
+ // set the name of the class
196
+ Object.defineProperty(Klass, 'name', { value: className })
197
+
198
+ // inject static functions
199
+ staticFuncs.forEach(f => {
200
+ Klass[f] = (...args) => {
201
+ return JSON.parse(
202
+ adapter.call(
203
+ JSON.stringify({
204
+ f,
205
+ c: className,
206
+ a: wrapArguments(className, f, ...args)
207
+ })
208
+ )
209
+ ).r
210
+ }
211
+ })
212
+ if (!staticFuncs.has('vrpcOn')) {
213
+ Klass.vrpcOn = (functionName, ...args) => {
214
+ if (!staticFuncs.has(functionName)) throw new Error('Bad magic')
215
+ return JSON.parse(
216
+ adapter.call(
217
+ JSON.stringify({
218
+ f: functionName,
219
+ c: className,
220
+ a: wrapArguments(className, `vrpcOn:${functionName}`, ...args)
221
+ })
222
+ )
223
+ ).r
224
+ }
225
+ }
226
+ return Klass
227
+ }
228
+
229
+ delete (proxy) {
230
+ if (!typeof proxy === 'object' || !proxy.vrpcProxyId) {
231
+ throw new Error('Provided argument seems not to be a VRPC proxy')
232
+ }
233
+ const json = {
234
+ c: proxy.constructor.name,
235
+ f: '__delete__',
236
+ a: [proxy.vrpcInstanceId]
237
+ }
238
+ return JSON.parse(this._adapter.call(JSON.stringify(json))).r
239
+ }
240
+
241
+ callStatic (className, functionName, ...args) {
242
+ if (functionName === 'vrpcOff') {
243
+ const id = `__f__${className}-vrpcOn:${args[0]}`
244
+ this._eventEmitter.removeAllListeners(id)
245
+ }
246
+ const wrapped = []
247
+ args.forEach((x, i) => {
248
+ // Check whether provided argument is a function
249
+ if (VrpcNative._isFunction(x)) {
250
+ if (functionName.startsWith('vrpcOn')) {
251
+ const id = `__f__${className}-${functionName}:${args[0]}`
252
+ wrapped.push(id)
253
+ this._eventEmitter.on(id, a => x.apply(null, a))
254
+ } else {
255
+ const id = `__f__${className}-${functionName}-${i}-${invokeId++ %
256
+ Number.MAX_SAFE_INTEGER}`
257
+ wrapped.push(id)
258
+ this._eventEmitter.once(id, a => x.apply(null, a))
259
+ }
260
+ } else if (VrpcNative._isEmitter(x)) {
261
+ const { emitter, event } = x
262
+ const id = `__f__${className}-${functionName}-${i}-${event}`
263
+ wrapped.push(id)
264
+ this._eventEmitter.on(id, a => emitter.emit(event, ...a))
265
+ } else {
266
+ wrapped.push(x)
267
+ }
268
+ })
269
+ return JSON.parse(
270
+ this._adapter.call(
271
+ JSON.stringify({
272
+ c: className,
273
+ f: functionName === 'vrpcOn' ? args[0] : functionName,
274
+ a: wrapped
275
+ })
276
+ )
277
+ ).r
278
+ }
279
+
280
+ /**
281
+ * Retrieves an array of all available classes (names only)
282
+ *
283
+ * @return {Array.<String>} Array of class names
284
+ */
285
+ getAvailableClasses () {
286
+ return JSON.parse(this._adapter.getClasses())
287
+ }
288
+
289
+ // private:
290
+
291
+ static _isFunction (v) {
292
+ const getType = {}
293
+ return v && getType.toString.call(v) === '[object Function]'
294
+ }
295
+
296
+ static _isEmitter (v) {
297
+ return (
298
+ typeof v === 'object' &&
299
+ v.hasOwnProperty('emitter') &&
300
+ v.hasOwnProperty('event') &&
301
+ typeof v.emitter === 'object' &&
302
+ typeof v.emitter.emit === 'function'
303
+ )
304
+ }
305
+ }
306
+
307
+ module.exports = VrpcNative