@oox/client 1.0.0 → 1.0.1

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.
package/browser.js CHANGED
@@ -1,1113 +1,1143 @@
1
1
  var oox = (function (exports) {
2
- 'use strict';
3
-
4
- class AppContext {
5
- // 请求溯源ID
6
- traceId = '';
7
- }
8
- class Context extends AppContext {
9
- // 请求溯源IP
10
- sourceIP = '';
11
- // 请求者IP
12
- ip = '';
13
- // 请求者名称
14
- caller = 'anonymous';
15
- // 请求者ID (长连接专用)
16
- callerId = '';
17
- // 请求者连接把柄
18
- connection;
19
- constructor(context) {
20
- super();
21
- if (context) {
22
- if ('toJSON' in context && typeof context.toJSON !== 'function') {
23
- throw new Error('Context.toJSON must be a function');
24
- }
25
- Object.assign(this, context);
26
- }
27
- }
28
- toJSON() {
29
- const context = Object.assign({}, this);
30
- delete context.connection;
31
- return context;
32
- }
33
- }
34
-
35
- class Config {
36
- id = '';
37
- name = 'DEFAULT_NAME';
38
- }
39
-
40
- const contexts = {};
41
- function parseTraceIdByStack(stack) {
42
- const [traceRow] = stack.split('/').filter(row => row.includes('OOX_TRACER.<computed>'));
43
- if (traceRow) {
44
- return traceRow.match(/(?<=as\s).*?(?=\s|\])/g)?.[0] || null;
45
- }
46
- else {
47
- return null;
48
- }
49
- }
50
- function enterWith(context) {
51
- const traceId = context.traceId || '';
52
- contexts[traceId] = context;
53
- }
54
- function exitWith(context) {
55
- const traceId = context.traceId || '';
56
- delete contexts[traceId];
57
- }
58
- function getContext$1() {
59
- const traceId = parseTraceIdByStack(new Error().stack || '') || '';
60
- return contexts[traceId] || null;
61
- }
62
-
63
- function getDefaultExportFromCjs (x) {
64
- return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
65
- }
66
-
67
- var events = {exports: {}};
68
-
69
- var hasRequiredEvents;
70
-
71
- function requireEvents () {
72
- if (hasRequiredEvents) return events.exports;
73
- hasRequiredEvents = 1;
74
-
75
- var R = typeof Reflect === 'object' ? Reflect : null;
76
- var ReflectApply = R && typeof R.apply === 'function'
77
- ? R.apply
78
- : function ReflectApply(target, receiver, args) {
79
- return Function.prototype.apply.call(target, receiver, args);
80
- };
81
-
82
- var ReflectOwnKeys;
83
- if (R && typeof R.ownKeys === 'function') {
84
- ReflectOwnKeys = R.ownKeys;
85
- } else if (Object.getOwnPropertySymbols) {
86
- ReflectOwnKeys = function ReflectOwnKeys(target) {
87
- return Object.getOwnPropertyNames(target)
88
- .concat(Object.getOwnPropertySymbols(target));
89
- };
90
- } else {
91
- ReflectOwnKeys = function ReflectOwnKeys(target) {
92
- return Object.getOwnPropertyNames(target);
93
- };
94
- }
95
-
96
- function ProcessEmitWarning(warning) {
97
- if (console && console.warn) console.warn(warning);
98
- }
99
-
100
- var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) {
101
- return value !== value;
102
- };
103
-
104
- function EventEmitter() {
105
- EventEmitter.init.call(this);
106
- }
107
- events.exports = EventEmitter;
108
- events.exports.once = once;
109
-
110
- // Backwards-compat with node 0.10.x
111
- EventEmitter.EventEmitter = EventEmitter;
112
-
113
- EventEmitter.prototype._events = undefined;
114
- EventEmitter.prototype._eventsCount = 0;
115
- EventEmitter.prototype._maxListeners = undefined;
116
-
117
- // By default EventEmitters will print a warning if more than 10 listeners are
118
- // added to it. This is a useful default which helps finding memory leaks.
119
- var defaultMaxListeners = 10;
120
-
121
- function checkListener(listener) {
122
- if (typeof listener !== 'function') {
123
- throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener);
124
- }
125
- }
126
-
127
- Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
128
- enumerable: true,
129
- get: function() {
130
- return defaultMaxListeners;
131
- },
132
- set: function(arg) {
133
- if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) {
134
- throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + '.');
135
- }
136
- defaultMaxListeners = arg;
137
- }
138
- });
139
-
140
- EventEmitter.init = function() {
141
-
142
- if (this._events === undefined ||
143
- this._events === Object.getPrototypeOf(this)._events) {
144
- this._events = Object.create(null);
145
- this._eventsCount = 0;
146
- }
147
-
148
- this._maxListeners = this._maxListeners || undefined;
149
- };
150
-
151
- // Obviously not all Emitters should be limited to 10. This function allows
152
- // that to be increased. Set to zero for unlimited.
153
- EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
154
- if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) {
155
- throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + '.');
156
- }
157
- this._maxListeners = n;
158
- return this;
159
- };
160
-
161
- function _getMaxListeners(that) {
162
- if (that._maxListeners === undefined)
163
- return EventEmitter.defaultMaxListeners;
164
- return that._maxListeners;
165
- }
166
-
167
- EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
168
- return _getMaxListeners(this);
169
- };
170
-
171
- EventEmitter.prototype.emit = function emit(type) {
172
- var args = [];
173
- for (var i = 1; i < arguments.length; i++) args.push(arguments[i]);
174
- var doError = (type === 'error');
175
-
176
- var events = this._events;
177
- if (events !== undefined)
178
- doError = (doError && events.error === undefined);
179
- else if (!doError)
180
- return false;
181
-
182
- // If there is no 'error' event listener then throw.
183
- if (doError) {
184
- var er;
185
- if (args.length > 0)
186
- er = args[0];
187
- if (er instanceof Error) {
188
- // Note: The comments on the `throw` lines are intentional, they show
189
- // up in Node's output if this results in an unhandled exception.
190
- throw er; // Unhandled 'error' event
191
- }
192
- // At least give some kind of context to the user
193
- var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : ''));
194
- err.context = er;
195
- throw err; // Unhandled 'error' event
196
- }
197
-
198
- var handler = events[type];
199
-
200
- if (handler === undefined)
201
- return false;
202
-
203
- if (typeof handler === 'function') {
204
- ReflectApply(handler, this, args);
205
- } else {
206
- var len = handler.length;
207
- var listeners = arrayClone(handler, len);
208
- for (var i = 0; i < len; ++i)
209
- ReflectApply(listeners[i], this, args);
210
- }
211
-
212
- return true;
213
- };
214
-
215
- function _addListener(target, type, listener, prepend) {
216
- var m;
217
- var events;
218
- var existing;
219
-
220
- checkListener(listener);
221
-
222
- events = target._events;
223
- if (events === undefined) {
224
- events = target._events = Object.create(null);
225
- target._eventsCount = 0;
226
- } else {
227
- // To avoid recursion in the case that type === "newListener"! Before
228
- // adding it to the listeners, first emit "newListener".
229
- if (events.newListener !== undefined) {
230
- target.emit('newListener', type,
231
- listener.listener ? listener.listener : listener);
232
-
233
- // Re-assign `events` because a newListener handler could have caused the
234
- // this._events to be assigned to a new object
235
- events = target._events;
236
- }
237
- existing = events[type];
238
- }
239
-
240
- if (existing === undefined) {
241
- // Optimize the case of one listener. Don't need the extra array object.
242
- existing = events[type] = listener;
243
- ++target._eventsCount;
244
- } else {
245
- if (typeof existing === 'function') {
246
- // Adding the second element, need to change to array.
247
- existing = events[type] =
248
- prepend ? [listener, existing] : [existing, listener];
249
- // If we've already got an array, just append.
250
- } else if (prepend) {
251
- existing.unshift(listener);
252
- } else {
253
- existing.push(listener);
254
- }
255
-
256
- // Check for listener leak
257
- m = _getMaxListeners(target);
258
- if (m > 0 && existing.length > m && !existing.warned) {
259
- existing.warned = true;
260
- // No error code for this since it is a Warning
261
- // eslint-disable-next-line no-restricted-syntax
262
- var w = new Error('Possible EventEmitter memory leak detected. ' +
263
- existing.length + ' ' + String(type) + ' listeners ' +
264
- 'added. Use emitter.setMaxListeners() to ' +
265
- 'increase limit');
266
- w.name = 'MaxListenersExceededWarning';
267
- w.emitter = target;
268
- w.type = type;
269
- w.count = existing.length;
270
- ProcessEmitWarning(w);
271
- }
272
- }
273
-
274
- return target;
275
- }
276
-
277
- EventEmitter.prototype.addListener = function addListener(type, listener) {
278
- return _addListener(this, type, listener, false);
279
- };
280
-
281
- EventEmitter.prototype.on = EventEmitter.prototype.addListener;
282
-
283
- EventEmitter.prototype.prependListener =
284
- function prependListener(type, listener) {
285
- return _addListener(this, type, listener, true);
286
- };
287
-
288
- function onceWrapper() {
289
- if (!this.fired) {
290
- this.target.removeListener(this.type, this.wrapFn);
291
- this.fired = true;
292
- if (arguments.length === 0)
293
- return this.listener.call(this.target);
294
- return this.listener.apply(this.target, arguments);
295
- }
296
- }
297
-
298
- function _onceWrap(target, type, listener) {
299
- var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };
300
- var wrapped = onceWrapper.bind(state);
301
- wrapped.listener = listener;
302
- state.wrapFn = wrapped;
303
- return wrapped;
304
- }
305
-
306
- EventEmitter.prototype.once = function once(type, listener) {
307
- checkListener(listener);
308
- this.on(type, _onceWrap(this, type, listener));
309
- return this;
310
- };
311
-
312
- EventEmitter.prototype.prependOnceListener =
313
- function prependOnceListener(type, listener) {
314
- checkListener(listener);
315
- this.prependListener(type, _onceWrap(this, type, listener));
316
- return this;
317
- };
318
-
319
- // Emits a 'removeListener' event if and only if the listener was removed.
320
- EventEmitter.prototype.removeListener =
321
- function removeListener(type, listener) {
322
- var list, events, position, i, originalListener;
323
-
324
- checkListener(listener);
325
-
326
- events = this._events;
327
- if (events === undefined)
328
- return this;
329
-
330
- list = events[type];
331
- if (list === undefined)
332
- return this;
333
-
334
- if (list === listener || list.listener === listener) {
335
- if (--this._eventsCount === 0)
336
- this._events = Object.create(null);
337
- else {
338
- delete events[type];
339
- if (events.removeListener)
340
- this.emit('removeListener', type, list.listener || listener);
341
- }
342
- } else if (typeof list !== 'function') {
343
- position = -1;
344
-
345
- for (i = list.length - 1; i >= 0; i--) {
346
- if (list[i] === listener || list[i].listener === listener) {
347
- originalListener = list[i].listener;
348
- position = i;
349
- break;
350
- }
351
- }
352
-
353
- if (position < 0)
354
- return this;
355
-
356
- if (position === 0)
357
- list.shift();
358
- else {
359
- spliceOne(list, position);
360
- }
361
-
362
- if (list.length === 1)
363
- events[type] = list[0];
364
-
365
- if (events.removeListener !== undefined)
366
- this.emit('removeListener', type, originalListener || listener);
367
- }
368
-
369
- return this;
370
- };
371
-
372
- EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
373
-
374
- EventEmitter.prototype.removeAllListeners =
375
- function removeAllListeners(type) {
376
- var listeners, events, i;
377
-
378
- events = this._events;
379
- if (events === undefined)
380
- return this;
381
-
382
- // not listening for removeListener, no need to emit
383
- if (events.removeListener === undefined) {
384
- if (arguments.length === 0) {
385
- this._events = Object.create(null);
386
- this._eventsCount = 0;
387
- } else if (events[type] !== undefined) {
388
- if (--this._eventsCount === 0)
389
- this._events = Object.create(null);
390
- else
391
- delete events[type];
392
- }
393
- return this;
394
- }
395
-
396
- // emit removeListener for all listeners on all events
397
- if (arguments.length === 0) {
398
- var keys = Object.keys(events);
399
- var key;
400
- for (i = 0; i < keys.length; ++i) {
401
- key = keys[i];
402
- if (key === 'removeListener') continue;
403
- this.removeAllListeners(key);
404
- }
405
- this.removeAllListeners('removeListener');
406
- this._events = Object.create(null);
407
- this._eventsCount = 0;
408
- return this;
409
- }
410
-
411
- listeners = events[type];
412
-
413
- if (typeof listeners === 'function') {
414
- this.removeListener(type, listeners);
415
- } else if (listeners !== undefined) {
416
- // LIFO order
417
- for (i = listeners.length - 1; i >= 0; i--) {
418
- this.removeListener(type, listeners[i]);
419
- }
420
- }
421
-
422
- return this;
423
- };
424
-
425
- function _listeners(target, type, unwrap) {
426
- var events = target._events;
427
-
428
- if (events === undefined)
429
- return [];
430
-
431
- var evlistener = events[type];
432
- if (evlistener === undefined)
433
- return [];
434
-
435
- if (typeof evlistener === 'function')
436
- return unwrap ? [evlistener.listener || evlistener] : [evlistener];
437
-
438
- return unwrap ?
439
- unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
440
- }
441
-
442
- EventEmitter.prototype.listeners = function listeners(type) {
443
- return _listeners(this, type, true);
444
- };
445
-
446
- EventEmitter.prototype.rawListeners = function rawListeners(type) {
447
- return _listeners(this, type, false);
448
- };
449
-
450
- EventEmitter.listenerCount = function(emitter, type) {
451
- if (typeof emitter.listenerCount === 'function') {
452
- return emitter.listenerCount(type);
453
- } else {
454
- return listenerCount.call(emitter, type);
455
- }
456
- };
457
-
458
- EventEmitter.prototype.listenerCount = listenerCount;
459
- function listenerCount(type) {
460
- var events = this._events;
461
-
462
- if (events !== undefined) {
463
- var evlistener = events[type];
464
-
465
- if (typeof evlistener === 'function') {
466
- return 1;
467
- } else if (evlistener !== undefined) {
468
- return evlistener.length;
469
- }
470
- }
471
-
472
- return 0;
473
- }
474
-
475
- EventEmitter.prototype.eventNames = function eventNames() {
476
- return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : [];
477
- };
478
-
479
- function arrayClone(arr, n) {
480
- var copy = new Array(n);
481
- for (var i = 0; i < n; ++i)
482
- copy[i] = arr[i];
483
- return copy;
484
- }
485
-
486
- function spliceOne(list, index) {
487
- for (; index + 1 < list.length; index++)
488
- list[index] = list[index + 1];
489
- list.pop();
490
- }
491
-
492
- function unwrapListeners(arr) {
493
- var ret = new Array(arr.length);
494
- for (var i = 0; i < ret.length; ++i) {
495
- ret[i] = arr[i].listener || arr[i];
496
- }
497
- return ret;
498
- }
499
-
500
- function once(emitter, name) {
501
- return new Promise(function (resolve, reject) {
502
- function errorListener(err) {
503
- emitter.removeListener(name, resolver);
504
- reject(err);
505
- }
506
-
507
- function resolver() {
508
- if (typeof emitter.removeListener === 'function') {
509
- emitter.removeListener('error', errorListener);
510
- }
511
- resolve([].slice.call(arguments));
512
- }
513
- eventTargetAgnosticAddListener(emitter, name, resolver, { once: true });
514
- if (name !== 'error') {
515
- addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true });
516
- }
517
- });
518
- }
519
-
520
- function addErrorHandlerIfEventEmitter(emitter, handler, flags) {
521
- if (typeof emitter.on === 'function') {
522
- eventTargetAgnosticAddListener(emitter, 'error', handler, flags);
523
- }
524
- }
525
-
526
- function eventTargetAgnosticAddListener(emitter, name, listener, flags) {
527
- if (typeof emitter.on === 'function') {
528
- if (flags.once) {
529
- emitter.once(name, listener);
530
- } else {
531
- emitter.on(name, listener);
532
- }
533
- } else if (typeof emitter.addEventListener === 'function') {
534
- // EventTarget does not have `error` event semantics like Node
535
- // EventEmitters, we do not listen for `error` events here.
536
- emitter.addEventListener(name, function wrapListener(arg) {
537
- // IE does not have builtin `{ once: true }` support so we
538
- // have to do it manually.
539
- if (flags.once) {
540
- emitter.removeEventListener(name, wrapListener);
541
- }
542
- listener(arg);
543
- });
544
- } else {
545
- throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof emitter);
546
- }
547
- }
548
- return events.exports;
549
- }
550
-
551
- var eventsExports = requireEvents();
552
- var EventEmitter = /*@__PURE__*/getDefaultExportFromCjs(eventsExports);
553
-
554
- class KeepAliveConnectionError extends Error {
555
- connection;
556
- constructor(message, connection) {
557
- super(message);
558
- this.connection = connection;
559
- }
560
- }
561
- class KeepAliveConnection extends EventEmitter {
562
- // 是否为注册服务连接
563
- isRegistry = false;
564
- // 连接是否可用
565
- #enabled = false;
566
- data;
567
- nativeConnection;
568
- adapter;
569
- constructor(adapter, nativeConnection, data) {
570
- super();
571
- this.adapter = adapter;
572
- this.nativeConnection = nativeConnection;
573
- this.data = Object.assign(data, {
574
- adapter: adapter.name,
575
- });
576
- }
577
- /**
578
- * 设置连接是否可用,并自动触发enabled或disabled事件
579
- * @param enabled 是否可用
580
- */
581
- set enabled(enabled) {
582
- if (enabled !== this.#enabled) {
583
- this.#enabled = enabled;
584
- this.emit(enabled ? 'enabled' : 'disabled');
585
- if (enabled) {
586
- enabledKeepAliveConnections.add(this);
587
- }
588
- else {
589
- enabledKeepAliveConnections.remove(this);
590
- }
591
- }
592
- }
593
- get enabled() {
594
- return this.#enabled;
595
- }
596
- /**
597
- * enable & mount connection
598
- * @param params
599
- * @returns
600
- */
601
- ready(params) {
602
- // 连接已就绪,不允许重复就绪
603
- if (this.enabled)
604
- return;
605
- const { id, name } = params;
606
- keepAliveConnections.remove(this);
607
- // 更新连接数据
608
- this.data.id = id;
609
- this.data.name = name;
610
- keepAliveConnections.add(this);
611
- this.enabled = true;
612
- }
613
- disconnect() {
614
- this.enabled = false;
615
- this.nativeConnection.disconnect();
616
- }
617
- }
618
- class KeepAliveConnectionStore {
619
- #map = new Map();
620
- entries() {
621
- return this.#map.entries();
622
- }
623
- getConnectionsOfService(name) {
624
- return this.#map.get(name) || new Map();
625
- }
626
- has(name, id) {
627
- const connections = this.#map.get(name);
628
- if (!connections)
629
- return false;
630
- return connections.has(id);
631
- }
632
- get(name, id) {
633
- const connections = this.#map.get(name);
634
- if (!connections)
635
- return null;
636
- return connections.get(id) || null;
637
- }
638
- add(connection) {
639
- const { name, id } = connection.data;
640
- const connections = this.#map.get(name);
641
- if (connections) {
642
- connections.set(id, connection);
643
- }
644
- else {
645
- this.#map.set(name, new Map([[id, connection]]));
646
- }
647
- }
648
- remove(name, id) {
649
- if (name instanceof KeepAliveConnection) {
650
- id = name.data.id;
651
- name = name.data.name;
652
- }
653
- const connections = this.#map.get(name);
654
- if (connections && id !== undefined) {
655
- connections.delete(id);
656
- }
657
- }
658
- }
659
- const keepAliveConnectionAdapters = new Map();
660
- const keepAliveConnections = new KeepAliveConnectionStore();
661
- const enabledKeepAliveConnections = new KeepAliveConnectionStore();
662
-
663
- function getAllCallablePropertyNames(obj) {
664
- if (!obj)
665
- return [];
666
- let props = [], tmpProps = [], index = 0, size = 0, tmpProp = '';
667
- const bans = ["constructor", "__defineGetter__", "__defineSetter__",
668
- "hasOwnProperty", "__lookupGetter__", "__lookupSetter__",
669
- "isPrototypeOf", "propertyIsEnumerable", "toString",
670
- "valueOf", "__proto__", "toLocaleString"];
671
- do {
672
- tmpProps = Object.getOwnPropertyNames(obj);
673
- index = -1, size = tmpProps.length;
674
- while (++index < size) {
675
- tmpProp = tmpProps[index];
676
- if (!props.includes(tmpProp) && !bans.includes(tmpProp)) {
677
- props.push(tmpProp);
678
- }
679
- }
680
- } while (obj = Object.getPrototypeOf(obj));
681
- return props;
682
- }
683
- function genKVMethods(methods, kvMethods = new Map(), sourceKVMethods = new Map(), nameStack = []) {
684
- let keys = getAllCallablePropertyNames(methods);
685
- for (const key of keys) {
686
- /**
687
- * @type {Function}
688
- */
689
- let val = methods[key];
690
- if ('function' === typeof val) {
691
- const action = nameStack.concat(key).join('.');
692
- // 原函数绑定
693
- sourceKVMethods.set(action, val);
694
- // 壳函数绑定
695
- kvMethods.set(action, val.bind(methods));
696
- }
697
- else {
698
- genKVMethods(val, kvMethods, sourceKVMethods, nameStack.concat(key));
699
- }
700
- }
701
- return { kvMethods, sourceKVMethods };
702
- }
703
-
704
- const eventHub = new eventsExports.EventEmitter();
705
- /**
706
- * sourceMethods => methods
707
- */
708
- let sourceMethods = {};
709
- /**
710
- * the kvMethods is all actions refs [has bind this]
711
- */
712
- const kvMethods = new Map();
713
- const sourceKVMethods = new Map();
714
- function setMethods(methods) {
715
- sourceMethods = methods;
716
- kvMethods.clear();
717
- sourceKVMethods.clear();
718
- genKVMethods(methods, kvMethods, sourceKVMethods);
719
- }
720
- function getMethods() {
721
- return sourceMethods;
722
- }
723
- function on(event, listener) {
724
- eventHub.on(event, listener);
725
- }
726
- function once(event, listener) {
727
- eventHub.once(event, listener);
728
- }
729
- function off(event, listener) {
730
- eventHub.off(event, listener);
731
- }
732
- function emit(event, ...args) {
733
- return eventHub.emit(event, ...args);
734
- }
735
- /**
736
- * Call an Function on RPC server
737
- * @param action
738
- * @param params
739
- * @param context
740
- * @returns
741
- */
742
- async function call(action, params = [], context) {
743
- if (!Array.isArray(params))
744
- params = [params];
745
- const { traceId } = context;
746
- emit('call:start', Date.now(), action, params, context);
747
- const returns = {
748
- traceId,
749
- success: true
750
- };
751
- const OOX_TRACER = {};
752
- OOX_TRACER[traceId] = async (action, [...params], context) => {
753
- return await execute(action, [...params], context);
754
- };
755
- enterWith(context);
756
- try {
757
- const result = await OOX_TRACER[traceId](action, [...params], context);
758
- returns.body = result;
759
- emit('call:success', Date.now(), action, params, context, result);
760
- }
761
- catch (error) {
762
- returns.success = false;
763
- returns.error = {
764
- message: error.message,
765
- stack: error.stack
766
- };
767
- emit('call:fail', Date.now(), action, params, context, error);
768
- }
769
- finally {
770
- exitWith(context);
771
- return returns;
772
- }
773
- }
774
- async function execute(action, params, context) {
775
- const __proxy = '__proxy', _proxy = '_proxy';
776
- if (__proxy === action || _proxy === action || action.endsWith(_proxy))
777
- throw new Error('Invalid Action[' + action + ']');
778
- const methods = kvMethods;
779
- // 目标函数
780
- const target = methods.get(action);
781
- // 目标代理函数
782
- const targetProxy = methods.get(action + _proxy);
783
- // 即不存在目标也不存在目标代理时, 报错函数不存在
784
- if (!target && !targetProxy)
785
- throw new Error('Unknown Action [' + action + ']');
786
- // ============================ PROXY BEGIN ============================
787
- // 最顶层代理
788
- const topProxy = methods.get(__proxy);
789
- if (topProxy) {
790
- const proxyReturns = await topProxy(action, params, context);
791
- if (proxyReturns !== undefined)
792
- return proxyReturns;
793
- }
794
- // 'x.y.z' => [ 'x', 'y', 'z' ]
795
- const nameStack = action.split('.'), size = nameStack.length - 1;
796
- let index = -1, proxyPrefix = '';
797
- // 根代理遍历
798
- while (++index < size) {
799
- // x.
800
- // x.y.
801
- proxyPrefix += nameStack[index] + '.';
802
- // x.__proxy
803
- // x.y.__proxy
804
- const rootProxy = methods.get(proxyPrefix + __proxy);
805
- // x.__proxy ( 'y.z', ... )
806
- // x.y.__proxy ( 'z', ... )
807
- if (rootProxy) {
808
- const proxyReturns = await rootProxy(nameStack.slice(index).join('.'), params, context);
809
- if (proxyReturns !== undefined)
810
- return proxyReturns;
811
- }
812
- }
813
- // 同级代理
814
- const layerProxy = methods.get(proxyPrefix + _proxy);
815
- if (layerProxy) {
816
- const proxyReturns = await layerProxy(nameStack[index], params, context);
817
- if (proxyReturns !== undefined)
818
- return proxyReturns;
819
- }
820
- if (targetProxy) {
821
- const proxyReturns = await targetProxy(params, context);
822
- if (proxyReturns !== undefined)
823
- return proxyReturns;
824
- }
825
- // ============================= PROXY END =============================
826
- // make sure target action execute after all proxies
827
- if (target) {
828
- return await target(...params);
829
- }
830
- }
831
-
832
- function info(...content) {
833
- const context = getContext$1() || null;
834
- emit('log', Date.now(), context, 'info', content);
835
- }
836
- function warn(...content) {
837
- const context = getContext$1() || null;
838
- emit('log', Date.now(), context, 'warn', content);
839
- }
840
- function error(...content) {
841
- const context = getContext$1() || null;
842
- emit('log', Date.now(), context, 'error', content);
843
- }
844
- function tag(name) {
845
- const context = getContext$1() || null;
846
- emit('log', Date.now(), context, 'tag', name);
847
- }
848
- function trace(name) {
849
- const context = getContext$1() || null;
850
- const trace = { stack: '' };
851
- Error.captureStackTrace(trace);
852
- const stack = trace.stack
853
- .replace(/.*\n.*logger.js.*\n/, name || 'Untitle\n');
854
- emit('log', Date.now(), context, 'trace', stack);
855
- }
856
-
857
- var logger = /*#__PURE__*/Object.freeze({
858
- __proto__: null,
859
- error: error,
860
- info: info,
861
- tag: tag,
862
- trace: trace,
863
- warn: warn
864
- });
865
-
866
- class SampleKeepAliveConnectionAdapter {
867
- OOXEvent = {
868
- CONNECT: 'connect',
869
- DISCONNECT: 'disconnect',
870
- ERROR: 'error',
871
- CALL: 'call',
872
- READY: 'oox:ready',
873
- ENABLED: 'oox:enabled',
874
- DISABLED: 'oox:disabled',
875
- REGISTRY_SYNC_CONNECTIONS: 'oox:registry:sync_connections',
876
- REGISTRY_SUBSCRIBE: 'oox:registry:subscribe',
877
- REGISTRY_NOTIFY: 'oox:registry:notify',
878
- };
879
- /**
880
- * 通知连接列表
881
- */
882
- ['registry:notify'](connection, datas) {
883
- connection.nativeConnection.emit(this.OOXEvent.REGISTRY_NOTIFY, datas);
884
- }
885
- /**
886
- * 订阅连接列表
887
- */
888
- ['registry:subscribe'](connection, query) {
889
- connection.nativeConnection.emit(this.OOXEvent.REGISTRY_SUBSCRIBE, query);
890
- }
891
- bindConnectionEvents(connection) {
892
- const socket = connection.nativeConnection;
893
- socket.on(this.OOXEvent.READY, (params) => {
894
- connection.ready(params);
895
- });
896
- socket.on(this.OOXEvent.ENABLED, () => {
897
- connection.enabled = true;
898
- });
899
- socket.on(this.OOXEvent.DISABLED, () => {
900
- connection.enabled = false;
901
- });
902
- socket.on(this.OOXEvent.DISCONNECT, () => {
903
- removeKeepAliveConnection(connection);
904
- socket.removeAllListeners();
905
- connection.emit('disconnect');
906
- });
907
- socket.on(this.OOXEvent.CONNECT, () => {
908
- connection.emit('connect');
909
- });
910
- socket.on(this.OOXEvent.ERROR, (error) => {
911
- removeKeepAliveConnection(connection);
912
- socket.removeAllListeners();
913
- connection.emit('error', new KeepAliveConnectionError(error.message, connection));
914
- });
915
- }
916
- async open(identify) {
917
- const connection = this.newConnection(identify);
918
- addKeepAliveConnection(connection);
919
- this.bindConnectionEvents(connection);
920
- this.bindCall(connection);
921
- await new Promise((resolve, reject) => {
922
- connection.once('enabled', resolve);
923
- connection.once('error', reject);
924
- connection.once('disconnect', () => {
925
- reject(new Error('disconnect'));
926
- });
927
- if (connection.nativeConnection.connect) {
928
- connection.nativeConnection.connect();
929
- }
930
- });
931
- return connection;
932
- }
933
- async close(connection) {
934
- connection.nativeConnection.disconnect();
935
- return Promise.resolve();
936
- }
937
- /**
938
- * 发送事件
939
- * @param socket
940
- * @param event
941
- * @param params
942
- */
943
- async emit(socket, event, params) {
944
- if (!socket.connected)
945
- throw new Error('Socket not connected');
946
- return await new Promise((resolve, reject) => {
947
- const onError = (reason) => {
948
- const message = 'string' === typeof reason ? reason : reason instanceof Error ? reason.message : 'connect error';
949
- reject(new Error(message));
950
- };
951
- // RPC 执行时中断连接
952
- socket.once(this.OOXEvent.DISCONNECT, onError);
953
- socket.emit(event, ...params, (returns) => {
954
- socket.off(this.OOXEvent.DISCONNECT, onError);
955
- resolve(returns);
956
- });
957
- });
958
- }
959
- /**
960
- * RPC
961
- */
962
- async rpc(connection, action, params, context) {
963
- if (!context)
964
- context = getContext();
965
- const miniContext = {
966
- sourceIP: context.sourceIP,
967
- traceId: context.traceId,
968
- };
969
- const { success, error, body } = await this.emit(connection.nativeConnection, this.OOXEvent.CALL, [action, params, miniContext]);
970
- if (success)
971
- return body;
972
- else if (error)
973
- throw new Error(error.message);
974
- else
975
- throw new Error('[RPC] Unknown Error');
976
- }
977
- /**
978
- * 绑定 call 事件
979
- * @param connection
980
- */
981
- bindCall(connection) {
982
- const { id, name, ip } = connection.data;
983
- connection.nativeConnection.on(this.OOXEvent.CALL, async (action, params, context, callback) => {
984
- const validContext = new Context({
985
- ...context,
986
- ip: ip,
987
- caller: name,
988
- callerId: id,
989
- connection
990
- });
991
- this.call(action, params, validContext, callback);
992
- });
993
- }
994
- async call(action, params, context, callback) {
995
- const returns = await call(action, params, context);
996
- 'function' === typeof callback && callback(returns);
997
- return returns;
998
- }
999
- }
1000
-
1001
- const config = new Config();
1002
- let genTraceIdFunction = () => crypto.randomUUID();
1003
- function setGenTraceIdFunction(fn) {
1004
- genTraceIdFunction = fn;
1005
- }
1006
- /**
1007
- * 生成随机不重复id
1008
- */
1009
- function genTraceId() {
1010
- return genTraceIdFunction();
1011
- }
1012
- function genContext(context) {
1013
- const newContext = new Context(context);
1014
- if (!newContext.traceId)
1015
- newContext.traceId = genTraceId();
1016
- if (!newContext.sourceIP)
1017
- newContext.sourceIP = newContext.ip;
1018
- return newContext;
1019
- }
1020
- function getContext() {
1021
- return getContext$1() || genContext();
1022
- }
1023
- function addKeepAliveConnection(connection) {
1024
- if (keepAliveConnections.has(connection.data.name, connection.data.id)) {
1025
- connection.disconnect();
1026
- throw new KeepAliveConnectionError('Connection already exists', connection);
1027
- }
1028
- keepAliveConnections.add(connection);
1029
- }
1030
- function removeKeepAliveConnection(arg1, arg2) {
1031
- if (typeof arg1 === 'string') {
1032
- const connection = keepAliveConnections.get(arg1, arg2);
1033
- if (connection)
1034
- connection.disconnect();
1035
- keepAliveConnections.remove(arg1, arg2);
1036
- enabledKeepAliveConnections.remove(arg1, arg2);
1037
- }
1038
- else {
1039
- arg1.disconnect();
1040
- keepAliveConnections.remove(arg1);
1041
- enabledKeepAliveConnections.remove(arg1);
1042
- }
1043
- }
1044
- /**
1045
- * random connection select for default load balance policy
1046
- * @param name service name
1047
- * @returns selected connection
1048
- */
1049
- let loadBalancePolicy = (name) => {
1050
- const connections = enabledKeepAliveConnections.getConnectionsOfService(name);
1051
- if (!connections || !connections.size)
1052
- return null;
1053
- const arrayConnections = Array.from(connections.values());
1054
- const index = Math.floor(Math.random() * arrayConnections.length);
1055
- return arrayConnections[index];
1056
- };
1057
- function setLoadBalancePolicy(policy) {
1058
- loadBalancePolicy = policy;
1059
- }
1060
- async function rpc(arg1, action, params, context) {
1061
- if (!context || !context.traceId) {
1062
- context = getContext();
1063
- }
1064
- let connection = null;
1065
- if (arg1 instanceof KeepAliveConnection) {
1066
- connection = arg1;
1067
- }
1068
- else if ('string' === typeof arg1) {
1069
- connection = loadBalancePolicy(arg1);
1070
- }
1071
- else
1072
- throw new Error(`Unknown rpc arg1<${arg1}>`);
1073
- if (!connection)
1074
- throw new Error(`Connection<${arg1}> not found`);
1075
- return connection.adapter.rpc(connection, action, params, context);
1076
- }
1077
-
1078
- exports.AppContext = AppContext;
1079
- exports.Config = Config;
1080
- exports.Context = Context;
1081
- exports.KeepAliveConnection = KeepAliveConnection;
1082
- exports.KeepAliveConnectionError = KeepAliveConnectionError;
1083
- exports.KeepAliveConnectionStore = KeepAliveConnectionStore;
1084
- exports.SampleKeepAliveConnectionAdapter = SampleKeepAliveConnectionAdapter;
1085
- exports.addKeepAliveConnection = addKeepAliveConnection;
1086
- exports.call = call;
1087
- exports.config = config;
1088
- exports.emit = emit;
1089
- exports.enabledKeepAliveConnections = enabledKeepAliveConnections;
1090
- exports.eventHub = eventHub;
1091
- exports.execute = execute;
1092
- exports.genContext = genContext;
1093
- exports.genTraceId = genTraceId;
1094
- exports.getContext = getContext;
1095
- exports.getMethods = getMethods;
1096
- exports.keepAliveConnectionAdapters = keepAliveConnectionAdapters;
1097
- exports.keepAliveConnections = keepAliveConnections;
1098
- exports.kvMethods = kvMethods;
1099
- exports.logger = logger;
1100
- exports.off = off;
1101
- exports.on = on;
1102
- exports.once = once;
1103
- exports.removeKeepAliveConnection = removeKeepAliveConnection;
1104
- exports.rpc = rpc;
1105
- exports.setGenTraceIdFunction = setGenTraceIdFunction;
1106
- exports.setLoadBalancePolicy = setLoadBalancePolicy;
1107
- exports.setMethods = setMethods;
1108
- exports.sourceKVMethods = sourceKVMethods;
1109
-
1110
- return exports;
2
+ 'use strict';
3
+
4
+ function getDefaultExportFromCjs (x) {
5
+ return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
6
+ }
7
+
8
+ var events = {exports: {}};
9
+
10
+ var hasRequiredEvents;
11
+
12
+ function requireEvents () {
13
+ if (hasRequiredEvents) return events.exports;
14
+ hasRequiredEvents = 1;
15
+
16
+ var R = typeof Reflect === 'object' ? Reflect : null;
17
+ var ReflectApply = R && typeof R.apply === 'function'
18
+ ? R.apply
19
+ : function ReflectApply(target, receiver, args) {
20
+ return Function.prototype.apply.call(target, receiver, args);
21
+ };
22
+
23
+ var ReflectOwnKeys;
24
+ if (R && typeof R.ownKeys === 'function') {
25
+ ReflectOwnKeys = R.ownKeys;
26
+ } else if (Object.getOwnPropertySymbols) {
27
+ ReflectOwnKeys = function ReflectOwnKeys(target) {
28
+ return Object.getOwnPropertyNames(target)
29
+ .concat(Object.getOwnPropertySymbols(target));
30
+ };
31
+ } else {
32
+ ReflectOwnKeys = function ReflectOwnKeys(target) {
33
+ return Object.getOwnPropertyNames(target);
34
+ };
35
+ }
36
+
37
+ function ProcessEmitWarning(warning) {
38
+ if (console && console.warn) console.warn(warning);
39
+ }
40
+
41
+ var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) {
42
+ return value !== value;
43
+ };
44
+
45
+ function EventEmitter() {
46
+ EventEmitter.init.call(this);
47
+ }
48
+ events.exports = EventEmitter;
49
+ events.exports.once = once;
50
+
51
+ // Backwards-compat with node 0.10.x
52
+ EventEmitter.EventEmitter = EventEmitter;
53
+
54
+ EventEmitter.prototype._events = undefined;
55
+ EventEmitter.prototype._eventsCount = 0;
56
+ EventEmitter.prototype._maxListeners = undefined;
57
+
58
+ // By default EventEmitters will print a warning if more than 10 listeners are
59
+ // added to it. This is a useful default which helps finding memory leaks.
60
+ var defaultMaxListeners = 10;
61
+
62
+ function checkListener(listener) {
63
+ if (typeof listener !== 'function') {
64
+ throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener);
65
+ }
66
+ }
67
+
68
+ Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
69
+ enumerable: true,
70
+ get: function() {
71
+ return defaultMaxListeners;
72
+ },
73
+ set: function(arg) {
74
+ if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) {
75
+ throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + '.');
76
+ }
77
+ defaultMaxListeners = arg;
78
+ }
79
+ });
80
+
81
+ EventEmitter.init = function() {
82
+
83
+ if (this._events === undefined ||
84
+ this._events === Object.getPrototypeOf(this)._events) {
85
+ this._events = Object.create(null);
86
+ this._eventsCount = 0;
87
+ }
88
+
89
+ this._maxListeners = this._maxListeners || undefined;
90
+ };
91
+
92
+ // Obviously not all Emitters should be limited to 10. This function allows
93
+ // that to be increased. Set to zero for unlimited.
94
+ EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
95
+ if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) {
96
+ throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + '.');
97
+ }
98
+ this._maxListeners = n;
99
+ return this;
100
+ };
101
+
102
+ function _getMaxListeners(that) {
103
+ if (that._maxListeners === undefined)
104
+ return EventEmitter.defaultMaxListeners;
105
+ return that._maxListeners;
106
+ }
107
+
108
+ EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
109
+ return _getMaxListeners(this);
110
+ };
111
+
112
+ EventEmitter.prototype.emit = function emit(type) {
113
+ var args = [];
114
+ for (var i = 1; i < arguments.length; i++) args.push(arguments[i]);
115
+ var doError = (type === 'error');
116
+
117
+ var events = this._events;
118
+ if (events !== undefined)
119
+ doError = (doError && events.error === undefined);
120
+ else if (!doError)
121
+ return false;
122
+
123
+ // If there is no 'error' event listener then throw.
124
+ if (doError) {
125
+ var er;
126
+ if (args.length > 0)
127
+ er = args[0];
128
+ if (er instanceof Error) {
129
+ // Note: The comments on the `throw` lines are intentional, they show
130
+ // up in Node's output if this results in an unhandled exception.
131
+ throw er; // Unhandled 'error' event
132
+ }
133
+ // At least give some kind of context to the user
134
+ var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : ''));
135
+ err.context = er;
136
+ throw err; // Unhandled 'error' event
137
+ }
138
+
139
+ var handler = events[type];
140
+
141
+ if (handler === undefined)
142
+ return false;
143
+
144
+ if (typeof handler === 'function') {
145
+ ReflectApply(handler, this, args);
146
+ } else {
147
+ var len = handler.length;
148
+ var listeners = arrayClone(handler, len);
149
+ for (var i = 0; i < len; ++i)
150
+ ReflectApply(listeners[i], this, args);
151
+ }
152
+
153
+ return true;
154
+ };
155
+
156
+ function _addListener(target, type, listener, prepend) {
157
+ var m;
158
+ var events;
159
+ var existing;
160
+
161
+ checkListener(listener);
162
+
163
+ events = target._events;
164
+ if (events === undefined) {
165
+ events = target._events = Object.create(null);
166
+ target._eventsCount = 0;
167
+ } else {
168
+ // To avoid recursion in the case that type === "newListener"! Before
169
+ // adding it to the listeners, first emit "newListener".
170
+ if (events.newListener !== undefined) {
171
+ target.emit('newListener', type,
172
+ listener.listener ? listener.listener : listener);
173
+
174
+ // Re-assign `events` because a newListener handler could have caused the
175
+ // this._events to be assigned to a new object
176
+ events = target._events;
177
+ }
178
+ existing = events[type];
179
+ }
180
+
181
+ if (existing === undefined) {
182
+ // Optimize the case of one listener. Don't need the extra array object.
183
+ existing = events[type] = listener;
184
+ ++target._eventsCount;
185
+ } else {
186
+ if (typeof existing === 'function') {
187
+ // Adding the second element, need to change to array.
188
+ existing = events[type] =
189
+ prepend ? [listener, existing] : [existing, listener];
190
+ // If we've already got an array, just append.
191
+ } else if (prepend) {
192
+ existing.unshift(listener);
193
+ } else {
194
+ existing.push(listener);
195
+ }
196
+
197
+ // Check for listener leak
198
+ m = _getMaxListeners(target);
199
+ if (m > 0 && existing.length > m && !existing.warned) {
200
+ existing.warned = true;
201
+ // No error code for this since it is a Warning
202
+ // eslint-disable-next-line no-restricted-syntax
203
+ var w = new Error('Possible EventEmitter memory leak detected. ' +
204
+ existing.length + ' ' + String(type) + ' listeners ' +
205
+ 'added. Use emitter.setMaxListeners() to ' +
206
+ 'increase limit');
207
+ w.name = 'MaxListenersExceededWarning';
208
+ w.emitter = target;
209
+ w.type = type;
210
+ w.count = existing.length;
211
+ ProcessEmitWarning(w);
212
+ }
213
+ }
214
+
215
+ return target;
216
+ }
217
+
218
+ EventEmitter.prototype.addListener = function addListener(type, listener) {
219
+ return _addListener(this, type, listener, false);
220
+ };
221
+
222
+ EventEmitter.prototype.on = EventEmitter.prototype.addListener;
223
+
224
+ EventEmitter.prototype.prependListener =
225
+ function prependListener(type, listener) {
226
+ return _addListener(this, type, listener, true);
227
+ };
228
+
229
+ function onceWrapper() {
230
+ if (!this.fired) {
231
+ this.target.removeListener(this.type, this.wrapFn);
232
+ this.fired = true;
233
+ if (arguments.length === 0)
234
+ return this.listener.call(this.target);
235
+ return this.listener.apply(this.target, arguments);
236
+ }
237
+ }
238
+
239
+ function _onceWrap(target, type, listener) {
240
+ var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };
241
+ var wrapped = onceWrapper.bind(state);
242
+ wrapped.listener = listener;
243
+ state.wrapFn = wrapped;
244
+ return wrapped;
245
+ }
246
+
247
+ EventEmitter.prototype.once = function once(type, listener) {
248
+ checkListener(listener);
249
+ this.on(type, _onceWrap(this, type, listener));
250
+ return this;
251
+ };
252
+
253
+ EventEmitter.prototype.prependOnceListener =
254
+ function prependOnceListener(type, listener) {
255
+ checkListener(listener);
256
+ this.prependListener(type, _onceWrap(this, type, listener));
257
+ return this;
258
+ };
259
+
260
+ // Emits a 'removeListener' event if and only if the listener was removed.
261
+ EventEmitter.prototype.removeListener =
262
+ function removeListener(type, listener) {
263
+ var list, events, position, i, originalListener;
264
+
265
+ checkListener(listener);
266
+
267
+ events = this._events;
268
+ if (events === undefined)
269
+ return this;
270
+
271
+ list = events[type];
272
+ if (list === undefined)
273
+ return this;
274
+
275
+ if (list === listener || list.listener === listener) {
276
+ if (--this._eventsCount === 0)
277
+ this._events = Object.create(null);
278
+ else {
279
+ delete events[type];
280
+ if (events.removeListener)
281
+ this.emit('removeListener', type, list.listener || listener);
282
+ }
283
+ } else if (typeof list !== 'function') {
284
+ position = -1;
285
+
286
+ for (i = list.length - 1; i >= 0; i--) {
287
+ if (list[i] === listener || list[i].listener === listener) {
288
+ originalListener = list[i].listener;
289
+ position = i;
290
+ break;
291
+ }
292
+ }
293
+
294
+ if (position < 0)
295
+ return this;
296
+
297
+ if (position === 0)
298
+ list.shift();
299
+ else {
300
+ spliceOne(list, position);
301
+ }
302
+
303
+ if (list.length === 1)
304
+ events[type] = list[0];
305
+
306
+ if (events.removeListener !== undefined)
307
+ this.emit('removeListener', type, originalListener || listener);
308
+ }
309
+
310
+ return this;
311
+ };
312
+
313
+ EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
314
+
315
+ EventEmitter.prototype.removeAllListeners =
316
+ function removeAllListeners(type) {
317
+ var listeners, events, i;
318
+
319
+ events = this._events;
320
+ if (events === undefined)
321
+ return this;
322
+
323
+ // not listening for removeListener, no need to emit
324
+ if (events.removeListener === undefined) {
325
+ if (arguments.length === 0) {
326
+ this._events = Object.create(null);
327
+ this._eventsCount = 0;
328
+ } else if (events[type] !== undefined) {
329
+ if (--this._eventsCount === 0)
330
+ this._events = Object.create(null);
331
+ else
332
+ delete events[type];
333
+ }
334
+ return this;
335
+ }
336
+
337
+ // emit removeListener for all listeners on all events
338
+ if (arguments.length === 0) {
339
+ var keys = Object.keys(events);
340
+ var key;
341
+ for (i = 0; i < keys.length; ++i) {
342
+ key = keys[i];
343
+ if (key === 'removeListener') continue;
344
+ this.removeAllListeners(key);
345
+ }
346
+ this.removeAllListeners('removeListener');
347
+ this._events = Object.create(null);
348
+ this._eventsCount = 0;
349
+ return this;
350
+ }
351
+
352
+ listeners = events[type];
353
+
354
+ if (typeof listeners === 'function') {
355
+ this.removeListener(type, listeners);
356
+ } else if (listeners !== undefined) {
357
+ // LIFO order
358
+ for (i = listeners.length - 1; i >= 0; i--) {
359
+ this.removeListener(type, listeners[i]);
360
+ }
361
+ }
362
+
363
+ return this;
364
+ };
365
+
366
+ function _listeners(target, type, unwrap) {
367
+ var events = target._events;
368
+
369
+ if (events === undefined)
370
+ return [];
371
+
372
+ var evlistener = events[type];
373
+ if (evlistener === undefined)
374
+ return [];
375
+
376
+ if (typeof evlistener === 'function')
377
+ return unwrap ? [evlistener.listener || evlistener] : [evlistener];
378
+
379
+ return unwrap ?
380
+ unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
381
+ }
382
+
383
+ EventEmitter.prototype.listeners = function listeners(type) {
384
+ return _listeners(this, type, true);
385
+ };
386
+
387
+ EventEmitter.prototype.rawListeners = function rawListeners(type) {
388
+ return _listeners(this, type, false);
389
+ };
390
+
391
+ EventEmitter.listenerCount = function(emitter, type) {
392
+ if (typeof emitter.listenerCount === 'function') {
393
+ return emitter.listenerCount(type);
394
+ } else {
395
+ return listenerCount.call(emitter, type);
396
+ }
397
+ };
398
+
399
+ EventEmitter.prototype.listenerCount = listenerCount;
400
+ function listenerCount(type) {
401
+ var events = this._events;
402
+
403
+ if (events !== undefined) {
404
+ var evlistener = events[type];
405
+
406
+ if (typeof evlistener === 'function') {
407
+ return 1;
408
+ } else if (evlistener !== undefined) {
409
+ return evlistener.length;
410
+ }
411
+ }
412
+
413
+ return 0;
414
+ }
415
+
416
+ EventEmitter.prototype.eventNames = function eventNames() {
417
+ return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : [];
418
+ };
419
+
420
+ function arrayClone(arr, n) {
421
+ var copy = new Array(n);
422
+ for (var i = 0; i < n; ++i)
423
+ copy[i] = arr[i];
424
+ return copy;
425
+ }
426
+
427
+ function spliceOne(list, index) {
428
+ for (; index + 1 < list.length; index++)
429
+ list[index] = list[index + 1];
430
+ list.pop();
431
+ }
432
+
433
+ function unwrapListeners(arr) {
434
+ var ret = new Array(arr.length);
435
+ for (var i = 0; i < ret.length; ++i) {
436
+ ret[i] = arr[i].listener || arr[i];
437
+ }
438
+ return ret;
439
+ }
440
+
441
+ function once(emitter, name) {
442
+ return new Promise(function (resolve, reject) {
443
+ function errorListener(err) {
444
+ emitter.removeListener(name, resolver);
445
+ reject(err);
446
+ }
447
+
448
+ function resolver() {
449
+ if (typeof emitter.removeListener === 'function') {
450
+ emitter.removeListener('error', errorListener);
451
+ }
452
+ resolve([].slice.call(arguments));
453
+ }
454
+ eventTargetAgnosticAddListener(emitter, name, resolver, { once: true });
455
+ if (name !== 'error') {
456
+ addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true });
457
+ }
458
+ });
459
+ }
460
+
461
+ function addErrorHandlerIfEventEmitter(emitter, handler, flags) {
462
+ if (typeof emitter.on === 'function') {
463
+ eventTargetAgnosticAddListener(emitter, 'error', handler, flags);
464
+ }
465
+ }
466
+
467
+ function eventTargetAgnosticAddListener(emitter, name, listener, flags) {
468
+ if (typeof emitter.on === 'function') {
469
+ if (flags.once) {
470
+ emitter.once(name, listener);
471
+ } else {
472
+ emitter.on(name, listener);
473
+ }
474
+ } else if (typeof emitter.addEventListener === 'function') {
475
+ // EventTarget does not have `error` event semantics like Node
476
+ // EventEmitters, we do not listen for `error` events here.
477
+ emitter.addEventListener(name, function wrapListener(arg) {
478
+ // IE does not have builtin `{ once: true }` support so we
479
+ // have to do it manually.
480
+ if (flags.once) {
481
+ emitter.removeEventListener(name, wrapListener);
482
+ }
483
+ listener(arg);
484
+ });
485
+ } else {
486
+ throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof emitter);
487
+ }
488
+ }
489
+ return events.exports;
490
+ }
491
+
492
+ var eventsExports = requireEvents();
493
+ var EventEmitter = /*@__PURE__*/getDefaultExportFromCjs(eventsExports);
494
+
495
+ function getAllCallablePropertyNames(obj) {
496
+ if (!obj)
497
+ return [];
498
+ let props = [], tmpProps = [], index = 0, size = 0, tmpProp = '';
499
+ const bans = ["constructor", "__defineGetter__", "__defineSetter__",
500
+ "hasOwnProperty", "__lookupGetter__", "__lookupSetter__",
501
+ "isPrototypeOf", "propertyIsEnumerable", "toString",
502
+ "valueOf", "__proto__", "toLocaleString"];
503
+ do {
504
+ tmpProps = Object.getOwnPropertyNames(obj);
505
+ index = -1, size = tmpProps.length;
506
+ while (++index < size) {
507
+ tmpProp = tmpProps[index];
508
+ if (!props.includes(tmpProp) && !bans.includes(tmpProp)) {
509
+ props.push(tmpProp);
510
+ }
511
+ }
512
+ } while (obj = Object.getPrototypeOf(obj));
513
+ return props;
514
+ }
515
+ function genKVMethods(methods, kvMethods = new Map(), sourceKVMethods = new Map(), nameStack = []) {
516
+ let keys = getAllCallablePropertyNames(methods);
517
+ for (const key of keys) {
518
+ /**
519
+ * @type {Function}
520
+ */
521
+ let val = methods[key];
522
+ if ('function' === typeof val) {
523
+ const action = nameStack.concat(key).join('.');
524
+ // 原函数绑定
525
+ sourceKVMethods.set(action, val);
526
+ // 壳函数绑定
527
+ kvMethods.set(action, val.bind(methods));
528
+ }
529
+ else {
530
+ genKVMethods(val, kvMethods, sourceKVMethods, nameStack.concat(key));
531
+ }
532
+ }
533
+ return { kvMethods, sourceKVMethods };
534
+ }
535
+
536
+ const contexts = {};
537
+ function parseTraceIdByStack(stack) {
538
+ const [traceRow] = stack.split('/').filter(row => row.includes('OOX_TRACER.<computed>'));
539
+ if (traceRow) {
540
+ return traceRow.match(/(?<=as\s).*?(?=\s|\])/g)?.[0] || null;
541
+ }
542
+ else {
543
+ return null;
544
+ }
545
+ }
546
+ function enterWith(context) {
547
+ const traceId = context.traceId || '';
548
+ contexts[traceId] = context;
549
+ }
550
+ function exitWith(context) {
551
+ const traceId = context.traceId || '';
552
+ delete contexts[traceId];
553
+ }
554
+ function getContext$1() {
555
+ const traceId = parseTraceIdByStack(new Error().stack || '') || '';
556
+ return contexts[traceId] || null;
557
+ }
558
+
559
+ const eventHub = new eventsExports.EventEmitter();
560
+ /**
561
+ * sourceMethods => methods
562
+ */
563
+ let sourceMethods = {};
564
+ /**
565
+ * the kvMethods is all actions refs [has bind this]
566
+ */
567
+ const kvMethods = new Map();
568
+ const sourceKVMethods = new Map();
569
+ function setMethods(methods) {
570
+ sourceMethods = methods;
571
+ kvMethods.clear();
572
+ sourceKVMethods.clear();
573
+ genKVMethods(methods, kvMethods, sourceKVMethods);
574
+ }
575
+ function getMethods() {
576
+ return sourceMethods;
577
+ }
578
+ function on(event, listener) {
579
+ eventHub.on(event, listener);
580
+ }
581
+ function once(event, listener) {
582
+ eventHub.once(event, listener);
583
+ }
584
+ function off(event, listener) {
585
+ eventHub.off(event, listener);
586
+ }
587
+ function emit(event, ...args) {
588
+ return eventHub.emit(event, ...args);
589
+ }
590
+ /**
591
+ * Call an Function on RPC server
592
+ * @param action
593
+ * @param params
594
+ * @param context
595
+ * @returns
596
+ */
597
+ async function call(action, params = [], context) {
598
+ if (!Array.isArray(params))
599
+ params = [params];
600
+ const { traceId } = context;
601
+ emit('call:start', Date.now(), action, params, context);
602
+ const returns = {
603
+ traceId,
604
+ success: true
605
+ };
606
+ const OOX_TRACER = {};
607
+ OOX_TRACER[traceId] = async (action, [...params], context) => {
608
+ return await execute(action, [...params], context);
609
+ };
610
+ enterWith(context);
611
+ try {
612
+ const result = await OOX_TRACER[traceId](action, [...params], context);
613
+ returns.body = result;
614
+ emit('call:success', Date.now(), action, params, context, result);
615
+ }
616
+ catch (error) {
617
+ returns.success = false;
618
+ returns.error = {
619
+ message: error.message,
620
+ stack: error.stack
621
+ };
622
+ emit('call:fail', Date.now(), action, params, context, error);
623
+ }
624
+ finally {
625
+ exitWith(context);
626
+ return returns;
627
+ }
628
+ }
629
+ async function execute(action, params, context) {
630
+ const __proxy = '__proxy', _proxy = '_proxy';
631
+ if (__proxy === action || _proxy === action || action.endsWith(_proxy))
632
+ throw new Error('Invalid Action[' + action + ']');
633
+ const methods = kvMethods;
634
+ // 目标函数
635
+ const target = methods.get(action);
636
+ // 目标代理函数
637
+ const targetProxy = methods.get(action + _proxy);
638
+ // 即不存在目标也不存在目标代理时, 报错函数不存在
639
+ if (!target && !targetProxy)
640
+ throw new Error('Unknown Action [' + action + ']');
641
+ // ============================ PROXY BEGIN ============================
642
+ // 最顶层代理
643
+ const topProxy = methods.get(__proxy);
644
+ if (topProxy) {
645
+ const proxyReturns = await topProxy(action, params, context);
646
+ if (proxyReturns !== undefined)
647
+ return proxyReturns;
648
+ }
649
+ // 'x.y.z' => [ 'x', 'y', 'z' ]
650
+ const nameStack = action.split('.'), size = nameStack.length - 1;
651
+ let index = -1, proxyPrefix = '';
652
+ // 根代理遍历
653
+ while (++index < size) {
654
+ // x.
655
+ // x.y.
656
+ proxyPrefix += nameStack[index] + '.';
657
+ // x.__proxy
658
+ // x.y.__proxy
659
+ const rootProxy = methods.get(proxyPrefix + __proxy);
660
+ // x.__proxy ( 'y.z', ... )
661
+ // x.y.__proxy ( 'z', ... )
662
+ if (rootProxy) {
663
+ const proxyReturns = await rootProxy(nameStack.slice(index).join('.'), params, context);
664
+ if (proxyReturns !== undefined)
665
+ return proxyReturns;
666
+ }
667
+ }
668
+ // 同级代理
669
+ const layerProxy = methods.get(proxyPrefix + _proxy);
670
+ if (layerProxy) {
671
+ const proxyReturns = await layerProxy(nameStack[index], params, context);
672
+ if (proxyReturns !== undefined)
673
+ return proxyReturns;
674
+ }
675
+ if (targetProxy) {
676
+ const proxyReturns = await targetProxy(params, context);
677
+ if (proxyReturns !== undefined)
678
+ return proxyReturns;
679
+ }
680
+ // ============================= PROXY END =============================
681
+ // make sure target action execute after all proxies
682
+ if (target) {
683
+ return await target(...params);
684
+ }
685
+ }
686
+
687
+ class Config {
688
+ id = '';
689
+ name = 'DEFAULT_NAME';
690
+ }
691
+ const config = new Config();
692
+
693
+ class AppContext {
694
+ // 请求溯源ID
695
+ traceId = '';
696
+ }
697
+ class Context extends AppContext {
698
+ // 请求溯源IP
699
+ sourceIP = '';
700
+ // 请求者IP
701
+ ip = '';
702
+ // 请求者名称
703
+ caller = 'anonymous';
704
+ // 请求者ID (长连接专用)
705
+ callerId = '';
706
+ // 请求者连接把柄
707
+ connection;
708
+ constructor(context) {
709
+ super();
710
+ if (context) {
711
+ if ('toJSON' in context && typeof context.toJSON !== 'function') {
712
+ throw new Error('Context.toJSON must be a function');
713
+ }
714
+ Object.assign(this, context);
715
+ }
716
+ }
717
+ toJSON() {
718
+ const context = Object.assign({}, this);
719
+ delete context.connection;
720
+ return context;
721
+ }
722
+ }
723
+ let genTraceIdFunction = () => crypto.randomUUID();
724
+ function setGenTraceIdFunction(fn) {
725
+ genTraceIdFunction = fn;
726
+ }
727
+ /**
728
+ * 生成随机不重复id
729
+ */
730
+ function genTraceId() {
731
+ return genTraceIdFunction();
732
+ }
733
+ function genContext(context) {
734
+ const newContext = new Context(context);
735
+ if (!newContext.traceId)
736
+ newContext.traceId = genTraceId();
737
+ if (!newContext.sourceIP)
738
+ newContext.sourceIP = newContext.ip;
739
+ return newContext;
740
+ }
741
+ function getContext() {
742
+ return getContext$1() || genContext();
743
+ }
744
+
745
+ class KeepAliveConnectionError extends Error {
746
+ connection;
747
+ constructor(message, connection) {
748
+ super(message);
749
+ this.connection = connection;
750
+ }
751
+ }
752
+ class KeepAliveConnection extends EventEmitter {
753
+ // 是否为注册服务连接
754
+ isRegistry = false;
755
+ // 连接是否可用
756
+ #enabled = false;
757
+ data;
758
+ nativeConnection;
759
+ adapter;
760
+ constructor(adapter, nativeConnection, data) {
761
+ super();
762
+ this.adapter = adapter;
763
+ this.nativeConnection = nativeConnection;
764
+ this.data = Object.assign(data, {
765
+ adapter: adapter.name,
766
+ });
767
+ }
768
+ /**
769
+ * 设置连接是否可用,并自动触发enabled或disabled事件
770
+ * @param enabled 是否可用
771
+ */
772
+ set enabled(enabled) {
773
+ if (enabled !== this.#enabled) {
774
+ this.#enabled = enabled;
775
+ this.emit(enabled ? 'enabled' : 'disabled');
776
+ if (enabled) {
777
+ enabledKeepAliveConnections.add(this);
778
+ }
779
+ else {
780
+ enabledKeepAliveConnections.remove(this);
781
+ }
782
+ }
783
+ }
784
+ get enabled() {
785
+ return this.#enabled;
786
+ }
787
+ /**
788
+ * enable & mount connection
789
+ * @param params
790
+ * @returns
791
+ */
792
+ ready(params) {
793
+ // 连接已就绪,不允许重复就绪
794
+ if (this.enabled)
795
+ return;
796
+ const { id, name } = params;
797
+ keepAliveConnections.remove(this);
798
+ // 更新连接数据
799
+ this.data.id = id;
800
+ this.data.name = name;
801
+ keepAliveConnections.add(this);
802
+ this.enabled = true;
803
+ }
804
+ disconnect() {
805
+ this.enabled = false;
806
+ this.nativeConnection.disconnect();
807
+ }
808
+ }
809
+ class KeepAliveConnectionStore {
810
+ #map = new Map();
811
+ entries() {
812
+ return this.#map.entries();
813
+ }
814
+ getConnectionsOfService(name) {
815
+ return this.#map.get(name) || new Map();
816
+ }
817
+ has(name, id) {
818
+ const connections = this.#map.get(name);
819
+ if (!connections)
820
+ return false;
821
+ return connections.has(id);
822
+ }
823
+ get(name, id) {
824
+ const connections = this.#map.get(name);
825
+ if (!connections)
826
+ return null;
827
+ return connections.get(id) || null;
828
+ }
829
+ add(connection) {
830
+ const { name, id } = connection.data;
831
+ const connections = this.#map.get(name);
832
+ if (connections) {
833
+ connections.set(id, connection);
834
+ }
835
+ else {
836
+ this.#map.set(name, new Map([[id, connection]]));
837
+ }
838
+ }
839
+ remove(name, id) {
840
+ if (name instanceof KeepAliveConnection) {
841
+ id = name.data.id;
842
+ name = name.data.name;
843
+ }
844
+ const connections = this.#map.get(name);
845
+ if (connections && id !== undefined) {
846
+ connections.delete(id);
847
+ }
848
+ }
849
+ }
850
+ const keepAliveConnectionAdapters = new Map();
851
+ const keepAliveConnections = new KeepAliveConnectionStore();
852
+ const enabledKeepAliveConnections = new KeepAliveConnectionStore();
853
+ function addKeepAliveConnection(connection) {
854
+ if (keepAliveConnections.has(connection.data.name, connection.data.id)) {
855
+ connection.disconnect();
856
+ throw new KeepAliveConnectionError('Connection already exists', connection);
857
+ }
858
+ keepAliveConnections.add(connection);
859
+ }
860
+ function removeKeepAliveConnection(arg1, arg2) {
861
+ if (typeof arg1 === 'string') {
862
+ const connection = keepAliveConnections.get(arg1, arg2);
863
+ if (connection)
864
+ connection.disconnect();
865
+ keepAliveConnections.remove(arg1, arg2);
866
+ enabledKeepAliveConnections.remove(arg1, arg2);
867
+ }
868
+ else {
869
+ arg1.disconnect();
870
+ keepAliveConnections.remove(arg1);
871
+ enabledKeepAliveConnections.remove(arg1);
872
+ }
873
+ }
874
+ /**
875
+ * random connection select for default load balance policy
876
+ * @param name service name
877
+ * @returns selected connection
878
+ */
879
+ let loadBalancePolicy = (name) => {
880
+ const connections = enabledKeepAliveConnections.getConnectionsOfService(name);
881
+ if (!connections || !connections.size)
882
+ return null;
883
+ const arrayConnections = Array.from(connections.values());
884
+ const index = Math.floor(Math.random() * arrayConnections.length);
885
+ return arrayConnections[index];
886
+ };
887
+ function setLoadBalancePolicy(policy) {
888
+ loadBalancePolicy = policy;
889
+ }
890
+ async function rpc(arg1, action, params, context) {
891
+ if (!context || !context.traceId) {
892
+ context = getContext();
893
+ }
894
+ let connection = null;
895
+ if (arg1 instanceof KeepAliveConnection) {
896
+ connection = arg1;
897
+ }
898
+ else if ('string' === typeof arg1) {
899
+ connection = loadBalancePolicy(arg1);
900
+ }
901
+ else
902
+ throw new Error(`Unknown rpc arg1<${arg1}>`);
903
+ if (!connection)
904
+ throw new Error(`Connection<${arg1}> not found`);
905
+ return connection.adapter.rpc(connection, action, params, context);
906
+ }
907
+
908
+ class SampleKeepAliveConnectionAdapter {
909
+ OOXEvent = {
910
+ CONNECT: 'connect',
911
+ DISCONNECT: 'disconnect',
912
+ ERROR: 'error',
913
+ CALL: 'call',
914
+ READY: 'oox:ready',
915
+ ENABLED: 'oox:enabled',
916
+ DISABLED: 'oox:disabled',
917
+ REGISTRY_SYNC_CONNECTIONS: 'oox:registry:sync_connections',
918
+ REGISTRY_SUBSCRIBE: 'oox:registry:subscribe',
919
+ REGISTRY_NOTIFY: 'oox:registry:notify',
920
+ };
921
+ /**
922
+ * 通知连接列表
923
+ */
924
+ ['registry:notify'](connection, datas) {
925
+ connection.nativeConnection.emit(this.OOXEvent.REGISTRY_NOTIFY, datas);
926
+ }
927
+ /**
928
+ * 订阅连接列表
929
+ */
930
+ ['registry:subscribe'](connection, query) {
931
+ connection.nativeConnection.emit(this.OOXEvent.REGISTRY_SUBSCRIBE, query);
932
+ }
933
+ bindConnectionEvents(connection) {
934
+ const socket = connection.nativeConnection;
935
+ socket.on(this.OOXEvent.READY, (params) => {
936
+ connection.ready(params);
937
+ });
938
+ socket.on(this.OOXEvent.ENABLED, () => {
939
+ connection.enabled = true;
940
+ });
941
+ socket.on(this.OOXEvent.DISABLED, () => {
942
+ connection.enabled = false;
943
+ });
944
+ socket.on(this.OOXEvent.DISCONNECT, () => {
945
+ removeKeepAliveConnection(connection);
946
+ socket.removeAllListeners();
947
+ connection.emit('disconnect');
948
+ });
949
+ socket.on(this.OOXEvent.CONNECT, () => {
950
+ connection.emit('connect');
951
+ });
952
+ socket.on(this.OOXEvent.ERROR, (error) => {
953
+ removeKeepAliveConnection(connection);
954
+ socket.removeAllListeners();
955
+ connection.emit('error', new KeepAliveConnectionError(error.message, connection));
956
+ });
957
+ }
958
+ async open(identify) {
959
+ const connection = this.newConnection(identify);
960
+ addKeepAliveConnection(connection);
961
+ this.bindConnectionEvents(connection);
962
+ this.bindCall(connection);
963
+ await new Promise((resolve, reject) => {
964
+ connection.once('enabled', resolve);
965
+ connection.once('error', reject);
966
+ connection.once('disconnect', () => {
967
+ reject(new Error('disconnect'));
968
+ });
969
+ if (connection.nativeConnection.connect) {
970
+ connection.nativeConnection.connect();
971
+ }
972
+ });
973
+ return connection;
974
+ }
975
+ async close(connection) {
976
+ connection.nativeConnection.disconnect();
977
+ return Promise.resolve();
978
+ }
979
+ /**
980
+ * 发送事件
981
+ * @param socket
982
+ * @param event
983
+ * @param params
984
+ */
985
+ async emit(socket, event, params) {
986
+ if (!socket.connected)
987
+ throw new Error('Socket not connected');
988
+ return await new Promise((resolve, reject) => {
989
+ const onError = (reason) => {
990
+ const message = 'string' === typeof reason ? reason : reason instanceof Error ? reason.message : 'connect error';
991
+ reject(new Error(message));
992
+ };
993
+ // RPC 执行时中断连接
994
+ socket.once(this.OOXEvent.DISCONNECT, onError);
995
+ socket.emit(event, ...params, (returns) => {
996
+ socket.off(this.OOXEvent.DISCONNECT, onError);
997
+ resolve(returns);
998
+ });
999
+ });
1000
+ }
1001
+ /**
1002
+ * RPC
1003
+ */
1004
+ async rpc(connection, action, params, context) {
1005
+ if (!context)
1006
+ context = getContext();
1007
+ const miniContext = {
1008
+ sourceIP: context.sourceIP,
1009
+ traceId: context.traceId,
1010
+ };
1011
+ const { success, error, body } = await this.emit(connection.nativeConnection, this.OOXEvent.CALL, [action, params, miniContext]);
1012
+ if (success)
1013
+ return body;
1014
+ else if (error)
1015
+ throw new Error(error.message);
1016
+ else
1017
+ throw new Error('[RPC] Unknown Error');
1018
+ }
1019
+ /**
1020
+ * 绑定 call 事件
1021
+ * @param connection
1022
+ */
1023
+ bindCall(connection) {
1024
+ const { id, name, ip } = connection.data;
1025
+ connection.nativeConnection.on(this.OOXEvent.CALL, async (action, params, context, callback) => {
1026
+ const validContext = new Context({
1027
+ ...context,
1028
+ ip: ip,
1029
+ caller: name,
1030
+ callerId: id,
1031
+ connection
1032
+ });
1033
+ this.call(action, params, validContext, callback);
1034
+ });
1035
+ }
1036
+ async call(action, params, context, callback) {
1037
+ const returns = await call(action, params, context);
1038
+ 'function' === typeof callback && callback(returns);
1039
+ return returns;
1040
+ }
1041
+ }
1042
+
1043
+ function info(...content) {
1044
+ const context = getContext$1() || null;
1045
+ emit('log', Date.now(), context, 'info', content);
1046
+ }
1047
+ function warn(...content) {
1048
+ const context = getContext$1() || null;
1049
+ emit('log', Date.now(), context, 'warn', content);
1050
+ }
1051
+ function error(...content) {
1052
+ const context = getContext$1() || null;
1053
+ emit('log', Date.now(), context, 'error', content);
1054
+ }
1055
+ function tag(name) {
1056
+ const context = getContext$1() || null;
1057
+ emit('log', Date.now(), context, 'tag', name);
1058
+ }
1059
+ function trace(name) {
1060
+ const context = getContext$1() || null;
1061
+ const trace = { stack: '' };
1062
+ Error.captureStackTrace(trace);
1063
+ const stack = trace.stack
1064
+ .replace(/.*\n.*logger.js.*\n/, name || 'Untitle\n');
1065
+ emit('log', Date.now(), context, 'trace', stack);
1066
+ }
1067
+
1068
+ var logger = /*#__PURE__*/Object.freeze({
1069
+ __proto__: null,
1070
+ error: error,
1071
+ info: info,
1072
+ tag: tag,
1073
+ trace: trace,
1074
+ warn: warn
1075
+ });
1076
+
1077
+ /**
1078
+ * 为了不重复创建Proxy,这个对象用于保存各个RPC服务的各个属性Proxy
1079
+ */
1080
+ const rpcServiceAttrMap = Object.create(null);
1081
+ function proxy(name, action = '') {
1082
+ return new Proxy(function () { }, {
1083
+ get(target, key) {
1084
+ if (typeof key !== 'string')
1085
+ return undefined;
1086
+ const attrKey = action ? action + '.' + key : key;
1087
+ const attrKeyPath = name + '.' + attrKey;
1088
+ if (attrKeyPath in rpcServiceAttrMap) {
1089
+ // 不重复创建Proxy
1090
+ return rpcServiceAttrMap[attrKeyPath];
1091
+ }
1092
+ const attrProxy = proxy(name, attrKey);
1093
+ rpcServiceAttrMap[attrKeyPath] = attrProxy;
1094
+ return attrProxy;
1095
+ },
1096
+ has(target, key) {
1097
+ if (typeof key !== 'string')
1098
+ return false;
1099
+ return true;
1100
+ },
1101
+ apply(target, thisArg, args) {
1102
+ return rpc(name, action, args);
1103
+ }
1104
+ });
1105
+ }
1106
+
1107
+ exports.AppContext = AppContext;
1108
+ exports.Config = Config;
1109
+ exports.Context = Context;
1110
+ exports.KeepAliveConnection = KeepAliveConnection;
1111
+ exports.KeepAliveConnectionError = KeepAliveConnectionError;
1112
+ exports.KeepAliveConnectionStore = KeepAliveConnectionStore;
1113
+ exports.SampleKeepAliveConnectionAdapter = SampleKeepAliveConnectionAdapter;
1114
+ exports.addKeepAliveConnection = addKeepAliveConnection;
1115
+ exports.call = call;
1116
+ exports.config = config;
1117
+ exports.emit = emit;
1118
+ exports.enabledKeepAliveConnections = enabledKeepAliveConnections;
1119
+ exports.eventHub = eventHub;
1120
+ exports.execute = execute;
1121
+ exports.genContext = genContext;
1122
+ exports.genTraceId = genTraceId;
1123
+ exports.getContext = getContext;
1124
+ exports.getMethods = getMethods;
1125
+ exports.keepAliveConnectionAdapters = keepAliveConnectionAdapters;
1126
+ exports.keepAliveConnections = keepAliveConnections;
1127
+ exports.kvMethods = kvMethods;
1128
+ exports.logger = logger;
1129
+ exports.off = off;
1130
+ exports.on = on;
1131
+ exports.once = once;
1132
+ exports.proxy = proxy;
1133
+ exports.removeKeepAliveConnection = removeKeepAliveConnection;
1134
+ exports.rpc = rpc;
1135
+ exports.setGenTraceIdFunction = setGenTraceIdFunction;
1136
+ exports.setLoadBalancePolicy = setLoadBalancePolicy;
1137
+ exports.setMethods = setMethods;
1138
+ exports.sourceKVMethods = sourceKVMethods;
1139
+
1140
+ return exports;
1111
1141
 
1112
1142
  })({});
1113
1143
  //# sourceMappingURL=browser.js.map