-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathrouter.js
executable file
·514 lines (433 loc) · 16.2 KB
/
router.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
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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
/* eslint-disable padded-blocks */
(function (factory) {
if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
try {
let ele = require('electron')
let ipc = ele.ipcMain
let proc = 1
let remote = { BrowserWindow: ele.BrowserWindow }
if (!ipc) {
proc = 0
ipc = ele.ipcRenderer
remote = ele.remote
}
module.exports = factory(require('eventemitter3'), ipc, remote, require('lodash'), require('uuid'), proc)
} catch (e) {
throw new Error('This module only works on an Electron environment!!', e)
}
} else {
throw new Error('This module only works on an Node-Electron environment!!')
}
})(function (EventEmitter, ipc, remote, lo, uuid, procSide) {
'use strict'
// Constants
const DUP_RCV_HEAD = 'DUPLEX::RCV'
const DUP_SND_HEAD = 'DUPLEX::SND'
const defaultCfg = {
timeoutEnabled: true,
timeoutTime: 200,
_mod: false
}
// Utils
const DEBUG = function (fn) {
let args = Array.prototype.slice.call(arguments, 0)
let debugFn = args[ 0 ]
if (
global.DEBUG && typeof global.DEBUG === 'string' &&
(
global.DEBUG === '*' ||
global.DEBUG.split('|').map(a => a.toLowerCase()).indexOf(debugFn.toLowerCase()) !== -1
)
) {
console.log.apply(console, args)
}
}
function _extractEvts (evt, allEvts) {
let ret = []
// We are on DUPLEX, when a DUPLEX::RCV:: evt is received we cannot go to DUPLEX::RCV,
// it can create a infinite loop
if (evt.indexOf(DUP_RCV_HEAD) !== -1) {
allEvts = allEvts.filter(ev => !!ev.indexOf(DUP_SND_HEAD))
} else if (evt.indexOf(DUP_SND_HEAD) !== -1) {
allEvts = allEvts.filter(ev => !!ev.indexOf(DUP_RCV_HEAD))
}
DEBUG('_extractEvts', '\n', 1, 'got...', evt, '_allEvts', allEvts)
if (evt.indexOf('*') !== -1 && evt !== '*') {
// It contains a wildcard, check against all events, convert the wildcard to a whatever `.*`
let regexp = new RegExp(`^${evt.replace(/\*/g, '.*')}$`, 'i')
ret = ret.concat(allEvts.filter(ev => regexp.test(ev.replace(/\*/g, ''))))
DEBUG('_extractEvts', '\n', 2.2, 'regexp', regexp, 'ret', ret)
regexp = null
} else if (evt !== '*') {
ret = [ evt ]
DEBUG('_extractEvts', '\n', 3, ret)
} else {
ret = allEvts
DEBUG('_extractEvts', '\n', 4, ret)
}
DEBUG('_extractEvts', '\n', 5, ret)
// Check events containing wildcards
ret = ret.concat(allEvts.filter(ev => {
DEBUG('_extractEvts', '\n', 6, ev, (new RegExp(`^${ev.replace(/\*/g, '.*')}$`, 'i')).test(evt.replace(/\*/g, '')))
return (new RegExp(`^${ev.replace(/\*/g, '.*')}$`, 'i')).test(evt.replace(/\*/g, ''))
}))
DEBUG('_extractEvts', '\n', 7, ret, '->', lo.uniq(ret))
return lo.uniq(ret)
}
class DefaultDict {
constructor (DefaultInit) {
return new Proxy({}, {
get: (target, name) => name in target
? target[name]
: (target[name] = typeof DefaultInit === 'function'
? new DefaultInit().valueOf()
: DefaultInit)
})
}
}
class Router extends EventEmitter {
constructor (name, proc, cfg) {
super()
this._procSide = proc
this._name = name || this._isRenderProcess()
? 'ROUTER_RENDERER'
: 'ROUTER_PROCESS'
this._config = {}
this._cache = new DefaultDict(Array)
this.routes = {
post: (...args) => { this.route.apply(this, ['post'].concat(args)) },
get: (...args) => { this.route.apply(this, ['get'].concat(args)) },
update: (...args) => { this.route.apply(this, ['update'].concat(args)) },
delete: (...args) => { this.route.apply(this, ['delete'].concat(args)) }
}
// Bind clean to instance to make it usable as event handler
this.clean = this.clean.bind(this)
this._setup(true, cfg)
}
_setup (firstTime, cfg) {
firstTime = !!firstTime
if (firstTime) {
// Register window close handler
if (this._isRenderProcess()) {
let win = this._getWindow()
// TODO => Check if this really works,
// is the close evt triggered on the current window?
win.on('close', this.clean)
}
}
// Parse and setup config
this._config = lo.pick(lo.merge(this._config, defaultCfg, cfg), Object.keys(defaultCfg))
this._config._mod = !lo.isEqual(this._config, defaultCfg)
DEBUG('_setup', 'config', this._config)
}
_getWindows () {
if (remote.getCurrentWindow) {
// We are on renderer process
let id = remote.getCurrentWindow().id
return remote.BrowserWindow.getAllWindows().filter(w => w.id !== id)
} else {
// We are on main process
return remote.BrowserWindow.getAllWindows()
}
}
_getWindow () {
if (remote.getCurrentWindow) {
// We are on renderer process
return remote.getCurrentWindow()
} else {
// We are on main process
return null
}
}
_isRenderProcess () {
return remote.hasOwnProperty('getCurrentWindow')
}
_common (argss, verb) {
var args = Array.prototype.slice.call(argss, 0)
if (args.length <= 1) {
throw new Error('Bad arguments, invalid number of arguments, expecting at least 1, got 0. MUST provide a route, a method and a callback')
}
let route = args.shift()
let ctx = args.pop()
let cb = args.pop()
let dupRecRoute = `${DUP_RCV_HEAD}::${route}::${verb.toUpperCase()}`
if (cb === undefined) {
cb = ctx
ctx = null
}
if (typeof cb !== 'function') {
throw new Error('Bad arguments, callback must be a function, MUST provide a route and a callback')
}
DEBUG('_common',
'\n_commonreg', 'on', `${DUP_RCV_HEAD}::${route}::${verb.toUpperCase()}`,
'\n_commonreg', 'send', `${DUP_SND_HEAD}::${route}::${verb.toUpperCase()}`
)
this.on(dupRecRoute, (function (callback, router, route, verb) {
function handler (evt) {
let req = { method: verb, params: Array.prototype.slice.call(evt.data, 0) }
let res = {
json: function (err, obj) {
if (arguments.length === 1) {
obj = err
err = null
}
DEBUG('_common', 'On the json end', arguments)
router.sendDuplexBack(
`${DUP_SND_HEAD}::${route}::${verb.toUpperCase()}`,
{ origEvt: evt.origEvt, count: evt.count, total: evt.total },
err,
obj ? JSON.parse(JSON.stringify(obj)) : undefined
)
}
}
callback(req, res)
// callback = router = route = verb = req = res = null
}
router._cache[dupRecRoute].push(handler)
return handler
})(cb, this, route, verb), ctx)
}
applyConfig (cfg) {
cfg && this._setup(false, cfg)
}
on (evt, listener, ctx) {
// TODO => If event has yet been emitted,
// do not register => trigger directly, Event Queue
super.on(evt, listener, ctx)
if (ipc && ipc.on) {
ipc.on(evt, (function (router, route, listener, ctx) {
function handler (event) {
// horrible hack, ipc send event as first paremeter,
// event emitter doesn't, duck-type to check it
let sliceIndex = 0
if (
('sender' in event && 'senderId' in event) ||
typeof event.preventDefault === 'function'
) {
sliceIndex = 1
}
let args = Array.prototype.slice.call(arguments, sliceIndex)
DEBUG('on', 'inside ipc on', event, args)
listener.apply(ctx, args)
args = event = null
// args = event = listener = ctx = null
}
router._cache[route].push(handler)
return handler
})(this, evt, listener, ctx))
}
}
send (evt) {
let _evt = evt.trim()
let _args = Array.prototype.slice.call(arguments, 1)
let _allEvts = super.eventNames().concat(lo.difference(Object.keys(this._cache), super.eventNames()))
let _evts = _extractEvts(_evt, _allEvts)
let _wins = this._getWindows()
let _winsLen = _wins.length
let len = _evts.length
for (let i = 0; i < len; i++) {
let msgArr = [ _evts[ i ] ].concat(_args)
DEBUG('send', 'sending...', msgArr, msgArr.length)
// Emit through eventemitter
super.emit.apply(this, msgArr)
// Emit through windows
for (let j = 0; j < _winsLen; j++) {
// we can be overwritten while sending...
if (this._getWindows().indexOf(_wins[ j ]) !== -1) _wins[ j ].send.apply(_wins[ j ], msgArr)
}
// Emit through ipc
ipc && ipc.send && ipc.send.apply(ipc, msgArr)
}
_evt = _args = _evts = _wins = null
}
sendDuplex (evt, data) {
let _evt = evt.trim()
let _args = Array.prototype.slice.call(data.args, 0)
let _origEvt = data.origEvt
let _allEvts = super.eventNames().concat(lo.difference(Object.keys(this._cache), super.eventNames()))
let _evts = _extractEvts(_evt, _allEvts)
let _wins = this._getWindows()
let _winsLen = _wins.length
let len = _evts.length
for (let i = 0; i < len; i++) {
let msgArr = [ _evts[ i ] ].concat({ origEvt: _origEvt, count: i + 1, total: len, data: _args })
DEBUG('sendDuplex', 'sending...', msgArr)
// Emit through eventemitter
super.emit.apply(this, msgArr)
// Emit through windows
for (let j = 0; j < _winsLen; j++) {
// we can be overwritten while sending...
if (this._getWindows().indexOf(_wins[ j ]) !== -1) _wins[ j ].send.apply(_wins[ j ], msgArr)
}
// Emit through ipc
ipc && ipc.send && ipc.send.apply(ipc, msgArr)
}
_evt = _args = _evts = _wins = null
}
sendDuplexBack (evt, origEvt, err, data) {
DEBUG('sendDuplexBack', '\n', 0, 'raw', arguments)
let _evt = origEvt.origEvt
let _iter = origEvt.count
let _total = origEvt.total
let _args = Array.prototype.slice.call(arguments, 2)
let _wins = this._getWindows()
let _winsLen = _wins.length
let msgArr = [ _evt ].concat({ count: _iter, total: _total, data: _args })
DEBUG('sendDuplexBack', 'sending...', msgArr)
// Emit through eventemitter
super.emit.apply(this, msgArr)
// Emit through windows
for (let j = 0; j < _winsLen; j++) {
// we can be overwritten while sending...
if (this._getWindows().indexOf(_wins[ j ]) !== -1) _wins[ j ].send.apply(_wins[ j ], msgArr)
}
// Emit through ipc
ipc && ipc.send && ipc.send.apply(ipc, msgArr)
_evt = _iter = _total = _args = _wins = _winsLen = msgArr = null
}
// verb, arg1, arg2, arg3..., callback
route () {
let args = Array.prototype.slice.call(arguments, 0)
if (args.length < 3) {
throw new Error(`Bad arguments, invalid number of arguments, expecting at least 3, got ${args.length}. MUST provide a route, a method and a callback`)
}
// Extract verb
let verb = args.shift().toUpperCase()
// Extract route
let route = args.shift()
let transactionId = `${uuid()}`
let params = { origEvt: transactionId, args: [] }
// Extract arguments
let len = args.length - 1
let i = 0
while (i++ < len) {
params.args.push(args.shift())
}
// Extract callback
let cb = args.pop()
if (typeof cb !== 'function') {
throw new Error('Bad arguments, callback must be a function, MUST provide a route and a callback')
}
let caller = (function (router, transactionId, cb) {
let results = []
let errored = null
let timer = 0
let fn = function fn (data) {
if (!errored) {
DEBUG('route', 'back fn', arguments, JSON.stringify(data, null, 2), results)
results.push(data.data[ 1 ])
// Data from caller comes like data: { data: [ err, result ] }
// If one errored finish immediately
// Or we are on the last callback, clean aux routes
if (data.data[ 0 ] || data.count === data.total) {
!(data.data[ 0 ]) || (results = [ data.data[ 0 ] ])
data.data[ 0 ] || (results = [ null, results.length > 1 ? results : results[0] ])
DEBUG('route', 'back fn', 'data', data, 'sending', results)
router.removeListener(transactionId, fn)
cb.apply(cb, results)
router = cb = results = errored = null
clearTimeout(timer)
}
}
}
// If we are not called back within 200 ms
// trigger error
if (router._config.timeoutEnabled) {
timer = setTimeout(function () {
cb.apply(cb, [new Error(`Timeout - ${router._config.timeoutTime}ms elapsed`)])
router.removeListener(transactionId, fn)
errored = true
router = cb = null
}, router._config.timeoutTime)
}
return fn
})(this, transactionId, cb)
this.on(transactionId, caller)
DEBUG('route', '\non', `${DUP_SND_HEAD}::${route}::${verb}`)
DEBUG('route', '\nsend', `${DUP_RCV_HEAD}::${route}::${verb}`, params)
this.sendDuplex.apply(this, [`${DUP_RCV_HEAD}::${route}::${verb}`].concat(params))
}
removeListener (evt, handler, ctx) {
// Try to remove the event "as is"
// duplex events must be removed with `removeDuplexListener`,
// by now, we try to remove it normally, and if it fails we try it
// on duplex comm, in the future it could be specified
super.removeListener(evt, handler, ctx)
if (evt in this._cache) {
for (let handler of this._cache[evt]) {
ipc.removeListener(evt, handler)
}
Reflect.deleteProperty(this._cache, evt)
} else {
// Unable to remove, might be because of bad handler or
// because it was duplex comm
this.removeDuplexListener(evt)
}
}
removeDuplexListener (evt) {
// then remove it from duplex cache
// By now, it is indistinguishable which verb the event is registered to
// delete them all (maybe add a parameter in the future?)
for (let verb of ['get', 'post', 'update', 'delete']) {
let dupRecRoute = `${DUP_RCV_HEAD}::${evt}::${verb.toUpperCase()}`
if (dupRecRoute in this._cache) {
for (let handler of this._cache[dupRecRoute]) {
super.removeListener(dupRecRoute, handler)
ipc.removeListener(dupRecRoute, handler)
}
Reflect.deleteProperty(this._cache, dupRecRoute)
}
}
}
removeAllListeners () {
super.removeAllListeners()
ipc.removeAllListeners()
this._cache = new DefaultDict(Array)
}
get () {
this._common(arguments, 'GET')
}
post () {
this._common(arguments, 'POST')
}
update () {
this._common(arguments, 'UPDATE')
}
delete () {
this._common(arguments, 'DELETE')
}
clean (e) {
let name = `${this._name.toUpperCase()}::CLOSE`
let wins = this._getWindows()
DEBUG('clean', 'sending close', name, 'pre', 'events', this.eventNames())
// Communicate we are closing
super.emit(name)
ipc && ipc.send && ipc.send(name)
wins.forEach(w => { w.send(name) })
// Remove listeners
this.removeAllListeners()
DEBUG('clean', 'sending close', name, 'post', 'events', this.eventNames())
// This ensures we do not interfere in the close process
e && (e.returnValue = undefined)
// Reset config
this._config = defaultCfg
}
}
var _router = null
// TODO => Think on name and window setup (ie: registerWindow??)
// TODO => Queue of sent events for late on'ss
return (name, cfg) => {
// Little parse
if (cfg === undefined && typeof name === 'object') {
cfg = name
name = null
}
if (!_router) {
_router = new Router(name, procSide, cfg || {})
} else if (cfg && !_router._config._mod) {
// Only allow config changes if there were not another config
_router._setup(false, cfg)
}
return _router
}
})