UNPKG

925 kBJavaScriptView Raw
1(function (global, factory) {
2 typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
3 typeof define === 'function' && define.amd ? define('leancloud-realtime', ['exports'], factory) :
4 (global = global || self, factory(global.AV = global.AV || {}));
5}(this, (function (exports) { 'use strict';
6
7 var define = undefined;
8 var require = require || function(id) {throw new Error('Unexpected required ' + id)};
9
10
11
12 var process = (typeof window !== 'undefined' && window.process) || {};
13 process.env = process.env || {};
14
15 var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
16
17 function unwrapExports (x) {
18 return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
19 }
20
21 function createCommonjsModule(fn, basedir, module) {
22 return module = {
23 path: basedir,
24 exports: {},
25 require: function (path, base) {
26 return commonjsRequire(path, (base === undefined || base === null) ? module.path : base);
27 }
28 }, fn(module, module.exports), module.exports;
29 }
30
31 function getCjsExportFromNamespace (n) {
32 return n && n['default'] || n;
33 }
34
35 function commonjsRequire () {
36 throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs');
37 }
38
39 var _typeof_1 = createCommonjsModule(function (module) {
40 function _typeof(obj) {
41 "@babel/helpers - typeof";
42
43 return (module.exports = _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) {
44 return typeof obj;
45 } : function (obj) {
46 return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
47 }, module.exports.__esModule = true, module.exports["default"] = module.exports), _typeof(obj);
48 }
49 module.exports = _typeof, module.exports.__esModule = true, module.exports["default"] = module.exports;
50 });
51
52 var _typeof = unwrapExports(_typeof_1);
53
54 var lib = createCommonjsModule(function (module, exports) {
55
56 Object.defineProperty(exports, '__esModule', {
57 value: true
58 });
59
60 /*! *****************************************************************************
61 Copyright (c) Microsoft Corporation.
62
63 Permission to use, copy, modify, and/or distribute this software for any
64 purpose with or without fee is hereby granted.
65
66 THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
67 REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
68 AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
69 INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
70 LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
71 OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
72 PERFORMANCE OF THIS SOFTWARE.
73 ***************************************************************************** */
74 /* global Reflect, Promise */
75
76 var _extendStatics = function extendStatics(d, b) {
77 _extendStatics = Object.setPrototypeOf || {
78 __proto__: []
79 } instanceof Array && function (d, b) {
80 d.__proto__ = b;
81 } || function (d, b) {
82 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
83 };
84 return _extendStatics(d, b);
85 };
86 function __extends(d, b) {
87 _extendStatics(d, b);
88 function __() {
89 this.constructor = d;
90 }
91 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
92 }
93 var _assign = function __assign() {
94 _assign = Object.assign || function __assign(t) {
95 for (var s, i = 1, n = arguments.length; i < n; i++) {
96 s = arguments[i];
97 for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
98 }
99 return t;
100 };
101 return _assign.apply(this, arguments);
102 };
103 function __rest(s, e) {
104 var t = {};
105 for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];
106 if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
107 if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]];
108 }
109 return t;
110 }
111 function __awaiter(thisArg, _arguments, P, generator) {
112 function adopt(value) {
113 return value instanceof P ? value : new P(function (resolve) {
114 resolve(value);
115 });
116 }
117 return new (P || (P = Promise))(function (resolve, reject) {
118 function fulfilled(value) {
119 try {
120 step(generator.next(value));
121 } catch (e) {
122 reject(e);
123 }
124 }
125 function rejected(value) {
126 try {
127 step(generator["throw"](value));
128 } catch (e) {
129 reject(e);
130 }
131 }
132 function step(result) {
133 result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
134 }
135 step((generator = generator.apply(thisArg, _arguments || [])).next());
136 });
137 }
138 function __generator(thisArg, body) {
139 var _ = {
140 label: 0,
141 sent: function sent() {
142 if (t[0] & 1) throw t[1];
143 return t[1];
144 },
145 trys: [],
146 ops: []
147 },
148 f,
149 y,
150 t,
151 g;
152 return g = {
153 next: verb(0),
154 "throw": verb(1),
155 "return": verb(2)
156 }, typeof Symbol === "function" && (g[Symbol.iterator] = function () {
157 return this;
158 }), g;
159 function verb(n) {
160 return function (v) {
161 return step([n, v]);
162 };
163 }
164 function step(op) {
165 if (f) throw new TypeError("Generator is already executing.");
166 while (_) try {
167 if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
168 if (y = 0, t) op = [op[0] & 2, t.value];
169 switch (op[0]) {
170 case 0:
171 case 1:
172 t = op;
173 break;
174 case 4:
175 _.label++;
176 return {
177 value: op[1],
178 done: false
179 };
180 case 5:
181 _.label++;
182 y = op[1];
183 op = [0];
184 continue;
185 case 7:
186 op = _.ops.pop();
187 _.trys.pop();
188 continue;
189 default:
190 if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
191 _ = 0;
192 continue;
193 }
194 if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
195 _.label = op[1];
196 break;
197 }
198 if (op[0] === 6 && _.label < t[1]) {
199 _.label = t[1];
200 t = op;
201 break;
202 }
203 if (t && _.label < t[2]) {
204 _.label = t[2];
205 _.ops.push(op);
206 break;
207 }
208 if (t[2]) _.ops.pop();
209 _.trys.pop();
210 continue;
211 }
212 op = body.call(thisArg, _);
213 } catch (e) {
214 op = [6, e];
215 y = 0;
216 } finally {
217 f = t = 0;
218 }
219 if (op[0] & 5) throw op[1];
220 return {
221 value: op[0] ? op[1] : void 0,
222 done: true
223 };
224 }
225 }
226 var PROVIDER = "lc_weapp";
227 var PLATFORM = "weixin";
228 function getLoginCode() {
229 return new Promise(function (resolve, reject) {
230 wx.login({
231 success: function success(res) {
232 return res.code ? resolve(res.code) : reject(new Error(res.errMsg));
233 },
234 fail: function fail(_a) {
235 var errMsg = _a.errMsg;
236 return reject(new Error(errMsg));
237 }
238 });
239 });
240 }
241 var getAuthInfo = function getAuthInfo(_a) {
242 var _b = _a === void 0 ? {} : _a,
243 _c = _b.platform,
244 platform = _c === void 0 ? PLATFORM : _c,
245 _d = _b.preferUnionId,
246 preferUnionId = _d === void 0 ? false : _d,
247 _e = _b.asMainAccount,
248 asMainAccount = _e === void 0 ? false : _e;
249 return __awaiter(this, void 0, void 0, function () {
250 var code, authData;
251 return __generator(this, function (_f) {
252 switch (_f.label) {
253 case 0:
254 return [4 /*yield*/, getLoginCode()];
255 case 1:
256 code = _f.sent();
257 authData = {
258 code: code
259 };
260 if (preferUnionId) {
261 authData.platform = platform;
262 authData.main_account = asMainAccount;
263 }
264 return [2 /*return*/, {
265 authData: authData,
266 platform: platform,
267 provider: PROVIDER
268 }];
269 }
270 });
271 });
272 };
273 var storage = {
274 getItem: function getItem(key) {
275 return wx.getStorageSync(key);
276 },
277 setItem: function setItem(key, value) {
278 return wx.setStorageSync(key, value);
279 },
280 removeItem: function removeItem(key) {
281 return wx.removeStorageSync(key);
282 },
283 clear: function clear() {
284 return wx.clearStorageSync();
285 }
286 };
287 var request = function request(url, _a) {
288 var _b = _a === void 0 ? {} : _a,
289 method = _b.method,
290 data = _b.data,
291 headers = _b.headers;
292 return new Promise(function (resolve, reject) {
293 return wx.request({
294 url: url,
295 method: method,
296 data: data,
297 header: headers,
298 responseType: "text",
299 success: function success(response) {
300 var status = response.statusCode,
301 data = response.data,
302 rest = __rest(response, ["statusCode", "data"]);
303 resolve(_assign(_assign({}, rest), {
304 data: typeof data === "string" ? JSON.parse(data) : data,
305 status: status,
306 ok: !(status >= 400)
307 }));
308 },
309 fail: function fail(response) {
310 reject(new Error(response.errMsg));
311 }
312 });
313 });
314 };
315 var upload = function upload(url, file, _a) {
316 var _b = _a === void 0 ? {} : _a,
317 headers = _b.headers,
318 data = _b.data,
319 onprogress = _b.onprogress;
320 if (!(file && file.data && file.data.uri)) {
321 return Promise.reject(new TypeError("File data must be an object like { uri: localPath }."));
322 }
323 return new Promise(function (resolve, reject) {
324 var _a;
325 var task = wx.uploadFile({
326 url: url,
327 header: headers,
328 filePath: file.data.uri,
329 name: file.field,
330 formData: data,
331 success: function success(response) {
332 var status = response.statusCode,
333 data = response.data,
334 rest = __rest(response, ["statusCode", "data"]);
335 resolve(_assign(_assign({}, rest), {
336 data: typeof data === "string" ? JSON.parse(data) : data,
337 status: status,
338 ok: !(status >= 400)
339 }));
340 },
341 fail: function fail(response) {
342 reject(new Error(response.errMsg));
343 }
344 });
345 (_a = task === null || task === void 0 ? void 0 : task.onProgressUpdate) === null || _a === void 0 ? void 0 : _a.call(task, function (_a) {
346 var progress = _a.progress,
347 totalBytesSent = _a.totalBytesSent,
348 totalBytesExpectedToSend = _a.totalBytesExpectedToSend;
349 return onprogress === null || onprogress === void 0 ? void 0 : onprogress({
350 percent: progress,
351 loaded: totalBytesSent,
352 total: totalBytesExpectedToSend
353 });
354 });
355 });
356 };
357
358 /**
359 * @author Toru Nagashima <https://github.com/mysticatea>
360 * @copyright 2015 Toru Nagashima. All rights reserved.
361 * See LICENSE file in root directory for full license.
362 */
363 /**
364 * @typedef {object} PrivateData
365 * @property {EventTarget} eventTarget The event target.
366 * @property {{type:string}} event The original event object.
367 * @property {number} eventPhase The current event phase.
368 * @property {EventTarget|null} currentTarget The current event target.
369 * @property {boolean} canceled The flag to prevent default.
370 * @property {boolean} stopped The flag to stop propagation.
371 * @property {boolean} immediateStopped The flag to stop propagation immediately.
372 * @property {Function|null} passiveListener The listener if the current listener is passive. Otherwise this is null.
373 * @property {number} timeStamp The unix time.
374 * @private
375 */
376
377 /**
378 * Private data for event wrappers.
379 * @type {WeakMap<Event, PrivateData>}
380 * @private
381 */
382 var privateData = new WeakMap();
383
384 /**
385 * Cache for wrapper classes.
386 * @type {WeakMap<Object, Function>}
387 * @private
388 */
389 var wrappers = new WeakMap();
390
391 /**
392 * Get private data.
393 * @param {Event} event The event object to get private data.
394 * @returns {PrivateData} The private data of the event.
395 * @private
396 */
397 function pd(event) {
398 var retv = privateData.get(event);
399 console.assert(retv != null, "'this' is expected an Event object, but got", event);
400 return retv;
401 }
402
403 /**
404 * https://dom.spec.whatwg.org/#set-the-canceled-flag
405 * @param data {PrivateData} private data.
406 */
407 function setCancelFlag(data) {
408 if (data.passiveListener != null) {
409 if (typeof console !== "undefined" && typeof console.error === "function") {
410 console.error("Unable to preventDefault inside passive event listener invocation.", data.passiveListener);
411 }
412 return;
413 }
414 if (!data.event.cancelable) {
415 return;
416 }
417 data.canceled = true;
418 if (typeof data.event.preventDefault === "function") {
419 data.event.preventDefault();
420 }
421 }
422
423 /**
424 * @see https://dom.spec.whatwg.org/#interface-event
425 * @private
426 */
427 /**
428 * The event wrapper.
429 * @constructor
430 * @param {EventTarget} eventTarget The event target of this dispatching.
431 * @param {Event|{type:string}} event The original event to wrap.
432 */
433 function Event(eventTarget, event) {
434 privateData.set(this, {
435 eventTarget: eventTarget,
436 event: event,
437 eventPhase: 2,
438 currentTarget: eventTarget,
439 canceled: false,
440 stopped: false,
441 immediateStopped: false,
442 passiveListener: null,
443 timeStamp: event.timeStamp || Date.now()
444 });
445
446 // https://heycam.github.io/webidl/#Unforgeable
447 Object.defineProperty(this, "isTrusted", {
448 value: false,
449 enumerable: true
450 });
451
452 // Define accessors
453 var keys = Object.keys(event);
454 for (var i = 0; i < keys.length; ++i) {
455 var key = keys[i];
456 if (!(key in this)) {
457 Object.defineProperty(this, key, defineRedirectDescriptor(key));
458 }
459 }
460 }
461
462 // Should be enumerable, but class methods are not enumerable.
463 Event.prototype = {
464 /**
465 * The type of this event.
466 * @type {string}
467 */
468 get type() {
469 return pd(this).event.type;
470 },
471 /**
472 * The target of this event.
473 * @type {EventTarget}
474 */
475 get target() {
476 return pd(this).eventTarget;
477 },
478 /**
479 * The target of this event.
480 * @type {EventTarget}
481 */
482 get currentTarget() {
483 return pd(this).currentTarget;
484 },
485 /**
486 * @returns {EventTarget[]} The composed path of this event.
487 */
488 composedPath: function composedPath() {
489 var currentTarget = pd(this).currentTarget;
490 if (currentTarget == null) {
491 return [];
492 }
493 return [currentTarget];
494 },
495 /**
496 * Constant of NONE.
497 * @type {number}
498 */
499 get NONE() {
500 return 0;
501 },
502 /**
503 * Constant of CAPTURING_PHASE.
504 * @type {number}
505 */
506 get CAPTURING_PHASE() {
507 return 1;
508 },
509 /**
510 * Constant of AT_TARGET.
511 * @type {number}
512 */
513 get AT_TARGET() {
514 return 2;
515 },
516 /**
517 * Constant of BUBBLING_PHASE.
518 * @type {number}
519 */
520 get BUBBLING_PHASE() {
521 return 3;
522 },
523 /**
524 * The target of this event.
525 * @type {number}
526 */
527 get eventPhase() {
528 return pd(this).eventPhase;
529 },
530 /**
531 * Stop event bubbling.
532 * @returns {void}
533 */
534 stopPropagation: function stopPropagation() {
535 var data = pd(this);
536 data.stopped = true;
537 if (typeof data.event.stopPropagation === "function") {
538 data.event.stopPropagation();
539 }
540 },
541 /**
542 * Stop event bubbling.
543 * @returns {void}
544 */
545 stopImmediatePropagation: function stopImmediatePropagation() {
546 var data = pd(this);
547 data.stopped = true;
548 data.immediateStopped = true;
549 if (typeof data.event.stopImmediatePropagation === "function") {
550 data.event.stopImmediatePropagation();
551 }
552 },
553 /**
554 * The flag to be bubbling.
555 * @type {boolean}
556 */
557 get bubbles() {
558 return Boolean(pd(this).event.bubbles);
559 },
560 /**
561 * The flag to be cancelable.
562 * @type {boolean}
563 */
564 get cancelable() {
565 return Boolean(pd(this).event.cancelable);
566 },
567 /**
568 * Cancel this event.
569 * @returns {void}
570 */
571 preventDefault: function preventDefault() {
572 setCancelFlag(pd(this));
573 },
574 /**
575 * The flag to indicate cancellation state.
576 * @type {boolean}
577 */
578 get defaultPrevented() {
579 return pd(this).canceled;
580 },
581 /**
582 * The flag to be composed.
583 * @type {boolean}
584 */
585 get composed() {
586 return Boolean(pd(this).event.composed);
587 },
588 /**
589 * The unix time of this event.
590 * @type {number}
591 */
592 get timeStamp() {
593 return pd(this).timeStamp;
594 },
595 /**
596 * The target of this event.
597 * @type {EventTarget}
598 * @deprecated
599 */
600 get srcElement() {
601 return pd(this).eventTarget;
602 },
603 /**
604 * The flag to stop event bubbling.
605 * @type {boolean}
606 * @deprecated
607 */
608 get cancelBubble() {
609 return pd(this).stopped;
610 },
611 set cancelBubble(value) {
612 if (!value) {
613 return;
614 }
615 var data = pd(this);
616 data.stopped = true;
617 if (typeof data.event.cancelBubble === "boolean") {
618 data.event.cancelBubble = true;
619 }
620 },
621 /**
622 * The flag to indicate cancellation state.
623 * @type {boolean}
624 * @deprecated
625 */
626 get returnValue() {
627 return !pd(this).canceled;
628 },
629 set returnValue(value) {
630 if (!value) {
631 setCancelFlag(pd(this));
632 }
633 },
634 /**
635 * Initialize this event object. But do nothing under event dispatching.
636 * @param {string} type The event type.
637 * @param {boolean} [bubbles=false] The flag to be possible to bubble up.
638 * @param {boolean} [cancelable=false] The flag to be possible to cancel.
639 * @deprecated
640 */
641 initEvent: function initEvent() {
642 // Do nothing.
643 }
644 };
645
646 // `constructor` is not enumerable.
647 Object.defineProperty(Event.prototype, "constructor", {
648 value: Event,
649 configurable: true,
650 writable: true
651 });
652
653 // Ensure `event instanceof window.Event` is `true`.
654 if (typeof window !== "undefined" && typeof window.Event !== "undefined") {
655 Object.setPrototypeOf(Event.prototype, window.Event.prototype);
656
657 // Make association for wrappers.
658 wrappers.set(window.Event.prototype, Event);
659 }
660
661 /**
662 * Get the property descriptor to redirect a given property.
663 * @param {string} key Property name to define property descriptor.
664 * @returns {PropertyDescriptor} The property descriptor to redirect the property.
665 * @private
666 */
667 function defineRedirectDescriptor(key) {
668 return {
669 get: function get() {
670 return pd(this).event[key];
671 },
672 set: function set(value) {
673 pd(this).event[key] = value;
674 },
675 configurable: true,
676 enumerable: true
677 };
678 }
679
680 /**
681 * Get the property descriptor to call a given method property.
682 * @param {string} key Property name to define property descriptor.
683 * @returns {PropertyDescriptor} The property descriptor to call the method property.
684 * @private
685 */
686 function defineCallDescriptor(key) {
687 return {
688 value: function value() {
689 var event = pd(this).event;
690 return event[key].apply(event, arguments);
691 },
692 configurable: true,
693 enumerable: true
694 };
695 }
696
697 /**
698 * Define new wrapper class.
699 * @param {Function} BaseEvent The base wrapper class.
700 * @param {Object} proto The prototype of the original event.
701 * @returns {Function} The defined wrapper class.
702 * @private
703 */
704 function defineWrapper(BaseEvent, proto) {
705 var keys = Object.keys(proto);
706 if (keys.length === 0) {
707 return BaseEvent;
708 }
709
710 /** CustomEvent */
711 function CustomEvent(eventTarget, event) {
712 BaseEvent.call(this, eventTarget, event);
713 }
714 CustomEvent.prototype = Object.create(BaseEvent.prototype, {
715 constructor: {
716 value: CustomEvent,
717 configurable: true,
718 writable: true
719 }
720 });
721
722 // Define accessors.
723 for (var i = 0; i < keys.length; ++i) {
724 var key = keys[i];
725 if (!(key in BaseEvent.prototype)) {
726 var descriptor = Object.getOwnPropertyDescriptor(proto, key);
727 var isFunc = typeof descriptor.value === "function";
728 Object.defineProperty(CustomEvent.prototype, key, isFunc ? defineCallDescriptor(key) : defineRedirectDescriptor(key));
729 }
730 }
731 return CustomEvent;
732 }
733
734 /**
735 * Get the wrapper class of a given prototype.
736 * @param {Object} proto The prototype of the original event to get its wrapper.
737 * @returns {Function} The wrapper class.
738 * @private
739 */
740 function getWrapper(proto) {
741 if (proto == null || proto === Object.prototype) {
742 return Event;
743 }
744 var wrapper = wrappers.get(proto);
745 if (wrapper == null) {
746 wrapper = defineWrapper(getWrapper(Object.getPrototypeOf(proto)), proto);
747 wrappers.set(proto, wrapper);
748 }
749 return wrapper;
750 }
751
752 /**
753 * Wrap a given event to management a dispatching.
754 * @param {EventTarget} eventTarget The event target of this dispatching.
755 * @param {Object} event The event to wrap.
756 * @returns {Event} The wrapper instance.
757 * @private
758 */
759 function wrapEvent(eventTarget, event) {
760 var Wrapper = getWrapper(Object.getPrototypeOf(event));
761 return new Wrapper(eventTarget, event);
762 }
763
764 /**
765 * Get the immediateStopped flag of a given event.
766 * @param {Event} event The event to get.
767 * @returns {boolean} The flag to stop propagation immediately.
768 * @private
769 */
770 function isStopped(event) {
771 return pd(event).immediateStopped;
772 }
773
774 /**
775 * Set the current event phase of a given event.
776 * @param {Event} event The event to set current target.
777 * @param {number} eventPhase New event phase.
778 * @returns {void}
779 * @private
780 */
781 function setEventPhase(event, eventPhase) {
782 pd(event).eventPhase = eventPhase;
783 }
784
785 /**
786 * Set the current target of a given event.
787 * @param {Event} event The event to set current target.
788 * @param {EventTarget|null} currentTarget New current target.
789 * @returns {void}
790 * @private
791 */
792 function setCurrentTarget(event, currentTarget) {
793 pd(event).currentTarget = currentTarget;
794 }
795
796 /**
797 * Set a passive listener of a given event.
798 * @param {Event} event The event to set current target.
799 * @param {Function|null} passiveListener New passive listener.
800 * @returns {void}
801 * @private
802 */
803 function setPassiveListener(event, passiveListener) {
804 pd(event).passiveListener = passiveListener;
805 }
806
807 /**
808 * @typedef {object} ListenerNode
809 * @property {Function} listener
810 * @property {1|2|3} listenerType
811 * @property {boolean} passive
812 * @property {boolean} once
813 * @property {ListenerNode|null} next
814 * @private
815 */
816
817 /**
818 * @type {WeakMap<object, Map<string, ListenerNode>>}
819 * @private
820 */
821 var listenersMap = new WeakMap();
822
823 // Listener types
824 var CAPTURE = 1;
825 var BUBBLE = 2;
826 var ATTRIBUTE = 3;
827
828 /**
829 * Check whether a given value is an object or not.
830 * @param {any} x The value to check.
831 * @returns {boolean} `true` if the value is an object.
832 */
833 function isObject(x) {
834 return x !== null && _typeof(x) === "object"; //eslint-disable-line no-restricted-syntax
835 }
836
837 /**
838 * Get listeners.
839 * @param {EventTarget} eventTarget The event target to get.
840 * @returns {Map<string, ListenerNode>} The listeners.
841 * @private
842 */
843 function getListeners(eventTarget) {
844 var listeners = listenersMap.get(eventTarget);
845 if (listeners == null) {
846 throw new TypeError("'this' is expected an EventTarget object, but got another value.");
847 }
848 return listeners;
849 }
850
851 /**
852 * Get the property descriptor for the event attribute of a given event.
853 * @param {string} eventName The event name to get property descriptor.
854 * @returns {PropertyDescriptor} The property descriptor.
855 * @private
856 */
857 function defineEventAttributeDescriptor(eventName) {
858 return {
859 get: function get() {
860 var listeners = getListeners(this);
861 var node = listeners.get(eventName);
862 while (node != null) {
863 if (node.listenerType === ATTRIBUTE) {
864 return node.listener;
865 }
866 node = node.next;
867 }
868 return null;
869 },
870 set: function set(listener) {
871 if (typeof listener !== "function" && !isObject(listener)) {
872 listener = null; // eslint-disable-line no-param-reassign
873 }
874
875 var listeners = getListeners(this);
876
877 // Traverse to the tail while removing old value.
878 var prev = null;
879 var node = listeners.get(eventName);
880 while (node != null) {
881 if (node.listenerType === ATTRIBUTE) {
882 // Remove old value.
883 if (prev !== null) {
884 prev.next = node.next;
885 } else if (node.next !== null) {
886 listeners.set(eventName, node.next);
887 } else {
888 listeners["delete"](eventName);
889 }
890 } else {
891 prev = node;
892 }
893 node = node.next;
894 }
895
896 // Add new value.
897 if (listener !== null) {
898 var newNode = {
899 listener: listener,
900 listenerType: ATTRIBUTE,
901 passive: false,
902 once: false,
903 next: null
904 };
905 if (prev === null) {
906 listeners.set(eventName, newNode);
907 } else {
908 prev.next = newNode;
909 }
910 }
911 },
912 configurable: true,
913 enumerable: true
914 };
915 }
916
917 /**
918 * Define an event attribute (e.g. `eventTarget.onclick`).
919 * @param {Object} eventTargetPrototype The event target prototype to define an event attrbite.
920 * @param {string} eventName The event name to define.
921 * @returns {void}
922 */
923 function defineEventAttribute(eventTargetPrototype, eventName) {
924 Object.defineProperty(eventTargetPrototype, "on".concat(eventName), defineEventAttributeDescriptor(eventName));
925 }
926
927 /**
928 * Define a custom EventTarget with event attributes.
929 * @param {string[]} eventNames Event names for event attributes.
930 * @returns {EventTarget} The custom EventTarget.
931 * @private
932 */
933 function defineCustomEventTarget(eventNames) {
934 /** CustomEventTarget */
935 function CustomEventTarget() {
936 EventTarget.call(this);
937 }
938 CustomEventTarget.prototype = Object.create(EventTarget.prototype, {
939 constructor: {
940 value: CustomEventTarget,
941 configurable: true,
942 writable: true
943 }
944 });
945 for (var i = 0; i < eventNames.length; ++i) {
946 defineEventAttribute(CustomEventTarget.prototype, eventNames[i]);
947 }
948 return CustomEventTarget;
949 }
950
951 /**
952 * EventTarget.
953 *
954 * - This is constructor if no arguments.
955 * - This is a function which returns a CustomEventTarget constructor if there are arguments.
956 *
957 * For example:
958 *
959 * class A extends EventTarget {}
960 * class B extends EventTarget("message") {}
961 * class C extends EventTarget("message", "error") {}
962 * class D extends EventTarget(["message", "error"]) {}
963 */
964 function EventTarget() {
965 /*eslint-disable consistent-return */
966 if (this instanceof EventTarget) {
967 listenersMap.set(this, new Map());
968 return;
969 }
970 if (arguments.length === 1 && Array.isArray(arguments[0])) {
971 return defineCustomEventTarget(arguments[0]);
972 }
973 if (arguments.length > 0) {
974 var types = new Array(arguments.length);
975 for (var i = 0; i < arguments.length; ++i) {
976 types[i] = arguments[i];
977 }
978 return defineCustomEventTarget(types);
979 }
980 throw new TypeError("Cannot call a class as a function");
981 /*eslint-enable consistent-return */
982 }
983
984 // Should be enumerable, but class methods are not enumerable.
985 EventTarget.prototype = {
986 /**
987 * Add a given listener to this event target.
988 * @param {string} eventName The event name to add.
989 * @param {Function} listener The listener to add.
990 * @param {boolean|{capture?:boolean,passive?:boolean,once?:boolean}} [options] The options for this listener.
991 * @returns {void}
992 */
993 addEventListener: function addEventListener(eventName, listener, options) {
994 if (listener == null) {
995 return;
996 }
997 if (typeof listener !== "function" && !isObject(listener)) {
998 throw new TypeError("'listener' should be a function or an object.");
999 }
1000 var listeners = getListeners(this);
1001 var optionsIsObj = isObject(options);
1002 var capture = optionsIsObj ? Boolean(options.capture) : Boolean(options);
1003 var listenerType = capture ? CAPTURE : BUBBLE;
1004 var newNode = {
1005 listener: listener,
1006 listenerType: listenerType,
1007 passive: optionsIsObj && Boolean(options.passive),
1008 once: optionsIsObj && Boolean(options.once),
1009 next: null
1010 };
1011
1012 // Set it as the first node if the first node is null.
1013 var node = listeners.get(eventName);
1014 if (node === undefined) {
1015 listeners.set(eventName, newNode);
1016 return;
1017 }
1018
1019 // Traverse to the tail while checking duplication..
1020 var prev = null;
1021 while (node != null) {
1022 if (node.listener === listener && node.listenerType === listenerType) {
1023 // Should ignore duplication.
1024 return;
1025 }
1026 prev = node;
1027 node = node.next;
1028 }
1029
1030 // Add it.
1031 prev.next = newNode;
1032 },
1033 /**
1034 * Remove a given listener from this event target.
1035 * @param {string} eventName The event name to remove.
1036 * @param {Function} listener The listener to remove.
1037 * @param {boolean|{capture?:boolean,passive?:boolean,once?:boolean}} [options] The options for this listener.
1038 * @returns {void}
1039 */
1040 removeEventListener: function removeEventListener(eventName, listener, options) {
1041 if (listener == null) {
1042 return;
1043 }
1044 var listeners = getListeners(this);
1045 var capture = isObject(options) ? Boolean(options.capture) : Boolean(options);
1046 var listenerType = capture ? CAPTURE : BUBBLE;
1047 var prev = null;
1048 var node = listeners.get(eventName);
1049 while (node != null) {
1050 if (node.listener === listener && node.listenerType === listenerType) {
1051 if (prev !== null) {
1052 prev.next = node.next;
1053 } else if (node.next !== null) {
1054 listeners.set(eventName, node.next);
1055 } else {
1056 listeners["delete"](eventName);
1057 }
1058 return;
1059 }
1060 prev = node;
1061 node = node.next;
1062 }
1063 },
1064 /**
1065 * Dispatch a given event.
1066 * @param {Event|{type:string}} event The event to dispatch.
1067 * @returns {boolean} `false` if canceled.
1068 */
1069 dispatchEvent: function dispatchEvent(event) {
1070 if (event == null || typeof event.type !== "string") {
1071 throw new TypeError('"event.type" should be a string.');
1072 }
1073
1074 // If listeners aren't registered, terminate.
1075 var listeners = getListeners(this);
1076 var eventName = event.type;
1077 var node = listeners.get(eventName);
1078 if (node == null) {
1079 return true;
1080 }
1081
1082 // Since we cannot rewrite several properties, so wrap object.
1083 var wrappedEvent = wrapEvent(this, event);
1084
1085 // This doesn't process capturing phase and bubbling phase.
1086 // This isn't participating in a tree.
1087 var prev = null;
1088 while (node != null) {
1089 // Remove this listener if it's once
1090 if (node.once) {
1091 if (prev !== null) {
1092 prev.next = node.next;
1093 } else if (node.next !== null) {
1094 listeners.set(eventName, node.next);
1095 } else {
1096 listeners["delete"](eventName);
1097 }
1098 } else {
1099 prev = node;
1100 }
1101
1102 // Call this listener
1103 setPassiveListener(wrappedEvent, node.passive ? node.listener : null);
1104 if (typeof node.listener === "function") {
1105 try {
1106 node.listener.call(this, wrappedEvent);
1107 } catch (err) {
1108 if (typeof console !== "undefined" && typeof console.error === "function") {
1109 console.error(err);
1110 }
1111 }
1112 } else if (node.listenerType !== ATTRIBUTE && typeof node.listener.handleEvent === "function") {
1113 node.listener.handleEvent(wrappedEvent);
1114 }
1115
1116 // Break if `event.stopImmediatePropagation` was called.
1117 if (isStopped(wrappedEvent)) {
1118 break;
1119 }
1120 node = node.next;
1121 }
1122 setPassiveListener(wrappedEvent, null);
1123 setEventPhase(wrappedEvent, 0);
1124 setCurrentTarget(wrappedEvent, null);
1125 return !wrappedEvent.defaultPrevented;
1126 }
1127 };
1128
1129 // `constructor` is not enumerable.
1130 Object.defineProperty(EventTarget.prototype, "constructor", {
1131 value: EventTarget,
1132 configurable: true,
1133 writable: true
1134 });
1135
1136 // Ensure `eventTarget instanceof window.EventTarget` is `true`.
1137 if (typeof window !== "undefined" && typeof window.EventTarget !== "undefined") {
1138 Object.setPrototypeOf(EventTarget.prototype, window.EventTarget.prototype);
1139 }
1140 var EVENTS = ["open", "error", "message", "close"];
1141 var WS = /** @class */function (_super) {
1142 __extends(WS, _super);
1143 function WS(url, protocol) {
1144 var _this = this;
1145 if (!url) {
1146 throw new TypeError("Failed to construct 'WebSocket': url required");
1147 }
1148 if (protocol && !(wx.canIUse && wx.canIUse("connectSocket.object.protocols"))) {
1149 throw new Error("subprotocol not supported in weapp");
1150 }
1151 _this = _super.call(this) || this;
1152 _this._url = url;
1153 _this._protocol = protocol;
1154 _this._readyState = WS.CONNECTING;
1155 var errorHandler = function errorHandler(event) {
1156 _this._readyState = WS.CLOSED;
1157 _this.dispatchEvent({
1158 type: "error",
1159 message: event.errMsg
1160 });
1161 };
1162 var socketTask = wx.connectSocket({
1163 url: url,
1164 protocols: _this._protocol === undefined || Array.isArray(_this._protocol) ? _this._protocol : [_this._protocol],
1165 fail: function fail(error) {
1166 return setTimeout(function () {
1167 return errorHandler(error);
1168 }, 0);
1169 }
1170 });
1171 _this._socketTask = socketTask;
1172 socketTask.onOpen(function (event) {
1173 _this._readyState = WS.OPEN;
1174 _this.dispatchEvent({
1175 type: "open"
1176 });
1177 });
1178 socketTask.onError(errorHandler);
1179 socketTask.onMessage(function (event) {
1180 var data = event.data;
1181 _this.dispatchEvent({
1182 data: data,
1183 type: "message"
1184 });
1185 });
1186 socketTask.onClose(function (event) {
1187 _this._readyState = WS.CLOSED;
1188 var code = event.code,
1189 reason = event.reason;
1190 _this.dispatchEvent({
1191 code: code,
1192 reason: reason,
1193 type: "close"
1194 });
1195 });
1196 return _this;
1197 }
1198 Object.defineProperty(WS.prototype, "url", {
1199 get: function get() {
1200 return this._url;
1201 },
1202 enumerable: true,
1203 configurable: true
1204 });
1205 Object.defineProperty(WS.prototype, "protocol", {
1206 get: function get() {
1207 return this._protocol;
1208 },
1209 enumerable: true,
1210 configurable: true
1211 });
1212 Object.defineProperty(WS.prototype, "readyState", {
1213 get: function get() {
1214 return this._readyState;
1215 },
1216 enumerable: true,
1217 configurable: true
1218 });
1219 WS.prototype.close = function () {
1220 if (this.readyState === WS.CLOSED) return;
1221 if (this.readyState === WS.CONNECTING) {
1222 console.warn("close WebSocket which is connecting might not work");
1223 }
1224 this._socketTask.close({});
1225 };
1226 WS.prototype.send = function (data) {
1227 if (this.readyState !== WS.OPEN) {
1228 throw new Error("INVALID_STATE_ERR");
1229 }
1230 if (!(typeof data === "string" || data instanceof ArrayBuffer)) {
1231 throw new TypeError("only String/ArrayBuffer supported");
1232 }
1233 this._socketTask.send({
1234 data: data
1235 });
1236 };
1237 WS.CONNECTING = 0;
1238 WS.OPEN = 1;
1239 WS.CLOSING = 2;
1240 WS.CLOSED = 3;
1241 return WS;
1242 }(EventTarget(EVENTS));
1243 var WebSocket = WS;
1244 var platformInfo = {
1245 name: "Weapp"
1246 };
1247 exports.WebSocket = WebSocket;
1248 exports.getAuthInfo = getAuthInfo;
1249 exports.platformInfo = platformInfo;
1250 exports.request = request;
1251 exports.storage = storage;
1252 exports.upload = upload;
1253 });
1254 unwrapExports(lib);
1255 var lib_1 = lib.WebSocket;
1256 var lib_2 = lib.getAuthInfo;
1257 var lib_3 = lib.platformInfo;
1258 var lib_4 = lib.request;
1259 var lib_5 = lib.storage;
1260 var lib_6 = lib.upload;
1261
1262 var toPrimitive = createCommonjsModule(function (module) {
1263 var _typeof = _typeof_1["default"];
1264 function _toPrimitive(input, hint) {
1265 if (_typeof(input) !== "object" || input === null) return input;
1266 var prim = input[Symbol.toPrimitive];
1267 if (prim !== undefined) {
1268 var res = prim.call(input, hint || "default");
1269 if (_typeof(res) !== "object") return res;
1270 throw new TypeError("@@toPrimitive must return a primitive value.");
1271 }
1272 return (hint === "string" ? String : Number)(input);
1273 }
1274 module.exports = _toPrimitive, module.exports.__esModule = true, module.exports["default"] = module.exports;
1275 });
1276
1277 unwrapExports(toPrimitive);
1278
1279 var toPropertyKey = createCommonjsModule(function (module) {
1280 var _typeof = _typeof_1["default"];
1281
1282 function _toPropertyKey(arg) {
1283 var key = toPrimitive(arg, "string");
1284 return _typeof(key) === "symbol" ? key : String(key);
1285 }
1286 module.exports = _toPropertyKey, module.exports.__esModule = true, module.exports["default"] = module.exports;
1287 });
1288
1289 unwrapExports(toPropertyKey);
1290
1291 var defineProperty = createCommonjsModule(function (module) {
1292 function _defineProperty(obj, key, value) {
1293 key = toPropertyKey(key);
1294 if (key in obj) {
1295 Object.defineProperty(obj, key, {
1296 value: value,
1297 enumerable: true,
1298 configurable: true,
1299 writable: true
1300 });
1301 } else {
1302 obj[key] = value;
1303 }
1304 return obj;
1305 }
1306 module.exports = _defineProperty, module.exports.__esModule = true, module.exports["default"] = module.exports;
1307 });
1308
1309 var _defineProperty = unwrapExports(defineProperty);
1310
1311 var long_1 = createCommonjsModule(function (module) {
1312 /*
1313 Copyright 2013 Daniel Wirtz <dcode@dcode.io>
1314 Copyright 2009 The Closure Library Authors. All Rights Reserved.
1315
1316 Licensed under the Apache License, Version 2.0 (the "License");
1317 you may not use this file except in compliance with the License.
1318 You may obtain a copy of the License at
1319
1320 http://www.apache.org/licenses/LICENSE-2.0
1321
1322 Unless required by applicable law or agreed to in writing, software
1323 distributed under the License is distributed on an "AS-IS" BASIS,
1324 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1325 See the License for the specific language governing permissions and
1326 limitations under the License.
1327 */
1328
1329 /**
1330 * @license long.js (c) 2013 Daniel Wirtz <dcode@dcode.io>
1331 * Released under the Apache License, Version 2.0
1332 * see: https://github.com/dcodeIO/long.js for details
1333 */
1334 (function(global, factory) {
1335
1336 /* AMD */ if (typeof commonjsRequire === 'function' && 'object' === "object" && module && module["exports"])
1337 module["exports"] = factory();
1338 /* Global */ else
1339 (global["dcodeIO"] = global["dcodeIO"] || {})["Long"] = factory();
1340
1341 })(commonjsGlobal, function() {
1342
1343 /**
1344 * Constructs a 64 bit two's-complement integer, given its low and high 32 bit values as *signed* integers.
1345 * See the from* functions below for more convenient ways of constructing Longs.
1346 * @exports Long
1347 * @class A Long class for representing a 64 bit two's-complement integer value.
1348 * @param {number} low The low (signed) 32 bits of the long
1349 * @param {number} high The high (signed) 32 bits of the long
1350 * @param {boolean=} unsigned Whether unsigned or not, defaults to `false` for signed
1351 * @constructor
1352 */
1353 function Long(low, high, unsigned) {
1354
1355 /**
1356 * The low 32 bits as a signed value.
1357 * @type {number}
1358 */
1359 this.low = low | 0;
1360
1361 /**
1362 * The high 32 bits as a signed value.
1363 * @type {number}
1364 */
1365 this.high = high | 0;
1366
1367 /**
1368 * Whether unsigned or not.
1369 * @type {boolean}
1370 */
1371 this.unsigned = !!unsigned;
1372 }
1373
1374 // The internal representation of a long is the two given signed, 32-bit values.
1375 // We use 32-bit pieces because these are the size of integers on which
1376 // Javascript performs bit-operations. For operations like addition and
1377 // multiplication, we split each number into 16 bit pieces, which can easily be
1378 // multiplied within Javascript's floating-point representation without overflow
1379 // or change in sign.
1380 //
1381 // In the algorithms below, we frequently reduce the negative case to the
1382 // positive case by negating the input(s) and then post-processing the result.
1383 // Note that we must ALWAYS check specially whether those values are MIN_VALUE
1384 // (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as
1385 // a positive number, it overflows back into a negative). Not handling this
1386 // case would often result in infinite recursion.
1387 //
1388 // Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the from*
1389 // methods on which they depend.
1390
1391 /**
1392 * An indicator used to reliably determine if an object is a Long or not.
1393 * @type {boolean}
1394 * @const
1395 * @private
1396 */
1397 Long.prototype.__isLong__;
1398
1399 Object.defineProperty(Long.prototype, "__isLong__", {
1400 value: true,
1401 enumerable: false,
1402 configurable: false
1403 });
1404
1405 /**
1406 * @function
1407 * @param {*} obj Object
1408 * @returns {boolean}
1409 * @inner
1410 */
1411 function isLong(obj) {
1412 return (obj && obj["__isLong__"]) === true;
1413 }
1414
1415 /**
1416 * Tests if the specified object is a Long.
1417 * @function
1418 * @param {*} obj Object
1419 * @returns {boolean}
1420 */
1421 Long.isLong = isLong;
1422
1423 /**
1424 * A cache of the Long representations of small integer values.
1425 * @type {!Object}
1426 * @inner
1427 */
1428 var INT_CACHE = {};
1429
1430 /**
1431 * A cache of the Long representations of small unsigned integer values.
1432 * @type {!Object}
1433 * @inner
1434 */
1435 var UINT_CACHE = {};
1436
1437 /**
1438 * @param {number} value
1439 * @param {boolean=} unsigned
1440 * @returns {!Long}
1441 * @inner
1442 */
1443 function fromInt(value, unsigned) {
1444 var obj, cachedObj, cache;
1445 if (unsigned) {
1446 value >>>= 0;
1447 if (cache = (0 <= value && value < 256)) {
1448 cachedObj = UINT_CACHE[value];
1449 if (cachedObj)
1450 return cachedObj;
1451 }
1452 obj = fromBits(value, (value | 0) < 0 ? -1 : 0, true);
1453 if (cache)
1454 UINT_CACHE[value] = obj;
1455 return obj;
1456 } else {
1457 value |= 0;
1458 if (cache = (-128 <= value && value < 128)) {
1459 cachedObj = INT_CACHE[value];
1460 if (cachedObj)
1461 return cachedObj;
1462 }
1463 obj = fromBits(value, value < 0 ? -1 : 0, false);
1464 if (cache)
1465 INT_CACHE[value] = obj;
1466 return obj;
1467 }
1468 }
1469
1470 /**
1471 * Returns a Long representing the given 32 bit integer value.
1472 * @function
1473 * @param {number} value The 32 bit integer in question
1474 * @param {boolean=} unsigned Whether unsigned or not, defaults to `false` for signed
1475 * @returns {!Long} The corresponding Long value
1476 */
1477 Long.fromInt = fromInt;
1478
1479 /**
1480 * @param {number} value
1481 * @param {boolean=} unsigned
1482 * @returns {!Long}
1483 * @inner
1484 */
1485 function fromNumber(value, unsigned) {
1486 if (isNaN(value) || !isFinite(value))
1487 return unsigned ? UZERO : ZERO;
1488 if (unsigned) {
1489 if (value < 0)
1490 return UZERO;
1491 if (value >= TWO_PWR_64_DBL)
1492 return MAX_UNSIGNED_VALUE;
1493 } else {
1494 if (value <= -TWO_PWR_63_DBL)
1495 return MIN_VALUE;
1496 if (value + 1 >= TWO_PWR_63_DBL)
1497 return MAX_VALUE;
1498 }
1499 if (value < 0)
1500 return fromNumber(-value, unsigned).neg();
1501 return fromBits((value % TWO_PWR_32_DBL) | 0, (value / TWO_PWR_32_DBL) | 0, unsigned);
1502 }
1503
1504 /**
1505 * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned.
1506 * @function
1507 * @param {number} value The number in question
1508 * @param {boolean=} unsigned Whether unsigned or not, defaults to `false` for signed
1509 * @returns {!Long} The corresponding Long value
1510 */
1511 Long.fromNumber = fromNumber;
1512
1513 /**
1514 * @param {number} lowBits
1515 * @param {number} highBits
1516 * @param {boolean=} unsigned
1517 * @returns {!Long}
1518 * @inner
1519 */
1520 function fromBits(lowBits, highBits, unsigned) {
1521 return new Long(lowBits, highBits, unsigned);
1522 }
1523
1524 /**
1525 * Returns a Long representing the 64 bit integer that comes by concatenating the given low and high bits. Each is
1526 * assumed to use 32 bits.
1527 * @function
1528 * @param {number} lowBits The low 32 bits
1529 * @param {number} highBits The high 32 bits
1530 * @param {boolean=} unsigned Whether unsigned or not, defaults to `false` for signed
1531 * @returns {!Long} The corresponding Long value
1532 */
1533 Long.fromBits = fromBits;
1534
1535 /**
1536 * @function
1537 * @param {number} base
1538 * @param {number} exponent
1539 * @returns {number}
1540 * @inner
1541 */
1542 var pow_dbl = Math.pow; // Used 4 times (4*8 to 15+4)
1543
1544 /**
1545 * @param {string} str
1546 * @param {(boolean|number)=} unsigned
1547 * @param {number=} radix
1548 * @returns {!Long}
1549 * @inner
1550 */
1551 function fromString(str, unsigned, radix) {
1552 if (str.length === 0)
1553 throw Error('empty string');
1554 if (str === "NaN" || str === "Infinity" || str === "+Infinity" || str === "-Infinity")
1555 return ZERO;
1556 if (typeof unsigned === 'number') {
1557 // For goog.math.long compatibility
1558 radix = unsigned,
1559 unsigned = false;
1560 } else {
1561 unsigned = !! unsigned;
1562 }
1563 radix = radix || 10;
1564 if (radix < 2 || 36 < radix)
1565 throw RangeError('radix');
1566
1567 var p;
1568 if ((p = str.indexOf('-')) > 0)
1569 throw Error('interior hyphen');
1570 else if (p === 0) {
1571 return fromString(str.substring(1), unsigned, radix).neg();
1572 }
1573
1574 // Do several (8) digits each time through the loop, so as to
1575 // minimize the calls to the very expensive emulated div.
1576 var radixToPower = fromNumber(pow_dbl(radix, 8));
1577
1578 var result = ZERO;
1579 for (var i = 0; i < str.length; i += 8) {
1580 var size = Math.min(8, str.length - i),
1581 value = parseInt(str.substring(i, i + size), radix);
1582 if (size < 8) {
1583 var power = fromNumber(pow_dbl(radix, size));
1584 result = result.mul(power).add(fromNumber(value));
1585 } else {
1586 result = result.mul(radixToPower);
1587 result = result.add(fromNumber(value));
1588 }
1589 }
1590 result.unsigned = unsigned;
1591 return result;
1592 }
1593
1594 /**
1595 * Returns a Long representation of the given string, written using the specified radix.
1596 * @function
1597 * @param {string} str The textual representation of the Long
1598 * @param {(boolean|number)=} unsigned Whether unsigned or not, defaults to `false` for signed
1599 * @param {number=} radix The radix in which the text is written (2-36), defaults to 10
1600 * @returns {!Long} The corresponding Long value
1601 */
1602 Long.fromString = fromString;
1603
1604 /**
1605 * @function
1606 * @param {!Long|number|string|!{low: number, high: number, unsigned: boolean}} val
1607 * @returns {!Long}
1608 * @inner
1609 */
1610 function fromValue(val) {
1611 if (val /* is compatible */ instanceof Long)
1612 return val;
1613 if (typeof val === 'number')
1614 return fromNumber(val);
1615 if (typeof val === 'string')
1616 return fromString(val);
1617 // Throws for non-objects, converts non-instanceof Long:
1618 return fromBits(val.low, val.high, val.unsigned);
1619 }
1620
1621 /**
1622 * Converts the specified value to a Long.
1623 * @function
1624 * @param {!Long|number|string|!{low: number, high: number, unsigned: boolean}} val Value
1625 * @returns {!Long}
1626 */
1627 Long.fromValue = fromValue;
1628
1629 // NOTE: the compiler should inline these constant values below and then remove these variables, so there should be
1630 // no runtime penalty for these.
1631
1632 /**
1633 * @type {number}
1634 * @const
1635 * @inner
1636 */
1637 var TWO_PWR_16_DBL = 1 << 16;
1638
1639 /**
1640 * @type {number}
1641 * @const
1642 * @inner
1643 */
1644 var TWO_PWR_24_DBL = 1 << 24;
1645
1646 /**
1647 * @type {number}
1648 * @const
1649 * @inner
1650 */
1651 var TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL;
1652
1653 /**
1654 * @type {number}
1655 * @const
1656 * @inner
1657 */
1658 var TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL;
1659
1660 /**
1661 * @type {number}
1662 * @const
1663 * @inner
1664 */
1665 var TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2;
1666
1667 /**
1668 * @type {!Long}
1669 * @const
1670 * @inner
1671 */
1672 var TWO_PWR_24 = fromInt(TWO_PWR_24_DBL);
1673
1674 /**
1675 * @type {!Long}
1676 * @inner
1677 */
1678 var ZERO = fromInt(0);
1679
1680 /**
1681 * Signed zero.
1682 * @type {!Long}
1683 */
1684 Long.ZERO = ZERO;
1685
1686 /**
1687 * @type {!Long}
1688 * @inner
1689 */
1690 var UZERO = fromInt(0, true);
1691
1692 /**
1693 * Unsigned zero.
1694 * @type {!Long}
1695 */
1696 Long.UZERO = UZERO;
1697
1698 /**
1699 * @type {!Long}
1700 * @inner
1701 */
1702 var ONE = fromInt(1);
1703
1704 /**
1705 * Signed one.
1706 * @type {!Long}
1707 */
1708 Long.ONE = ONE;
1709
1710 /**
1711 * @type {!Long}
1712 * @inner
1713 */
1714 var UONE = fromInt(1, true);
1715
1716 /**
1717 * Unsigned one.
1718 * @type {!Long}
1719 */
1720 Long.UONE = UONE;
1721
1722 /**
1723 * @type {!Long}
1724 * @inner
1725 */
1726 var NEG_ONE = fromInt(-1);
1727
1728 /**
1729 * Signed negative one.
1730 * @type {!Long}
1731 */
1732 Long.NEG_ONE = NEG_ONE;
1733
1734 /**
1735 * @type {!Long}
1736 * @inner
1737 */
1738 var MAX_VALUE = fromBits(0xFFFFFFFF|0, 0x7FFFFFFF|0, false);
1739
1740 /**
1741 * Maximum signed value.
1742 * @type {!Long}
1743 */
1744 Long.MAX_VALUE = MAX_VALUE;
1745
1746 /**
1747 * @type {!Long}
1748 * @inner
1749 */
1750 var MAX_UNSIGNED_VALUE = fromBits(0xFFFFFFFF|0, 0xFFFFFFFF|0, true);
1751
1752 /**
1753 * Maximum unsigned value.
1754 * @type {!Long}
1755 */
1756 Long.MAX_UNSIGNED_VALUE = MAX_UNSIGNED_VALUE;
1757
1758 /**
1759 * @type {!Long}
1760 * @inner
1761 */
1762 var MIN_VALUE = fromBits(0, 0x80000000|0, false);
1763
1764 /**
1765 * Minimum signed value.
1766 * @type {!Long}
1767 */
1768 Long.MIN_VALUE = MIN_VALUE;
1769
1770 /**
1771 * @alias Long.prototype
1772 * @inner
1773 */
1774 var LongPrototype = Long.prototype;
1775
1776 /**
1777 * Converts the Long to a 32 bit integer, assuming it is a 32 bit integer.
1778 * @returns {number}
1779 */
1780 LongPrototype.toInt = function toInt() {
1781 return this.unsigned ? this.low >>> 0 : this.low;
1782 };
1783
1784 /**
1785 * Converts the Long to a the nearest floating-point representation of this value (double, 53 bit mantissa).
1786 * @returns {number}
1787 */
1788 LongPrototype.toNumber = function toNumber() {
1789 if (this.unsigned)
1790 return ((this.high >>> 0) * TWO_PWR_32_DBL) + (this.low >>> 0);
1791 return this.high * TWO_PWR_32_DBL + (this.low >>> 0);
1792 };
1793
1794 /**
1795 * Converts the Long to a string written in the specified radix.
1796 * @param {number=} radix Radix (2-36), defaults to 10
1797 * @returns {string}
1798 * @override
1799 * @throws {RangeError} If `radix` is out of range
1800 */
1801 LongPrototype.toString = function toString(radix) {
1802 radix = radix || 10;
1803 if (radix < 2 || 36 < radix)
1804 throw RangeError('radix');
1805 if (this.isZero())
1806 return '0';
1807 if (this.isNegative()) { // Unsigned Longs are never negative
1808 if (this.eq(MIN_VALUE)) {
1809 // We need to change the Long value before it can be negated, so we remove
1810 // the bottom-most digit in this base and then recurse to do the rest.
1811 var radixLong = fromNumber(radix),
1812 div = this.div(radixLong),
1813 rem1 = div.mul(radixLong).sub(this);
1814 return div.toString(radix) + rem1.toInt().toString(radix);
1815 } else
1816 return '-' + this.neg().toString(radix);
1817 }
1818
1819 // Do several (6) digits each time through the loop, so as to
1820 // minimize the calls to the very expensive emulated div.
1821 var radixToPower = fromNumber(pow_dbl(radix, 6), this.unsigned),
1822 rem = this;
1823 var result = '';
1824 while (true) {
1825 var remDiv = rem.div(radixToPower),
1826 intval = rem.sub(remDiv.mul(radixToPower)).toInt() >>> 0,
1827 digits = intval.toString(radix);
1828 rem = remDiv;
1829 if (rem.isZero())
1830 return digits + result;
1831 else {
1832 while (digits.length < 6)
1833 digits = '0' + digits;
1834 result = '' + digits + result;
1835 }
1836 }
1837 };
1838
1839 /**
1840 * Gets the high 32 bits as a signed integer.
1841 * @returns {number} Signed high bits
1842 */
1843 LongPrototype.getHighBits = function getHighBits() {
1844 return this.high;
1845 };
1846
1847 /**
1848 * Gets the high 32 bits as an unsigned integer.
1849 * @returns {number} Unsigned high bits
1850 */
1851 LongPrototype.getHighBitsUnsigned = function getHighBitsUnsigned() {
1852 return this.high >>> 0;
1853 };
1854
1855 /**
1856 * Gets the low 32 bits as a signed integer.
1857 * @returns {number} Signed low bits
1858 */
1859 LongPrototype.getLowBits = function getLowBits() {
1860 return this.low;
1861 };
1862
1863 /**
1864 * Gets the low 32 bits as an unsigned integer.
1865 * @returns {number} Unsigned low bits
1866 */
1867 LongPrototype.getLowBitsUnsigned = function getLowBitsUnsigned() {
1868 return this.low >>> 0;
1869 };
1870
1871 /**
1872 * Gets the number of bits needed to represent the absolute value of this Long.
1873 * @returns {number}
1874 */
1875 LongPrototype.getNumBitsAbs = function getNumBitsAbs() {
1876 if (this.isNegative()) // Unsigned Longs are never negative
1877 return this.eq(MIN_VALUE) ? 64 : this.neg().getNumBitsAbs();
1878 var val = this.high != 0 ? this.high : this.low;
1879 for (var bit = 31; bit > 0; bit--)
1880 if ((val & (1 << bit)) != 0)
1881 break;
1882 return this.high != 0 ? bit + 33 : bit + 1;
1883 };
1884
1885 /**
1886 * Tests if this Long's value equals zero.
1887 * @returns {boolean}
1888 */
1889 LongPrototype.isZero = function isZero() {
1890 return this.high === 0 && this.low === 0;
1891 };
1892
1893 /**
1894 * Tests if this Long's value is negative.
1895 * @returns {boolean}
1896 */
1897 LongPrototype.isNegative = function isNegative() {
1898 return !this.unsigned && this.high < 0;
1899 };
1900
1901 /**
1902 * Tests if this Long's value is positive.
1903 * @returns {boolean}
1904 */
1905 LongPrototype.isPositive = function isPositive() {
1906 return this.unsigned || this.high >= 0;
1907 };
1908
1909 /**
1910 * Tests if this Long's value is odd.
1911 * @returns {boolean}
1912 */
1913 LongPrototype.isOdd = function isOdd() {
1914 return (this.low & 1) === 1;
1915 };
1916
1917 /**
1918 * Tests if this Long's value is even.
1919 * @returns {boolean}
1920 */
1921 LongPrototype.isEven = function isEven() {
1922 return (this.low & 1) === 0;
1923 };
1924
1925 /**
1926 * Tests if this Long's value equals the specified's.
1927 * @param {!Long|number|string} other Other value
1928 * @returns {boolean}
1929 */
1930 LongPrototype.equals = function equals(other) {
1931 if (!isLong(other))
1932 other = fromValue(other);
1933 if (this.unsigned !== other.unsigned && (this.high >>> 31) === 1 && (other.high >>> 31) === 1)
1934 return false;
1935 return this.high === other.high && this.low === other.low;
1936 };
1937
1938 /**
1939 * Tests if this Long's value equals the specified's. This is an alias of {@link Long#equals}.
1940 * @function
1941 * @param {!Long|number|string} other Other value
1942 * @returns {boolean}
1943 */
1944 LongPrototype.eq = LongPrototype.equals;
1945
1946 /**
1947 * Tests if this Long's value differs from the specified's.
1948 * @param {!Long|number|string} other Other value
1949 * @returns {boolean}
1950 */
1951 LongPrototype.notEquals = function notEquals(other) {
1952 return !this.eq(/* validates */ other);
1953 };
1954
1955 /**
1956 * Tests if this Long's value differs from the specified's. This is an alias of {@link Long#notEquals}.
1957 * @function
1958 * @param {!Long|number|string} other Other value
1959 * @returns {boolean}
1960 */
1961 LongPrototype.neq = LongPrototype.notEquals;
1962
1963 /**
1964 * Tests if this Long's value is less than the specified's.
1965 * @param {!Long|number|string} other Other value
1966 * @returns {boolean}
1967 */
1968 LongPrototype.lessThan = function lessThan(other) {
1969 return this.comp(/* validates */ other) < 0;
1970 };
1971
1972 /**
1973 * Tests if this Long's value is less than the specified's. This is an alias of {@link Long#lessThan}.
1974 * @function
1975 * @param {!Long|number|string} other Other value
1976 * @returns {boolean}
1977 */
1978 LongPrototype.lt = LongPrototype.lessThan;
1979
1980 /**
1981 * Tests if this Long's value is less than or equal the specified's.
1982 * @param {!Long|number|string} other Other value
1983 * @returns {boolean}
1984 */
1985 LongPrototype.lessThanOrEqual = function lessThanOrEqual(other) {
1986 return this.comp(/* validates */ other) <= 0;
1987 };
1988
1989 /**
1990 * Tests if this Long's value is less than or equal the specified's. This is an alias of {@link Long#lessThanOrEqual}.
1991 * @function
1992 * @param {!Long|number|string} other Other value
1993 * @returns {boolean}
1994 */
1995 LongPrototype.lte = LongPrototype.lessThanOrEqual;
1996
1997 /**
1998 * Tests if this Long's value is greater than the specified's.
1999 * @param {!Long|number|string} other Other value
2000 * @returns {boolean}
2001 */
2002 LongPrototype.greaterThan = function greaterThan(other) {
2003 return this.comp(/* validates */ other) > 0;
2004 };
2005
2006 /**
2007 * Tests if this Long's value is greater than the specified's. This is an alias of {@link Long#greaterThan}.
2008 * @function
2009 * @param {!Long|number|string} other Other value
2010 * @returns {boolean}
2011 */
2012 LongPrototype.gt = LongPrototype.greaterThan;
2013
2014 /**
2015 * Tests if this Long's value is greater than or equal the specified's.
2016 * @param {!Long|number|string} other Other value
2017 * @returns {boolean}
2018 */
2019 LongPrototype.greaterThanOrEqual = function greaterThanOrEqual(other) {
2020 return this.comp(/* validates */ other) >= 0;
2021 };
2022
2023 /**
2024 * Tests if this Long's value is greater than or equal the specified's. This is an alias of {@link Long#greaterThanOrEqual}.
2025 * @function
2026 * @param {!Long|number|string} other Other value
2027 * @returns {boolean}
2028 */
2029 LongPrototype.gte = LongPrototype.greaterThanOrEqual;
2030
2031 /**
2032 * Compares this Long's value with the specified's.
2033 * @param {!Long|number|string} other Other value
2034 * @returns {number} 0 if they are the same, 1 if the this is greater and -1
2035 * if the given one is greater
2036 */
2037 LongPrototype.compare = function compare(other) {
2038 if (!isLong(other))
2039 other = fromValue(other);
2040 if (this.eq(other))
2041 return 0;
2042 var thisNeg = this.isNegative(),
2043 otherNeg = other.isNegative();
2044 if (thisNeg && !otherNeg)
2045 return -1;
2046 if (!thisNeg && otherNeg)
2047 return 1;
2048 // At this point the sign bits are the same
2049 if (!this.unsigned)
2050 return this.sub(other).isNegative() ? -1 : 1;
2051 // Both are positive if at least one is unsigned
2052 return (other.high >>> 0) > (this.high >>> 0) || (other.high === this.high && (other.low >>> 0) > (this.low >>> 0)) ? -1 : 1;
2053 };
2054
2055 /**
2056 * Compares this Long's value with the specified's. This is an alias of {@link Long#compare}.
2057 * @function
2058 * @param {!Long|number|string} other Other value
2059 * @returns {number} 0 if they are the same, 1 if the this is greater and -1
2060 * if the given one is greater
2061 */
2062 LongPrototype.comp = LongPrototype.compare;
2063
2064 /**
2065 * Negates this Long's value.
2066 * @returns {!Long} Negated Long
2067 */
2068 LongPrototype.negate = function negate() {
2069 if (!this.unsigned && this.eq(MIN_VALUE))
2070 return MIN_VALUE;
2071 return this.not().add(ONE);
2072 };
2073
2074 /**
2075 * Negates this Long's value. This is an alias of {@link Long#negate}.
2076 * @function
2077 * @returns {!Long} Negated Long
2078 */
2079 LongPrototype.neg = LongPrototype.negate;
2080
2081 /**
2082 * Returns the sum of this and the specified Long.
2083 * @param {!Long|number|string} addend Addend
2084 * @returns {!Long} Sum
2085 */
2086 LongPrototype.add = function add(addend) {
2087 if (!isLong(addend))
2088 addend = fromValue(addend);
2089
2090 // Divide each number into 4 chunks of 16 bits, and then sum the chunks.
2091
2092 var a48 = this.high >>> 16;
2093 var a32 = this.high & 0xFFFF;
2094 var a16 = this.low >>> 16;
2095 var a00 = this.low & 0xFFFF;
2096
2097 var b48 = addend.high >>> 16;
2098 var b32 = addend.high & 0xFFFF;
2099 var b16 = addend.low >>> 16;
2100 var b00 = addend.low & 0xFFFF;
2101
2102 var c48 = 0, c32 = 0, c16 = 0, c00 = 0;
2103 c00 += a00 + b00;
2104 c16 += c00 >>> 16;
2105 c00 &= 0xFFFF;
2106 c16 += a16 + b16;
2107 c32 += c16 >>> 16;
2108 c16 &= 0xFFFF;
2109 c32 += a32 + b32;
2110 c48 += c32 >>> 16;
2111 c32 &= 0xFFFF;
2112 c48 += a48 + b48;
2113 c48 &= 0xFFFF;
2114 return fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned);
2115 };
2116
2117 /**
2118 * Returns the difference of this and the specified Long.
2119 * @param {!Long|number|string} subtrahend Subtrahend
2120 * @returns {!Long} Difference
2121 */
2122 LongPrototype.subtract = function subtract(subtrahend) {
2123 if (!isLong(subtrahend))
2124 subtrahend = fromValue(subtrahend);
2125 return this.add(subtrahend.neg());
2126 };
2127
2128 /**
2129 * Returns the difference of this and the specified Long. This is an alias of {@link Long#subtract}.
2130 * @function
2131 * @param {!Long|number|string} subtrahend Subtrahend
2132 * @returns {!Long} Difference
2133 */
2134 LongPrototype.sub = LongPrototype.subtract;
2135
2136 /**
2137 * Returns the product of this and the specified Long.
2138 * @param {!Long|number|string} multiplier Multiplier
2139 * @returns {!Long} Product
2140 */
2141 LongPrototype.multiply = function multiply(multiplier) {
2142 if (this.isZero())
2143 return ZERO;
2144 if (!isLong(multiplier))
2145 multiplier = fromValue(multiplier);
2146 if (multiplier.isZero())
2147 return ZERO;
2148 if (this.eq(MIN_VALUE))
2149 return multiplier.isOdd() ? MIN_VALUE : ZERO;
2150 if (multiplier.eq(MIN_VALUE))
2151 return this.isOdd() ? MIN_VALUE : ZERO;
2152
2153 if (this.isNegative()) {
2154 if (multiplier.isNegative())
2155 return this.neg().mul(multiplier.neg());
2156 else
2157 return this.neg().mul(multiplier).neg();
2158 } else if (multiplier.isNegative())
2159 return this.mul(multiplier.neg()).neg();
2160
2161 // If both longs are small, use float multiplication
2162 if (this.lt(TWO_PWR_24) && multiplier.lt(TWO_PWR_24))
2163 return fromNumber(this.toNumber() * multiplier.toNumber(), this.unsigned);
2164
2165 // Divide each long into 4 chunks of 16 bits, and then add up 4x4 products.
2166 // We can skip products that would overflow.
2167
2168 var a48 = this.high >>> 16;
2169 var a32 = this.high & 0xFFFF;
2170 var a16 = this.low >>> 16;
2171 var a00 = this.low & 0xFFFF;
2172
2173 var b48 = multiplier.high >>> 16;
2174 var b32 = multiplier.high & 0xFFFF;
2175 var b16 = multiplier.low >>> 16;
2176 var b00 = multiplier.low & 0xFFFF;
2177
2178 var c48 = 0, c32 = 0, c16 = 0, c00 = 0;
2179 c00 += a00 * b00;
2180 c16 += c00 >>> 16;
2181 c00 &= 0xFFFF;
2182 c16 += a16 * b00;
2183 c32 += c16 >>> 16;
2184 c16 &= 0xFFFF;
2185 c16 += a00 * b16;
2186 c32 += c16 >>> 16;
2187 c16 &= 0xFFFF;
2188 c32 += a32 * b00;
2189 c48 += c32 >>> 16;
2190 c32 &= 0xFFFF;
2191 c32 += a16 * b16;
2192 c48 += c32 >>> 16;
2193 c32 &= 0xFFFF;
2194 c32 += a00 * b32;
2195 c48 += c32 >>> 16;
2196 c32 &= 0xFFFF;
2197 c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48;
2198 c48 &= 0xFFFF;
2199 return fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned);
2200 };
2201
2202 /**
2203 * Returns the product of this and the specified Long. This is an alias of {@link Long#multiply}.
2204 * @function
2205 * @param {!Long|number|string} multiplier Multiplier
2206 * @returns {!Long} Product
2207 */
2208 LongPrototype.mul = LongPrototype.multiply;
2209
2210 /**
2211 * Returns this Long divided by the specified. The result is signed if this Long is signed or
2212 * unsigned if this Long is unsigned.
2213 * @param {!Long|number|string} divisor Divisor
2214 * @returns {!Long} Quotient
2215 */
2216 LongPrototype.divide = function divide(divisor) {
2217 if (!isLong(divisor))
2218 divisor = fromValue(divisor);
2219 if (divisor.isZero())
2220 throw Error('division by zero');
2221 if (this.isZero())
2222 return this.unsigned ? UZERO : ZERO;
2223 var approx, rem, res;
2224 if (!this.unsigned) {
2225 // This section is only relevant for signed longs and is derived from the
2226 // closure library as a whole.
2227 if (this.eq(MIN_VALUE)) {
2228 if (divisor.eq(ONE) || divisor.eq(NEG_ONE))
2229 return MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE
2230 else if (divisor.eq(MIN_VALUE))
2231 return ONE;
2232 else {
2233 // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|.
2234 var halfThis = this.shr(1);
2235 approx = halfThis.div(divisor).shl(1);
2236 if (approx.eq(ZERO)) {
2237 return divisor.isNegative() ? ONE : NEG_ONE;
2238 } else {
2239 rem = this.sub(divisor.mul(approx));
2240 res = approx.add(rem.div(divisor));
2241 return res;
2242 }
2243 }
2244 } else if (divisor.eq(MIN_VALUE))
2245 return this.unsigned ? UZERO : ZERO;
2246 if (this.isNegative()) {
2247 if (divisor.isNegative())
2248 return this.neg().div(divisor.neg());
2249 return this.neg().div(divisor).neg();
2250 } else if (divisor.isNegative())
2251 return this.div(divisor.neg()).neg();
2252 res = ZERO;
2253 } else {
2254 // The algorithm below has not been made for unsigned longs. It's therefore
2255 // required to take special care of the MSB prior to running it.
2256 if (!divisor.unsigned)
2257 divisor = divisor.toUnsigned();
2258 if (divisor.gt(this))
2259 return UZERO;
2260 if (divisor.gt(this.shru(1))) // 15 >>> 1 = 7 ; with divisor = 8 ; true
2261 return UONE;
2262 res = UZERO;
2263 }
2264
2265 // Repeat the following until the remainder is less than other: find a
2266 // floating-point that approximates remainder / other *from below*, add this
2267 // into the result, and subtract it from the remainder. It is critical that
2268 // the approximate value is less than or equal to the real value so that the
2269 // remainder never becomes negative.
2270 rem = this;
2271 while (rem.gte(divisor)) {
2272 // Approximate the result of division. This may be a little greater or
2273 // smaller than the actual value.
2274 approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber()));
2275
2276 // We will tweak the approximate result by changing it in the 48-th digit or
2277 // the smallest non-fractional digit, whichever is larger.
2278 var log2 = Math.ceil(Math.log(approx) / Math.LN2),
2279 delta = (log2 <= 48) ? 1 : pow_dbl(2, log2 - 48),
2280
2281 // Decrease the approximation until it is smaller than the remainder. Note
2282 // that if it is too large, the product overflows and is negative.
2283 approxRes = fromNumber(approx),
2284 approxRem = approxRes.mul(divisor);
2285 while (approxRem.isNegative() || approxRem.gt(rem)) {
2286 approx -= delta;
2287 approxRes = fromNumber(approx, this.unsigned);
2288 approxRem = approxRes.mul(divisor);
2289 }
2290
2291 // We know the answer can't be zero... and actually, zero would cause
2292 // infinite recursion since we would make no progress.
2293 if (approxRes.isZero())
2294 approxRes = ONE;
2295
2296 res = res.add(approxRes);
2297 rem = rem.sub(approxRem);
2298 }
2299 return res;
2300 };
2301
2302 /**
2303 * Returns this Long divided by the specified. This is an alias of {@link Long#divide}.
2304 * @function
2305 * @param {!Long|number|string} divisor Divisor
2306 * @returns {!Long} Quotient
2307 */
2308 LongPrototype.div = LongPrototype.divide;
2309
2310 /**
2311 * Returns this Long modulo the specified.
2312 * @param {!Long|number|string} divisor Divisor
2313 * @returns {!Long} Remainder
2314 */
2315 LongPrototype.modulo = function modulo(divisor) {
2316 if (!isLong(divisor))
2317 divisor = fromValue(divisor);
2318 return this.sub(this.div(divisor).mul(divisor));
2319 };
2320
2321 /**
2322 * Returns this Long modulo the specified. This is an alias of {@link Long#modulo}.
2323 * @function
2324 * @param {!Long|number|string} divisor Divisor
2325 * @returns {!Long} Remainder
2326 */
2327 LongPrototype.mod = LongPrototype.modulo;
2328
2329 /**
2330 * Returns the bitwise NOT of this Long.
2331 * @returns {!Long}
2332 */
2333 LongPrototype.not = function not() {
2334 return fromBits(~this.low, ~this.high, this.unsigned);
2335 };
2336
2337 /**
2338 * Returns the bitwise AND of this Long and the specified.
2339 * @param {!Long|number|string} other Other Long
2340 * @returns {!Long}
2341 */
2342 LongPrototype.and = function and(other) {
2343 if (!isLong(other))
2344 other = fromValue(other);
2345 return fromBits(this.low & other.low, this.high & other.high, this.unsigned);
2346 };
2347
2348 /**
2349 * Returns the bitwise OR of this Long and the specified.
2350 * @param {!Long|number|string} other Other Long
2351 * @returns {!Long}
2352 */
2353 LongPrototype.or = function or(other) {
2354 if (!isLong(other))
2355 other = fromValue(other);
2356 return fromBits(this.low | other.low, this.high | other.high, this.unsigned);
2357 };
2358
2359 /**
2360 * Returns the bitwise XOR of this Long and the given one.
2361 * @param {!Long|number|string} other Other Long
2362 * @returns {!Long}
2363 */
2364 LongPrototype.xor = function xor(other) {
2365 if (!isLong(other))
2366 other = fromValue(other);
2367 return fromBits(this.low ^ other.low, this.high ^ other.high, this.unsigned);
2368 };
2369
2370 /**
2371 * Returns this Long with bits shifted to the left by the given amount.
2372 * @param {number|!Long} numBits Number of bits
2373 * @returns {!Long} Shifted Long
2374 */
2375 LongPrototype.shiftLeft = function shiftLeft(numBits) {
2376 if (isLong(numBits))
2377 numBits = numBits.toInt();
2378 if ((numBits &= 63) === 0)
2379 return this;
2380 else if (numBits < 32)
2381 return fromBits(this.low << numBits, (this.high << numBits) | (this.low >>> (32 - numBits)), this.unsigned);
2382 else
2383 return fromBits(0, this.low << (numBits - 32), this.unsigned);
2384 };
2385
2386 /**
2387 * Returns this Long with bits shifted to the left by the given amount. This is an alias of {@link Long#shiftLeft}.
2388 * @function
2389 * @param {number|!Long} numBits Number of bits
2390 * @returns {!Long} Shifted Long
2391 */
2392 LongPrototype.shl = LongPrototype.shiftLeft;
2393
2394 /**
2395 * Returns this Long with bits arithmetically shifted to the right by the given amount.
2396 * @param {number|!Long} numBits Number of bits
2397 * @returns {!Long} Shifted Long
2398 */
2399 LongPrototype.shiftRight = function shiftRight(numBits) {
2400 if (isLong(numBits))
2401 numBits = numBits.toInt();
2402 if ((numBits &= 63) === 0)
2403 return this;
2404 else if (numBits < 32)
2405 return fromBits((this.low >>> numBits) | (this.high << (32 - numBits)), this.high >> numBits, this.unsigned);
2406 else
2407 return fromBits(this.high >> (numBits - 32), this.high >= 0 ? 0 : -1, this.unsigned);
2408 };
2409
2410 /**
2411 * Returns this Long with bits arithmetically shifted to the right by the given amount. This is an alias of {@link Long#shiftRight}.
2412 * @function
2413 * @param {number|!Long} numBits Number of bits
2414 * @returns {!Long} Shifted Long
2415 */
2416 LongPrototype.shr = LongPrototype.shiftRight;
2417
2418 /**
2419 * Returns this Long with bits logically shifted to the right by the given amount.
2420 * @param {number|!Long} numBits Number of bits
2421 * @returns {!Long} Shifted Long
2422 */
2423 LongPrototype.shiftRightUnsigned = function shiftRightUnsigned(numBits) {
2424 if (isLong(numBits))
2425 numBits = numBits.toInt();
2426 numBits &= 63;
2427 if (numBits === 0)
2428 return this;
2429 else {
2430 var high = this.high;
2431 if (numBits < 32) {
2432 var low = this.low;
2433 return fromBits((low >>> numBits) | (high << (32 - numBits)), high >>> numBits, this.unsigned);
2434 } else if (numBits === 32)
2435 return fromBits(high, 0, this.unsigned);
2436 else
2437 return fromBits(high >>> (numBits - 32), 0, this.unsigned);
2438 }
2439 };
2440
2441 /**
2442 * Returns this Long with bits logically shifted to the right by the given amount. This is an alias of {@link Long#shiftRightUnsigned}.
2443 * @function
2444 * @param {number|!Long} numBits Number of bits
2445 * @returns {!Long} Shifted Long
2446 */
2447 LongPrototype.shru = LongPrototype.shiftRightUnsigned;
2448
2449 /**
2450 * Converts this Long to signed.
2451 * @returns {!Long} Signed long
2452 */
2453 LongPrototype.toSigned = function toSigned() {
2454 if (!this.unsigned)
2455 return this;
2456 return fromBits(this.low, this.high, false);
2457 };
2458
2459 /**
2460 * Converts this Long to unsigned.
2461 * @returns {!Long} Unsigned long
2462 */
2463 LongPrototype.toUnsigned = function toUnsigned() {
2464 if (this.unsigned)
2465 return this;
2466 return fromBits(this.low, this.high, true);
2467 };
2468
2469 /**
2470 * Converts this Long to its byte representation.
2471 * @param {boolean=} le Whether little or big endian, defaults to big endian
2472 * @returns {!Array.<number>} Byte representation
2473 */
2474 LongPrototype.toBytes = function(le) {
2475 return le ? this.toBytesLE() : this.toBytesBE();
2476 };
2477
2478 /**
2479 * Converts this Long to its little endian byte representation.
2480 * @returns {!Array.<number>} Little endian byte representation
2481 */
2482 LongPrototype.toBytesLE = function() {
2483 var hi = this.high,
2484 lo = this.low;
2485 return [
2486 lo & 0xff,
2487 (lo >>> 8) & 0xff,
2488 (lo >>> 16) & 0xff,
2489 (lo >>> 24) & 0xff,
2490 hi & 0xff,
2491 (hi >>> 8) & 0xff,
2492 (hi >>> 16) & 0xff,
2493 (hi >>> 24) & 0xff
2494 ];
2495 };
2496
2497 /**
2498 * Converts this Long to its big endian byte representation.
2499 * @returns {!Array.<number>} Big endian byte representation
2500 */
2501 LongPrototype.toBytesBE = function() {
2502 var hi = this.high,
2503 lo = this.low;
2504 return [
2505 (hi >>> 24) & 0xff,
2506 (hi >>> 16) & 0xff,
2507 (hi >>> 8) & 0xff,
2508 hi & 0xff,
2509 (lo >>> 24) & 0xff,
2510 (lo >>> 16) & 0xff,
2511 (lo >>> 8) & 0xff,
2512 lo & 0xff
2513 ];
2514 };
2515
2516 return Long;
2517 });
2518 });
2519
2520 var bytebuffer = createCommonjsModule(function (module) {
2521 /*
2522 Copyright 2013-2014 Daniel Wirtz <dcode@dcode.io>
2523
2524 Licensed under the Apache License, Version 2.0 (the "License");
2525 you may not use this file except in compliance with the License.
2526 You may obtain a copy of the License at
2527
2528 http://www.apache.org/licenses/LICENSE-2.0
2529
2530 Unless required by applicable law or agreed to in writing, software
2531 distributed under the License is distributed on an "AS IS" BASIS,
2532 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2533 See the License for the specific language governing permissions and
2534 limitations under the License.
2535 */
2536
2537 /**
2538 * @license bytebuffer.js (c) 2015 Daniel Wirtz <dcode@dcode.io>
2539 * Backing buffer: ArrayBuffer, Accessor: Uint8Array
2540 * Released under the Apache License, Version 2.0
2541 * see: https://github.com/dcodeIO/bytebuffer.js for details
2542 */
2543 (function(global, factory) {
2544
2545 /* AMD */ if (typeof commonjsRequire === 'function' && 'object' === "object" && module && module["exports"])
2546 module['exports'] = (function() {
2547 var Long; try { Long = long_1; } catch (e) {}
2548 return factory(Long);
2549 })();
2550 /* Global */ else
2551 (global["dcodeIO"] = global["dcodeIO"] || {})["ByteBuffer"] = factory(global["dcodeIO"]["Long"]);
2552
2553 })(commonjsGlobal, function(Long) {
2554
2555 /**
2556 * Constructs a new ByteBuffer.
2557 * @class The swiss army knife for binary data in JavaScript.
2558 * @exports ByteBuffer
2559 * @constructor
2560 * @param {number=} capacity Initial capacity. Defaults to {@link ByteBuffer.DEFAULT_CAPACITY}.
2561 * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
2562 * {@link ByteBuffer.DEFAULT_ENDIAN}.
2563 * @param {boolean=} noAssert Whether to skip assertions of offsets and values. Defaults to
2564 * {@link ByteBuffer.DEFAULT_NOASSERT}.
2565 * @expose
2566 */
2567 var ByteBuffer = function(capacity, littleEndian, noAssert) {
2568 if (typeof capacity === 'undefined')
2569 capacity = ByteBuffer.DEFAULT_CAPACITY;
2570 if (typeof littleEndian === 'undefined')
2571 littleEndian = ByteBuffer.DEFAULT_ENDIAN;
2572 if (typeof noAssert === 'undefined')
2573 noAssert = ByteBuffer.DEFAULT_NOASSERT;
2574 if (!noAssert) {
2575 capacity = capacity | 0;
2576 if (capacity < 0)
2577 throw RangeError("Illegal capacity");
2578 littleEndian = !!littleEndian;
2579 noAssert = !!noAssert;
2580 }
2581
2582 /**
2583 * Backing ArrayBuffer.
2584 * @type {!ArrayBuffer}
2585 * @expose
2586 */
2587 this.buffer = capacity === 0 ? EMPTY_BUFFER : new ArrayBuffer(capacity);
2588
2589 /**
2590 * Uint8Array utilized to manipulate the backing buffer. Becomes `null` if the backing buffer has a capacity of `0`.
2591 * @type {?Uint8Array}
2592 * @expose
2593 */
2594 this.view = capacity === 0 ? null : new Uint8Array(this.buffer);
2595
2596 /**
2597 * Absolute read/write offset.
2598 * @type {number}
2599 * @expose
2600 * @see ByteBuffer#flip
2601 * @see ByteBuffer#clear
2602 */
2603 this.offset = 0;
2604
2605 /**
2606 * Marked offset.
2607 * @type {number}
2608 * @expose
2609 * @see ByteBuffer#mark
2610 * @see ByteBuffer#reset
2611 */
2612 this.markedOffset = -1;
2613
2614 /**
2615 * Absolute limit of the contained data. Set to the backing buffer's capacity upon allocation.
2616 * @type {number}
2617 * @expose
2618 * @see ByteBuffer#flip
2619 * @see ByteBuffer#clear
2620 */
2621 this.limit = capacity;
2622
2623 /**
2624 * Whether to use little endian byte order, defaults to `false` for big endian.
2625 * @type {boolean}
2626 * @expose
2627 */
2628 this.littleEndian = littleEndian;
2629
2630 /**
2631 * Whether to skip assertions of offsets and values, defaults to `false`.
2632 * @type {boolean}
2633 * @expose
2634 */
2635 this.noAssert = noAssert;
2636 };
2637
2638 /**
2639 * ByteBuffer version.
2640 * @type {string}
2641 * @const
2642 * @expose
2643 */
2644 ByteBuffer.VERSION = "5.0.1";
2645
2646 /**
2647 * Little endian constant that can be used instead of its boolean value. Evaluates to `true`.
2648 * @type {boolean}
2649 * @const
2650 * @expose
2651 */
2652 ByteBuffer.LITTLE_ENDIAN = true;
2653
2654 /**
2655 * Big endian constant that can be used instead of its boolean value. Evaluates to `false`.
2656 * @type {boolean}
2657 * @const
2658 * @expose
2659 */
2660 ByteBuffer.BIG_ENDIAN = false;
2661
2662 /**
2663 * Default initial capacity of `16`.
2664 * @type {number}
2665 * @expose
2666 */
2667 ByteBuffer.DEFAULT_CAPACITY = 16;
2668
2669 /**
2670 * Default endianess of `false` for big endian.
2671 * @type {boolean}
2672 * @expose
2673 */
2674 ByteBuffer.DEFAULT_ENDIAN = ByteBuffer.BIG_ENDIAN;
2675
2676 /**
2677 * Default no assertions flag of `false`.
2678 * @type {boolean}
2679 * @expose
2680 */
2681 ByteBuffer.DEFAULT_NOASSERT = false;
2682
2683 /**
2684 * A `Long` class for representing a 64-bit two's-complement integer value. May be `null` if Long.js has not been loaded
2685 * and int64 support is not available.
2686 * @type {?Long}
2687 * @const
2688 * @see https://github.com/dcodeIO/long.js
2689 * @expose
2690 */
2691 ByteBuffer.Long = Long || null;
2692
2693 /**
2694 * @alias ByteBuffer.prototype
2695 * @inner
2696 */
2697 var ByteBufferPrototype = ByteBuffer.prototype;
2698
2699 /**
2700 * An indicator used to reliably determine if an object is a ByteBuffer or not.
2701 * @type {boolean}
2702 * @const
2703 * @expose
2704 * @private
2705 */
2706 ByteBufferPrototype.__isByteBuffer__;
2707
2708 Object.defineProperty(ByteBufferPrototype, "__isByteBuffer__", {
2709 value: true,
2710 enumerable: false,
2711 configurable: false
2712 });
2713
2714 // helpers
2715
2716 /**
2717 * @type {!ArrayBuffer}
2718 * @inner
2719 */
2720 var EMPTY_BUFFER = new ArrayBuffer(0);
2721
2722 /**
2723 * String.fromCharCode reference for compile-time renaming.
2724 * @type {function(...number):string}
2725 * @inner
2726 */
2727 var stringFromCharCode = String.fromCharCode;
2728
2729 /**
2730 * Creates a source function for a string.
2731 * @param {string} s String to read from
2732 * @returns {function():number|null} Source function returning the next char code respectively `null` if there are
2733 * no more characters left.
2734 * @throws {TypeError} If the argument is invalid
2735 * @inner
2736 */
2737 function stringSource(s) {
2738 var i=0; return function() {
2739 return i < s.length ? s.charCodeAt(i++) : null;
2740 };
2741 }
2742
2743 /**
2744 * Creates a destination function for a string.
2745 * @returns {function(number=):undefined|string} Destination function successively called with the next char code.
2746 * Returns the final string when called without arguments.
2747 * @inner
2748 */
2749 function stringDestination() {
2750 var cs = [], ps = []; return function() {
2751 if (arguments.length === 0)
2752 return ps.join('')+stringFromCharCode.apply(String, cs);
2753 if (cs.length + arguments.length > 1024)
2754 ps.push(stringFromCharCode.apply(String, cs)),
2755 cs.length = 0;
2756 Array.prototype.push.apply(cs, arguments);
2757 };
2758 }
2759
2760 /**
2761 * Gets the accessor type.
2762 * @returns {Function} `Buffer` under node.js, `Uint8Array` respectively `DataView` in the browser (classes)
2763 * @expose
2764 */
2765 ByteBuffer.accessor = function() {
2766 return Uint8Array;
2767 };
2768 /**
2769 * Allocates a new ByteBuffer backed by a buffer of the specified capacity.
2770 * @param {number=} capacity Initial capacity. Defaults to {@link ByteBuffer.DEFAULT_CAPACITY}.
2771 * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
2772 * {@link ByteBuffer.DEFAULT_ENDIAN}.
2773 * @param {boolean=} noAssert Whether to skip assertions of offsets and values. Defaults to
2774 * {@link ByteBuffer.DEFAULT_NOASSERT}.
2775 * @returns {!ByteBuffer}
2776 * @expose
2777 */
2778 ByteBuffer.allocate = function(capacity, littleEndian, noAssert) {
2779 return new ByteBuffer(capacity, littleEndian, noAssert);
2780 };
2781
2782 /**
2783 * Concatenates multiple ByteBuffers into one.
2784 * @param {!Array.<!ByteBuffer|!ArrayBuffer|!Uint8Array|string>} buffers Buffers to concatenate
2785 * @param {(string|boolean)=} encoding String encoding if `buffers` contains a string ("base64", "hex", "binary",
2786 * defaults to "utf8")
2787 * @param {boolean=} littleEndian Whether to use little or big endian byte order for the resulting ByteBuffer. Defaults
2788 * to {@link ByteBuffer.DEFAULT_ENDIAN}.
2789 * @param {boolean=} noAssert Whether to skip assertions of offsets and values for the resulting ByteBuffer. Defaults to
2790 * {@link ByteBuffer.DEFAULT_NOASSERT}.
2791 * @returns {!ByteBuffer} Concatenated ByteBuffer
2792 * @expose
2793 */
2794 ByteBuffer.concat = function(buffers, encoding, littleEndian, noAssert) {
2795 if (typeof encoding === 'boolean' || typeof encoding !== 'string') {
2796 noAssert = littleEndian;
2797 littleEndian = encoding;
2798 encoding = undefined;
2799 }
2800 var capacity = 0;
2801 for (var i=0, k=buffers.length, length; i<k; ++i) {
2802 if (!ByteBuffer.isByteBuffer(buffers[i]))
2803 buffers[i] = ByteBuffer.wrap(buffers[i], encoding);
2804 length = buffers[i].limit - buffers[i].offset;
2805 if (length > 0) capacity += length;
2806 }
2807 if (capacity === 0)
2808 return new ByteBuffer(0, littleEndian, noAssert);
2809 var bb = new ByteBuffer(capacity, littleEndian, noAssert),
2810 bi;
2811 i=0; while (i<k) {
2812 bi = buffers[i++];
2813 length = bi.limit - bi.offset;
2814 if (length <= 0) continue;
2815 bb.view.set(bi.view.subarray(bi.offset, bi.limit), bb.offset);
2816 bb.offset += length;
2817 }
2818 bb.limit = bb.offset;
2819 bb.offset = 0;
2820 return bb;
2821 };
2822
2823 /**
2824 * Tests if the specified type is a ByteBuffer.
2825 * @param {*} bb ByteBuffer to test
2826 * @returns {boolean} `true` if it is a ByteBuffer, otherwise `false`
2827 * @expose
2828 */
2829 ByteBuffer.isByteBuffer = function(bb) {
2830 return (bb && bb["__isByteBuffer__"]) === true;
2831 };
2832 /**
2833 * Gets the backing buffer type.
2834 * @returns {Function} `Buffer` under node.js, `ArrayBuffer` in the browser (classes)
2835 * @expose
2836 */
2837 ByteBuffer.type = function() {
2838 return ArrayBuffer;
2839 };
2840 /**
2841 * Wraps a buffer or a string. Sets the allocated ByteBuffer's {@link ByteBuffer#offset} to `0` and its
2842 * {@link ByteBuffer#limit} to the length of the wrapped data.
2843 * @param {!ByteBuffer|!ArrayBuffer|!Uint8Array|string|!Array.<number>} buffer Anything that can be wrapped
2844 * @param {(string|boolean)=} encoding String encoding if `buffer` is a string ("base64", "hex", "binary", defaults to
2845 * "utf8")
2846 * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
2847 * {@link ByteBuffer.DEFAULT_ENDIAN}.
2848 * @param {boolean=} noAssert Whether to skip assertions of offsets and values. Defaults to
2849 * {@link ByteBuffer.DEFAULT_NOASSERT}.
2850 * @returns {!ByteBuffer} A ByteBuffer wrapping `buffer`
2851 * @expose
2852 */
2853 ByteBuffer.wrap = function(buffer, encoding, littleEndian, noAssert) {
2854 if (typeof encoding !== 'string') {
2855 noAssert = littleEndian;
2856 littleEndian = encoding;
2857 encoding = undefined;
2858 }
2859 if (typeof buffer === 'string') {
2860 if (typeof encoding === 'undefined')
2861 encoding = "utf8";
2862 switch (encoding) {
2863 case "base64":
2864 return ByteBuffer.fromBase64(buffer, littleEndian);
2865 case "hex":
2866 return ByteBuffer.fromHex(buffer, littleEndian);
2867 case "binary":
2868 return ByteBuffer.fromBinary(buffer, littleEndian);
2869 case "utf8":
2870 return ByteBuffer.fromUTF8(buffer, littleEndian);
2871 case "debug":
2872 return ByteBuffer.fromDebug(buffer, littleEndian);
2873 default:
2874 throw Error("Unsupported encoding: "+encoding);
2875 }
2876 }
2877 if (buffer === null || typeof buffer !== 'object')
2878 throw TypeError("Illegal buffer");
2879 var bb;
2880 if (ByteBuffer.isByteBuffer(buffer)) {
2881 bb = ByteBufferPrototype.clone.call(buffer);
2882 bb.markedOffset = -1;
2883 return bb;
2884 }
2885 if (buffer instanceof Uint8Array) { // Extract ArrayBuffer from Uint8Array
2886 bb = new ByteBuffer(0, littleEndian, noAssert);
2887 if (buffer.length > 0) { // Avoid references to more than one EMPTY_BUFFER
2888 bb.buffer = buffer.buffer;
2889 bb.offset = buffer.byteOffset;
2890 bb.limit = buffer.byteOffset + buffer.byteLength;
2891 bb.view = new Uint8Array(buffer.buffer);
2892 }
2893 } else if (buffer instanceof ArrayBuffer) { // Reuse ArrayBuffer
2894 bb = new ByteBuffer(0, littleEndian, noAssert);
2895 if (buffer.byteLength > 0) {
2896 bb.buffer = buffer;
2897 bb.offset = 0;
2898 bb.limit = buffer.byteLength;
2899 bb.view = buffer.byteLength > 0 ? new Uint8Array(buffer) : null;
2900 }
2901 } else if (Object.prototype.toString.call(buffer) === "[object Array]") { // Create from octets
2902 bb = new ByteBuffer(buffer.length, littleEndian, noAssert);
2903 bb.limit = buffer.length;
2904 for (var i=0; i<buffer.length; ++i)
2905 bb.view[i] = buffer[i];
2906 } else
2907 throw TypeError("Illegal buffer"); // Otherwise fail
2908 return bb;
2909 };
2910
2911 /**
2912 * Writes the array as a bitset.
2913 * @param {Array<boolean>} value Array of booleans to write
2914 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `length` if omitted.
2915 * @returns {!ByteBuffer}
2916 * @expose
2917 */
2918 ByteBufferPrototype.writeBitSet = function(value, offset) {
2919 var relative = typeof offset === 'undefined';
2920 if (relative) offset = this.offset;
2921 if (!this.noAssert) {
2922 if (!(value instanceof Array))
2923 throw TypeError("Illegal BitSet: Not an array");
2924 if (typeof offset !== 'number' || offset % 1 !== 0)
2925 throw TypeError("Illegal offset: "+offset+" (not an integer)");
2926 offset >>>= 0;
2927 if (offset < 0 || offset + 0 > this.buffer.byteLength)
2928 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
2929 }
2930
2931 var start = offset,
2932 bits = value.length,
2933 bytes = (bits >> 3),
2934 bit = 0,
2935 k;
2936
2937 offset += this.writeVarint32(bits,offset);
2938
2939 while(bytes--) {
2940 k = (!!value[bit++] & 1) |
2941 ((!!value[bit++] & 1) << 1) |
2942 ((!!value[bit++] & 1) << 2) |
2943 ((!!value[bit++] & 1) << 3) |
2944 ((!!value[bit++] & 1) << 4) |
2945 ((!!value[bit++] & 1) << 5) |
2946 ((!!value[bit++] & 1) << 6) |
2947 ((!!value[bit++] & 1) << 7);
2948 this.writeByte(k,offset++);
2949 }
2950
2951 if(bit < bits) {
2952 var m = 0; k = 0;
2953 while(bit < bits) k = k | ((!!value[bit++] & 1) << (m++));
2954 this.writeByte(k,offset++);
2955 }
2956
2957 if (relative) {
2958 this.offset = offset;
2959 return this;
2960 }
2961 return offset - start;
2962 };
2963
2964 /**
2965 * Reads a BitSet as an array of booleans.
2966 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `length` if omitted.
2967 * @returns {Array<boolean>
2968 * @expose
2969 */
2970 ByteBufferPrototype.readBitSet = function(offset) {
2971 var relative = typeof offset === 'undefined';
2972 if (relative) offset = this.offset;
2973
2974 var ret = this.readVarint32(offset),
2975 bits = ret.value,
2976 bytes = (bits >> 3),
2977 bit = 0,
2978 value = [],
2979 k;
2980
2981 offset += ret.length;
2982
2983 while(bytes--) {
2984 k = this.readByte(offset++);
2985 value[bit++] = !!(k & 0x01);
2986 value[bit++] = !!(k & 0x02);
2987 value[bit++] = !!(k & 0x04);
2988 value[bit++] = !!(k & 0x08);
2989 value[bit++] = !!(k & 0x10);
2990 value[bit++] = !!(k & 0x20);
2991 value[bit++] = !!(k & 0x40);
2992 value[bit++] = !!(k & 0x80);
2993 }
2994
2995 if(bit < bits) {
2996 var m = 0;
2997 k = this.readByte(offset++);
2998 while(bit < bits) value[bit++] = !!((k >> (m++)) & 1);
2999 }
3000
3001 if (relative) {
3002 this.offset = offset;
3003 }
3004 return value;
3005 };
3006 /**
3007 * Reads the specified number of bytes.
3008 * @param {number} length Number of bytes to read
3009 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `length` if omitted.
3010 * @returns {!ByteBuffer}
3011 * @expose
3012 */
3013 ByteBufferPrototype.readBytes = function(length, offset) {
3014 var relative = typeof offset === 'undefined';
3015 if (relative) offset = this.offset;
3016 if (!this.noAssert) {
3017 if (typeof offset !== 'number' || offset % 1 !== 0)
3018 throw TypeError("Illegal offset: "+offset+" (not an integer)");
3019 offset >>>= 0;
3020 if (offset < 0 || offset + length > this.buffer.byteLength)
3021 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+length+") <= "+this.buffer.byteLength);
3022 }
3023 var slice = this.slice(offset, offset + length);
3024 if (relative) this.offset += length;
3025 return slice;
3026 };
3027
3028 /**
3029 * Writes a payload of bytes. This is an alias of {@link ByteBuffer#append}.
3030 * @function
3031 * @param {!ByteBuffer|!ArrayBuffer|!Uint8Array|string} source Data to write. If `source` is a ByteBuffer, its offsets
3032 * will be modified according to the performed read operation.
3033 * @param {(string|number)=} encoding Encoding if `data` is a string ("base64", "hex", "binary", defaults to "utf8")
3034 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
3035 * written if omitted.
3036 * @returns {!ByteBuffer} this
3037 * @expose
3038 */
3039 ByteBufferPrototype.writeBytes = ByteBufferPrototype.append;
3040
3041 // types/ints/int8
3042
3043 /**
3044 * Writes an 8bit signed integer.
3045 * @param {number} value Value to write
3046 * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `1` if omitted.
3047 * @returns {!ByteBuffer} this
3048 * @expose
3049 */
3050 ByteBufferPrototype.writeInt8 = function(value, offset) {
3051 var relative = typeof offset === 'undefined';
3052 if (relative) offset = this.offset;
3053 if (!this.noAssert) {
3054 if (typeof value !== 'number' || value % 1 !== 0)
3055 throw TypeError("Illegal value: "+value+" (not an integer)");
3056 value |= 0;
3057 if (typeof offset !== 'number' || offset % 1 !== 0)
3058 throw TypeError("Illegal offset: "+offset+" (not an integer)");
3059 offset >>>= 0;
3060 if (offset < 0 || offset + 0 > this.buffer.byteLength)
3061 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
3062 }
3063 offset += 1;
3064 var capacity0 = this.buffer.byteLength;
3065 if (offset > capacity0)
3066 this.resize((capacity0 *= 2) > offset ? capacity0 : offset);
3067 offset -= 1;
3068 this.view[offset] = value;
3069 if (relative) this.offset += 1;
3070 return this;
3071 };
3072
3073 /**
3074 * Writes an 8bit signed integer. This is an alias of {@link ByteBuffer#writeInt8}.
3075 * @function
3076 * @param {number} value Value to write
3077 * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `1` if omitted.
3078 * @returns {!ByteBuffer} this
3079 * @expose
3080 */
3081 ByteBufferPrototype.writeByte = ByteBufferPrototype.writeInt8;
3082
3083 /**
3084 * Reads an 8bit signed integer.
3085 * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `1` if omitted.
3086 * @returns {number} Value read
3087 * @expose
3088 */
3089 ByteBufferPrototype.readInt8 = function(offset) {
3090 var relative = typeof offset === 'undefined';
3091 if (relative) offset = this.offset;
3092 if (!this.noAssert) {
3093 if (typeof offset !== 'number' || offset % 1 !== 0)
3094 throw TypeError("Illegal offset: "+offset+" (not an integer)");
3095 offset >>>= 0;
3096 if (offset < 0 || offset + 1 > this.buffer.byteLength)
3097 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+1+") <= "+this.buffer.byteLength);
3098 }
3099 var value = this.view[offset];
3100 if ((value & 0x80) === 0x80) value = -(0xFF - value + 1); // Cast to signed
3101 if (relative) this.offset += 1;
3102 return value;
3103 };
3104
3105 /**
3106 * Reads an 8bit signed integer. This is an alias of {@link ByteBuffer#readInt8}.
3107 * @function
3108 * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `1` if omitted.
3109 * @returns {number} Value read
3110 * @expose
3111 */
3112 ByteBufferPrototype.readByte = ByteBufferPrototype.readInt8;
3113
3114 /**
3115 * Writes an 8bit unsigned integer.
3116 * @param {number} value Value to write
3117 * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `1` if omitted.
3118 * @returns {!ByteBuffer} this
3119 * @expose
3120 */
3121 ByteBufferPrototype.writeUint8 = function(value, offset) {
3122 var relative = typeof offset === 'undefined';
3123 if (relative) offset = this.offset;
3124 if (!this.noAssert) {
3125 if (typeof value !== 'number' || value % 1 !== 0)
3126 throw TypeError("Illegal value: "+value+" (not an integer)");
3127 value >>>= 0;
3128 if (typeof offset !== 'number' || offset % 1 !== 0)
3129 throw TypeError("Illegal offset: "+offset+" (not an integer)");
3130 offset >>>= 0;
3131 if (offset < 0 || offset + 0 > this.buffer.byteLength)
3132 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
3133 }
3134 offset += 1;
3135 var capacity1 = this.buffer.byteLength;
3136 if (offset > capacity1)
3137 this.resize((capacity1 *= 2) > offset ? capacity1 : offset);
3138 offset -= 1;
3139 this.view[offset] = value;
3140 if (relative) this.offset += 1;
3141 return this;
3142 };
3143
3144 /**
3145 * Writes an 8bit unsigned integer. This is an alias of {@link ByteBuffer#writeUint8}.
3146 * @function
3147 * @param {number} value Value to write
3148 * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `1` if omitted.
3149 * @returns {!ByteBuffer} this
3150 * @expose
3151 */
3152 ByteBufferPrototype.writeUInt8 = ByteBufferPrototype.writeUint8;
3153
3154 /**
3155 * Reads an 8bit unsigned integer.
3156 * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `1` if omitted.
3157 * @returns {number} Value read
3158 * @expose
3159 */
3160 ByteBufferPrototype.readUint8 = function(offset) {
3161 var relative = typeof offset === 'undefined';
3162 if (relative) offset = this.offset;
3163 if (!this.noAssert) {
3164 if (typeof offset !== 'number' || offset % 1 !== 0)
3165 throw TypeError("Illegal offset: "+offset+" (not an integer)");
3166 offset >>>= 0;
3167 if (offset < 0 || offset + 1 > this.buffer.byteLength)
3168 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+1+") <= "+this.buffer.byteLength);
3169 }
3170 var value = this.view[offset];
3171 if (relative) this.offset += 1;
3172 return value;
3173 };
3174
3175 /**
3176 * Reads an 8bit unsigned integer. This is an alias of {@link ByteBuffer#readUint8}.
3177 * @function
3178 * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `1` if omitted.
3179 * @returns {number} Value read
3180 * @expose
3181 */
3182 ByteBufferPrototype.readUInt8 = ByteBufferPrototype.readUint8;
3183
3184 // types/ints/int16
3185
3186 /**
3187 * Writes a 16bit signed integer.
3188 * @param {number} value Value to write
3189 * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `2` if omitted.
3190 * @throws {TypeError} If `offset` or `value` is not a valid number
3191 * @throws {RangeError} If `offset` is out of bounds
3192 * @expose
3193 */
3194 ByteBufferPrototype.writeInt16 = function(value, offset) {
3195 var relative = typeof offset === 'undefined';
3196 if (relative) offset = this.offset;
3197 if (!this.noAssert) {
3198 if (typeof value !== 'number' || value % 1 !== 0)
3199 throw TypeError("Illegal value: "+value+" (not an integer)");
3200 value |= 0;
3201 if (typeof offset !== 'number' || offset % 1 !== 0)
3202 throw TypeError("Illegal offset: "+offset+" (not an integer)");
3203 offset >>>= 0;
3204 if (offset < 0 || offset + 0 > this.buffer.byteLength)
3205 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
3206 }
3207 offset += 2;
3208 var capacity2 = this.buffer.byteLength;
3209 if (offset > capacity2)
3210 this.resize((capacity2 *= 2) > offset ? capacity2 : offset);
3211 offset -= 2;
3212 if (this.littleEndian) {
3213 this.view[offset+1] = (value & 0xFF00) >>> 8;
3214 this.view[offset ] = value & 0x00FF;
3215 } else {
3216 this.view[offset] = (value & 0xFF00) >>> 8;
3217 this.view[offset+1] = value & 0x00FF;
3218 }
3219 if (relative) this.offset += 2;
3220 return this;
3221 };
3222
3223 /**
3224 * Writes a 16bit signed integer. This is an alias of {@link ByteBuffer#writeInt16}.
3225 * @function
3226 * @param {number} value Value to write
3227 * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `2` if omitted.
3228 * @throws {TypeError} If `offset` or `value` is not a valid number
3229 * @throws {RangeError} If `offset` is out of bounds
3230 * @expose
3231 */
3232 ByteBufferPrototype.writeShort = ByteBufferPrototype.writeInt16;
3233
3234 /**
3235 * Reads a 16bit signed integer.
3236 * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `2` if omitted.
3237 * @returns {number} Value read
3238 * @throws {TypeError} If `offset` is not a valid number
3239 * @throws {RangeError} If `offset` is out of bounds
3240 * @expose
3241 */
3242 ByteBufferPrototype.readInt16 = function(offset) {
3243 var relative = typeof offset === 'undefined';
3244 if (relative) offset = this.offset;
3245 if (!this.noAssert) {
3246 if (typeof offset !== 'number' || offset % 1 !== 0)
3247 throw TypeError("Illegal offset: "+offset+" (not an integer)");
3248 offset >>>= 0;
3249 if (offset < 0 || offset + 2 > this.buffer.byteLength)
3250 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+2+") <= "+this.buffer.byteLength);
3251 }
3252 var value = 0;
3253 if (this.littleEndian) {
3254 value = this.view[offset ];
3255 value |= this.view[offset+1] << 8;
3256 } else {
3257 value = this.view[offset ] << 8;
3258 value |= this.view[offset+1];
3259 }
3260 if ((value & 0x8000) === 0x8000) value = -(0xFFFF - value + 1); // Cast to signed
3261 if (relative) this.offset += 2;
3262 return value;
3263 };
3264
3265 /**
3266 * Reads a 16bit signed integer. This is an alias of {@link ByteBuffer#readInt16}.
3267 * @function
3268 * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `2` if omitted.
3269 * @returns {number} Value read
3270 * @throws {TypeError} If `offset` is not a valid number
3271 * @throws {RangeError} If `offset` is out of bounds
3272 * @expose
3273 */
3274 ByteBufferPrototype.readShort = ByteBufferPrototype.readInt16;
3275
3276 /**
3277 * Writes a 16bit unsigned integer.
3278 * @param {number} value Value to write
3279 * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `2` if omitted.
3280 * @throws {TypeError} If `offset` or `value` is not a valid number
3281 * @throws {RangeError} If `offset` is out of bounds
3282 * @expose
3283 */
3284 ByteBufferPrototype.writeUint16 = function(value, offset) {
3285 var relative = typeof offset === 'undefined';
3286 if (relative) offset = this.offset;
3287 if (!this.noAssert) {
3288 if (typeof value !== 'number' || value % 1 !== 0)
3289 throw TypeError("Illegal value: "+value+" (not an integer)");
3290 value >>>= 0;
3291 if (typeof offset !== 'number' || offset % 1 !== 0)
3292 throw TypeError("Illegal offset: "+offset+" (not an integer)");
3293 offset >>>= 0;
3294 if (offset < 0 || offset + 0 > this.buffer.byteLength)
3295 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
3296 }
3297 offset += 2;
3298 var capacity3 = this.buffer.byteLength;
3299 if (offset > capacity3)
3300 this.resize((capacity3 *= 2) > offset ? capacity3 : offset);
3301 offset -= 2;
3302 if (this.littleEndian) {
3303 this.view[offset+1] = (value & 0xFF00) >>> 8;
3304 this.view[offset ] = value & 0x00FF;
3305 } else {
3306 this.view[offset] = (value & 0xFF00) >>> 8;
3307 this.view[offset+1] = value & 0x00FF;
3308 }
3309 if (relative) this.offset += 2;
3310 return this;
3311 };
3312
3313 /**
3314 * Writes a 16bit unsigned integer. This is an alias of {@link ByteBuffer#writeUint16}.
3315 * @function
3316 * @param {number} value Value to write
3317 * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `2` if omitted.
3318 * @throws {TypeError} If `offset` or `value` is not a valid number
3319 * @throws {RangeError} If `offset` is out of bounds
3320 * @expose
3321 */
3322 ByteBufferPrototype.writeUInt16 = ByteBufferPrototype.writeUint16;
3323
3324 /**
3325 * Reads a 16bit unsigned integer.
3326 * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `2` if omitted.
3327 * @returns {number} Value read
3328 * @throws {TypeError} If `offset` is not a valid number
3329 * @throws {RangeError} If `offset` is out of bounds
3330 * @expose
3331 */
3332 ByteBufferPrototype.readUint16 = function(offset) {
3333 var relative = typeof offset === 'undefined';
3334 if (relative) offset = this.offset;
3335 if (!this.noAssert) {
3336 if (typeof offset !== 'number' || offset % 1 !== 0)
3337 throw TypeError("Illegal offset: "+offset+" (not an integer)");
3338 offset >>>= 0;
3339 if (offset < 0 || offset + 2 > this.buffer.byteLength)
3340 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+2+") <= "+this.buffer.byteLength);
3341 }
3342 var value = 0;
3343 if (this.littleEndian) {
3344 value = this.view[offset ];
3345 value |= this.view[offset+1] << 8;
3346 } else {
3347 value = this.view[offset ] << 8;
3348 value |= this.view[offset+1];
3349 }
3350 if (relative) this.offset += 2;
3351 return value;
3352 };
3353
3354 /**
3355 * Reads a 16bit unsigned integer. This is an alias of {@link ByteBuffer#readUint16}.
3356 * @function
3357 * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `2` if omitted.
3358 * @returns {number} Value read
3359 * @throws {TypeError} If `offset` is not a valid number
3360 * @throws {RangeError} If `offset` is out of bounds
3361 * @expose
3362 */
3363 ByteBufferPrototype.readUInt16 = ByteBufferPrototype.readUint16;
3364
3365 // types/ints/int32
3366
3367 /**
3368 * Writes a 32bit signed integer.
3369 * @param {number} value Value to write
3370 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
3371 * @expose
3372 */
3373 ByteBufferPrototype.writeInt32 = function(value, offset) {
3374 var relative = typeof offset === 'undefined';
3375 if (relative) offset = this.offset;
3376 if (!this.noAssert) {
3377 if (typeof value !== 'number' || value % 1 !== 0)
3378 throw TypeError("Illegal value: "+value+" (not an integer)");
3379 value |= 0;
3380 if (typeof offset !== 'number' || offset % 1 !== 0)
3381 throw TypeError("Illegal offset: "+offset+" (not an integer)");
3382 offset >>>= 0;
3383 if (offset < 0 || offset + 0 > this.buffer.byteLength)
3384 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
3385 }
3386 offset += 4;
3387 var capacity4 = this.buffer.byteLength;
3388 if (offset > capacity4)
3389 this.resize((capacity4 *= 2) > offset ? capacity4 : offset);
3390 offset -= 4;
3391 if (this.littleEndian) {
3392 this.view[offset+3] = (value >>> 24) & 0xFF;
3393 this.view[offset+2] = (value >>> 16) & 0xFF;
3394 this.view[offset+1] = (value >>> 8) & 0xFF;
3395 this.view[offset ] = value & 0xFF;
3396 } else {
3397 this.view[offset ] = (value >>> 24) & 0xFF;
3398 this.view[offset+1] = (value >>> 16) & 0xFF;
3399 this.view[offset+2] = (value >>> 8) & 0xFF;
3400 this.view[offset+3] = value & 0xFF;
3401 }
3402 if (relative) this.offset += 4;
3403 return this;
3404 };
3405
3406 /**
3407 * Writes a 32bit signed integer. This is an alias of {@link ByteBuffer#writeInt32}.
3408 * @param {number} value Value to write
3409 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
3410 * @expose
3411 */
3412 ByteBufferPrototype.writeInt = ByteBufferPrototype.writeInt32;
3413
3414 /**
3415 * Reads a 32bit signed integer.
3416 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
3417 * @returns {number} Value read
3418 * @expose
3419 */
3420 ByteBufferPrototype.readInt32 = function(offset) {
3421 var relative = typeof offset === 'undefined';
3422 if (relative) offset = this.offset;
3423 if (!this.noAssert) {
3424 if (typeof offset !== 'number' || offset % 1 !== 0)
3425 throw TypeError("Illegal offset: "+offset+" (not an integer)");
3426 offset >>>= 0;
3427 if (offset < 0 || offset + 4 > this.buffer.byteLength)
3428 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+4+") <= "+this.buffer.byteLength);
3429 }
3430 var value = 0;
3431 if (this.littleEndian) {
3432 value = this.view[offset+2] << 16;
3433 value |= this.view[offset+1] << 8;
3434 value |= this.view[offset ];
3435 value += this.view[offset+3] << 24 >>> 0;
3436 } else {
3437 value = this.view[offset+1] << 16;
3438 value |= this.view[offset+2] << 8;
3439 value |= this.view[offset+3];
3440 value += this.view[offset ] << 24 >>> 0;
3441 }
3442 value |= 0; // Cast to signed
3443 if (relative) this.offset += 4;
3444 return value;
3445 };
3446
3447 /**
3448 * Reads a 32bit signed integer. This is an alias of {@link ByteBuffer#readInt32}.
3449 * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `4` if omitted.
3450 * @returns {number} Value read
3451 * @expose
3452 */
3453 ByteBufferPrototype.readInt = ByteBufferPrototype.readInt32;
3454
3455 /**
3456 * Writes a 32bit unsigned integer.
3457 * @param {number} value Value to write
3458 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
3459 * @expose
3460 */
3461 ByteBufferPrototype.writeUint32 = function(value, offset) {
3462 var relative = typeof offset === 'undefined';
3463 if (relative) offset = this.offset;
3464 if (!this.noAssert) {
3465 if (typeof value !== 'number' || value % 1 !== 0)
3466 throw TypeError("Illegal value: "+value+" (not an integer)");
3467 value >>>= 0;
3468 if (typeof offset !== 'number' || offset % 1 !== 0)
3469 throw TypeError("Illegal offset: "+offset+" (not an integer)");
3470 offset >>>= 0;
3471 if (offset < 0 || offset + 0 > this.buffer.byteLength)
3472 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
3473 }
3474 offset += 4;
3475 var capacity5 = this.buffer.byteLength;
3476 if (offset > capacity5)
3477 this.resize((capacity5 *= 2) > offset ? capacity5 : offset);
3478 offset -= 4;
3479 if (this.littleEndian) {
3480 this.view[offset+3] = (value >>> 24) & 0xFF;
3481 this.view[offset+2] = (value >>> 16) & 0xFF;
3482 this.view[offset+1] = (value >>> 8) & 0xFF;
3483 this.view[offset ] = value & 0xFF;
3484 } else {
3485 this.view[offset ] = (value >>> 24) & 0xFF;
3486 this.view[offset+1] = (value >>> 16) & 0xFF;
3487 this.view[offset+2] = (value >>> 8) & 0xFF;
3488 this.view[offset+3] = value & 0xFF;
3489 }
3490 if (relative) this.offset += 4;
3491 return this;
3492 };
3493
3494 /**
3495 * Writes a 32bit unsigned integer. This is an alias of {@link ByteBuffer#writeUint32}.
3496 * @function
3497 * @param {number} value Value to write
3498 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
3499 * @expose
3500 */
3501 ByteBufferPrototype.writeUInt32 = ByteBufferPrototype.writeUint32;
3502
3503 /**
3504 * Reads a 32bit unsigned integer.
3505 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
3506 * @returns {number} Value read
3507 * @expose
3508 */
3509 ByteBufferPrototype.readUint32 = function(offset) {
3510 var relative = typeof offset === 'undefined';
3511 if (relative) offset = this.offset;
3512 if (!this.noAssert) {
3513 if (typeof offset !== 'number' || offset % 1 !== 0)
3514 throw TypeError("Illegal offset: "+offset+" (not an integer)");
3515 offset >>>= 0;
3516 if (offset < 0 || offset + 4 > this.buffer.byteLength)
3517 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+4+") <= "+this.buffer.byteLength);
3518 }
3519 var value = 0;
3520 if (this.littleEndian) {
3521 value = this.view[offset+2] << 16;
3522 value |= this.view[offset+1] << 8;
3523 value |= this.view[offset ];
3524 value += this.view[offset+3] << 24 >>> 0;
3525 } else {
3526 value = this.view[offset+1] << 16;
3527 value |= this.view[offset+2] << 8;
3528 value |= this.view[offset+3];
3529 value += this.view[offset ] << 24 >>> 0;
3530 }
3531 if (relative) this.offset += 4;
3532 return value;
3533 };
3534
3535 /**
3536 * Reads a 32bit unsigned integer. This is an alias of {@link ByteBuffer#readUint32}.
3537 * @function
3538 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
3539 * @returns {number} Value read
3540 * @expose
3541 */
3542 ByteBufferPrototype.readUInt32 = ByteBufferPrototype.readUint32;
3543
3544 // types/ints/int64
3545
3546 if (Long) {
3547
3548 /**
3549 * Writes a 64bit signed integer.
3550 * @param {number|!Long} value Value to write
3551 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
3552 * @returns {!ByteBuffer} this
3553 * @expose
3554 */
3555 ByteBufferPrototype.writeInt64 = function(value, offset) {
3556 var relative = typeof offset === 'undefined';
3557 if (relative) offset = this.offset;
3558 if (!this.noAssert) {
3559 if (typeof value === 'number')
3560 value = Long.fromNumber(value);
3561 else if (typeof value === 'string')
3562 value = Long.fromString(value);
3563 else if (!(value && value instanceof Long))
3564 throw TypeError("Illegal value: "+value+" (not an integer or Long)");
3565 if (typeof offset !== 'number' || offset % 1 !== 0)
3566 throw TypeError("Illegal offset: "+offset+" (not an integer)");
3567 offset >>>= 0;
3568 if (offset < 0 || offset + 0 > this.buffer.byteLength)
3569 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
3570 }
3571 if (typeof value === 'number')
3572 value = Long.fromNumber(value);
3573 else if (typeof value === 'string')
3574 value = Long.fromString(value);
3575 offset += 8;
3576 var capacity6 = this.buffer.byteLength;
3577 if (offset > capacity6)
3578 this.resize((capacity6 *= 2) > offset ? capacity6 : offset);
3579 offset -= 8;
3580 var lo = value.low,
3581 hi = value.high;
3582 if (this.littleEndian) {
3583 this.view[offset+3] = (lo >>> 24) & 0xFF;
3584 this.view[offset+2] = (lo >>> 16) & 0xFF;
3585 this.view[offset+1] = (lo >>> 8) & 0xFF;
3586 this.view[offset ] = lo & 0xFF;
3587 offset += 4;
3588 this.view[offset+3] = (hi >>> 24) & 0xFF;
3589 this.view[offset+2] = (hi >>> 16) & 0xFF;
3590 this.view[offset+1] = (hi >>> 8) & 0xFF;
3591 this.view[offset ] = hi & 0xFF;
3592 } else {
3593 this.view[offset ] = (hi >>> 24) & 0xFF;
3594 this.view[offset+1] = (hi >>> 16) & 0xFF;
3595 this.view[offset+2] = (hi >>> 8) & 0xFF;
3596 this.view[offset+3] = hi & 0xFF;
3597 offset += 4;
3598 this.view[offset ] = (lo >>> 24) & 0xFF;
3599 this.view[offset+1] = (lo >>> 16) & 0xFF;
3600 this.view[offset+2] = (lo >>> 8) & 0xFF;
3601 this.view[offset+3] = lo & 0xFF;
3602 }
3603 if (relative) this.offset += 8;
3604 return this;
3605 };
3606
3607 /**
3608 * Writes a 64bit signed integer. This is an alias of {@link ByteBuffer#writeInt64}.
3609 * @param {number|!Long} value Value to write
3610 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
3611 * @returns {!ByteBuffer} this
3612 * @expose
3613 */
3614 ByteBufferPrototype.writeLong = ByteBufferPrototype.writeInt64;
3615
3616 /**
3617 * Reads a 64bit signed integer.
3618 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
3619 * @returns {!Long}
3620 * @expose
3621 */
3622 ByteBufferPrototype.readInt64 = function(offset) {
3623 var relative = typeof offset === 'undefined';
3624 if (relative) offset = this.offset;
3625 if (!this.noAssert) {
3626 if (typeof offset !== 'number' || offset % 1 !== 0)
3627 throw TypeError("Illegal offset: "+offset+" (not an integer)");
3628 offset >>>= 0;
3629 if (offset < 0 || offset + 8 > this.buffer.byteLength)
3630 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+8+") <= "+this.buffer.byteLength);
3631 }
3632 var lo = 0,
3633 hi = 0;
3634 if (this.littleEndian) {
3635 lo = this.view[offset+2] << 16;
3636 lo |= this.view[offset+1] << 8;
3637 lo |= this.view[offset ];
3638 lo += this.view[offset+3] << 24 >>> 0;
3639 offset += 4;
3640 hi = this.view[offset+2] << 16;
3641 hi |= this.view[offset+1] << 8;
3642 hi |= this.view[offset ];
3643 hi += this.view[offset+3] << 24 >>> 0;
3644 } else {
3645 hi = this.view[offset+1] << 16;
3646 hi |= this.view[offset+2] << 8;
3647 hi |= this.view[offset+3];
3648 hi += this.view[offset ] << 24 >>> 0;
3649 offset += 4;
3650 lo = this.view[offset+1] << 16;
3651 lo |= this.view[offset+2] << 8;
3652 lo |= this.view[offset+3];
3653 lo += this.view[offset ] << 24 >>> 0;
3654 }
3655 var value = new Long(lo, hi, false);
3656 if (relative) this.offset += 8;
3657 return value;
3658 };
3659
3660 /**
3661 * Reads a 64bit signed integer. This is an alias of {@link ByteBuffer#readInt64}.
3662 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
3663 * @returns {!Long}
3664 * @expose
3665 */
3666 ByteBufferPrototype.readLong = ByteBufferPrototype.readInt64;
3667
3668 /**
3669 * Writes a 64bit unsigned integer.
3670 * @param {number|!Long} value Value to write
3671 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
3672 * @returns {!ByteBuffer} this
3673 * @expose
3674 */
3675 ByteBufferPrototype.writeUint64 = function(value, offset) {
3676 var relative = typeof offset === 'undefined';
3677 if (relative) offset = this.offset;
3678 if (!this.noAssert) {
3679 if (typeof value === 'number')
3680 value = Long.fromNumber(value);
3681 else if (typeof value === 'string')
3682 value = Long.fromString(value);
3683 else if (!(value && value instanceof Long))
3684 throw TypeError("Illegal value: "+value+" (not an integer or Long)");
3685 if (typeof offset !== 'number' || offset % 1 !== 0)
3686 throw TypeError("Illegal offset: "+offset+" (not an integer)");
3687 offset >>>= 0;
3688 if (offset < 0 || offset + 0 > this.buffer.byteLength)
3689 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
3690 }
3691 if (typeof value === 'number')
3692 value = Long.fromNumber(value);
3693 else if (typeof value === 'string')
3694 value = Long.fromString(value);
3695 offset += 8;
3696 var capacity7 = this.buffer.byteLength;
3697 if (offset > capacity7)
3698 this.resize((capacity7 *= 2) > offset ? capacity7 : offset);
3699 offset -= 8;
3700 var lo = value.low,
3701 hi = value.high;
3702 if (this.littleEndian) {
3703 this.view[offset+3] = (lo >>> 24) & 0xFF;
3704 this.view[offset+2] = (lo >>> 16) & 0xFF;
3705 this.view[offset+1] = (lo >>> 8) & 0xFF;
3706 this.view[offset ] = lo & 0xFF;
3707 offset += 4;
3708 this.view[offset+3] = (hi >>> 24) & 0xFF;
3709 this.view[offset+2] = (hi >>> 16) & 0xFF;
3710 this.view[offset+1] = (hi >>> 8) & 0xFF;
3711 this.view[offset ] = hi & 0xFF;
3712 } else {
3713 this.view[offset ] = (hi >>> 24) & 0xFF;
3714 this.view[offset+1] = (hi >>> 16) & 0xFF;
3715 this.view[offset+2] = (hi >>> 8) & 0xFF;
3716 this.view[offset+3] = hi & 0xFF;
3717 offset += 4;
3718 this.view[offset ] = (lo >>> 24) & 0xFF;
3719 this.view[offset+1] = (lo >>> 16) & 0xFF;
3720 this.view[offset+2] = (lo >>> 8) & 0xFF;
3721 this.view[offset+3] = lo & 0xFF;
3722 }
3723 if (relative) this.offset += 8;
3724 return this;
3725 };
3726
3727 /**
3728 * Writes a 64bit unsigned integer. This is an alias of {@link ByteBuffer#writeUint64}.
3729 * @function
3730 * @param {number|!Long} value Value to write
3731 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
3732 * @returns {!ByteBuffer} this
3733 * @expose
3734 */
3735 ByteBufferPrototype.writeUInt64 = ByteBufferPrototype.writeUint64;
3736
3737 /**
3738 * Reads a 64bit unsigned integer.
3739 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
3740 * @returns {!Long}
3741 * @expose
3742 */
3743 ByteBufferPrototype.readUint64 = function(offset) {
3744 var relative = typeof offset === 'undefined';
3745 if (relative) offset = this.offset;
3746 if (!this.noAssert) {
3747 if (typeof offset !== 'number' || offset % 1 !== 0)
3748 throw TypeError("Illegal offset: "+offset+" (not an integer)");
3749 offset >>>= 0;
3750 if (offset < 0 || offset + 8 > this.buffer.byteLength)
3751 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+8+") <= "+this.buffer.byteLength);
3752 }
3753 var lo = 0,
3754 hi = 0;
3755 if (this.littleEndian) {
3756 lo = this.view[offset+2] << 16;
3757 lo |= this.view[offset+1] << 8;
3758 lo |= this.view[offset ];
3759 lo += this.view[offset+3] << 24 >>> 0;
3760 offset += 4;
3761 hi = this.view[offset+2] << 16;
3762 hi |= this.view[offset+1] << 8;
3763 hi |= this.view[offset ];
3764 hi += this.view[offset+3] << 24 >>> 0;
3765 } else {
3766 hi = this.view[offset+1] << 16;
3767 hi |= this.view[offset+2] << 8;
3768 hi |= this.view[offset+3];
3769 hi += this.view[offset ] << 24 >>> 0;
3770 offset += 4;
3771 lo = this.view[offset+1] << 16;
3772 lo |= this.view[offset+2] << 8;
3773 lo |= this.view[offset+3];
3774 lo += this.view[offset ] << 24 >>> 0;
3775 }
3776 var value = new Long(lo, hi, true);
3777 if (relative) this.offset += 8;
3778 return value;
3779 };
3780
3781 /**
3782 * Reads a 64bit unsigned integer. This is an alias of {@link ByteBuffer#readUint64}.
3783 * @function
3784 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
3785 * @returns {!Long}
3786 * @expose
3787 */
3788 ByteBufferPrototype.readUInt64 = ByteBufferPrototype.readUint64;
3789
3790 } // Long
3791
3792
3793 // types/floats/float32
3794
3795 /*
3796 ieee754 - https://github.com/feross/ieee754
3797
3798 The MIT License (MIT)
3799
3800 Copyright (c) Feross Aboukhadijeh
3801
3802 Permission is hereby granted, free of charge, to any person obtaining a copy
3803 of this software and associated documentation files (the "Software"), to deal
3804 in the Software without restriction, including without limitation the rights
3805 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
3806 copies of the Software, and to permit persons to whom the Software is
3807 furnished to do so, subject to the following conditions:
3808
3809 The above copyright notice and this permission notice shall be included in
3810 all copies or substantial portions of the Software.
3811
3812 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
3813 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
3814 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
3815 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
3816 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
3817 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
3818 THE SOFTWARE.
3819 */
3820
3821 /**
3822 * Reads an IEEE754 float from a byte array.
3823 * @param {!Array} buffer
3824 * @param {number} offset
3825 * @param {boolean} isLE
3826 * @param {number} mLen
3827 * @param {number} nBytes
3828 * @returns {number}
3829 * @inner
3830 */
3831 function ieee754_read(buffer, offset, isLE, mLen, nBytes) {
3832 var e, m,
3833 eLen = nBytes * 8 - mLen - 1,
3834 eMax = (1 << eLen) - 1,
3835 eBias = eMax >> 1,
3836 nBits = -7,
3837 i = isLE ? (nBytes - 1) : 0,
3838 d = isLE ? -1 : 1,
3839 s = buffer[offset + i];
3840
3841 i += d;
3842
3843 e = s & ((1 << (-nBits)) - 1);
3844 s >>= (-nBits);
3845 nBits += eLen;
3846 for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
3847
3848 m = e & ((1 << (-nBits)) - 1);
3849 e >>= (-nBits);
3850 nBits += mLen;
3851 for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
3852
3853 if (e === 0) {
3854 e = 1 - eBias;
3855 } else if (e === eMax) {
3856 return m ? NaN : ((s ? -1 : 1) * Infinity);
3857 } else {
3858 m = m + Math.pow(2, mLen);
3859 e = e - eBias;
3860 }
3861 return (s ? -1 : 1) * m * Math.pow(2, e - mLen);
3862 }
3863
3864 /**
3865 * Writes an IEEE754 float to a byte array.
3866 * @param {!Array} buffer
3867 * @param {number} value
3868 * @param {number} offset
3869 * @param {boolean} isLE
3870 * @param {number} mLen
3871 * @param {number} nBytes
3872 * @inner
3873 */
3874 function ieee754_write(buffer, value, offset, isLE, mLen, nBytes) {
3875 var e, m, c,
3876 eLen = nBytes * 8 - mLen - 1,
3877 eMax = (1 << eLen) - 1,
3878 eBias = eMax >> 1,
3879 rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0),
3880 i = isLE ? 0 : (nBytes - 1),
3881 d = isLE ? 1 : -1,
3882 s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0;
3883
3884 value = Math.abs(value);
3885
3886 if (isNaN(value) || value === Infinity) {
3887 m = isNaN(value) ? 1 : 0;
3888 e = eMax;
3889 } else {
3890 e = Math.floor(Math.log(value) / Math.LN2);
3891 if (value * (c = Math.pow(2, -e)) < 1) {
3892 e--;
3893 c *= 2;
3894 }
3895 if (e + eBias >= 1) {
3896 value += rt / c;
3897 } else {
3898 value += rt * Math.pow(2, 1 - eBias);
3899 }
3900 if (value * c >= 2) {
3901 e++;
3902 c /= 2;
3903 }
3904
3905 if (e + eBias >= eMax) {
3906 m = 0;
3907 e = eMax;
3908 } else if (e + eBias >= 1) {
3909 m = (value * c - 1) * Math.pow(2, mLen);
3910 e = e + eBias;
3911 } else {
3912 m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
3913 e = 0;
3914 }
3915 }
3916
3917 for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
3918
3919 e = (e << mLen) | m;
3920 eLen += mLen;
3921 for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
3922
3923 buffer[offset + i - d] |= s * 128;
3924 }
3925
3926 /**
3927 * Writes a 32bit float.
3928 * @param {number} value Value to write
3929 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
3930 * @returns {!ByteBuffer} this
3931 * @expose
3932 */
3933 ByteBufferPrototype.writeFloat32 = function(value, offset) {
3934 var relative = typeof offset === 'undefined';
3935 if (relative) offset = this.offset;
3936 if (!this.noAssert) {
3937 if (typeof value !== 'number')
3938 throw TypeError("Illegal value: "+value+" (not a number)");
3939 if (typeof offset !== 'number' || offset % 1 !== 0)
3940 throw TypeError("Illegal offset: "+offset+" (not an integer)");
3941 offset >>>= 0;
3942 if (offset < 0 || offset + 0 > this.buffer.byteLength)
3943 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
3944 }
3945 offset += 4;
3946 var capacity8 = this.buffer.byteLength;
3947 if (offset > capacity8)
3948 this.resize((capacity8 *= 2) > offset ? capacity8 : offset);
3949 offset -= 4;
3950 ieee754_write(this.view, value, offset, this.littleEndian, 23, 4);
3951 if (relative) this.offset += 4;
3952 return this;
3953 };
3954
3955 /**
3956 * Writes a 32bit float. This is an alias of {@link ByteBuffer#writeFloat32}.
3957 * @function
3958 * @param {number} value Value to write
3959 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
3960 * @returns {!ByteBuffer} this
3961 * @expose
3962 */
3963 ByteBufferPrototype.writeFloat = ByteBufferPrototype.writeFloat32;
3964
3965 /**
3966 * Reads a 32bit float.
3967 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
3968 * @returns {number}
3969 * @expose
3970 */
3971 ByteBufferPrototype.readFloat32 = function(offset) {
3972 var relative = typeof offset === 'undefined';
3973 if (relative) offset = this.offset;
3974 if (!this.noAssert) {
3975 if (typeof offset !== 'number' || offset % 1 !== 0)
3976 throw TypeError("Illegal offset: "+offset+" (not an integer)");
3977 offset >>>= 0;
3978 if (offset < 0 || offset + 4 > this.buffer.byteLength)
3979 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+4+") <= "+this.buffer.byteLength);
3980 }
3981 var value = ieee754_read(this.view, offset, this.littleEndian, 23, 4);
3982 if (relative) this.offset += 4;
3983 return value;
3984 };
3985
3986 /**
3987 * Reads a 32bit float. This is an alias of {@link ByteBuffer#readFloat32}.
3988 * @function
3989 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
3990 * @returns {number}
3991 * @expose
3992 */
3993 ByteBufferPrototype.readFloat = ByteBufferPrototype.readFloat32;
3994
3995 // types/floats/float64
3996
3997 /**
3998 * Writes a 64bit float.
3999 * @param {number} value Value to write
4000 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
4001 * @returns {!ByteBuffer} this
4002 * @expose
4003 */
4004 ByteBufferPrototype.writeFloat64 = function(value, offset) {
4005 var relative = typeof offset === 'undefined';
4006 if (relative) offset = this.offset;
4007 if (!this.noAssert) {
4008 if (typeof value !== 'number')
4009 throw TypeError("Illegal value: "+value+" (not a number)");
4010 if (typeof offset !== 'number' || offset % 1 !== 0)
4011 throw TypeError("Illegal offset: "+offset+" (not an integer)");
4012 offset >>>= 0;
4013 if (offset < 0 || offset + 0 > this.buffer.byteLength)
4014 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
4015 }
4016 offset += 8;
4017 var capacity9 = this.buffer.byteLength;
4018 if (offset > capacity9)
4019 this.resize((capacity9 *= 2) > offset ? capacity9 : offset);
4020 offset -= 8;
4021 ieee754_write(this.view, value, offset, this.littleEndian, 52, 8);
4022 if (relative) this.offset += 8;
4023 return this;
4024 };
4025
4026 /**
4027 * Writes a 64bit float. This is an alias of {@link ByteBuffer#writeFloat64}.
4028 * @function
4029 * @param {number} value Value to write
4030 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
4031 * @returns {!ByteBuffer} this
4032 * @expose
4033 */
4034 ByteBufferPrototype.writeDouble = ByteBufferPrototype.writeFloat64;
4035
4036 /**
4037 * Reads a 64bit float.
4038 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
4039 * @returns {number}
4040 * @expose
4041 */
4042 ByteBufferPrototype.readFloat64 = function(offset) {
4043 var relative = typeof offset === 'undefined';
4044 if (relative) offset = this.offset;
4045 if (!this.noAssert) {
4046 if (typeof offset !== 'number' || offset % 1 !== 0)
4047 throw TypeError("Illegal offset: "+offset+" (not an integer)");
4048 offset >>>= 0;
4049 if (offset < 0 || offset + 8 > this.buffer.byteLength)
4050 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+8+") <= "+this.buffer.byteLength);
4051 }
4052 var value = ieee754_read(this.view, offset, this.littleEndian, 52, 8);
4053 if (relative) this.offset += 8;
4054 return value;
4055 };
4056
4057 /**
4058 * Reads a 64bit float. This is an alias of {@link ByteBuffer#readFloat64}.
4059 * @function
4060 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
4061 * @returns {number}
4062 * @expose
4063 */
4064 ByteBufferPrototype.readDouble = ByteBufferPrototype.readFloat64;
4065
4066
4067 // types/varints/varint32
4068
4069 /**
4070 * Maximum number of bytes required to store a 32bit base 128 variable-length integer.
4071 * @type {number}
4072 * @const
4073 * @expose
4074 */
4075 ByteBuffer.MAX_VARINT32_BYTES = 5;
4076
4077 /**
4078 * Calculates the actual number of bytes required to store a 32bit base 128 variable-length integer.
4079 * @param {number} value Value to encode
4080 * @returns {number} Number of bytes required. Capped to {@link ByteBuffer.MAX_VARINT32_BYTES}
4081 * @expose
4082 */
4083 ByteBuffer.calculateVarint32 = function(value) {
4084 // ref: src/google/protobuf/io/coded_stream.cc
4085 value = value >>> 0;
4086 if (value < 1 << 7 ) return 1;
4087 else if (value < 1 << 14) return 2;
4088 else if (value < 1 << 21) return 3;
4089 else if (value < 1 << 28) return 4;
4090 else return 5;
4091 };
4092
4093 /**
4094 * Zigzag encodes a signed 32bit integer so that it can be effectively used with varint encoding.
4095 * @param {number} n Signed 32bit integer
4096 * @returns {number} Unsigned zigzag encoded 32bit integer
4097 * @expose
4098 */
4099 ByteBuffer.zigZagEncode32 = function(n) {
4100 return (((n |= 0) << 1) ^ (n >> 31)) >>> 0; // ref: src/google/protobuf/wire_format_lite.h
4101 };
4102
4103 /**
4104 * Decodes a zigzag encoded signed 32bit integer.
4105 * @param {number} n Unsigned zigzag encoded 32bit integer
4106 * @returns {number} Signed 32bit integer
4107 * @expose
4108 */
4109 ByteBuffer.zigZagDecode32 = function(n) {
4110 return ((n >>> 1) ^ -(n & 1)) | 0; // // ref: src/google/protobuf/wire_format_lite.h
4111 };
4112
4113 /**
4114 * Writes a 32bit base 128 variable-length integer.
4115 * @param {number} value Value to write
4116 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
4117 * written if omitted.
4118 * @returns {!ByteBuffer|number} this if `offset` is omitted, else the actual number of bytes written
4119 * @expose
4120 */
4121 ByteBufferPrototype.writeVarint32 = function(value, offset) {
4122 var relative = typeof offset === 'undefined';
4123 if (relative) offset = this.offset;
4124 if (!this.noAssert) {
4125 if (typeof value !== 'number' || value % 1 !== 0)
4126 throw TypeError("Illegal value: "+value+" (not an integer)");
4127 value |= 0;
4128 if (typeof offset !== 'number' || offset % 1 !== 0)
4129 throw TypeError("Illegal offset: "+offset+" (not an integer)");
4130 offset >>>= 0;
4131 if (offset < 0 || offset + 0 > this.buffer.byteLength)
4132 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
4133 }
4134 var size = ByteBuffer.calculateVarint32(value),
4135 b;
4136 offset += size;
4137 var capacity10 = this.buffer.byteLength;
4138 if (offset > capacity10)
4139 this.resize((capacity10 *= 2) > offset ? capacity10 : offset);
4140 offset -= size;
4141 value >>>= 0;
4142 while (value >= 0x80) {
4143 b = (value & 0x7f) | 0x80;
4144 this.view[offset++] = b;
4145 value >>>= 7;
4146 }
4147 this.view[offset++] = value;
4148 if (relative) {
4149 this.offset = offset;
4150 return this;
4151 }
4152 return size;
4153 };
4154
4155 /**
4156 * Writes a zig-zag encoded (signed) 32bit base 128 variable-length integer.
4157 * @param {number} value Value to write
4158 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
4159 * written if omitted.
4160 * @returns {!ByteBuffer|number} this if `offset` is omitted, else the actual number of bytes written
4161 * @expose
4162 */
4163 ByteBufferPrototype.writeVarint32ZigZag = function(value, offset) {
4164 return this.writeVarint32(ByteBuffer.zigZagEncode32(value), offset);
4165 };
4166
4167 /**
4168 * Reads a 32bit base 128 variable-length integer.
4169 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
4170 * written if omitted.
4171 * @returns {number|!{value: number, length: number}} The value read if offset is omitted, else the value read
4172 * and the actual number of bytes read.
4173 * @throws {Error} If it's not a valid varint. Has a property `truncated = true` if there is not enough data available
4174 * to fully decode the varint.
4175 * @expose
4176 */
4177 ByteBufferPrototype.readVarint32 = function(offset) {
4178 var relative = typeof offset === 'undefined';
4179 if (relative) offset = this.offset;
4180 if (!this.noAssert) {
4181 if (typeof offset !== 'number' || offset % 1 !== 0)
4182 throw TypeError("Illegal offset: "+offset+" (not an integer)");
4183 offset >>>= 0;
4184 if (offset < 0 || offset + 1 > this.buffer.byteLength)
4185 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+1+") <= "+this.buffer.byteLength);
4186 }
4187 var c = 0,
4188 value = 0 >>> 0,
4189 b;
4190 do {
4191 if (!this.noAssert && offset > this.limit) {
4192 var err = Error("Truncated");
4193 err['truncated'] = true;
4194 throw err;
4195 }
4196 b = this.view[offset++];
4197 if (c < 5)
4198 value |= (b & 0x7f) << (7*c);
4199 ++c;
4200 } while ((b & 0x80) !== 0);
4201 value |= 0;
4202 if (relative) {
4203 this.offset = offset;
4204 return value;
4205 }
4206 return {
4207 "value": value,
4208 "length": c
4209 };
4210 };
4211
4212 /**
4213 * Reads a zig-zag encoded (signed) 32bit base 128 variable-length integer.
4214 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
4215 * written if omitted.
4216 * @returns {number|!{value: number, length: number}} The value read if offset is omitted, else the value read
4217 * and the actual number of bytes read.
4218 * @throws {Error} If it's not a valid varint
4219 * @expose
4220 */
4221 ByteBufferPrototype.readVarint32ZigZag = function(offset) {
4222 var val = this.readVarint32(offset);
4223 if (typeof val === 'object')
4224 val["value"] = ByteBuffer.zigZagDecode32(val["value"]);
4225 else
4226 val = ByteBuffer.zigZagDecode32(val);
4227 return val;
4228 };
4229
4230 // types/varints/varint64
4231
4232 if (Long) {
4233
4234 /**
4235 * Maximum number of bytes required to store a 64bit base 128 variable-length integer.
4236 * @type {number}
4237 * @const
4238 * @expose
4239 */
4240 ByteBuffer.MAX_VARINT64_BYTES = 10;
4241
4242 /**
4243 * Calculates the actual number of bytes required to store a 64bit base 128 variable-length integer.
4244 * @param {number|!Long} value Value to encode
4245 * @returns {number} Number of bytes required. Capped to {@link ByteBuffer.MAX_VARINT64_BYTES}
4246 * @expose
4247 */
4248 ByteBuffer.calculateVarint64 = function(value) {
4249 if (typeof value === 'number')
4250 value = Long.fromNumber(value);
4251 else if (typeof value === 'string')
4252 value = Long.fromString(value);
4253 // ref: src/google/protobuf/io/coded_stream.cc
4254 var part0 = value.toInt() >>> 0,
4255 part1 = value.shiftRightUnsigned(28).toInt() >>> 0,
4256 part2 = value.shiftRightUnsigned(56).toInt() >>> 0;
4257 if (part2 == 0) {
4258 if (part1 == 0) {
4259 if (part0 < 1 << 14)
4260 return part0 < 1 << 7 ? 1 : 2;
4261 else
4262 return part0 < 1 << 21 ? 3 : 4;
4263 } else {
4264 if (part1 < 1 << 14)
4265 return part1 < 1 << 7 ? 5 : 6;
4266 else
4267 return part1 < 1 << 21 ? 7 : 8;
4268 }
4269 } else
4270 return part2 < 1 << 7 ? 9 : 10;
4271 };
4272
4273 /**
4274 * Zigzag encodes a signed 64bit integer so that it can be effectively used with varint encoding.
4275 * @param {number|!Long} value Signed long
4276 * @returns {!Long} Unsigned zigzag encoded long
4277 * @expose
4278 */
4279 ByteBuffer.zigZagEncode64 = function(value) {
4280 if (typeof value === 'number')
4281 value = Long.fromNumber(value, false);
4282 else if (typeof value === 'string')
4283 value = Long.fromString(value, false);
4284 else if (value.unsigned !== false) value = value.toSigned();
4285 // ref: src/google/protobuf/wire_format_lite.h
4286 return value.shiftLeft(1).xor(value.shiftRight(63)).toUnsigned();
4287 };
4288
4289 /**
4290 * Decodes a zigzag encoded signed 64bit integer.
4291 * @param {!Long|number} value Unsigned zigzag encoded long or JavaScript number
4292 * @returns {!Long} Signed long
4293 * @expose
4294 */
4295 ByteBuffer.zigZagDecode64 = function(value) {
4296 if (typeof value === 'number')
4297 value = Long.fromNumber(value, false);
4298 else if (typeof value === 'string')
4299 value = Long.fromString(value, false);
4300 else if (value.unsigned !== false) value = value.toSigned();
4301 // ref: src/google/protobuf/wire_format_lite.h
4302 return value.shiftRightUnsigned(1).xor(value.and(Long.ONE).toSigned().negate()).toSigned();
4303 };
4304
4305 /**
4306 * Writes a 64bit base 128 variable-length integer.
4307 * @param {number|Long} value Value to write
4308 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
4309 * written if omitted.
4310 * @returns {!ByteBuffer|number} `this` if offset is omitted, else the actual number of bytes written.
4311 * @expose
4312 */
4313 ByteBufferPrototype.writeVarint64 = function(value, offset) {
4314 var relative = typeof offset === 'undefined';
4315 if (relative) offset = this.offset;
4316 if (!this.noAssert) {
4317 if (typeof value === 'number')
4318 value = Long.fromNumber(value);
4319 else if (typeof value === 'string')
4320 value = Long.fromString(value);
4321 else if (!(value && value instanceof Long))
4322 throw TypeError("Illegal value: "+value+" (not an integer or Long)");
4323 if (typeof offset !== 'number' || offset % 1 !== 0)
4324 throw TypeError("Illegal offset: "+offset+" (not an integer)");
4325 offset >>>= 0;
4326 if (offset < 0 || offset + 0 > this.buffer.byteLength)
4327 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
4328 }
4329 if (typeof value === 'number')
4330 value = Long.fromNumber(value, false);
4331 else if (typeof value === 'string')
4332 value = Long.fromString(value, false);
4333 else if (value.unsigned !== false) value = value.toSigned();
4334 var size = ByteBuffer.calculateVarint64(value),
4335 part0 = value.toInt() >>> 0,
4336 part1 = value.shiftRightUnsigned(28).toInt() >>> 0,
4337 part2 = value.shiftRightUnsigned(56).toInt() >>> 0;
4338 offset += size;
4339 var capacity11 = this.buffer.byteLength;
4340 if (offset > capacity11)
4341 this.resize((capacity11 *= 2) > offset ? capacity11 : offset);
4342 offset -= size;
4343 switch (size) {
4344 case 10: this.view[offset+9] = (part2 >>> 7) & 0x01;
4345 case 9 : this.view[offset+8] = size !== 9 ? (part2 ) | 0x80 : (part2 ) & 0x7F;
4346 case 8 : this.view[offset+7] = size !== 8 ? (part1 >>> 21) | 0x80 : (part1 >>> 21) & 0x7F;
4347 case 7 : this.view[offset+6] = size !== 7 ? (part1 >>> 14) | 0x80 : (part1 >>> 14) & 0x7F;
4348 case 6 : this.view[offset+5] = size !== 6 ? (part1 >>> 7) | 0x80 : (part1 >>> 7) & 0x7F;
4349 case 5 : this.view[offset+4] = size !== 5 ? (part1 ) | 0x80 : (part1 ) & 0x7F;
4350 case 4 : this.view[offset+3] = size !== 4 ? (part0 >>> 21) | 0x80 : (part0 >>> 21) & 0x7F;
4351 case 3 : this.view[offset+2] = size !== 3 ? (part0 >>> 14) | 0x80 : (part0 >>> 14) & 0x7F;
4352 case 2 : this.view[offset+1] = size !== 2 ? (part0 >>> 7) | 0x80 : (part0 >>> 7) & 0x7F;
4353 case 1 : this.view[offset ] = size !== 1 ? (part0 ) | 0x80 : (part0 ) & 0x7F;
4354 }
4355 if (relative) {
4356 this.offset += size;
4357 return this;
4358 } else {
4359 return size;
4360 }
4361 };
4362
4363 /**
4364 * Writes a zig-zag encoded 64bit base 128 variable-length integer.
4365 * @param {number|Long} value Value to write
4366 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
4367 * written if omitted.
4368 * @returns {!ByteBuffer|number} `this` if offset is omitted, else the actual number of bytes written.
4369 * @expose
4370 */
4371 ByteBufferPrototype.writeVarint64ZigZag = function(value, offset) {
4372 return this.writeVarint64(ByteBuffer.zigZagEncode64(value), offset);
4373 };
4374
4375 /**
4376 * Reads a 64bit base 128 variable-length integer. Requires Long.js.
4377 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
4378 * read if omitted.
4379 * @returns {!Long|!{value: Long, length: number}} The value read if offset is omitted, else the value read and
4380 * the actual number of bytes read.
4381 * @throws {Error} If it's not a valid varint
4382 * @expose
4383 */
4384 ByteBufferPrototype.readVarint64 = function(offset) {
4385 var relative = typeof offset === 'undefined';
4386 if (relative) offset = this.offset;
4387 if (!this.noAssert) {
4388 if (typeof offset !== 'number' || offset % 1 !== 0)
4389 throw TypeError("Illegal offset: "+offset+" (not an integer)");
4390 offset >>>= 0;
4391 if (offset < 0 || offset + 1 > this.buffer.byteLength)
4392 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+1+") <= "+this.buffer.byteLength);
4393 }
4394 // ref: src/google/protobuf/io/coded_stream.cc
4395 var start = offset,
4396 part0 = 0,
4397 part1 = 0,
4398 part2 = 0,
4399 b = 0;
4400 b = this.view[offset++]; part0 = (b & 0x7F) ; if ( b & 0x80 ) {
4401 b = this.view[offset++]; part0 |= (b & 0x7F) << 7; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
4402 b = this.view[offset++]; part0 |= (b & 0x7F) << 14; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
4403 b = this.view[offset++]; part0 |= (b & 0x7F) << 21; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
4404 b = this.view[offset++]; part1 = (b & 0x7F) ; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
4405 b = this.view[offset++]; part1 |= (b & 0x7F) << 7; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
4406 b = this.view[offset++]; part1 |= (b & 0x7F) << 14; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
4407 b = this.view[offset++]; part1 |= (b & 0x7F) << 21; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
4408 b = this.view[offset++]; part2 = (b & 0x7F) ; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
4409 b = this.view[offset++]; part2 |= (b & 0x7F) << 7; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
4410 throw Error("Buffer overrun"); }}}}}}}}}}
4411 var value = Long.fromBits(part0 | (part1 << 28), (part1 >>> 4) | (part2) << 24, false);
4412 if (relative) {
4413 this.offset = offset;
4414 return value;
4415 } else {
4416 return {
4417 'value': value,
4418 'length': offset-start
4419 };
4420 }
4421 };
4422
4423 /**
4424 * Reads a zig-zag encoded 64bit base 128 variable-length integer. Requires Long.js.
4425 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
4426 * read if omitted.
4427 * @returns {!Long|!{value: Long, length: number}} The value read if offset is omitted, else the value read and
4428 * the actual number of bytes read.
4429 * @throws {Error} If it's not a valid varint
4430 * @expose
4431 */
4432 ByteBufferPrototype.readVarint64ZigZag = function(offset) {
4433 var val = this.readVarint64(offset);
4434 if (val && val['value'] instanceof Long)
4435 val["value"] = ByteBuffer.zigZagDecode64(val["value"]);
4436 else
4437 val = ByteBuffer.zigZagDecode64(val);
4438 return val;
4439 };
4440
4441 } // Long
4442
4443
4444 // types/strings/cstring
4445
4446 /**
4447 * Writes a NULL-terminated UTF8 encoded string. For this to work the specified string must not contain any NULL
4448 * characters itself.
4449 * @param {string} str String to write
4450 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
4451 * contained in `str` + 1 if omitted.
4452 * @returns {!ByteBuffer|number} this if offset is omitted, else the actual number of bytes written
4453 * @expose
4454 */
4455 ByteBufferPrototype.writeCString = function(str, offset) {
4456 var relative = typeof offset === 'undefined';
4457 if (relative) offset = this.offset;
4458 var i,
4459 k = str.length;
4460 if (!this.noAssert) {
4461 if (typeof str !== 'string')
4462 throw TypeError("Illegal str: Not a string");
4463 for (i=0; i<k; ++i) {
4464 if (str.charCodeAt(i) === 0)
4465 throw RangeError("Illegal str: Contains NULL-characters");
4466 }
4467 if (typeof offset !== 'number' || offset % 1 !== 0)
4468 throw TypeError("Illegal offset: "+offset+" (not an integer)");
4469 offset >>>= 0;
4470 if (offset < 0 || offset + 0 > this.buffer.byteLength)
4471 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
4472 }
4473 // UTF8 strings do not contain zero bytes in between except for the zero character, so:
4474 k = utfx.calculateUTF16asUTF8(stringSource(str))[1];
4475 offset += k+1;
4476 var capacity12 = this.buffer.byteLength;
4477 if (offset > capacity12)
4478 this.resize((capacity12 *= 2) > offset ? capacity12 : offset);
4479 offset -= k+1;
4480 utfx.encodeUTF16toUTF8(stringSource(str), function(b) {
4481 this.view[offset++] = b;
4482 }.bind(this));
4483 this.view[offset++] = 0;
4484 if (relative) {
4485 this.offset = offset;
4486 return this;
4487 }
4488 return k;
4489 };
4490
4491 /**
4492 * Reads a NULL-terminated UTF8 encoded string. For this to work the string read must not contain any NULL characters
4493 * itself.
4494 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
4495 * read if omitted.
4496 * @returns {string|!{string: string, length: number}} The string read if offset is omitted, else the string
4497 * read and the actual number of bytes read.
4498 * @expose
4499 */
4500 ByteBufferPrototype.readCString = function(offset) {
4501 var relative = typeof offset === 'undefined';
4502 if (relative) offset = this.offset;
4503 if (!this.noAssert) {
4504 if (typeof offset !== 'number' || offset % 1 !== 0)
4505 throw TypeError("Illegal offset: "+offset+" (not an integer)");
4506 offset >>>= 0;
4507 if (offset < 0 || offset + 1 > this.buffer.byteLength)
4508 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+1+") <= "+this.buffer.byteLength);
4509 }
4510 var start = offset;
4511 // UTF8 strings do not contain zero bytes in between except for the zero character itself, so:
4512 var sd, b = -1;
4513 utfx.decodeUTF8toUTF16(function() {
4514 if (b === 0) return null;
4515 if (offset >= this.limit)
4516 throw RangeError("Illegal range: Truncated data, "+offset+" < "+this.limit);
4517 b = this.view[offset++];
4518 return b === 0 ? null : b;
4519 }.bind(this), sd = stringDestination(), true);
4520 if (relative) {
4521 this.offset = offset;
4522 return sd();
4523 } else {
4524 return {
4525 "string": sd(),
4526 "length": offset - start
4527 };
4528 }
4529 };
4530
4531 // types/strings/istring
4532
4533 /**
4534 * Writes a length as uint32 prefixed UTF8 encoded string.
4535 * @param {string} str String to write
4536 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
4537 * written if omitted.
4538 * @returns {!ByteBuffer|number} `this` if `offset` is omitted, else the actual number of bytes written
4539 * @expose
4540 * @see ByteBuffer#writeVarint32
4541 */
4542 ByteBufferPrototype.writeIString = function(str, offset) {
4543 var relative = typeof offset === 'undefined';
4544 if (relative) offset = this.offset;
4545 if (!this.noAssert) {
4546 if (typeof str !== 'string')
4547 throw TypeError("Illegal str: Not a string");
4548 if (typeof offset !== 'number' || offset % 1 !== 0)
4549 throw TypeError("Illegal offset: "+offset+" (not an integer)");
4550 offset >>>= 0;
4551 if (offset < 0 || offset + 0 > this.buffer.byteLength)
4552 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
4553 }
4554 var start = offset,
4555 k;
4556 k = utfx.calculateUTF16asUTF8(stringSource(str), this.noAssert)[1];
4557 offset += 4+k;
4558 var capacity13 = this.buffer.byteLength;
4559 if (offset > capacity13)
4560 this.resize((capacity13 *= 2) > offset ? capacity13 : offset);
4561 offset -= 4+k;
4562 if (this.littleEndian) {
4563 this.view[offset+3] = (k >>> 24) & 0xFF;
4564 this.view[offset+2] = (k >>> 16) & 0xFF;
4565 this.view[offset+1] = (k >>> 8) & 0xFF;
4566 this.view[offset ] = k & 0xFF;
4567 } else {
4568 this.view[offset ] = (k >>> 24) & 0xFF;
4569 this.view[offset+1] = (k >>> 16) & 0xFF;
4570 this.view[offset+2] = (k >>> 8) & 0xFF;
4571 this.view[offset+3] = k & 0xFF;
4572 }
4573 offset += 4;
4574 utfx.encodeUTF16toUTF8(stringSource(str), function(b) {
4575 this.view[offset++] = b;
4576 }.bind(this));
4577 if (offset !== start + 4 + k)
4578 throw RangeError("Illegal range: Truncated data, "+offset+" == "+(offset+4+k));
4579 if (relative) {
4580 this.offset = offset;
4581 return this;
4582 }
4583 return offset - start;
4584 };
4585
4586 /**
4587 * Reads a length as uint32 prefixed UTF8 encoded string.
4588 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
4589 * read if omitted.
4590 * @returns {string|!{string: string, length: number}} The string read if offset is omitted, else the string
4591 * read and the actual number of bytes read.
4592 * @expose
4593 * @see ByteBuffer#readVarint32
4594 */
4595 ByteBufferPrototype.readIString = function(offset) {
4596 var relative = typeof offset === 'undefined';
4597 if (relative) offset = this.offset;
4598 if (!this.noAssert) {
4599 if (typeof offset !== 'number' || offset % 1 !== 0)
4600 throw TypeError("Illegal offset: "+offset+" (not an integer)");
4601 offset >>>= 0;
4602 if (offset < 0 || offset + 4 > this.buffer.byteLength)
4603 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+4+") <= "+this.buffer.byteLength);
4604 }
4605 var start = offset;
4606 var len = this.readUint32(offset);
4607 var str = this.readUTF8String(len, ByteBuffer.METRICS_BYTES, offset += 4);
4608 offset += str['length'];
4609 if (relative) {
4610 this.offset = offset;
4611 return str['string'];
4612 } else {
4613 return {
4614 'string': str['string'],
4615 'length': offset - start
4616 };
4617 }
4618 };
4619
4620 // types/strings/utf8string
4621
4622 /**
4623 * Metrics representing number of UTF8 characters. Evaluates to `c`.
4624 * @type {string}
4625 * @const
4626 * @expose
4627 */
4628 ByteBuffer.METRICS_CHARS = 'c';
4629
4630 /**
4631 * Metrics representing number of bytes. Evaluates to `b`.
4632 * @type {string}
4633 * @const
4634 * @expose
4635 */
4636 ByteBuffer.METRICS_BYTES = 'b';
4637
4638 /**
4639 * Writes an UTF8 encoded string.
4640 * @param {string} str String to write
4641 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} if omitted.
4642 * @returns {!ByteBuffer|number} this if offset is omitted, else the actual number of bytes written.
4643 * @expose
4644 */
4645 ByteBufferPrototype.writeUTF8String = function(str, offset) {
4646 var relative = typeof offset === 'undefined';
4647 if (relative) offset = this.offset;
4648 if (!this.noAssert) {
4649 if (typeof offset !== 'number' || offset % 1 !== 0)
4650 throw TypeError("Illegal offset: "+offset+" (not an integer)");
4651 offset >>>= 0;
4652 if (offset < 0 || offset + 0 > this.buffer.byteLength)
4653 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
4654 }
4655 var k;
4656 var start = offset;
4657 k = utfx.calculateUTF16asUTF8(stringSource(str))[1];
4658 offset += k;
4659 var capacity14 = this.buffer.byteLength;
4660 if (offset > capacity14)
4661 this.resize((capacity14 *= 2) > offset ? capacity14 : offset);
4662 offset -= k;
4663 utfx.encodeUTF16toUTF8(stringSource(str), function(b) {
4664 this.view[offset++] = b;
4665 }.bind(this));
4666 if (relative) {
4667 this.offset = offset;
4668 return this;
4669 }
4670 return offset - start;
4671 };
4672
4673 /**
4674 * Writes an UTF8 encoded string. This is an alias of {@link ByteBuffer#writeUTF8String}.
4675 * @function
4676 * @param {string} str String to write
4677 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} if omitted.
4678 * @returns {!ByteBuffer|number} this if offset is omitted, else the actual number of bytes written.
4679 * @expose
4680 */
4681 ByteBufferPrototype.writeString = ByteBufferPrototype.writeUTF8String;
4682
4683 /**
4684 * Calculates the number of UTF8 characters of a string. JavaScript itself uses UTF-16, so that a string's
4685 * `length` property does not reflect its actual UTF8 size if it contains code points larger than 0xFFFF.
4686 * @param {string} str String to calculate
4687 * @returns {number} Number of UTF8 characters
4688 * @expose
4689 */
4690 ByteBuffer.calculateUTF8Chars = function(str) {
4691 return utfx.calculateUTF16asUTF8(stringSource(str))[0];
4692 };
4693
4694 /**
4695 * Calculates the number of UTF8 bytes of a string.
4696 * @param {string} str String to calculate
4697 * @returns {number} Number of UTF8 bytes
4698 * @expose
4699 */
4700 ByteBuffer.calculateUTF8Bytes = function(str) {
4701 return utfx.calculateUTF16asUTF8(stringSource(str))[1];
4702 };
4703
4704 /**
4705 * Calculates the number of UTF8 bytes of a string. This is an alias of {@link ByteBuffer.calculateUTF8Bytes}.
4706 * @function
4707 * @param {string} str String to calculate
4708 * @returns {number} Number of UTF8 bytes
4709 * @expose
4710 */
4711 ByteBuffer.calculateString = ByteBuffer.calculateUTF8Bytes;
4712
4713 /**
4714 * Reads an UTF8 encoded string.
4715 * @param {number} length Number of characters or bytes to read.
4716 * @param {string=} metrics Metrics specifying what `length` is meant to count. Defaults to
4717 * {@link ByteBuffer.METRICS_CHARS}.
4718 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
4719 * read if omitted.
4720 * @returns {string|!{string: string, length: number}} The string read if offset is omitted, else the string
4721 * read and the actual number of bytes read.
4722 * @expose
4723 */
4724 ByteBufferPrototype.readUTF8String = function(length, metrics, offset) {
4725 if (typeof metrics === 'number') {
4726 offset = metrics;
4727 metrics = undefined;
4728 }
4729 var relative = typeof offset === 'undefined';
4730 if (relative) offset = this.offset;
4731 if (typeof metrics === 'undefined') metrics = ByteBuffer.METRICS_CHARS;
4732 if (!this.noAssert) {
4733 if (typeof length !== 'number' || length % 1 !== 0)
4734 throw TypeError("Illegal length: "+length+" (not an integer)");
4735 length |= 0;
4736 if (typeof offset !== 'number' || offset % 1 !== 0)
4737 throw TypeError("Illegal offset: "+offset+" (not an integer)");
4738 offset >>>= 0;
4739 if (offset < 0 || offset + 0 > this.buffer.byteLength)
4740 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
4741 }
4742 var i = 0,
4743 start = offset,
4744 sd;
4745 if (metrics === ByteBuffer.METRICS_CHARS) { // The same for node and the browser
4746 sd = stringDestination();
4747 utfx.decodeUTF8(function() {
4748 return i < length && offset < this.limit ? this.view[offset++] : null;
4749 }.bind(this), function(cp) {
4750 ++i; utfx.UTF8toUTF16(cp, sd);
4751 });
4752 if (i !== length)
4753 throw RangeError("Illegal range: Truncated data, "+i+" == "+length);
4754 if (relative) {
4755 this.offset = offset;
4756 return sd();
4757 } else {
4758 return {
4759 "string": sd(),
4760 "length": offset - start
4761 };
4762 }
4763 } else if (metrics === ByteBuffer.METRICS_BYTES) {
4764 if (!this.noAssert) {
4765 if (typeof offset !== 'number' || offset % 1 !== 0)
4766 throw TypeError("Illegal offset: "+offset+" (not an integer)");
4767 offset >>>= 0;
4768 if (offset < 0 || offset + length > this.buffer.byteLength)
4769 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+length+") <= "+this.buffer.byteLength);
4770 }
4771 var k = offset + length;
4772 utfx.decodeUTF8toUTF16(function() {
4773 return offset < k ? this.view[offset++] : null;
4774 }.bind(this), sd = stringDestination(), this.noAssert);
4775 if (offset !== k)
4776 throw RangeError("Illegal range: Truncated data, "+offset+" == "+k);
4777 if (relative) {
4778 this.offset = offset;
4779 return sd();
4780 } else {
4781 return {
4782 'string': sd(),
4783 'length': offset - start
4784 };
4785 }
4786 } else
4787 throw TypeError("Unsupported metrics: "+metrics);
4788 };
4789
4790 /**
4791 * Reads an UTF8 encoded string. This is an alias of {@link ByteBuffer#readUTF8String}.
4792 * @function
4793 * @param {number} length Number of characters or bytes to read
4794 * @param {number=} metrics Metrics specifying what `n` is meant to count. Defaults to
4795 * {@link ByteBuffer.METRICS_CHARS}.
4796 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
4797 * read if omitted.
4798 * @returns {string|!{string: string, length: number}} The string read if offset is omitted, else the string
4799 * read and the actual number of bytes read.
4800 * @expose
4801 */
4802 ByteBufferPrototype.readString = ByteBufferPrototype.readUTF8String;
4803
4804 // types/strings/vstring
4805
4806 /**
4807 * Writes a length as varint32 prefixed UTF8 encoded string.
4808 * @param {string} str String to write
4809 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
4810 * written if omitted.
4811 * @returns {!ByteBuffer|number} `this` if `offset` is omitted, else the actual number of bytes written
4812 * @expose
4813 * @see ByteBuffer#writeVarint32
4814 */
4815 ByteBufferPrototype.writeVString = function(str, offset) {
4816 var relative = typeof offset === 'undefined';
4817 if (relative) offset = this.offset;
4818 if (!this.noAssert) {
4819 if (typeof str !== 'string')
4820 throw TypeError("Illegal str: Not a string");
4821 if (typeof offset !== 'number' || offset % 1 !== 0)
4822 throw TypeError("Illegal offset: "+offset+" (not an integer)");
4823 offset >>>= 0;
4824 if (offset < 0 || offset + 0 > this.buffer.byteLength)
4825 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
4826 }
4827 var start = offset,
4828 k, l;
4829 k = utfx.calculateUTF16asUTF8(stringSource(str), this.noAssert)[1];
4830 l = ByteBuffer.calculateVarint32(k);
4831 offset += l+k;
4832 var capacity15 = this.buffer.byteLength;
4833 if (offset > capacity15)
4834 this.resize((capacity15 *= 2) > offset ? capacity15 : offset);
4835 offset -= l+k;
4836 offset += this.writeVarint32(k, offset);
4837 utfx.encodeUTF16toUTF8(stringSource(str), function(b) {
4838 this.view[offset++] = b;
4839 }.bind(this));
4840 if (offset !== start+k+l)
4841 throw RangeError("Illegal range: Truncated data, "+offset+" == "+(offset+k+l));
4842 if (relative) {
4843 this.offset = offset;
4844 return this;
4845 }
4846 return offset - start;
4847 };
4848
4849 /**
4850 * Reads a length as varint32 prefixed UTF8 encoded string.
4851 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
4852 * read if omitted.
4853 * @returns {string|!{string: string, length: number}} The string read if offset is omitted, else the string
4854 * read and the actual number of bytes read.
4855 * @expose
4856 * @see ByteBuffer#readVarint32
4857 */
4858 ByteBufferPrototype.readVString = function(offset) {
4859 var relative = typeof offset === 'undefined';
4860 if (relative) offset = this.offset;
4861 if (!this.noAssert) {
4862 if (typeof offset !== 'number' || offset % 1 !== 0)
4863 throw TypeError("Illegal offset: "+offset+" (not an integer)");
4864 offset >>>= 0;
4865 if (offset < 0 || offset + 1 > this.buffer.byteLength)
4866 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+1+") <= "+this.buffer.byteLength);
4867 }
4868 var start = offset;
4869 var len = this.readVarint32(offset);
4870 var str = this.readUTF8String(len['value'], ByteBuffer.METRICS_BYTES, offset += len['length']);
4871 offset += str['length'];
4872 if (relative) {
4873 this.offset = offset;
4874 return str['string'];
4875 } else {
4876 return {
4877 'string': str['string'],
4878 'length': offset - start
4879 };
4880 }
4881 };
4882
4883
4884 /**
4885 * Appends some data to this ByteBuffer. This will overwrite any contents behind the specified offset up to the appended
4886 * data's length.
4887 * @param {!ByteBuffer|!ArrayBuffer|!Uint8Array|string} source Data to append. If `source` is a ByteBuffer, its offsets
4888 * will be modified according to the performed read operation.
4889 * @param {(string|number)=} encoding Encoding if `data` is a string ("base64", "hex", "binary", defaults to "utf8")
4890 * @param {number=} offset Offset to append at. Will use and increase {@link ByteBuffer#offset} by the number of bytes
4891 * written if omitted.
4892 * @returns {!ByteBuffer} this
4893 * @expose
4894 * @example A relative `<01 02>03.append(<04 05>)` will result in `<01 02 04 05>, 04 05|`
4895 * @example An absolute `<01 02>03.append(04 05>, 1)` will result in `<01 04>05, 04 05|`
4896 */
4897 ByteBufferPrototype.append = function(source, encoding, offset) {
4898 if (typeof encoding === 'number' || typeof encoding !== 'string') {
4899 offset = encoding;
4900 encoding = undefined;
4901 }
4902 var relative = typeof offset === 'undefined';
4903 if (relative) offset = this.offset;
4904 if (!this.noAssert) {
4905 if (typeof offset !== 'number' || offset % 1 !== 0)
4906 throw TypeError("Illegal offset: "+offset+" (not an integer)");
4907 offset >>>= 0;
4908 if (offset < 0 || offset + 0 > this.buffer.byteLength)
4909 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
4910 }
4911 if (!(source instanceof ByteBuffer))
4912 source = ByteBuffer.wrap(source, encoding);
4913 var length = source.limit - source.offset;
4914 if (length <= 0) return this; // Nothing to append
4915 offset += length;
4916 var capacity16 = this.buffer.byteLength;
4917 if (offset > capacity16)
4918 this.resize((capacity16 *= 2) > offset ? capacity16 : offset);
4919 offset -= length;
4920 this.view.set(source.view.subarray(source.offset, source.limit), offset);
4921 source.offset += length;
4922 if (relative) this.offset += length;
4923 return this;
4924 };
4925
4926 /**
4927 * Appends this ByteBuffer's contents to another ByteBuffer. This will overwrite any contents at and after the
4928 specified offset up to the length of this ByteBuffer's data.
4929 * @param {!ByteBuffer} target Target ByteBuffer
4930 * @param {number=} offset Offset to append to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
4931 * read if omitted.
4932 * @returns {!ByteBuffer} this
4933 * @expose
4934 * @see ByteBuffer#append
4935 */
4936 ByteBufferPrototype.appendTo = function(target, offset) {
4937 target.append(this, offset);
4938 return this;
4939 };
4940
4941 /**
4942 * Enables or disables assertions of argument types and offsets. Assertions are enabled by default but you can opt to
4943 * disable them if your code already makes sure that everything is valid.
4944 * @param {boolean} assert `true` to enable assertions, otherwise `false`
4945 * @returns {!ByteBuffer} this
4946 * @expose
4947 */
4948 ByteBufferPrototype.assert = function(assert) {
4949 this.noAssert = !assert;
4950 return this;
4951 };
4952
4953 /**
4954 * Gets the capacity of this ByteBuffer's backing buffer.
4955 * @returns {number} Capacity of the backing buffer
4956 * @expose
4957 */
4958 ByteBufferPrototype.capacity = function() {
4959 return this.buffer.byteLength;
4960 };
4961 /**
4962 * Clears this ByteBuffer's offsets by setting {@link ByteBuffer#offset} to `0` and {@link ByteBuffer#limit} to the
4963 * backing buffer's capacity. Discards {@link ByteBuffer#markedOffset}.
4964 * @returns {!ByteBuffer} this
4965 * @expose
4966 */
4967 ByteBufferPrototype.clear = function() {
4968 this.offset = 0;
4969 this.limit = this.buffer.byteLength;
4970 this.markedOffset = -1;
4971 return this;
4972 };
4973
4974 /**
4975 * Creates a cloned instance of this ByteBuffer, preset with this ByteBuffer's values for {@link ByteBuffer#offset},
4976 * {@link ByteBuffer#markedOffset} and {@link ByteBuffer#limit}.
4977 * @param {boolean=} copy Whether to copy the backing buffer or to return another view on the same, defaults to `false`
4978 * @returns {!ByteBuffer} Cloned instance
4979 * @expose
4980 */
4981 ByteBufferPrototype.clone = function(copy) {
4982 var bb = new ByteBuffer(0, this.littleEndian, this.noAssert);
4983 if (copy) {
4984 bb.buffer = new ArrayBuffer(this.buffer.byteLength);
4985 bb.view = new Uint8Array(bb.buffer);
4986 } else {
4987 bb.buffer = this.buffer;
4988 bb.view = this.view;
4989 }
4990 bb.offset = this.offset;
4991 bb.markedOffset = this.markedOffset;
4992 bb.limit = this.limit;
4993 return bb;
4994 };
4995
4996 /**
4997 * Compacts this ByteBuffer to be backed by a {@link ByteBuffer#buffer} of its contents' length. Contents are the bytes
4998 * between {@link ByteBuffer#offset} and {@link ByteBuffer#limit}. Will set `offset = 0` and `limit = capacity` and
4999 * adapt {@link ByteBuffer#markedOffset} to the same relative position if set.
5000 * @param {number=} begin Offset to start at, defaults to {@link ByteBuffer#offset}
5001 * @param {number=} end Offset to end at, defaults to {@link ByteBuffer#limit}
5002 * @returns {!ByteBuffer} this
5003 * @expose
5004 */
5005 ByteBufferPrototype.compact = function(begin, end) {
5006 if (typeof begin === 'undefined') begin = this.offset;
5007 if (typeof end === 'undefined') end = this.limit;
5008 if (!this.noAssert) {
5009 if (typeof begin !== 'number' || begin % 1 !== 0)
5010 throw TypeError("Illegal begin: Not an integer");
5011 begin >>>= 0;
5012 if (typeof end !== 'number' || end % 1 !== 0)
5013 throw TypeError("Illegal end: Not an integer");
5014 end >>>= 0;
5015 if (begin < 0 || begin > end || end > this.buffer.byteLength)
5016 throw RangeError("Illegal range: 0 <= "+begin+" <= "+end+" <= "+this.buffer.byteLength);
5017 }
5018 if (begin === 0 && end === this.buffer.byteLength)
5019 return this; // Already compacted
5020 var len = end - begin;
5021 if (len === 0) {
5022 this.buffer = EMPTY_BUFFER;
5023 this.view = null;
5024 if (this.markedOffset >= 0) this.markedOffset -= begin;
5025 this.offset = 0;
5026 this.limit = 0;
5027 return this;
5028 }
5029 var buffer = new ArrayBuffer(len);
5030 var view = new Uint8Array(buffer);
5031 view.set(this.view.subarray(begin, end));
5032 this.buffer = buffer;
5033 this.view = view;
5034 if (this.markedOffset >= 0) this.markedOffset -= begin;
5035 this.offset = 0;
5036 this.limit = len;
5037 return this;
5038 };
5039
5040 /**
5041 * Creates a copy of this ByteBuffer's contents. Contents are the bytes between {@link ByteBuffer#offset} and
5042 * {@link ByteBuffer#limit}.
5043 * @param {number=} begin Begin offset, defaults to {@link ByteBuffer#offset}.
5044 * @param {number=} end End offset, defaults to {@link ByteBuffer#limit}.
5045 * @returns {!ByteBuffer} Copy
5046 * @expose
5047 */
5048 ByteBufferPrototype.copy = function(begin, end) {
5049 if (typeof begin === 'undefined') begin = this.offset;
5050 if (typeof end === 'undefined') end = this.limit;
5051 if (!this.noAssert) {
5052 if (typeof begin !== 'number' || begin % 1 !== 0)
5053 throw TypeError("Illegal begin: Not an integer");
5054 begin >>>= 0;
5055 if (typeof end !== 'number' || end % 1 !== 0)
5056 throw TypeError("Illegal end: Not an integer");
5057 end >>>= 0;
5058 if (begin < 0 || begin > end || end > this.buffer.byteLength)
5059 throw RangeError("Illegal range: 0 <= "+begin+" <= "+end+" <= "+this.buffer.byteLength);
5060 }
5061 if (begin === end)
5062 return new ByteBuffer(0, this.littleEndian, this.noAssert);
5063 var capacity = end - begin,
5064 bb = new ByteBuffer(capacity, this.littleEndian, this.noAssert);
5065 bb.offset = 0;
5066 bb.limit = capacity;
5067 if (bb.markedOffset >= 0) bb.markedOffset -= begin;
5068 this.copyTo(bb, 0, begin, end);
5069 return bb;
5070 };
5071
5072 /**
5073 * Copies this ByteBuffer's contents to another ByteBuffer. Contents are the bytes between {@link ByteBuffer#offset} and
5074 * {@link ByteBuffer#limit}.
5075 * @param {!ByteBuffer} target Target ByteBuffer
5076 * @param {number=} targetOffset Offset to copy to. Will use and increase the target's {@link ByteBuffer#offset}
5077 * by the number of bytes copied if omitted.
5078 * @param {number=} sourceOffset Offset to start copying from. Will use and increase {@link ByteBuffer#offset} by the
5079 * number of bytes copied if omitted.
5080 * @param {number=} sourceLimit Offset to end copying from, defaults to {@link ByteBuffer#limit}
5081 * @returns {!ByteBuffer} this
5082 * @expose
5083 */
5084 ByteBufferPrototype.copyTo = function(target, targetOffset, sourceOffset, sourceLimit) {
5085 var relative,
5086 targetRelative;
5087 if (!this.noAssert) {
5088 if (!ByteBuffer.isByteBuffer(target))
5089 throw TypeError("Illegal target: Not a ByteBuffer");
5090 }
5091 targetOffset = (targetRelative = typeof targetOffset === 'undefined') ? target.offset : targetOffset | 0;
5092 sourceOffset = (relative = typeof sourceOffset === 'undefined') ? this.offset : sourceOffset | 0;
5093 sourceLimit = typeof sourceLimit === 'undefined' ? this.limit : sourceLimit | 0;
5094
5095 if (targetOffset < 0 || targetOffset > target.buffer.byteLength)
5096 throw RangeError("Illegal target range: 0 <= "+targetOffset+" <= "+target.buffer.byteLength);
5097 if (sourceOffset < 0 || sourceLimit > this.buffer.byteLength)
5098 throw RangeError("Illegal source range: 0 <= "+sourceOffset+" <= "+this.buffer.byteLength);
5099
5100 var len = sourceLimit - sourceOffset;
5101 if (len === 0)
5102 return target; // Nothing to copy
5103
5104 target.ensureCapacity(targetOffset + len);
5105
5106 target.view.set(this.view.subarray(sourceOffset, sourceLimit), targetOffset);
5107
5108 if (relative) this.offset += len;
5109 if (targetRelative) target.offset += len;
5110
5111 return this;
5112 };
5113
5114 /**
5115 * Makes sure that this ByteBuffer is backed by a {@link ByteBuffer#buffer} of at least the specified capacity. If the
5116 * current capacity is exceeded, it will be doubled. If double the current capacity is less than the required capacity,
5117 * the required capacity will be used instead.
5118 * @param {number} capacity Required capacity
5119 * @returns {!ByteBuffer} this
5120 * @expose
5121 */
5122 ByteBufferPrototype.ensureCapacity = function(capacity) {
5123 var current = this.buffer.byteLength;
5124 if (current < capacity)
5125 return this.resize((current *= 2) > capacity ? current : capacity);
5126 return this;
5127 };
5128
5129 /**
5130 * Overwrites this ByteBuffer's contents with the specified value. Contents are the bytes between
5131 * {@link ByteBuffer#offset} and {@link ByteBuffer#limit}.
5132 * @param {number|string} value Byte value to fill with. If given as a string, the first character is used.
5133 * @param {number=} begin Begin offset. Will use and increase {@link ByteBuffer#offset} by the number of bytes
5134 * written if omitted. defaults to {@link ByteBuffer#offset}.
5135 * @param {number=} end End offset, defaults to {@link ByteBuffer#limit}.
5136 * @returns {!ByteBuffer} this
5137 * @expose
5138 * @example `someByteBuffer.clear().fill(0)` fills the entire backing buffer with zeroes
5139 */
5140 ByteBufferPrototype.fill = function(value, begin, end) {
5141 var relative = typeof begin === 'undefined';
5142 if (relative) begin = this.offset;
5143 if (typeof value === 'string' && value.length > 0)
5144 value = value.charCodeAt(0);
5145 if (typeof begin === 'undefined') begin = this.offset;
5146 if (typeof end === 'undefined') end = this.limit;
5147 if (!this.noAssert) {
5148 if (typeof value !== 'number' || value % 1 !== 0)
5149 throw TypeError("Illegal value: "+value+" (not an integer)");
5150 value |= 0;
5151 if (typeof begin !== 'number' || begin % 1 !== 0)
5152 throw TypeError("Illegal begin: Not an integer");
5153 begin >>>= 0;
5154 if (typeof end !== 'number' || end % 1 !== 0)
5155 throw TypeError("Illegal end: Not an integer");
5156 end >>>= 0;
5157 if (begin < 0 || begin > end || end > this.buffer.byteLength)
5158 throw RangeError("Illegal range: 0 <= "+begin+" <= "+end+" <= "+this.buffer.byteLength);
5159 }
5160 if (begin >= end)
5161 return this; // Nothing to fill
5162 while (begin < end) this.view[begin++] = value;
5163 if (relative) this.offset = begin;
5164 return this;
5165 };
5166
5167 /**
5168 * Makes this ByteBuffer ready for a new sequence of write or relative read operations. Sets `limit = offset` and
5169 * `offset = 0`. Make sure always to flip a ByteBuffer when all relative read or write operations are complete.
5170 * @returns {!ByteBuffer} this
5171 * @expose
5172 */
5173 ByteBufferPrototype.flip = function() {
5174 this.limit = this.offset;
5175 this.offset = 0;
5176 return this;
5177 };
5178 /**
5179 * Marks an offset on this ByteBuffer to be used later.
5180 * @param {number=} offset Offset to mark. Defaults to {@link ByteBuffer#offset}.
5181 * @returns {!ByteBuffer} this
5182 * @throws {TypeError} If `offset` is not a valid number
5183 * @throws {RangeError} If `offset` is out of bounds
5184 * @see ByteBuffer#reset
5185 * @expose
5186 */
5187 ByteBufferPrototype.mark = function(offset) {
5188 offset = typeof offset === 'undefined' ? this.offset : offset;
5189 if (!this.noAssert) {
5190 if (typeof offset !== 'number' || offset % 1 !== 0)
5191 throw TypeError("Illegal offset: "+offset+" (not an integer)");
5192 offset >>>= 0;
5193 if (offset < 0 || offset + 0 > this.buffer.byteLength)
5194 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
5195 }
5196 this.markedOffset = offset;
5197 return this;
5198 };
5199 /**
5200 * Sets the byte order.
5201 * @param {boolean} littleEndian `true` for little endian byte order, `false` for big endian
5202 * @returns {!ByteBuffer} this
5203 * @expose
5204 */
5205 ByteBufferPrototype.order = function(littleEndian) {
5206 if (!this.noAssert) {
5207 if (typeof littleEndian !== 'boolean')
5208 throw TypeError("Illegal littleEndian: Not a boolean");
5209 }
5210 this.littleEndian = !!littleEndian;
5211 return this;
5212 };
5213
5214 /**
5215 * Switches (to) little endian byte order.
5216 * @param {boolean=} littleEndian Defaults to `true`, otherwise uses big endian
5217 * @returns {!ByteBuffer} this
5218 * @expose
5219 */
5220 ByteBufferPrototype.LE = function(littleEndian) {
5221 this.littleEndian = typeof littleEndian !== 'undefined' ? !!littleEndian : true;
5222 return this;
5223 };
5224
5225 /**
5226 * Switches (to) big endian byte order.
5227 * @param {boolean=} bigEndian Defaults to `true`, otherwise uses little endian
5228 * @returns {!ByteBuffer} this
5229 * @expose
5230 */
5231 ByteBufferPrototype.BE = function(bigEndian) {
5232 this.littleEndian = typeof bigEndian !== 'undefined' ? !bigEndian : false;
5233 return this;
5234 };
5235 /**
5236 * Prepends some data to this ByteBuffer. This will overwrite any contents before the specified offset up to the
5237 * prepended data's length. If there is not enough space available before the specified `offset`, the backing buffer
5238 * will be resized and its contents moved accordingly.
5239 * @param {!ByteBuffer|string|!ArrayBuffer} source Data to prepend. If `source` is a ByteBuffer, its offset will be
5240 * modified according to the performed read operation.
5241 * @param {(string|number)=} encoding Encoding if `data` is a string ("base64", "hex", "binary", defaults to "utf8")
5242 * @param {number=} offset Offset to prepend at. Will use and decrease {@link ByteBuffer#offset} by the number of bytes
5243 * prepended if omitted.
5244 * @returns {!ByteBuffer} this
5245 * @expose
5246 * @example A relative `00<01 02 03>.prepend(<04 05>)` results in `<04 05 01 02 03>, 04 05|`
5247 * @example An absolute `00<01 02 03>.prepend(<04 05>, 2)` results in `04<05 02 03>, 04 05|`
5248 */
5249 ByteBufferPrototype.prepend = function(source, encoding, offset) {
5250 if (typeof encoding === 'number' || typeof encoding !== 'string') {
5251 offset = encoding;
5252 encoding = undefined;
5253 }
5254 var relative = typeof offset === 'undefined';
5255 if (relative) offset = this.offset;
5256 if (!this.noAssert) {
5257 if (typeof offset !== 'number' || offset % 1 !== 0)
5258 throw TypeError("Illegal offset: "+offset+" (not an integer)");
5259 offset >>>= 0;
5260 if (offset < 0 || offset + 0 > this.buffer.byteLength)
5261 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
5262 }
5263 if (!(source instanceof ByteBuffer))
5264 source = ByteBuffer.wrap(source, encoding);
5265 var len = source.limit - source.offset;
5266 if (len <= 0) return this; // Nothing to prepend
5267 var diff = len - offset;
5268 if (diff > 0) { // Not enough space before offset, so resize + move
5269 var buffer = new ArrayBuffer(this.buffer.byteLength + diff);
5270 var view = new Uint8Array(buffer);
5271 view.set(this.view.subarray(offset, this.buffer.byteLength), len);
5272 this.buffer = buffer;
5273 this.view = view;
5274 this.offset += diff;
5275 if (this.markedOffset >= 0) this.markedOffset += diff;
5276 this.limit += diff;
5277 offset += diff;
5278 } else {
5279 var arrayView = new Uint8Array(this.buffer);
5280 }
5281 this.view.set(source.view.subarray(source.offset, source.limit), offset - len);
5282
5283 source.offset = source.limit;
5284 if (relative)
5285 this.offset -= len;
5286 return this;
5287 };
5288
5289 /**
5290 * Prepends this ByteBuffer to another ByteBuffer. This will overwrite any contents before the specified offset up to the
5291 * prepended data's length. If there is not enough space available before the specified `offset`, the backing buffer
5292 * will be resized and its contents moved accordingly.
5293 * @param {!ByteBuffer} target Target ByteBuffer
5294 * @param {number=} offset Offset to prepend at. Will use and decrease {@link ByteBuffer#offset} by the number of bytes
5295 * prepended if omitted.
5296 * @returns {!ByteBuffer} this
5297 * @expose
5298 * @see ByteBuffer#prepend
5299 */
5300 ByteBufferPrototype.prependTo = function(target, offset) {
5301 target.prepend(this, offset);
5302 return this;
5303 };
5304 /**
5305 * Prints debug information about this ByteBuffer's contents.
5306 * @param {function(string)=} out Output function to call, defaults to console.log
5307 * @expose
5308 */
5309 ByteBufferPrototype.printDebug = function(out) {
5310 if (typeof out !== 'function') out = console.log.bind(console);
5311 out(
5312 this.toString()+"\n"+
5313 "-------------------------------------------------------------------\n"+
5314 this.toDebug(/* columns */ true)
5315 );
5316 };
5317
5318 /**
5319 * Gets the number of remaining readable bytes. Contents are the bytes between {@link ByteBuffer#offset} and
5320 * {@link ByteBuffer#limit}, so this returns `limit - offset`.
5321 * @returns {number} Remaining readable bytes. May be negative if `offset > limit`.
5322 * @expose
5323 */
5324 ByteBufferPrototype.remaining = function() {
5325 return this.limit - this.offset;
5326 };
5327 /**
5328 * Resets this ByteBuffer's {@link ByteBuffer#offset}. If an offset has been marked through {@link ByteBuffer#mark}
5329 * before, `offset` will be set to {@link ByteBuffer#markedOffset}, which will then be discarded. If no offset has been
5330 * marked, sets `offset = 0`.
5331 * @returns {!ByteBuffer} this
5332 * @see ByteBuffer#mark
5333 * @expose
5334 */
5335 ByteBufferPrototype.reset = function() {
5336 if (this.markedOffset >= 0) {
5337 this.offset = this.markedOffset;
5338 this.markedOffset = -1;
5339 } else {
5340 this.offset = 0;
5341 }
5342 return this;
5343 };
5344 /**
5345 * Resizes this ByteBuffer to be backed by a buffer of at least the given capacity. Will do nothing if already that
5346 * large or larger.
5347 * @param {number} capacity Capacity required
5348 * @returns {!ByteBuffer} this
5349 * @throws {TypeError} If `capacity` is not a number
5350 * @throws {RangeError} If `capacity < 0`
5351 * @expose
5352 */
5353 ByteBufferPrototype.resize = function(capacity) {
5354 if (!this.noAssert) {
5355 if (typeof capacity !== 'number' || capacity % 1 !== 0)
5356 throw TypeError("Illegal capacity: "+capacity+" (not an integer)");
5357 capacity |= 0;
5358 if (capacity < 0)
5359 throw RangeError("Illegal capacity: 0 <= "+capacity);
5360 }
5361 if (this.buffer.byteLength < capacity) {
5362 var buffer = new ArrayBuffer(capacity);
5363 var view = new Uint8Array(buffer);
5364 view.set(this.view);
5365 this.buffer = buffer;
5366 this.view = view;
5367 }
5368 return this;
5369 };
5370 /**
5371 * Reverses this ByteBuffer's contents.
5372 * @param {number=} begin Offset to start at, defaults to {@link ByteBuffer#offset}
5373 * @param {number=} end Offset to end at, defaults to {@link ByteBuffer#limit}
5374 * @returns {!ByteBuffer} this
5375 * @expose
5376 */
5377 ByteBufferPrototype.reverse = function(begin, end) {
5378 if (typeof begin === 'undefined') begin = this.offset;
5379 if (typeof end === 'undefined') end = this.limit;
5380 if (!this.noAssert) {
5381 if (typeof begin !== 'number' || begin % 1 !== 0)
5382 throw TypeError("Illegal begin: Not an integer");
5383 begin >>>= 0;
5384 if (typeof end !== 'number' || end % 1 !== 0)
5385 throw TypeError("Illegal end: Not an integer");
5386 end >>>= 0;
5387 if (begin < 0 || begin > end || end > this.buffer.byteLength)
5388 throw RangeError("Illegal range: 0 <= "+begin+" <= "+end+" <= "+this.buffer.byteLength);
5389 }
5390 if (begin === end)
5391 return this; // Nothing to reverse
5392 Array.prototype.reverse.call(this.view.subarray(begin, end));
5393 return this;
5394 };
5395 /**
5396 * Skips the next `length` bytes. This will just advance
5397 * @param {number} length Number of bytes to skip. May also be negative to move the offset back.
5398 * @returns {!ByteBuffer} this
5399 * @expose
5400 */
5401 ByteBufferPrototype.skip = function(length) {
5402 if (!this.noAssert) {
5403 if (typeof length !== 'number' || length % 1 !== 0)
5404 throw TypeError("Illegal length: "+length+" (not an integer)");
5405 length |= 0;
5406 }
5407 var offset = this.offset + length;
5408 if (!this.noAssert) {
5409 if (offset < 0 || offset > this.buffer.byteLength)
5410 throw RangeError("Illegal length: 0 <= "+this.offset+" + "+length+" <= "+this.buffer.byteLength);
5411 }
5412 this.offset = offset;
5413 return this;
5414 };
5415
5416 /**
5417 * Slices this ByteBuffer by creating a cloned instance with `offset = begin` and `limit = end`.
5418 * @param {number=} begin Begin offset, defaults to {@link ByteBuffer#offset}.
5419 * @param {number=} end End offset, defaults to {@link ByteBuffer#limit}.
5420 * @returns {!ByteBuffer} Clone of this ByteBuffer with slicing applied, backed by the same {@link ByteBuffer#buffer}
5421 * @expose
5422 */
5423 ByteBufferPrototype.slice = function(begin, end) {
5424 if (typeof begin === 'undefined') begin = this.offset;
5425 if (typeof end === 'undefined') end = this.limit;
5426 if (!this.noAssert) {
5427 if (typeof begin !== 'number' || begin % 1 !== 0)
5428 throw TypeError("Illegal begin: Not an integer");
5429 begin >>>= 0;
5430 if (typeof end !== 'number' || end % 1 !== 0)
5431 throw TypeError("Illegal end: Not an integer");
5432 end >>>= 0;
5433 if (begin < 0 || begin > end || end > this.buffer.byteLength)
5434 throw RangeError("Illegal range: 0 <= "+begin+" <= "+end+" <= "+this.buffer.byteLength);
5435 }
5436 var bb = this.clone();
5437 bb.offset = begin;
5438 bb.limit = end;
5439 return bb;
5440 };
5441 /**
5442 * Returns a copy of the backing buffer that contains this ByteBuffer's contents. Contents are the bytes between
5443 * {@link ByteBuffer#offset} and {@link ByteBuffer#limit}.
5444 * @param {boolean=} forceCopy If `true` returns a copy, otherwise returns a view referencing the same memory if
5445 * possible. Defaults to `false`
5446 * @returns {!ArrayBuffer} Contents as an ArrayBuffer
5447 * @expose
5448 */
5449 ByteBufferPrototype.toBuffer = function(forceCopy) {
5450 var offset = this.offset,
5451 limit = this.limit;
5452 if (!this.noAssert) {
5453 if (typeof offset !== 'number' || offset % 1 !== 0)
5454 throw TypeError("Illegal offset: Not an integer");
5455 offset >>>= 0;
5456 if (typeof limit !== 'number' || limit % 1 !== 0)
5457 throw TypeError("Illegal limit: Not an integer");
5458 limit >>>= 0;
5459 if (offset < 0 || offset > limit || limit > this.buffer.byteLength)
5460 throw RangeError("Illegal range: 0 <= "+offset+" <= "+limit+" <= "+this.buffer.byteLength);
5461 }
5462 // NOTE: It's not possible to have another ArrayBuffer reference the same memory as the backing buffer. This is
5463 // possible with Uint8Array#subarray only, but we have to return an ArrayBuffer by contract. So:
5464 if (!forceCopy && offset === 0 && limit === this.buffer.byteLength)
5465 return this.buffer;
5466 if (offset === limit)
5467 return EMPTY_BUFFER;
5468 var buffer = new ArrayBuffer(limit - offset);
5469 new Uint8Array(buffer).set(new Uint8Array(this.buffer).subarray(offset, limit), 0);
5470 return buffer;
5471 };
5472
5473 /**
5474 * Returns a raw buffer compacted to contain this ByteBuffer's contents. Contents are the bytes between
5475 * {@link ByteBuffer#offset} and {@link ByteBuffer#limit}. This is an alias of {@link ByteBuffer#toBuffer}.
5476 * @function
5477 * @param {boolean=} forceCopy If `true` returns a copy, otherwise returns a view referencing the same memory.
5478 * Defaults to `false`
5479 * @returns {!ArrayBuffer} Contents as an ArrayBuffer
5480 * @expose
5481 */
5482 ByteBufferPrototype.toArrayBuffer = ByteBufferPrototype.toBuffer;
5483
5484 /**
5485 * Converts the ByteBuffer's contents to a string.
5486 * @param {string=} encoding Output encoding. Returns an informative string representation if omitted but also allows
5487 * direct conversion to "utf8", "hex", "base64" and "binary" encoding. "debug" returns a hex representation with
5488 * highlighted offsets.
5489 * @param {number=} begin Offset to begin at, defaults to {@link ByteBuffer#offset}
5490 * @param {number=} end Offset to end at, defaults to {@link ByteBuffer#limit}
5491 * @returns {string} String representation
5492 * @throws {Error} If `encoding` is invalid
5493 * @expose
5494 */
5495 ByteBufferPrototype.toString = function(encoding, begin, end) {
5496 if (typeof encoding === 'undefined')
5497 return "ByteBufferAB(offset="+this.offset+",markedOffset="+this.markedOffset+",limit="+this.limit+",capacity="+this.capacity()+")";
5498 if (typeof encoding === 'number')
5499 encoding = "utf8",
5500 begin = encoding,
5501 end = begin;
5502 switch (encoding) {
5503 case "utf8":
5504 return this.toUTF8(begin, end);
5505 case "base64":
5506 return this.toBase64(begin, end);
5507 case "hex":
5508 return this.toHex(begin, end);
5509 case "binary":
5510 return this.toBinary(begin, end);
5511 case "debug":
5512 return this.toDebug();
5513 case "columns":
5514 return this.toColumns();
5515 default:
5516 throw Error("Unsupported encoding: "+encoding);
5517 }
5518 };
5519
5520 // lxiv-embeddable
5521
5522 /**
5523 * lxiv-embeddable (c) 2014 Daniel Wirtz <dcode@dcode.io>
5524 * Released under the Apache License, Version 2.0
5525 * see: https://github.com/dcodeIO/lxiv for details
5526 */
5527 var lxiv = function() {
5528
5529 /**
5530 * lxiv namespace.
5531 * @type {!Object.<string,*>}
5532 * @exports lxiv
5533 */
5534 var lxiv = {};
5535
5536 /**
5537 * Character codes for output.
5538 * @type {!Array.<number>}
5539 * @inner
5540 */
5541 var aout = [
5542 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80,
5543 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 97, 98, 99, 100, 101, 102,
5544 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118,
5545 119, 120, 121, 122, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 43, 47
5546 ];
5547
5548 /**
5549 * Character codes for input.
5550 * @type {!Array.<number>}
5551 * @inner
5552 */
5553 var ain = [];
5554 for (var i=0, k=aout.length; i<k; ++i)
5555 ain[aout[i]] = i;
5556
5557 /**
5558 * Encodes bytes to base64 char codes.
5559 * @param {!function():number|null} src Bytes source as a function returning the next byte respectively `null` if
5560 * there are no more bytes left.
5561 * @param {!function(number)} dst Characters destination as a function successively called with each encoded char
5562 * code.
5563 */
5564 lxiv.encode = function(src, dst) {
5565 var b, t;
5566 while ((b = src()) !== null) {
5567 dst(aout[(b>>2)&0x3f]);
5568 t = (b&0x3)<<4;
5569 if ((b = src()) !== null) {
5570 t |= (b>>4)&0xf;
5571 dst(aout[(t|((b>>4)&0xf))&0x3f]);
5572 t = (b&0xf)<<2;
5573 if ((b = src()) !== null)
5574 dst(aout[(t|((b>>6)&0x3))&0x3f]),
5575 dst(aout[b&0x3f]);
5576 else
5577 dst(aout[t&0x3f]),
5578 dst(61);
5579 } else
5580 dst(aout[t&0x3f]),
5581 dst(61),
5582 dst(61);
5583 }
5584 };
5585
5586 /**
5587 * Decodes base64 char codes to bytes.
5588 * @param {!function():number|null} src Characters source as a function returning the next char code respectively
5589 * `null` if there are no more characters left.
5590 * @param {!function(number)} dst Bytes destination as a function successively called with the next byte.
5591 * @throws {Error} If a character code is invalid
5592 */
5593 lxiv.decode = function(src, dst) {
5594 var c, t1, t2;
5595 function fail(c) {
5596 throw Error("Illegal character code: "+c);
5597 }
5598 while ((c = src()) !== null) {
5599 t1 = ain[c];
5600 if (typeof t1 === 'undefined') fail(c);
5601 if ((c = src()) !== null) {
5602 t2 = ain[c];
5603 if (typeof t2 === 'undefined') fail(c);
5604 dst((t1<<2)>>>0|(t2&0x30)>>4);
5605 if ((c = src()) !== null) {
5606 t1 = ain[c];
5607 if (typeof t1 === 'undefined')
5608 if (c === 61) break; else fail(c);
5609 dst(((t2&0xf)<<4)>>>0|(t1&0x3c)>>2);
5610 if ((c = src()) !== null) {
5611 t2 = ain[c];
5612 if (typeof t2 === 'undefined')
5613 if (c === 61) break; else fail(c);
5614 dst(((t1&0x3)<<6)>>>0|t2);
5615 }
5616 }
5617 }
5618 }
5619 };
5620
5621 /**
5622 * Tests if a string is valid base64.
5623 * @param {string} str String to test
5624 * @returns {boolean} `true` if valid, otherwise `false`
5625 */
5626 lxiv.test = function(str) {
5627 return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(str);
5628 };
5629
5630 return lxiv;
5631 }();
5632
5633 // encodings/base64
5634
5635 /**
5636 * Encodes this ByteBuffer's contents to a base64 encoded string.
5637 * @param {number=} begin Offset to begin at, defaults to {@link ByteBuffer#offset}.
5638 * @param {number=} end Offset to end at, defaults to {@link ByteBuffer#limit}.
5639 * @returns {string} Base64 encoded string
5640 * @throws {RangeError} If `begin` or `end` is out of bounds
5641 * @expose
5642 */
5643 ByteBufferPrototype.toBase64 = function(begin, end) {
5644 if (typeof begin === 'undefined')
5645 begin = this.offset;
5646 if (typeof end === 'undefined')
5647 end = this.limit;
5648 begin = begin | 0; end = end | 0;
5649 if (begin < 0 || end > this.capacity || begin > end)
5650 throw RangeError("begin, end");
5651 var sd; lxiv.encode(function() {
5652 return begin < end ? this.view[begin++] : null;
5653 }.bind(this), sd = stringDestination());
5654 return sd();
5655 };
5656
5657 /**
5658 * Decodes a base64 encoded string to a ByteBuffer.
5659 * @param {string} str String to decode
5660 * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
5661 * {@link ByteBuffer.DEFAULT_ENDIAN}.
5662 * @returns {!ByteBuffer} ByteBuffer
5663 * @expose
5664 */
5665 ByteBuffer.fromBase64 = function(str, littleEndian) {
5666 if (typeof str !== 'string')
5667 throw TypeError("str");
5668 var bb = new ByteBuffer(str.length/4*3, littleEndian),
5669 i = 0;
5670 lxiv.decode(stringSource(str), function(b) {
5671 bb.view[i++] = b;
5672 });
5673 bb.limit = i;
5674 return bb;
5675 };
5676
5677 /**
5678 * Encodes a binary string to base64 like `window.btoa` does.
5679 * @param {string} str Binary string
5680 * @returns {string} Base64 encoded string
5681 * @see https://developer.mozilla.org/en-US/docs/Web/API/Window.btoa
5682 * @expose
5683 */
5684 ByteBuffer.btoa = function(str) {
5685 return ByteBuffer.fromBinary(str).toBase64();
5686 };
5687
5688 /**
5689 * Decodes a base64 encoded string to binary like `window.atob` does.
5690 * @param {string} b64 Base64 encoded string
5691 * @returns {string} Binary string
5692 * @see https://developer.mozilla.org/en-US/docs/Web/API/Window.atob
5693 * @expose
5694 */
5695 ByteBuffer.atob = function(b64) {
5696 return ByteBuffer.fromBase64(b64).toBinary();
5697 };
5698
5699 // encodings/binary
5700
5701 /**
5702 * Encodes this ByteBuffer to a binary encoded string, that is using only characters 0x00-0xFF as bytes.
5703 * @param {number=} begin Offset to begin at. Defaults to {@link ByteBuffer#offset}.
5704 * @param {number=} end Offset to end at. Defaults to {@link ByteBuffer#limit}.
5705 * @returns {string} Binary encoded string
5706 * @throws {RangeError} If `offset > limit`
5707 * @expose
5708 */
5709 ByteBufferPrototype.toBinary = function(begin, end) {
5710 if (typeof begin === 'undefined')
5711 begin = this.offset;
5712 if (typeof end === 'undefined')
5713 end = this.limit;
5714 begin |= 0; end |= 0;
5715 if (begin < 0 || end > this.capacity() || begin > end)
5716 throw RangeError("begin, end");
5717 if (begin === end)
5718 return "";
5719 var chars = [],
5720 parts = [];
5721 while (begin < end) {
5722 chars.push(this.view[begin++]);
5723 if (chars.length >= 1024)
5724 parts.push(String.fromCharCode.apply(String, chars)),
5725 chars = [];
5726 }
5727 return parts.join('') + String.fromCharCode.apply(String, chars);
5728 };
5729
5730 /**
5731 * Decodes a binary encoded string, that is using only characters 0x00-0xFF as bytes, to a ByteBuffer.
5732 * @param {string} str String to decode
5733 * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
5734 * {@link ByteBuffer.DEFAULT_ENDIAN}.
5735 * @returns {!ByteBuffer} ByteBuffer
5736 * @expose
5737 */
5738 ByteBuffer.fromBinary = function(str, littleEndian) {
5739 if (typeof str !== 'string')
5740 throw TypeError("str");
5741 var i = 0,
5742 k = str.length,
5743 charCode,
5744 bb = new ByteBuffer(k, littleEndian);
5745 while (i<k) {
5746 charCode = str.charCodeAt(i);
5747 if (charCode > 0xff)
5748 throw RangeError("illegal char code: "+charCode);
5749 bb.view[i++] = charCode;
5750 }
5751 bb.limit = k;
5752 return bb;
5753 };
5754
5755 // encodings/debug
5756
5757 /**
5758 * Encodes this ByteBuffer to a hex encoded string with marked offsets. Offset symbols are:
5759 * * `<` : offset,
5760 * * `'` : markedOffset,
5761 * * `>` : limit,
5762 * * `|` : offset and limit,
5763 * * `[` : offset and markedOffset,
5764 * * `]` : markedOffset and limit,
5765 * * `!` : offset, markedOffset and limit
5766 * @param {boolean=} columns If `true` returns two columns hex + ascii, defaults to `false`
5767 * @returns {string|!Array.<string>} Debug string or array of lines if `asArray = true`
5768 * @expose
5769 * @example `>00'01 02<03` contains four bytes with `limit=0, markedOffset=1, offset=3`
5770 * @example `00[01 02 03>` contains four bytes with `offset=markedOffset=1, limit=4`
5771 * @example `00|01 02 03` contains four bytes with `offset=limit=1, markedOffset=-1`
5772 * @example `|` contains zero bytes with `offset=limit=0, markedOffset=-1`
5773 */
5774 ByteBufferPrototype.toDebug = function(columns) {
5775 var i = -1,
5776 k = this.buffer.byteLength,
5777 b,
5778 hex = "",
5779 asc = "",
5780 out = "";
5781 while (i<k) {
5782 if (i !== -1) {
5783 b = this.view[i];
5784 if (b < 0x10) hex += "0"+b.toString(16).toUpperCase();
5785 else hex += b.toString(16).toUpperCase();
5786 if (columns)
5787 asc += b > 32 && b < 127 ? String.fromCharCode(b) : '.';
5788 }
5789 ++i;
5790 if (columns) {
5791 if (i > 0 && i % 16 === 0 && i !== k) {
5792 while (hex.length < 3*16+3) hex += " ";
5793 out += hex+asc+"\n";
5794 hex = asc = "";
5795 }
5796 }
5797 if (i === this.offset && i === this.limit)
5798 hex += i === this.markedOffset ? "!" : "|";
5799 else if (i === this.offset)
5800 hex += i === this.markedOffset ? "[" : "<";
5801 else if (i === this.limit)
5802 hex += i === this.markedOffset ? "]" : ">";
5803 else
5804 hex += i === this.markedOffset ? "'" : (columns || (i !== 0 && i !== k) ? " " : "");
5805 }
5806 if (columns && hex !== " ") {
5807 while (hex.length < 3*16+3)
5808 hex += " ";
5809 out += hex + asc + "\n";
5810 }
5811 return columns ? out : hex;
5812 };
5813
5814 /**
5815 * Decodes a hex encoded string with marked offsets to a ByteBuffer.
5816 * @param {string} str Debug string to decode (not be generated with `columns = true`)
5817 * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
5818 * {@link ByteBuffer.DEFAULT_ENDIAN}.
5819 * @param {boolean=} noAssert Whether to skip assertions of offsets and values. Defaults to
5820 * {@link ByteBuffer.DEFAULT_NOASSERT}.
5821 * @returns {!ByteBuffer} ByteBuffer
5822 * @expose
5823 * @see ByteBuffer#toDebug
5824 */
5825 ByteBuffer.fromDebug = function(str, littleEndian, noAssert) {
5826 var k = str.length,
5827 bb = new ByteBuffer(((k+1)/3)|0, littleEndian, noAssert);
5828 var i = 0, j = 0, ch, b,
5829 rs = false, // Require symbol next
5830 ho = false, hm = false, hl = false, // Already has offset (ho), markedOffset (hm), limit (hl)?
5831 fail = false;
5832 while (i<k) {
5833 switch (ch = str.charAt(i++)) {
5834 case '!':
5835 if (!noAssert) {
5836 if (ho || hm || hl) {
5837 fail = true;
5838 break;
5839 }
5840 ho = hm = hl = true;
5841 }
5842 bb.offset = bb.markedOffset = bb.limit = j;
5843 rs = false;
5844 break;
5845 case '|':
5846 if (!noAssert) {
5847 if (ho || hl) {
5848 fail = true;
5849 break;
5850 }
5851 ho = hl = true;
5852 }
5853 bb.offset = bb.limit = j;
5854 rs = false;
5855 break;
5856 case '[':
5857 if (!noAssert) {
5858 if (ho || hm) {
5859 fail = true;
5860 break;
5861 }
5862 ho = hm = true;
5863 }
5864 bb.offset = bb.markedOffset = j;
5865 rs = false;
5866 break;
5867 case '<':
5868 if (!noAssert) {
5869 if (ho) {
5870 fail = true;
5871 break;
5872 }
5873 ho = true;
5874 }
5875 bb.offset = j;
5876 rs = false;
5877 break;
5878 case ']':
5879 if (!noAssert) {
5880 if (hl || hm) {
5881 fail = true;
5882 break;
5883 }
5884 hl = hm = true;
5885 }
5886 bb.limit = bb.markedOffset = j;
5887 rs = false;
5888 break;
5889 case '>':
5890 if (!noAssert) {
5891 if (hl) {
5892 fail = true;
5893 break;
5894 }
5895 hl = true;
5896 }
5897 bb.limit = j;
5898 rs = false;
5899 break;
5900 case "'":
5901 if (!noAssert) {
5902 if (hm) {
5903 fail = true;
5904 break;
5905 }
5906 hm = true;
5907 }
5908 bb.markedOffset = j;
5909 rs = false;
5910 break;
5911 case ' ':
5912 rs = false;
5913 break;
5914 default:
5915 if (!noAssert) {
5916 if (rs) {
5917 fail = true;
5918 break;
5919 }
5920 }
5921 b = parseInt(ch+str.charAt(i++), 16);
5922 if (!noAssert) {
5923 if (isNaN(b) || b < 0 || b > 255)
5924 throw TypeError("Illegal str: Not a debug encoded string");
5925 }
5926 bb.view[j++] = b;
5927 rs = true;
5928 }
5929 if (fail)
5930 throw TypeError("Illegal str: Invalid symbol at "+i);
5931 }
5932 if (!noAssert) {
5933 if (!ho || !hl)
5934 throw TypeError("Illegal str: Missing offset or limit");
5935 if (j<bb.buffer.byteLength)
5936 throw TypeError("Illegal str: Not a debug encoded string (is it hex?) "+j+" < "+k);
5937 }
5938 return bb;
5939 };
5940
5941 // encodings/hex
5942
5943 /**
5944 * Encodes this ByteBuffer's contents to a hex encoded string.
5945 * @param {number=} begin Offset to begin at. Defaults to {@link ByteBuffer#offset}.
5946 * @param {number=} end Offset to end at. Defaults to {@link ByteBuffer#limit}.
5947 * @returns {string} Hex encoded string
5948 * @expose
5949 */
5950 ByteBufferPrototype.toHex = function(begin, end) {
5951 begin = typeof begin === 'undefined' ? this.offset : begin;
5952 end = typeof end === 'undefined' ? this.limit : end;
5953 if (!this.noAssert) {
5954 if (typeof begin !== 'number' || begin % 1 !== 0)
5955 throw TypeError("Illegal begin: Not an integer");
5956 begin >>>= 0;
5957 if (typeof end !== 'number' || end % 1 !== 0)
5958 throw TypeError("Illegal end: Not an integer");
5959 end >>>= 0;
5960 if (begin < 0 || begin > end || end > this.buffer.byteLength)
5961 throw RangeError("Illegal range: 0 <= "+begin+" <= "+end+" <= "+this.buffer.byteLength);
5962 }
5963 var out = new Array(end - begin),
5964 b;
5965 while (begin < end) {
5966 b = this.view[begin++];
5967 if (b < 0x10)
5968 out.push("0", b.toString(16));
5969 else out.push(b.toString(16));
5970 }
5971 return out.join('');
5972 };
5973
5974 /**
5975 * Decodes a hex encoded string to a ByteBuffer.
5976 * @param {string} str String to decode
5977 * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
5978 * {@link ByteBuffer.DEFAULT_ENDIAN}.
5979 * @param {boolean=} noAssert Whether to skip assertions of offsets and values. Defaults to
5980 * {@link ByteBuffer.DEFAULT_NOASSERT}.
5981 * @returns {!ByteBuffer} ByteBuffer
5982 * @expose
5983 */
5984 ByteBuffer.fromHex = function(str, littleEndian, noAssert) {
5985 if (!noAssert) {
5986 if (typeof str !== 'string')
5987 throw TypeError("Illegal str: Not a string");
5988 if (str.length % 2 !== 0)
5989 throw TypeError("Illegal str: Length not a multiple of 2");
5990 }
5991 var k = str.length,
5992 bb = new ByteBuffer((k / 2) | 0, littleEndian),
5993 b;
5994 for (var i=0, j=0; i<k; i+=2) {
5995 b = parseInt(str.substring(i, i+2), 16);
5996 if (!noAssert)
5997 if (!isFinite(b) || b < 0 || b > 255)
5998 throw TypeError("Illegal str: Contains non-hex characters");
5999 bb.view[j++] = b;
6000 }
6001 bb.limit = j;
6002 return bb;
6003 };
6004
6005 // utfx-embeddable
6006
6007 /**
6008 * utfx-embeddable (c) 2014 Daniel Wirtz <dcode@dcode.io>
6009 * Released under the Apache License, Version 2.0
6010 * see: https://github.com/dcodeIO/utfx for details
6011 */
6012 var utfx = function() {
6013
6014 /**
6015 * utfx namespace.
6016 * @inner
6017 * @type {!Object.<string,*>}
6018 */
6019 var utfx = {};
6020
6021 /**
6022 * Maximum valid code point.
6023 * @type {number}
6024 * @const
6025 */
6026 utfx.MAX_CODEPOINT = 0x10FFFF;
6027
6028 /**
6029 * Encodes UTF8 code points to UTF8 bytes.
6030 * @param {(!function():number|null) | number} src Code points source, either as a function returning the next code point
6031 * respectively `null` if there are no more code points left or a single numeric code point.
6032 * @param {!function(number)} dst Bytes destination as a function successively called with the next byte
6033 */
6034 utfx.encodeUTF8 = function(src, dst) {
6035 var cp = null;
6036 if (typeof src === 'number')
6037 cp = src,
6038 src = function() { return null; };
6039 while (cp !== null || (cp = src()) !== null) {
6040 if (cp < 0x80)
6041 dst(cp&0x7F);
6042 else if (cp < 0x800)
6043 dst(((cp>>6)&0x1F)|0xC0),
6044 dst((cp&0x3F)|0x80);
6045 else if (cp < 0x10000)
6046 dst(((cp>>12)&0x0F)|0xE0),
6047 dst(((cp>>6)&0x3F)|0x80),
6048 dst((cp&0x3F)|0x80);
6049 else
6050 dst(((cp>>18)&0x07)|0xF0),
6051 dst(((cp>>12)&0x3F)|0x80),
6052 dst(((cp>>6)&0x3F)|0x80),
6053 dst((cp&0x3F)|0x80);
6054 cp = null;
6055 }
6056 };
6057
6058 /**
6059 * Decodes UTF8 bytes to UTF8 code points.
6060 * @param {!function():number|null} src Bytes source as a function returning the next byte respectively `null` if there
6061 * are no more bytes left.
6062 * @param {!function(number)} dst Code points destination as a function successively called with each decoded code point.
6063 * @throws {RangeError} If a starting byte is invalid in UTF8
6064 * @throws {Error} If the last sequence is truncated. Has an array property `bytes` holding the
6065 * remaining bytes.
6066 */
6067 utfx.decodeUTF8 = function(src, dst) {
6068 var a, b, c, d, fail = function(b) {
6069 b = b.slice(0, b.indexOf(null));
6070 var err = Error(b.toString());
6071 err.name = "TruncatedError";
6072 err['bytes'] = b;
6073 throw err;
6074 };
6075 while ((a = src()) !== null) {
6076 if ((a&0x80) === 0)
6077 dst(a);
6078 else if ((a&0xE0) === 0xC0)
6079 ((b = src()) === null) && fail([a, b]),
6080 dst(((a&0x1F)<<6) | (b&0x3F));
6081 else if ((a&0xF0) === 0xE0)
6082 ((b=src()) === null || (c=src()) === null) && fail([a, b, c]),
6083 dst(((a&0x0F)<<12) | ((b&0x3F)<<6) | (c&0x3F));
6084 else if ((a&0xF8) === 0xF0)
6085 ((b=src()) === null || (c=src()) === null || (d=src()) === null) && fail([a, b, c ,d]),
6086 dst(((a&0x07)<<18) | ((b&0x3F)<<12) | ((c&0x3F)<<6) | (d&0x3F));
6087 else throw RangeError("Illegal starting byte: "+a);
6088 }
6089 };
6090
6091 /**
6092 * Converts UTF16 characters to UTF8 code points.
6093 * @param {!function():number|null} src Characters source as a function returning the next char code respectively
6094 * `null` if there are no more characters left.
6095 * @param {!function(number)} dst Code points destination as a function successively called with each converted code
6096 * point.
6097 */
6098 utfx.UTF16toUTF8 = function(src, dst) {
6099 var c1, c2 = null;
6100 while (true) {
6101 if ((c1 = c2 !== null ? c2 : src()) === null)
6102 break;
6103 if (c1 >= 0xD800 && c1 <= 0xDFFF) {
6104 if ((c2 = src()) !== null) {
6105 if (c2 >= 0xDC00 && c2 <= 0xDFFF) {
6106 dst((c1-0xD800)*0x400+c2-0xDC00+0x10000);
6107 c2 = null; continue;
6108 }
6109 }
6110 }
6111 dst(c1);
6112 }
6113 if (c2 !== null) dst(c2);
6114 };
6115
6116 /**
6117 * Converts UTF8 code points to UTF16 characters.
6118 * @param {(!function():number|null) | number} src Code points source, either as a function returning the next code point
6119 * respectively `null` if there are no more code points left or a single numeric code point.
6120 * @param {!function(number)} dst Characters destination as a function successively called with each converted char code.
6121 * @throws {RangeError} If a code point is out of range
6122 */
6123 utfx.UTF8toUTF16 = function(src, dst) {
6124 var cp = null;
6125 if (typeof src === 'number')
6126 cp = src, src = function() { return null; };
6127 while (cp !== null || (cp = src()) !== null) {
6128 if (cp <= 0xFFFF)
6129 dst(cp);
6130 else
6131 cp -= 0x10000,
6132 dst((cp>>10)+0xD800),
6133 dst((cp%0x400)+0xDC00);
6134 cp = null;
6135 }
6136 };
6137
6138 /**
6139 * Converts and encodes UTF16 characters to UTF8 bytes.
6140 * @param {!function():number|null} src Characters source as a function returning the next char code respectively `null`
6141 * if there are no more characters left.
6142 * @param {!function(number)} dst Bytes destination as a function successively called with the next byte.
6143 */
6144 utfx.encodeUTF16toUTF8 = function(src, dst) {
6145 utfx.UTF16toUTF8(src, function(cp) {
6146 utfx.encodeUTF8(cp, dst);
6147 });
6148 };
6149
6150 /**
6151 * Decodes and converts UTF8 bytes to UTF16 characters.
6152 * @param {!function():number|null} src Bytes source as a function returning the next byte respectively `null` if there
6153 * are no more bytes left.
6154 * @param {!function(number)} dst Characters destination as a function successively called with each converted char code.
6155 * @throws {RangeError} If a starting byte is invalid in UTF8
6156 * @throws {Error} If the last sequence is truncated. Has an array property `bytes` holding the remaining bytes.
6157 */
6158 utfx.decodeUTF8toUTF16 = function(src, dst) {
6159 utfx.decodeUTF8(src, function(cp) {
6160 utfx.UTF8toUTF16(cp, dst);
6161 });
6162 };
6163
6164 /**
6165 * Calculates the byte length of an UTF8 code point.
6166 * @param {number} cp UTF8 code point
6167 * @returns {number} Byte length
6168 */
6169 utfx.calculateCodePoint = function(cp) {
6170 return (cp < 0x80) ? 1 : (cp < 0x800) ? 2 : (cp < 0x10000) ? 3 : 4;
6171 };
6172
6173 /**
6174 * Calculates the number of UTF8 bytes required to store UTF8 code points.
6175 * @param {(!function():number|null)} src Code points source as a function returning the next code point respectively
6176 * `null` if there are no more code points left.
6177 * @returns {number} The number of UTF8 bytes required
6178 */
6179 utfx.calculateUTF8 = function(src) {
6180 var cp, l=0;
6181 while ((cp = src()) !== null)
6182 l += (cp < 0x80) ? 1 : (cp < 0x800) ? 2 : (cp < 0x10000) ? 3 : 4;
6183 return l;
6184 };
6185
6186 /**
6187 * Calculates the number of UTF8 code points respectively UTF8 bytes required to store UTF16 char codes.
6188 * @param {(!function():number|null)} src Characters source as a function returning the next char code respectively
6189 * `null` if there are no more characters left.
6190 * @returns {!Array.<number>} The number of UTF8 code points at index 0 and the number of UTF8 bytes required at index 1.
6191 */
6192 utfx.calculateUTF16asUTF8 = function(src) {
6193 var n=0, l=0;
6194 utfx.UTF16toUTF8(src, function(cp) {
6195 ++n; l += (cp < 0x80) ? 1 : (cp < 0x800) ? 2 : (cp < 0x10000) ? 3 : 4;
6196 });
6197 return [n,l];
6198 };
6199
6200 return utfx;
6201 }();
6202
6203 // encodings/utf8
6204
6205 /**
6206 * Encodes this ByteBuffer's contents between {@link ByteBuffer#offset} and {@link ByteBuffer#limit} to an UTF8 encoded
6207 * string.
6208 * @returns {string} Hex encoded string
6209 * @throws {RangeError} If `offset > limit`
6210 * @expose
6211 */
6212 ByteBufferPrototype.toUTF8 = function(begin, end) {
6213 if (typeof begin === 'undefined') begin = this.offset;
6214 if (typeof end === 'undefined') end = this.limit;
6215 if (!this.noAssert) {
6216 if (typeof begin !== 'number' || begin % 1 !== 0)
6217 throw TypeError("Illegal begin: Not an integer");
6218 begin >>>= 0;
6219 if (typeof end !== 'number' || end % 1 !== 0)
6220 throw TypeError("Illegal end: Not an integer");
6221 end >>>= 0;
6222 if (begin < 0 || begin > end || end > this.buffer.byteLength)
6223 throw RangeError("Illegal range: 0 <= "+begin+" <= "+end+" <= "+this.buffer.byteLength);
6224 }
6225 var sd; try {
6226 utfx.decodeUTF8toUTF16(function() {
6227 return begin < end ? this.view[begin++] : null;
6228 }.bind(this), sd = stringDestination());
6229 } catch (e) {
6230 if (begin !== end)
6231 throw RangeError("Illegal range: Truncated data, "+begin+" != "+end);
6232 }
6233 return sd();
6234 };
6235
6236 /**
6237 * Decodes an UTF8 encoded string to a ByteBuffer.
6238 * @param {string} str String to decode
6239 * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
6240 * {@link ByteBuffer.DEFAULT_ENDIAN}.
6241 * @param {boolean=} noAssert Whether to skip assertions of offsets and values. Defaults to
6242 * {@link ByteBuffer.DEFAULT_NOASSERT}.
6243 * @returns {!ByteBuffer} ByteBuffer
6244 * @expose
6245 */
6246 ByteBuffer.fromUTF8 = function(str, littleEndian, noAssert) {
6247 if (!noAssert)
6248 if (typeof str !== 'string')
6249 throw TypeError("Illegal str: Not a string");
6250 var bb = new ByteBuffer(utfx.calculateUTF16asUTF8(stringSource(str), true)[1], littleEndian, noAssert),
6251 i = 0;
6252 utfx.encodeUTF16toUTF8(stringSource(str), function(b) {
6253 bb.view[i++] = b;
6254 });
6255 bb.limit = i;
6256 return bb;
6257 };
6258
6259 return ByteBuffer;
6260 });
6261 });
6262
6263 var _nodeResolve_empty = {};
6264
6265 var _nodeResolve_empty$1 = /*#__PURE__*/Object.freeze({
6266 __proto__: null,
6267 'default': _nodeResolve_empty
6268 });
6269
6270 var require$$2 = getCjsExportFromNamespace(_nodeResolve_empty$1);
6271
6272 var protobufLight = createCommonjsModule(function (module) {
6273 /*
6274 Copyright 2013 Daniel Wirtz <dcode@dcode.io>
6275
6276 Licensed under the Apache License, Version 2.0 (the "License");
6277 you may not use this file except in compliance with the License.
6278 You may obtain a copy of the License at
6279
6280 http://www.apache.org/licenses/LICENSE-2.0
6281
6282 Unless required by applicable law or agreed to in writing, software
6283 distributed under the License is distributed on an "AS IS" BASIS,
6284 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
6285 See the License for the specific language governing permissions and
6286 limitations under the License.
6287 */
6288
6289 /**
6290 * @license protobuf.js (c) 2013 Daniel Wirtz <dcode@dcode.io>
6291 * Released under the Apache License, Version 2.0
6292 * see: https://github.com/dcodeIO/protobuf.js for details
6293 */
6294 (function(global, factory) {
6295
6296 /* AMD */ if (typeof commonjsRequire === "function" && 'object' === "object" && module && module["exports"])
6297 module["exports"] = factory(bytebuffer, true);
6298 /* Global */ else
6299 (global["dcodeIO"] = global["dcodeIO"] || {})["ProtoBuf"] = factory(global["dcodeIO"]["ByteBuffer"]);
6300
6301 })(commonjsGlobal, function(ByteBuffer, isCommonJS) {
6302
6303 /**
6304 * The ProtoBuf namespace.
6305 * @exports ProtoBuf
6306 * @namespace
6307 * @expose
6308 */
6309 var ProtoBuf = {};
6310
6311 /**
6312 * @type {!function(new: ByteBuffer, ...[*])}
6313 * @expose
6314 */
6315 ProtoBuf.ByteBuffer = ByteBuffer;
6316
6317 /**
6318 * @type {?function(new: Long, ...[*])}
6319 * @expose
6320 */
6321 ProtoBuf.Long = ByteBuffer.Long || null;
6322
6323 /**
6324 * ProtoBuf.js version.
6325 * @type {string}
6326 * @const
6327 * @expose
6328 */
6329 ProtoBuf.VERSION = "5.0.3";
6330
6331 /**
6332 * Wire types.
6333 * @type {Object.<string,number>}
6334 * @const
6335 * @expose
6336 */
6337 ProtoBuf.WIRE_TYPES = {};
6338
6339 /**
6340 * Varint wire type.
6341 * @type {number}
6342 * @expose
6343 */
6344 ProtoBuf.WIRE_TYPES.VARINT = 0;
6345
6346 /**
6347 * Fixed 64 bits wire type.
6348 * @type {number}
6349 * @const
6350 * @expose
6351 */
6352 ProtoBuf.WIRE_TYPES.BITS64 = 1;
6353
6354 /**
6355 * Length delimited wire type.
6356 * @type {number}
6357 * @const
6358 * @expose
6359 */
6360 ProtoBuf.WIRE_TYPES.LDELIM = 2;
6361
6362 /**
6363 * Start group wire type.
6364 * @type {number}
6365 * @const
6366 * @expose
6367 */
6368 ProtoBuf.WIRE_TYPES.STARTGROUP = 3;
6369
6370 /**
6371 * End group wire type.
6372 * @type {number}
6373 * @const
6374 * @expose
6375 */
6376 ProtoBuf.WIRE_TYPES.ENDGROUP = 4;
6377
6378 /**
6379 * Fixed 32 bits wire type.
6380 * @type {number}
6381 * @const
6382 * @expose
6383 */
6384 ProtoBuf.WIRE_TYPES.BITS32 = 5;
6385
6386 /**
6387 * Packable wire types.
6388 * @type {!Array.<number>}
6389 * @const
6390 * @expose
6391 */
6392 ProtoBuf.PACKABLE_WIRE_TYPES = [
6393 ProtoBuf.WIRE_TYPES.VARINT,
6394 ProtoBuf.WIRE_TYPES.BITS64,
6395 ProtoBuf.WIRE_TYPES.BITS32
6396 ];
6397
6398 /**
6399 * Types.
6400 * @dict
6401 * @type {!Object.<string,{name: string, wireType: number, defaultValue: *}>}
6402 * @const
6403 * @expose
6404 */
6405 ProtoBuf.TYPES = {
6406 // According to the protobuf spec.
6407 "int32": {
6408 name: "int32",
6409 wireType: ProtoBuf.WIRE_TYPES.VARINT,
6410 defaultValue: 0
6411 },
6412 "uint32": {
6413 name: "uint32",
6414 wireType: ProtoBuf.WIRE_TYPES.VARINT,
6415 defaultValue: 0
6416 },
6417 "sint32": {
6418 name: "sint32",
6419 wireType: ProtoBuf.WIRE_TYPES.VARINT,
6420 defaultValue: 0
6421 },
6422 "int64": {
6423 name: "int64",
6424 wireType: ProtoBuf.WIRE_TYPES.VARINT,
6425 defaultValue: ProtoBuf.Long ? ProtoBuf.Long.ZERO : undefined
6426 },
6427 "uint64": {
6428 name: "uint64",
6429 wireType: ProtoBuf.WIRE_TYPES.VARINT,
6430 defaultValue: ProtoBuf.Long ? ProtoBuf.Long.UZERO : undefined
6431 },
6432 "sint64": {
6433 name: "sint64",
6434 wireType: ProtoBuf.WIRE_TYPES.VARINT,
6435 defaultValue: ProtoBuf.Long ? ProtoBuf.Long.ZERO : undefined
6436 },
6437 "bool": {
6438 name: "bool",
6439 wireType: ProtoBuf.WIRE_TYPES.VARINT,
6440 defaultValue: false
6441 },
6442 "double": {
6443 name: "double",
6444 wireType: ProtoBuf.WIRE_TYPES.BITS64,
6445 defaultValue: 0
6446 },
6447 "string": {
6448 name: "string",
6449 wireType: ProtoBuf.WIRE_TYPES.LDELIM,
6450 defaultValue: ""
6451 },
6452 "bytes": {
6453 name: "bytes",
6454 wireType: ProtoBuf.WIRE_TYPES.LDELIM,
6455 defaultValue: null // overridden in the code, must be a unique instance
6456 },
6457 "fixed32": {
6458 name: "fixed32",
6459 wireType: ProtoBuf.WIRE_TYPES.BITS32,
6460 defaultValue: 0
6461 },
6462 "sfixed32": {
6463 name: "sfixed32",
6464 wireType: ProtoBuf.WIRE_TYPES.BITS32,
6465 defaultValue: 0
6466 },
6467 "fixed64": {
6468 name: "fixed64",
6469 wireType: ProtoBuf.WIRE_TYPES.BITS64,
6470 defaultValue: ProtoBuf.Long ? ProtoBuf.Long.UZERO : undefined
6471 },
6472 "sfixed64": {
6473 name: "sfixed64",
6474 wireType: ProtoBuf.WIRE_TYPES.BITS64,
6475 defaultValue: ProtoBuf.Long ? ProtoBuf.Long.ZERO : undefined
6476 },
6477 "float": {
6478 name: "float",
6479 wireType: ProtoBuf.WIRE_TYPES.BITS32,
6480 defaultValue: 0
6481 },
6482 "enum": {
6483 name: "enum",
6484 wireType: ProtoBuf.WIRE_TYPES.VARINT,
6485 defaultValue: 0
6486 },
6487 "message": {
6488 name: "message",
6489 wireType: ProtoBuf.WIRE_TYPES.LDELIM,
6490 defaultValue: null
6491 },
6492 "group": {
6493 name: "group",
6494 wireType: ProtoBuf.WIRE_TYPES.STARTGROUP,
6495 defaultValue: null
6496 }
6497 };
6498
6499 /**
6500 * Valid map key types.
6501 * @type {!Array.<!Object.<string,{name: string, wireType: number, defaultValue: *}>>}
6502 * @const
6503 * @expose
6504 */
6505 ProtoBuf.MAP_KEY_TYPES = [
6506 ProtoBuf.TYPES["int32"],
6507 ProtoBuf.TYPES["sint32"],
6508 ProtoBuf.TYPES["sfixed32"],
6509 ProtoBuf.TYPES["uint32"],
6510 ProtoBuf.TYPES["fixed32"],
6511 ProtoBuf.TYPES["int64"],
6512 ProtoBuf.TYPES["sint64"],
6513 ProtoBuf.TYPES["sfixed64"],
6514 ProtoBuf.TYPES["uint64"],
6515 ProtoBuf.TYPES["fixed64"],
6516 ProtoBuf.TYPES["bool"],
6517 ProtoBuf.TYPES["string"],
6518 ProtoBuf.TYPES["bytes"]
6519 ];
6520
6521 /**
6522 * Minimum field id.
6523 * @type {number}
6524 * @const
6525 * @expose
6526 */
6527 ProtoBuf.ID_MIN = 1;
6528
6529 /**
6530 * Maximum field id.
6531 * @type {number}
6532 * @const
6533 * @expose
6534 */
6535 ProtoBuf.ID_MAX = 0x1FFFFFFF;
6536
6537 /**
6538 * If set to `true`, field names will be converted from underscore notation to camel case. Defaults to `false`.
6539 * Must be set prior to parsing.
6540 * @type {boolean}
6541 * @expose
6542 */
6543 ProtoBuf.convertFieldsToCamelCase = false;
6544
6545 /**
6546 * By default, messages are populated with (setX, set_x) accessors for each field. This can be disabled by
6547 * setting this to `false` prior to building messages.
6548 * @type {boolean}
6549 * @expose
6550 */
6551 ProtoBuf.populateAccessors = true;
6552
6553 /**
6554 * By default, messages are populated with default values if a field is not present on the wire. To disable
6555 * this behavior, set this setting to `false`.
6556 * @type {boolean}
6557 * @expose
6558 */
6559 ProtoBuf.populateDefaults = true;
6560
6561 /**
6562 * @alias ProtoBuf.Util
6563 * @expose
6564 */
6565 ProtoBuf.Util = (function() {
6566
6567 /**
6568 * ProtoBuf utilities.
6569 * @exports ProtoBuf.Util
6570 * @namespace
6571 */
6572 var Util = {};
6573
6574 /**
6575 * Flag if running in node or not.
6576 * @type {boolean}
6577 * @const
6578 * @expose
6579 */
6580 Util.IS_NODE = !!(
6581 typeof process === 'object' && process+'' === '[object process]' && !process['browser']
6582 );
6583
6584 /**
6585 * Constructs a XMLHttpRequest object.
6586 * @return {XMLHttpRequest}
6587 * @throws {Error} If XMLHttpRequest is not supported
6588 * @expose
6589 */
6590 Util.XHR = function() {
6591 // No dependencies please, ref: http://www.quirksmode.org/js/xmlhttp.html
6592 var XMLHttpFactories = [
6593 function () {return new XMLHttpRequest()},
6594 function () {return new ActiveXObject("Msxml2.XMLHTTP")},
6595 function () {return new ActiveXObject("Msxml3.XMLHTTP")},
6596 function () {return new ActiveXObject("Microsoft.XMLHTTP")}
6597 ];
6598 /** @type {?XMLHttpRequest} */
6599 var xhr = null;
6600 for (var i=0;i<XMLHttpFactories.length;i++) {
6601 try { xhr = XMLHttpFactories[i](); }
6602 catch (e) { continue; }
6603 break;
6604 }
6605 if (!xhr)
6606 throw Error("XMLHttpRequest is not supported");
6607 return xhr;
6608 };
6609
6610 /**
6611 * Fetches a resource.
6612 * @param {string} path Resource path
6613 * @param {function(?string)=} callback Callback receiving the resource's contents. If omitted the resource will
6614 * be fetched synchronously. If the request failed, contents will be null.
6615 * @return {?string|undefined} Resource contents if callback is omitted (null if the request failed), else undefined.
6616 * @expose
6617 */
6618 Util.fetch = function(path, callback) {
6619 if (callback && typeof callback != 'function')
6620 callback = null;
6621 if (Util.IS_NODE) {
6622 var fs = require$$2;
6623 if (callback) {
6624 fs.readFile(path, function(err, data) {
6625 if (err)
6626 callback(null);
6627 else
6628 callback(""+data);
6629 });
6630 } else
6631 try {
6632 return fs.readFileSync(path);
6633 } catch (e) {
6634 return null;
6635 }
6636 } else {
6637 var xhr = Util.XHR();
6638 xhr.open('GET', path, callback ? true : false);
6639 // xhr.setRequestHeader('User-Agent', 'XMLHTTP/1.0');
6640 xhr.setRequestHeader('Accept', 'text/plain');
6641 if (typeof xhr.overrideMimeType === 'function') xhr.overrideMimeType('text/plain');
6642 if (callback) {
6643 xhr.onreadystatechange = function() {
6644 if (xhr.readyState != 4) return;
6645 if (/* remote */ xhr.status == 200 || /* local */ (xhr.status == 0 && typeof xhr.responseText === 'string'))
6646 callback(xhr.responseText);
6647 else
6648 callback(null);
6649 };
6650 if (xhr.readyState == 4)
6651 return;
6652 xhr.send(null);
6653 } else {
6654 xhr.send(null);
6655 if (/* remote */ xhr.status == 200 || /* local */ (xhr.status == 0 && typeof xhr.responseText === 'string'))
6656 return xhr.responseText;
6657 return null;
6658 }
6659 }
6660 };
6661
6662 /**
6663 * Converts a string to camel case.
6664 * @param {string} str
6665 * @returns {string}
6666 * @expose
6667 */
6668 Util.toCamelCase = function(str) {
6669 return str.replace(/_([a-zA-Z])/g, function ($0, $1) {
6670 return $1.toUpperCase();
6671 });
6672 };
6673
6674 return Util;
6675 })();
6676
6677 /**
6678 * Language expressions.
6679 * @type {!Object.<string,!RegExp>}
6680 * @expose
6681 */
6682 ProtoBuf.Lang = {
6683
6684 // Characters always ending a statement
6685 DELIM: /[\s\{\}=;:\[\],'"\(\)<>]/g,
6686
6687 // Field rules
6688 RULE: /^(?:required|optional|repeated|map)$/,
6689
6690 // Field types
6691 TYPE: /^(?:double|float|int32|uint32|sint32|int64|uint64|sint64|fixed32|sfixed32|fixed64|sfixed64|bool|string|bytes)$/,
6692
6693 // Names
6694 NAME: /^[a-zA-Z_][a-zA-Z_0-9]*$/,
6695
6696 // Type definitions
6697 TYPEDEF: /^[a-zA-Z][a-zA-Z_0-9]*$/,
6698
6699 // Type references
6700 TYPEREF: /^(?:\.?[a-zA-Z_][a-zA-Z_0-9]*)(?:\.[a-zA-Z_][a-zA-Z_0-9]*)*$/,
6701
6702 // Fully qualified type references
6703 FQTYPEREF: /^(?:\.[a-zA-Z_][a-zA-Z_0-9]*)+$/,
6704
6705 // All numbers
6706 NUMBER: /^-?(?:[1-9][0-9]*|0|0[xX][0-9a-fA-F]+|0[0-7]+|([0-9]*(\.[0-9]*)?([Ee][+-]?[0-9]+)?)|inf|nan)$/,
6707
6708 // Decimal numbers
6709 NUMBER_DEC: /^(?:[1-9][0-9]*|0)$/,
6710
6711 // Hexadecimal numbers
6712 NUMBER_HEX: /^0[xX][0-9a-fA-F]+$/,
6713
6714 // Octal numbers
6715 NUMBER_OCT: /^0[0-7]+$/,
6716
6717 // Floating point numbers
6718 NUMBER_FLT: /^([0-9]*(\.[0-9]*)?([Ee][+-]?[0-9]+)?|inf|nan)$/,
6719
6720 // Booleans
6721 BOOL: /^(?:true|false)$/i,
6722
6723 // Id numbers
6724 ID: /^(?:[1-9][0-9]*|0|0[xX][0-9a-fA-F]+|0[0-7]+)$/,
6725
6726 // Negative id numbers (enum values)
6727 NEGID: /^\-?(?:[1-9][0-9]*|0|0[xX][0-9a-fA-F]+|0[0-7]+)$/,
6728
6729 // Whitespaces
6730 WHITESPACE: /\s/,
6731
6732 // All strings
6733 STRING: /(?:"([^"\\]*(?:\\.[^"\\]*)*)")|(?:'([^'\\]*(?:\\.[^'\\]*)*)')/g,
6734
6735 // Double quoted strings
6736 STRING_DQ: /(?:"([^"\\]*(?:\\.[^"\\]*)*)")/g,
6737
6738 // Single quoted strings
6739 STRING_SQ: /(?:'([^'\\]*(?:\\.[^'\\]*)*)')/g
6740 };
6741
6742
6743 /**
6744 * @alias ProtoBuf.Reflect
6745 * @expose
6746 */
6747 ProtoBuf.Reflect = (function(ProtoBuf) {
6748
6749 /**
6750 * Reflection types.
6751 * @exports ProtoBuf.Reflect
6752 * @namespace
6753 */
6754 var Reflect = {};
6755
6756 /**
6757 * Constructs a Reflect base class.
6758 * @exports ProtoBuf.Reflect.T
6759 * @constructor
6760 * @abstract
6761 * @param {!ProtoBuf.Builder} builder Builder reference
6762 * @param {?ProtoBuf.Reflect.T} parent Parent object
6763 * @param {string} name Object name
6764 */
6765 var T = function(builder, parent, name) {
6766
6767 /**
6768 * Builder reference.
6769 * @type {!ProtoBuf.Builder}
6770 * @expose
6771 */
6772 this.builder = builder;
6773
6774 /**
6775 * Parent object.
6776 * @type {?ProtoBuf.Reflect.T}
6777 * @expose
6778 */
6779 this.parent = parent;
6780
6781 /**
6782 * Object name in namespace.
6783 * @type {string}
6784 * @expose
6785 */
6786 this.name = name;
6787
6788 /**
6789 * Fully qualified class name
6790 * @type {string}
6791 * @expose
6792 */
6793 this.className;
6794 };
6795
6796 /**
6797 * @alias ProtoBuf.Reflect.T.prototype
6798 * @inner
6799 */
6800 var TPrototype = T.prototype;
6801
6802 /**
6803 * Returns the fully qualified name of this object.
6804 * @returns {string} Fully qualified name as of ".PATH.TO.THIS"
6805 * @expose
6806 */
6807 TPrototype.fqn = function() {
6808 var name = this.name,
6809 ptr = this;
6810 do {
6811 ptr = ptr.parent;
6812 if (ptr == null)
6813 break;
6814 name = ptr.name+"."+name;
6815 } while (true);
6816 return name;
6817 };
6818
6819 /**
6820 * Returns a string representation of this Reflect object (its fully qualified name).
6821 * @param {boolean=} includeClass Set to true to include the class name. Defaults to false.
6822 * @return String representation
6823 * @expose
6824 */
6825 TPrototype.toString = function(includeClass) {
6826 return (includeClass ? this.className + " " : "") + this.fqn();
6827 };
6828
6829 /**
6830 * Builds this type.
6831 * @throws {Error} If this type cannot be built directly
6832 * @expose
6833 */
6834 TPrototype.build = function() {
6835 throw Error(this.toString(true)+" cannot be built directly");
6836 };
6837
6838 /**
6839 * @alias ProtoBuf.Reflect.T
6840 * @expose
6841 */
6842 Reflect.T = T;
6843
6844 /**
6845 * Constructs a new Namespace.
6846 * @exports ProtoBuf.Reflect.Namespace
6847 * @param {!ProtoBuf.Builder} builder Builder reference
6848 * @param {?ProtoBuf.Reflect.Namespace} parent Namespace parent
6849 * @param {string} name Namespace name
6850 * @param {Object.<string,*>=} options Namespace options
6851 * @param {string?} syntax The syntax level of this definition (e.g., proto3)
6852 * @constructor
6853 * @extends ProtoBuf.Reflect.T
6854 */
6855 var Namespace = function(builder, parent, name, options, syntax) {
6856 T.call(this, builder, parent, name);
6857
6858 /**
6859 * @override
6860 */
6861 this.className = "Namespace";
6862
6863 /**
6864 * Children inside the namespace.
6865 * @type {!Array.<ProtoBuf.Reflect.T>}
6866 */
6867 this.children = [];
6868
6869 /**
6870 * Options.
6871 * @type {!Object.<string, *>}
6872 */
6873 this.options = options || {};
6874
6875 /**
6876 * Syntax level (e.g., proto2 or proto3).
6877 * @type {!string}
6878 */
6879 this.syntax = syntax || "proto2";
6880 };
6881
6882 /**
6883 * @alias ProtoBuf.Reflect.Namespace.prototype
6884 * @inner
6885 */
6886 var NamespacePrototype = Namespace.prototype = Object.create(T.prototype);
6887
6888 /**
6889 * Returns an array of the namespace's children.
6890 * @param {ProtoBuf.Reflect.T=} type Filter type (returns instances of this type only). Defaults to null (all children).
6891 * @return {Array.<ProtoBuf.Reflect.T>}
6892 * @expose
6893 */
6894 NamespacePrototype.getChildren = function(type) {
6895 type = type || null;
6896 if (type == null)
6897 return this.children.slice();
6898 var children = [];
6899 for (var i=0, k=this.children.length; i<k; ++i)
6900 if (this.children[i] instanceof type)
6901 children.push(this.children[i]);
6902 return children;
6903 };
6904
6905 /**
6906 * Adds a child to the namespace.
6907 * @param {ProtoBuf.Reflect.T} child Child
6908 * @throws {Error} If the child cannot be added (duplicate)
6909 * @expose
6910 */
6911 NamespacePrototype.addChild = function(child) {
6912 var other;
6913 if (other = this.getChild(child.name)) {
6914 // Try to revert camelcase transformation on collision
6915 if (other instanceof Message.Field && other.name !== other.originalName && this.getChild(other.originalName) === null)
6916 other.name = other.originalName; // Revert previous first (effectively keeps both originals)
6917 else if (child instanceof Message.Field && child.name !== child.originalName && this.getChild(child.originalName) === null)
6918 child.name = child.originalName;
6919 else
6920 throw Error("Duplicate name in namespace "+this.toString(true)+": "+child.name);
6921 }
6922 this.children.push(child);
6923 };
6924
6925 /**
6926 * Gets a child by its name or id.
6927 * @param {string|number} nameOrId Child name or id
6928 * @return {?ProtoBuf.Reflect.T} The child or null if not found
6929 * @expose
6930 */
6931 NamespacePrototype.getChild = function(nameOrId) {
6932 var key = typeof nameOrId === 'number' ? 'id' : 'name';
6933 for (var i=0, k=this.children.length; i<k; ++i)
6934 if (this.children[i][key] === nameOrId)
6935 return this.children[i];
6936 return null;
6937 };
6938
6939 /**
6940 * Resolves a reflect object inside of this namespace.
6941 * @param {string|!Array.<string>} qn Qualified name to resolve
6942 * @param {boolean=} excludeNonNamespace Excludes non-namespace types, defaults to `false`
6943 * @return {?ProtoBuf.Reflect.Namespace} The resolved type or null if not found
6944 * @expose
6945 */
6946 NamespacePrototype.resolve = function(qn, excludeNonNamespace) {
6947 var part = typeof qn === 'string' ? qn.split(".") : qn,
6948 ptr = this,
6949 i = 0;
6950 if (part[i] === "") { // Fully qualified name, e.g. ".My.Message'
6951 while (ptr.parent !== null)
6952 ptr = ptr.parent;
6953 i++;
6954 }
6955 var child;
6956 do {
6957 do {
6958 if (!(ptr instanceof Reflect.Namespace)) {
6959 ptr = null;
6960 break;
6961 }
6962 child = ptr.getChild(part[i]);
6963 if (!child || !(child instanceof Reflect.T) || (excludeNonNamespace && !(child instanceof Reflect.Namespace))) {
6964 ptr = null;
6965 break;
6966 }
6967 ptr = child; i++;
6968 } while (i < part.length);
6969 if (ptr != null)
6970 break; // Found
6971 // Else search the parent
6972 if (this.parent !== null)
6973 return this.parent.resolve(qn, excludeNonNamespace);
6974 } while (ptr != null);
6975 return ptr;
6976 };
6977
6978 /**
6979 * Determines the shortest qualified name of the specified type, if any, relative to this namespace.
6980 * @param {!ProtoBuf.Reflect.T} t Reflection type
6981 * @returns {string} The shortest qualified name or, if there is none, the fqn
6982 * @expose
6983 */
6984 NamespacePrototype.qn = function(t) {
6985 var part = [], ptr = t;
6986 do {
6987 part.unshift(ptr.name);
6988 ptr = ptr.parent;
6989 } while (ptr !== null);
6990 for (var len=1; len <= part.length; len++) {
6991 var qn = part.slice(part.length-len);
6992 if (t === this.resolve(qn, t instanceof Reflect.Namespace))
6993 return qn.join(".");
6994 }
6995 return t.fqn();
6996 };
6997
6998 /**
6999 * Builds the namespace and returns the runtime counterpart.
7000 * @return {Object.<string,Function|Object>} Runtime namespace
7001 * @expose
7002 */
7003 NamespacePrototype.build = function() {
7004 /** @dict */
7005 var ns = {};
7006 var children = this.children;
7007 for (var i=0, k=children.length, child; i<k; ++i) {
7008 child = children[i];
7009 if (child instanceof Namespace)
7010 ns[child.name] = child.build();
7011 }
7012 if (Object.defineProperty)
7013 Object.defineProperty(ns, "$options", { "value": this.buildOpt() });
7014 return ns;
7015 };
7016
7017 /**
7018 * Builds the namespace's '$options' property.
7019 * @return {Object.<string,*>}
7020 */
7021 NamespacePrototype.buildOpt = function() {
7022 var opt = {},
7023 keys = Object.keys(this.options);
7024 for (var i=0, k=keys.length; i<k; ++i) {
7025 var key = keys[i],
7026 val = this.options[keys[i]];
7027 // TODO: Options are not resolved, yet.
7028 // if (val instanceof Namespace) {
7029 // opt[key] = val.build();
7030 // } else {
7031 opt[key] = val;
7032 // }
7033 }
7034 return opt;
7035 };
7036
7037 /**
7038 * Gets the value assigned to the option with the specified name.
7039 * @param {string=} name Returns the option value if specified, otherwise all options are returned.
7040 * @return {*|Object.<string,*>}null} Option value or NULL if there is no such option
7041 */
7042 NamespacePrototype.getOption = function(name) {
7043 if (typeof name === 'undefined')
7044 return this.options;
7045 return typeof this.options[name] !== 'undefined' ? this.options[name] : null;
7046 };
7047
7048 /**
7049 * @alias ProtoBuf.Reflect.Namespace
7050 * @expose
7051 */
7052 Reflect.Namespace = Namespace;
7053
7054 /**
7055 * Constructs a new Element implementation that checks and converts values for a
7056 * particular field type, as appropriate.
7057 *
7058 * An Element represents a single value: either the value of a singular field,
7059 * or a value contained in one entry of a repeated field or map field. This
7060 * class does not implement these higher-level concepts; it only encapsulates
7061 * the low-level typechecking and conversion.
7062 *
7063 * @exports ProtoBuf.Reflect.Element
7064 * @param {{name: string, wireType: number}} type Resolved data type
7065 * @param {ProtoBuf.Reflect.T|null} resolvedType Resolved type, if relevant
7066 * (e.g. submessage field).
7067 * @param {boolean} isMapKey Is this element a Map key? The value will be
7068 * converted to string form if so.
7069 * @param {string} syntax Syntax level of defining message type, e.g.,
7070 * proto2 or proto3.
7071 * @param {string} name Name of the field containing this element (for error
7072 * messages)
7073 * @constructor
7074 */
7075 var Element = function(type, resolvedType, isMapKey, syntax, name) {
7076
7077 /**
7078 * Element type, as a string (e.g., int32).
7079 * @type {{name: string, wireType: number}}
7080 */
7081 this.type = type;
7082
7083 /**
7084 * Element type reference to submessage or enum definition, if needed.
7085 * @type {ProtoBuf.Reflect.T|null}
7086 */
7087 this.resolvedType = resolvedType;
7088
7089 /**
7090 * Element is a map key.
7091 * @type {boolean}
7092 */
7093 this.isMapKey = isMapKey;
7094
7095 /**
7096 * Syntax level of defining message type, e.g., proto2 or proto3.
7097 * @type {string}
7098 */
7099 this.syntax = syntax;
7100
7101 /**
7102 * Name of the field containing this element (for error messages)
7103 * @type {string}
7104 */
7105 this.name = name;
7106
7107 if (isMapKey && ProtoBuf.MAP_KEY_TYPES.indexOf(type) < 0)
7108 throw Error("Invalid map key type: " + type.name);
7109 };
7110
7111 var ElementPrototype = Element.prototype;
7112
7113 /**
7114 * Obtains a (new) default value for the specified type.
7115 * @param type {string|{name: string, wireType: number}} Field type
7116 * @returns {*} Default value
7117 * @inner
7118 */
7119 function mkDefault(type) {
7120 if (typeof type === 'string')
7121 type = ProtoBuf.TYPES[type];
7122 if (typeof type.defaultValue === 'undefined')
7123 throw Error("default value for type "+type.name+" is not supported");
7124 if (type == ProtoBuf.TYPES["bytes"])
7125 return new ByteBuffer(0);
7126 return type.defaultValue;
7127 }
7128
7129 /**
7130 * Returns the default value for this field in proto3.
7131 * @function
7132 * @param type {string|{name: string, wireType: number}} the field type
7133 * @returns {*} Default value
7134 */
7135 Element.defaultFieldValue = mkDefault;
7136
7137 /**
7138 * Makes a Long from a value.
7139 * @param {{low: number, high: number, unsigned: boolean}|string|number} value Value
7140 * @param {boolean=} unsigned Whether unsigned or not, defaults to reuse it from Long-like objects or to signed for
7141 * strings and numbers
7142 * @returns {!Long}
7143 * @throws {Error} If the value cannot be converted to a Long
7144 * @inner
7145 */
7146 function mkLong(value, unsigned) {
7147 if (value && typeof value.low === 'number' && typeof value.high === 'number' && typeof value.unsigned === 'boolean'
7148 && value.low === value.low && value.high === value.high)
7149 return new ProtoBuf.Long(value.low, value.high, typeof unsigned === 'undefined' ? value.unsigned : unsigned);
7150 if (typeof value === 'string')
7151 return ProtoBuf.Long.fromString(value, unsigned || false, 10);
7152 if (typeof value === 'number')
7153 return ProtoBuf.Long.fromNumber(value, unsigned || false);
7154 throw Error("not convertible to Long");
7155 }
7156
7157 ElementPrototype.toString = function() {
7158 return (this.name || '') + (this.isMapKey ? 'map' : 'value') + ' element';
7159 };
7160
7161 /**
7162 * Checks if the given value can be set for an element of this type (singular
7163 * field or one element of a repeated field or map).
7164 * @param {*} value Value to check
7165 * @return {*} Verified, maybe adjusted, value
7166 * @throws {Error} If the value cannot be verified for this element slot
7167 * @expose
7168 */
7169 ElementPrototype.verifyValue = function(value) {
7170 var self = this;
7171 function fail(val, msg) {
7172 throw Error("Illegal value for "+self.toString(true)+" of type "+self.type.name+": "+val+" ("+msg+")");
7173 }
7174 switch (this.type) {
7175 // Signed 32bit
7176 case ProtoBuf.TYPES["int32"]:
7177 case ProtoBuf.TYPES["sint32"]:
7178 case ProtoBuf.TYPES["sfixed32"]:
7179 // Account for !NaN: value === value
7180 if (typeof value !== 'number' || (value === value && value % 1 !== 0))
7181 fail(typeof value, "not an integer");
7182 return value > 4294967295 ? value | 0 : value;
7183
7184 // Unsigned 32bit
7185 case ProtoBuf.TYPES["uint32"]:
7186 case ProtoBuf.TYPES["fixed32"]:
7187 if (typeof value !== 'number' || (value === value && value % 1 !== 0))
7188 fail(typeof value, "not an integer");
7189 return value < 0 ? value >>> 0 : value;
7190
7191 // Signed 64bit
7192 case ProtoBuf.TYPES["int64"]:
7193 case ProtoBuf.TYPES["sint64"]:
7194 case ProtoBuf.TYPES["sfixed64"]: {
7195 if (ProtoBuf.Long)
7196 try {
7197 return mkLong(value, false);
7198 } catch (e) {
7199 fail(typeof value, e.message);
7200 }
7201 else
7202 fail(typeof value, "requires Long.js");
7203 }
7204
7205 // Unsigned 64bit
7206 case ProtoBuf.TYPES["uint64"]:
7207 case ProtoBuf.TYPES["fixed64"]: {
7208 if (ProtoBuf.Long)
7209 try {
7210 return mkLong(value, true);
7211 } catch (e) {
7212 fail(typeof value, e.message);
7213 }
7214 else
7215 fail(typeof value, "requires Long.js");
7216 }
7217
7218 // Bool
7219 case ProtoBuf.TYPES["bool"]:
7220 if (typeof value !== 'boolean')
7221 fail(typeof value, "not a boolean");
7222 return value;
7223
7224 // Float
7225 case ProtoBuf.TYPES["float"]:
7226 case ProtoBuf.TYPES["double"]:
7227 if (typeof value !== 'number')
7228 fail(typeof value, "not a number");
7229 return value;
7230
7231 // Length-delimited string
7232 case ProtoBuf.TYPES["string"]:
7233 if (typeof value !== 'string' && !(value && value instanceof String))
7234 fail(typeof value, "not a string");
7235 return ""+value; // Convert String object to string
7236
7237 // Length-delimited bytes
7238 case ProtoBuf.TYPES["bytes"]:
7239 if (ByteBuffer.isByteBuffer(value))
7240 return value;
7241 return ByteBuffer.wrap(value, "base64");
7242
7243 // Constant enum value
7244 case ProtoBuf.TYPES["enum"]: {
7245 var values = this.resolvedType.getChildren(ProtoBuf.Reflect.Enum.Value);
7246 for (i=0; i<values.length; i++)
7247 if (values[i].name == value)
7248 return values[i].id;
7249 else if (values[i].id == value)
7250 return values[i].id;
7251
7252 if (this.syntax === 'proto3') {
7253 // proto3: just make sure it's an integer.
7254 if (typeof value !== 'number' || (value === value && value % 1 !== 0))
7255 fail(typeof value, "not an integer");
7256 if (value > 4294967295 || value < 0)
7257 fail(typeof value, "not in range for uint32");
7258 return value;
7259 } else {
7260 // proto2 requires enum values to be valid.
7261 fail(value, "not a valid enum value");
7262 }
7263 }
7264 // Embedded message
7265 case ProtoBuf.TYPES["group"]:
7266 case ProtoBuf.TYPES["message"]: {
7267 if (!value || typeof value !== 'object')
7268 fail(typeof value, "object expected");
7269 if (value instanceof this.resolvedType.clazz)
7270 return value;
7271 if (value instanceof ProtoBuf.Builder.Message) {
7272 // Mismatched type: Convert to object (see: https://github.com/dcodeIO/ProtoBuf.js/issues/180)
7273 var obj = {};
7274 for (var i in value)
7275 if (value.hasOwnProperty(i))
7276 obj[i] = value[i];
7277 value = obj;
7278 }
7279 // Else let's try to construct one from a key-value object
7280 return new (this.resolvedType.clazz)(value); // May throw for a hundred of reasons
7281 }
7282 }
7283
7284 // We should never end here
7285 throw Error("[INTERNAL] Illegal value for "+this.toString(true)+": "+value+" (undefined type "+this.type+")");
7286 };
7287
7288 /**
7289 * Calculates the byte length of an element on the wire.
7290 * @param {number} id Field number
7291 * @param {*} value Field value
7292 * @returns {number} Byte length
7293 * @throws {Error} If the value cannot be calculated
7294 * @expose
7295 */
7296 ElementPrototype.calculateLength = function(id, value) {
7297 if (value === null) return 0; // Nothing to encode
7298 // Tag has already been written
7299 var n;
7300 switch (this.type) {
7301 case ProtoBuf.TYPES["int32"]:
7302 return value < 0 ? ByteBuffer.calculateVarint64(value) : ByteBuffer.calculateVarint32(value);
7303 case ProtoBuf.TYPES["uint32"]:
7304 return ByteBuffer.calculateVarint32(value);
7305 case ProtoBuf.TYPES["sint32"]:
7306 return ByteBuffer.calculateVarint32(ByteBuffer.zigZagEncode32(value));
7307 case ProtoBuf.TYPES["fixed32"]:
7308 case ProtoBuf.TYPES["sfixed32"]:
7309 case ProtoBuf.TYPES["float"]:
7310 return 4;
7311 case ProtoBuf.TYPES["int64"]:
7312 case ProtoBuf.TYPES["uint64"]:
7313 return ByteBuffer.calculateVarint64(value);
7314 case ProtoBuf.TYPES["sint64"]:
7315 return ByteBuffer.calculateVarint64(ByteBuffer.zigZagEncode64(value));
7316 case ProtoBuf.TYPES["fixed64"]:
7317 case ProtoBuf.TYPES["sfixed64"]:
7318 return 8;
7319 case ProtoBuf.TYPES["bool"]:
7320 return 1;
7321 case ProtoBuf.TYPES["enum"]:
7322 return ByteBuffer.calculateVarint32(value);
7323 case ProtoBuf.TYPES["double"]:
7324 return 8;
7325 case ProtoBuf.TYPES["string"]:
7326 n = ByteBuffer.calculateUTF8Bytes(value);
7327 return ByteBuffer.calculateVarint32(n) + n;
7328 case ProtoBuf.TYPES["bytes"]:
7329 if (value.remaining() < 0)
7330 throw Error("Illegal value for "+this.toString(true)+": "+value.remaining()+" bytes remaining");
7331 return ByteBuffer.calculateVarint32(value.remaining()) + value.remaining();
7332 case ProtoBuf.TYPES["message"]:
7333 n = this.resolvedType.calculate(value);
7334 return ByteBuffer.calculateVarint32(n) + n;
7335 case ProtoBuf.TYPES["group"]:
7336 n = this.resolvedType.calculate(value);
7337 return n + ByteBuffer.calculateVarint32((id << 3) | ProtoBuf.WIRE_TYPES.ENDGROUP);
7338 }
7339 // We should never end here
7340 throw Error("[INTERNAL] Illegal value to encode in "+this.toString(true)+": "+value+" (unknown type)");
7341 };
7342
7343 /**
7344 * Encodes a value to the specified buffer. Does not encode the key.
7345 * @param {number} id Field number
7346 * @param {*} value Field value
7347 * @param {ByteBuffer} buffer ByteBuffer to encode to
7348 * @return {ByteBuffer} The ByteBuffer for chaining
7349 * @throws {Error} If the value cannot be encoded
7350 * @expose
7351 */
7352 ElementPrototype.encodeValue = function(id, value, buffer) {
7353 if (value === null) return buffer; // Nothing to encode
7354 // Tag has already been written
7355
7356 switch (this.type) {
7357 // 32bit signed varint
7358 case ProtoBuf.TYPES["int32"]:
7359 // "If you use int32 or int64 as the type for a negative number, the resulting varint is always ten bytes
7360 // long – it is, effectively, treated like a very large unsigned integer." (see #122)
7361 if (value < 0)
7362 buffer.writeVarint64(value);
7363 else
7364 buffer.writeVarint32(value);
7365 break;
7366
7367 // 32bit unsigned varint
7368 case ProtoBuf.TYPES["uint32"]:
7369 buffer.writeVarint32(value);
7370 break;
7371
7372 // 32bit varint zig-zag
7373 case ProtoBuf.TYPES["sint32"]:
7374 buffer.writeVarint32ZigZag(value);
7375 break;
7376
7377 // Fixed unsigned 32bit
7378 case ProtoBuf.TYPES["fixed32"]:
7379 buffer.writeUint32(value);
7380 break;
7381
7382 // Fixed signed 32bit
7383 case ProtoBuf.TYPES["sfixed32"]:
7384 buffer.writeInt32(value);
7385 break;
7386
7387 // 64bit varint as-is
7388 case ProtoBuf.TYPES["int64"]:
7389 case ProtoBuf.TYPES["uint64"]:
7390 buffer.writeVarint64(value); // throws
7391 break;
7392
7393 // 64bit varint zig-zag
7394 case ProtoBuf.TYPES["sint64"]:
7395 buffer.writeVarint64ZigZag(value); // throws
7396 break;
7397
7398 // Fixed unsigned 64bit
7399 case ProtoBuf.TYPES["fixed64"]:
7400 buffer.writeUint64(value); // throws
7401 break;
7402
7403 // Fixed signed 64bit
7404 case ProtoBuf.TYPES["sfixed64"]:
7405 buffer.writeInt64(value); // throws
7406 break;
7407
7408 // Bool
7409 case ProtoBuf.TYPES["bool"]:
7410 if (typeof value === 'string')
7411 buffer.writeVarint32(value.toLowerCase() === 'false' ? 0 : !!value);
7412 else
7413 buffer.writeVarint32(value ? 1 : 0);
7414 break;
7415
7416 // Constant enum value
7417 case ProtoBuf.TYPES["enum"]:
7418 buffer.writeVarint32(value);
7419 break;
7420
7421 // 32bit float
7422 case ProtoBuf.TYPES["float"]:
7423 buffer.writeFloat32(value);
7424 break;
7425
7426 // 64bit float
7427 case ProtoBuf.TYPES["double"]:
7428 buffer.writeFloat64(value);
7429 break;
7430
7431 // Length-delimited string
7432 case ProtoBuf.TYPES["string"]:
7433 buffer.writeVString(value);
7434 break;
7435
7436 // Length-delimited bytes
7437 case ProtoBuf.TYPES["bytes"]:
7438 if (value.remaining() < 0)
7439 throw Error("Illegal value for "+this.toString(true)+": "+value.remaining()+" bytes remaining");
7440 var prevOffset = value.offset;
7441 buffer.writeVarint32(value.remaining());
7442 buffer.append(value);
7443 value.offset = prevOffset;
7444 break;
7445
7446 // Embedded message
7447 case ProtoBuf.TYPES["message"]:
7448 var bb = new ByteBuffer().LE();
7449 this.resolvedType.encode(value, bb);
7450 buffer.writeVarint32(bb.offset);
7451 buffer.append(bb.flip());
7452 break;
7453
7454 // Legacy group
7455 case ProtoBuf.TYPES["group"]:
7456 this.resolvedType.encode(value, buffer);
7457 buffer.writeVarint32((id << 3) | ProtoBuf.WIRE_TYPES.ENDGROUP);
7458 break;
7459
7460 default:
7461 // We should never end here
7462 throw Error("[INTERNAL] Illegal value to encode in "+this.toString(true)+": "+value+" (unknown type)");
7463 }
7464 return buffer;
7465 };
7466
7467 /**
7468 * Decode one element value from the specified buffer.
7469 * @param {ByteBuffer} buffer ByteBuffer to decode from
7470 * @param {number} wireType The field wire type
7471 * @param {number} id The field number
7472 * @return {*} Decoded value
7473 * @throws {Error} If the field cannot be decoded
7474 * @expose
7475 */
7476 ElementPrototype.decode = function(buffer, wireType, id) {
7477 if (wireType != this.type.wireType)
7478 throw Error("Unexpected wire type for element");
7479
7480 var value, nBytes;
7481 switch (this.type) {
7482 // 32bit signed varint
7483 case ProtoBuf.TYPES["int32"]:
7484 return buffer.readVarint32() | 0;
7485
7486 // 32bit unsigned varint
7487 case ProtoBuf.TYPES["uint32"]:
7488 return buffer.readVarint32() >>> 0;
7489
7490 // 32bit signed varint zig-zag
7491 case ProtoBuf.TYPES["sint32"]:
7492 return buffer.readVarint32ZigZag() | 0;
7493
7494 // Fixed 32bit unsigned
7495 case ProtoBuf.TYPES["fixed32"]:
7496 return buffer.readUint32() >>> 0;
7497
7498 case ProtoBuf.TYPES["sfixed32"]:
7499 return buffer.readInt32() | 0;
7500
7501 // 64bit signed varint
7502 case ProtoBuf.TYPES["int64"]:
7503 return buffer.readVarint64();
7504
7505 // 64bit unsigned varint
7506 case ProtoBuf.TYPES["uint64"]:
7507 return buffer.readVarint64().toUnsigned();
7508
7509 // 64bit signed varint zig-zag
7510 case ProtoBuf.TYPES["sint64"]:
7511 return buffer.readVarint64ZigZag();
7512
7513 // Fixed 64bit unsigned
7514 case ProtoBuf.TYPES["fixed64"]:
7515 return buffer.readUint64();
7516
7517 // Fixed 64bit signed
7518 case ProtoBuf.TYPES["sfixed64"]:
7519 return buffer.readInt64();
7520
7521 // Bool varint
7522 case ProtoBuf.TYPES["bool"]:
7523 return !!buffer.readVarint32();
7524
7525 // Constant enum value (varint)
7526 case ProtoBuf.TYPES["enum"]:
7527 // The following Builder.Message#set will already throw
7528 return buffer.readVarint32();
7529
7530 // 32bit float
7531 case ProtoBuf.TYPES["float"]:
7532 return buffer.readFloat();
7533
7534 // 64bit float
7535 case ProtoBuf.TYPES["double"]:
7536 return buffer.readDouble();
7537
7538 // Length-delimited string
7539 case ProtoBuf.TYPES["string"]:
7540 return buffer.readVString();
7541
7542 // Length-delimited bytes
7543 case ProtoBuf.TYPES["bytes"]: {
7544 nBytes = buffer.readVarint32();
7545 if (buffer.remaining() < nBytes)
7546 throw Error("Illegal number of bytes for "+this.toString(true)+": "+nBytes+" required but got only "+buffer.remaining());
7547 value = buffer.clone(); // Offset already set
7548 value.limit = value.offset+nBytes;
7549 buffer.offset += nBytes;
7550 return value;
7551 }
7552
7553 // Length-delimited embedded message
7554 case ProtoBuf.TYPES["message"]: {
7555 nBytes = buffer.readVarint32();
7556 return this.resolvedType.decode(buffer, nBytes);
7557 }
7558
7559 // Legacy group
7560 case ProtoBuf.TYPES["group"]:
7561 return this.resolvedType.decode(buffer, -1, id);
7562 }
7563
7564 // We should never end here
7565 throw Error("[INTERNAL] Illegal decode type");
7566 };
7567
7568 /**
7569 * Converts a value from a string to the canonical element type.
7570 *
7571 * Legal only when isMapKey is true.
7572 *
7573 * @param {string} str The string value
7574 * @returns {*} The value
7575 */
7576 ElementPrototype.valueFromString = function(str) {
7577 if (!this.isMapKey) {
7578 throw Error("valueFromString() called on non-map-key element");
7579 }
7580
7581 switch (this.type) {
7582 case ProtoBuf.TYPES["int32"]:
7583 case ProtoBuf.TYPES["sint32"]:
7584 case ProtoBuf.TYPES["sfixed32"]:
7585 case ProtoBuf.TYPES["uint32"]:
7586 case ProtoBuf.TYPES["fixed32"]:
7587 return this.verifyValue(parseInt(str));
7588
7589 case ProtoBuf.TYPES["int64"]:
7590 case ProtoBuf.TYPES["sint64"]:
7591 case ProtoBuf.TYPES["sfixed64"]:
7592 case ProtoBuf.TYPES["uint64"]:
7593 case ProtoBuf.TYPES["fixed64"]:
7594 // Long-based fields support conversions from string already.
7595 return this.verifyValue(str);
7596
7597 case ProtoBuf.TYPES["bool"]:
7598 return str === "true";
7599
7600 case ProtoBuf.TYPES["string"]:
7601 return this.verifyValue(str);
7602
7603 case ProtoBuf.TYPES["bytes"]:
7604 return ByteBuffer.fromBinary(str);
7605 }
7606 };
7607
7608 /**
7609 * Converts a value from the canonical element type to a string.
7610 *
7611 * It should be the case that `valueFromString(valueToString(val))` returns
7612 * a value equivalent to `verifyValue(val)` for every legal value of `val`
7613 * according to this element type.
7614 *
7615 * This may be used when the element must be stored or used as a string,
7616 * e.g., as a map key on an Object.
7617 *
7618 * Legal only when isMapKey is true.
7619 *
7620 * @param {*} val The value
7621 * @returns {string} The string form of the value.
7622 */
7623 ElementPrototype.valueToString = function(value) {
7624 if (!this.isMapKey) {
7625 throw Error("valueToString() called on non-map-key element");
7626 }
7627
7628 if (this.type === ProtoBuf.TYPES["bytes"]) {
7629 return value.toString("binary");
7630 } else {
7631 return value.toString();
7632 }
7633 };
7634
7635 /**
7636 * @alias ProtoBuf.Reflect.Element
7637 * @expose
7638 */
7639 Reflect.Element = Element;
7640
7641 /**
7642 * Constructs a new Message.
7643 * @exports ProtoBuf.Reflect.Message
7644 * @param {!ProtoBuf.Builder} builder Builder reference
7645 * @param {!ProtoBuf.Reflect.Namespace} parent Parent message or namespace
7646 * @param {string} name Message name
7647 * @param {Object.<string,*>=} options Message options
7648 * @param {boolean=} isGroup `true` if this is a legacy group
7649 * @param {string?} syntax The syntax level of this definition (e.g., proto3)
7650 * @constructor
7651 * @extends ProtoBuf.Reflect.Namespace
7652 */
7653 var Message = function(builder, parent, name, options, isGroup, syntax) {
7654 Namespace.call(this, builder, parent, name, options, syntax);
7655
7656 /**
7657 * @override
7658 */
7659 this.className = "Message";
7660
7661 /**
7662 * Extensions range.
7663 * @type {!Array.<number>|undefined}
7664 * @expose
7665 */
7666 this.extensions = undefined;
7667
7668 /**
7669 * Runtime message class.
7670 * @type {?function(new:ProtoBuf.Builder.Message)}
7671 * @expose
7672 */
7673 this.clazz = null;
7674
7675 /**
7676 * Whether this is a legacy group or not.
7677 * @type {boolean}
7678 * @expose
7679 */
7680 this.isGroup = !!isGroup;
7681
7682 // The following cached collections are used to efficiently iterate over or look up fields when decoding.
7683
7684 /**
7685 * Cached fields.
7686 * @type {?Array.<!ProtoBuf.Reflect.Message.Field>}
7687 * @private
7688 */
7689 this._fields = null;
7690
7691 /**
7692 * Cached fields by id.
7693 * @type {?Object.<number,!ProtoBuf.Reflect.Message.Field>}
7694 * @private
7695 */
7696 this._fieldsById = null;
7697
7698 /**
7699 * Cached fields by name.
7700 * @type {?Object.<string,!ProtoBuf.Reflect.Message.Field>}
7701 * @private
7702 */
7703 this._fieldsByName = null;
7704 };
7705
7706 /**
7707 * @alias ProtoBuf.Reflect.Message.prototype
7708 * @inner
7709 */
7710 var MessagePrototype = Message.prototype = Object.create(Namespace.prototype);
7711
7712 /**
7713 * Builds the message and returns the runtime counterpart, which is a fully functional class.
7714 * @see ProtoBuf.Builder.Message
7715 * @param {boolean=} rebuild Whether to rebuild or not, defaults to false
7716 * @return {ProtoBuf.Reflect.Message} Message class
7717 * @throws {Error} If the message cannot be built
7718 * @expose
7719 */
7720 MessagePrototype.build = function(rebuild) {
7721 if (this.clazz && !rebuild)
7722 return this.clazz;
7723
7724 // Create the runtime Message class in its own scope
7725 var clazz = (function(ProtoBuf, T) {
7726
7727 var fields = T.getChildren(ProtoBuf.Reflect.Message.Field),
7728 oneofs = T.getChildren(ProtoBuf.Reflect.Message.OneOf);
7729
7730 /**
7731 * Constructs a new runtime Message.
7732 * @name ProtoBuf.Builder.Message
7733 * @class Barebone of all runtime messages.
7734 * @param {!Object.<string,*>|string} values Preset values
7735 * @param {...string} var_args
7736 * @constructor
7737 * @throws {Error} If the message cannot be created
7738 */
7739 var Message = function(values, var_args) {
7740 ProtoBuf.Builder.Message.call(this);
7741
7742 // Create virtual oneof properties
7743 for (var i=0, k=oneofs.length; i<k; ++i)
7744 this[oneofs[i].name] = null;
7745 // Create fields and set default values
7746 for (i=0, k=fields.length; i<k; ++i) {
7747 var field = fields[i];
7748 this[field.name] =
7749 field.repeated ? [] :
7750 (field.map ? new ProtoBuf.Map(field) : null);
7751 if ((field.required || T.syntax === 'proto3') &&
7752 field.defaultValue !== null)
7753 this[field.name] = field.defaultValue;
7754 }
7755
7756 if (arguments.length > 0) {
7757 var value;
7758 // Set field values from a values object
7759 if (arguments.length === 1 && values !== null && typeof values === 'object' &&
7760 /* not _another_ Message */ (typeof values.encode !== 'function' || values instanceof Message) &&
7761 /* not a repeated field */ !Array.isArray(values) &&
7762 /* not a Map */ !(values instanceof ProtoBuf.Map) &&
7763 /* not a ByteBuffer */ !ByteBuffer.isByteBuffer(values) &&
7764 /* not an ArrayBuffer */ !(values instanceof ArrayBuffer) &&
7765 /* not a Long */ !(ProtoBuf.Long && values instanceof ProtoBuf.Long)) {
7766 this.$set(values);
7767 } else // Set field values from arguments, in declaration order
7768 for (i=0, k=arguments.length; i<k; ++i)
7769 if (typeof (value = arguments[i]) !== 'undefined')
7770 this.$set(fields[i].name, value); // May throw
7771 }
7772 };
7773
7774 /**
7775 * @alias ProtoBuf.Builder.Message.prototype
7776 * @inner
7777 */
7778 var MessagePrototype = Message.prototype = Object.create(ProtoBuf.Builder.Message.prototype);
7779
7780 /**
7781 * Adds a value to a repeated field.
7782 * @name ProtoBuf.Builder.Message#add
7783 * @function
7784 * @param {string} key Field name
7785 * @param {*} value Value to add
7786 * @param {boolean=} noAssert Whether to assert the value or not (asserts by default)
7787 * @returns {!ProtoBuf.Builder.Message} this
7788 * @throws {Error} If the value cannot be added
7789 * @expose
7790 */
7791 MessagePrototype.add = function(key, value, noAssert) {
7792 var field = T._fieldsByName[key];
7793 if (!noAssert) {
7794 if (!field)
7795 throw Error(this+"#"+key+" is undefined");
7796 if (!(field instanceof ProtoBuf.Reflect.Message.Field))
7797 throw Error(this+"#"+key+" is not a field: "+field.toString(true)); // May throw if it's an enum or embedded message
7798 if (!field.repeated)
7799 throw Error(this+"#"+key+" is not a repeated field");
7800 value = field.verifyValue(value, true);
7801 }
7802 if (this[key] === null)
7803 this[key] = [];
7804 this[key].push(value);
7805 return this;
7806 };
7807
7808 /**
7809 * Adds a value to a repeated field. This is an alias for {@link ProtoBuf.Builder.Message#add}.
7810 * @name ProtoBuf.Builder.Message#$add
7811 * @function
7812 * @param {string} key Field name
7813 * @param {*} value Value to add
7814 * @param {boolean=} noAssert Whether to assert the value or not (asserts by default)
7815 * @returns {!ProtoBuf.Builder.Message} this
7816 * @throws {Error} If the value cannot be added
7817 * @expose
7818 */
7819 MessagePrototype.$add = MessagePrototype.add;
7820
7821 /**
7822 * Sets a field's value.
7823 * @name ProtoBuf.Builder.Message#set
7824 * @function
7825 * @param {string|!Object.<string,*>} keyOrObj String key or plain object holding multiple values
7826 * @param {(*|boolean)=} value Value to set if key is a string, otherwise omitted
7827 * @param {boolean=} noAssert Whether to not assert for an actual field / proper value type, defaults to `false`
7828 * @returns {!ProtoBuf.Builder.Message} this
7829 * @throws {Error} If the value cannot be set
7830 * @expose
7831 */
7832 MessagePrototype.set = function(keyOrObj, value, noAssert) {
7833 if (keyOrObj && typeof keyOrObj === 'object') {
7834 noAssert = value;
7835 for (var ikey in keyOrObj) {
7836 // Check if virtual oneof field - don't set these
7837 if (keyOrObj.hasOwnProperty(ikey) && typeof (value = keyOrObj[ikey]) !== 'undefined' && T._oneofsByName[ikey] === undefined)
7838 this.$set(ikey, value, noAssert);
7839 }
7840 return this;
7841 }
7842 var field = T._fieldsByName[keyOrObj];
7843 if (!noAssert) {
7844 if (!field)
7845 throw Error(this+"#"+keyOrObj+" is not a field: undefined");
7846 if (!(field instanceof ProtoBuf.Reflect.Message.Field))
7847 throw Error(this+"#"+keyOrObj+" is not a field: "+field.toString(true));
7848 this[field.name] = (value = field.verifyValue(value)); // May throw
7849 } else
7850 this[keyOrObj] = value;
7851 if (field && field.oneof) { // Field is part of an OneOf (not a virtual OneOf field)
7852 var currentField = this[field.oneof.name]; // Virtual field references currently set field
7853 if (value !== null) {
7854 if (currentField !== null && currentField !== field.name)
7855 this[currentField] = null; // Clear currently set field
7856 this[field.oneof.name] = field.name; // Point virtual field at this field
7857 } else if (/* value === null && */currentField === keyOrObj)
7858 this[field.oneof.name] = null; // Clear virtual field (current field explicitly cleared)
7859 }
7860 return this;
7861 };
7862
7863 /**
7864 * Sets a field's value. This is an alias for [@link ProtoBuf.Builder.Message#set}.
7865 * @name ProtoBuf.Builder.Message#$set
7866 * @function
7867 * @param {string|!Object.<string,*>} keyOrObj String key or plain object holding multiple values
7868 * @param {(*|boolean)=} value Value to set if key is a string, otherwise omitted
7869 * @param {boolean=} noAssert Whether to not assert the value, defaults to `false`
7870 * @throws {Error} If the value cannot be set
7871 * @expose
7872 */
7873 MessagePrototype.$set = MessagePrototype.set;
7874
7875 /**
7876 * Gets a field's value.
7877 * @name ProtoBuf.Builder.Message#get
7878 * @function
7879 * @param {string} key Key
7880 * @param {boolean=} noAssert Whether to not assert for an actual field, defaults to `false`
7881 * @return {*} Value
7882 * @throws {Error} If there is no such field
7883 * @expose
7884 */
7885 MessagePrototype.get = function(key, noAssert) {
7886 if (noAssert)
7887 return this[key];
7888 var field = T._fieldsByName[key];
7889 if (!field || !(field instanceof ProtoBuf.Reflect.Message.Field))
7890 throw Error(this+"#"+key+" is not a field: undefined");
7891 if (!(field instanceof ProtoBuf.Reflect.Message.Field))
7892 throw Error(this+"#"+key+" is not a field: "+field.toString(true));
7893 return this[field.name];
7894 };
7895
7896 /**
7897 * Gets a field's value. This is an alias for {@link ProtoBuf.Builder.Message#$get}.
7898 * @name ProtoBuf.Builder.Message#$get
7899 * @function
7900 * @param {string} key Key
7901 * @return {*} Value
7902 * @throws {Error} If there is no such field
7903 * @expose
7904 */
7905 MessagePrototype.$get = MessagePrototype.get;
7906
7907 // Getters and setters
7908
7909 for (var i=0; i<fields.length; i++) {
7910 var field = fields[i];
7911 // no setters for extension fields as these are named by their fqn
7912 if (field instanceof ProtoBuf.Reflect.Message.ExtensionField)
7913 continue;
7914
7915 if (T.builder.options['populateAccessors'])
7916 (function(field) {
7917 // set/get[SomeValue]
7918 var Name = field.originalName.replace(/(_[a-zA-Z])/g, function(match) {
7919 return match.toUpperCase().replace('_','');
7920 });
7921 Name = Name.substring(0,1).toUpperCase() + Name.substring(1);
7922
7923 // set/get_[some_value] FIXME: Do we really need these?
7924 var name = field.originalName.replace(/([A-Z])/g, function(match) {
7925 return "_"+match;
7926 });
7927
7928 /**
7929 * The current field's unbound setter function.
7930 * @function
7931 * @param {*} value
7932 * @param {boolean=} noAssert
7933 * @returns {!ProtoBuf.Builder.Message}
7934 * @inner
7935 */
7936 var setter = function(value, noAssert) {
7937 this[field.name] = noAssert ? value : field.verifyValue(value);
7938 return this;
7939 };
7940
7941 /**
7942 * The current field's unbound getter function.
7943 * @function
7944 * @returns {*}
7945 * @inner
7946 */
7947 var getter = function() {
7948 return this[field.name];
7949 };
7950
7951 if (T.getChild("set"+Name) === null)
7952 /**
7953 * Sets a value. This method is present for each field, but only if there is no name conflict with
7954 * another field.
7955 * @name ProtoBuf.Builder.Message#set[SomeField]
7956 * @function
7957 * @param {*} value Value to set
7958 * @param {boolean=} noAssert Whether to not assert the value, defaults to `false`
7959 * @returns {!ProtoBuf.Builder.Message} this
7960 * @abstract
7961 * @throws {Error} If the value cannot be set
7962 */
7963 MessagePrototype["set"+Name] = setter;
7964
7965 if (T.getChild("set_"+name) === null)
7966 /**
7967 * Sets a value. This method is present for each field, but only if there is no name conflict with
7968 * another field.
7969 * @name ProtoBuf.Builder.Message#set_[some_field]
7970 * @function
7971 * @param {*} value Value to set
7972 * @param {boolean=} noAssert Whether to not assert the value, defaults to `false`
7973 * @returns {!ProtoBuf.Builder.Message} this
7974 * @abstract
7975 * @throws {Error} If the value cannot be set
7976 */
7977 MessagePrototype["set_"+name] = setter;
7978
7979 if (T.getChild("get"+Name) === null)
7980 /**
7981 * Gets a value. This method is present for each field, but only if there is no name conflict with
7982 * another field.
7983 * @name ProtoBuf.Builder.Message#get[SomeField]
7984 * @function
7985 * @abstract
7986 * @return {*} The value
7987 */
7988 MessagePrototype["get"+Name] = getter;
7989
7990 if (T.getChild("get_"+name) === null)
7991 /**
7992 * Gets a value. This method is present for each field, but only if there is no name conflict with
7993 * another field.
7994 * @name ProtoBuf.Builder.Message#get_[some_field]
7995 * @function
7996 * @return {*} The value
7997 * @abstract
7998 */
7999 MessagePrototype["get_"+name] = getter;
8000
8001 })(field);
8002 }
8003
8004 // En-/decoding
8005
8006 /**
8007 * Encodes the message.
8008 * @name ProtoBuf.Builder.Message#$encode
8009 * @function
8010 * @param {(!ByteBuffer|boolean)=} buffer ByteBuffer to encode to. Will create a new one and flip it if omitted.
8011 * @param {boolean=} noVerify Whether to not verify field values, defaults to `false`
8012 * @return {!ByteBuffer} Encoded message as a ByteBuffer
8013 * @throws {Error} If the message cannot be encoded or if required fields are missing. The later still
8014 * returns the encoded ByteBuffer in the `encoded` property on the error.
8015 * @expose
8016 * @see ProtoBuf.Builder.Message#encode64
8017 * @see ProtoBuf.Builder.Message#encodeHex
8018 * @see ProtoBuf.Builder.Message#encodeAB
8019 */
8020 MessagePrototype.encode = function(buffer, noVerify) {
8021 if (typeof buffer === 'boolean')
8022 noVerify = buffer,
8023 buffer = undefined;
8024 var isNew = false;
8025 if (!buffer)
8026 buffer = new ByteBuffer(),
8027 isNew = true;
8028 var le = buffer.littleEndian;
8029 try {
8030 T.encode(this, buffer.LE(), noVerify);
8031 return (isNew ? buffer.flip() : buffer).LE(le);
8032 } catch (e) {
8033 buffer.LE(le);
8034 throw(e);
8035 }
8036 };
8037
8038 /**
8039 * Encodes a message using the specified data payload.
8040 * @param {!Object.<string,*>} data Data payload
8041 * @param {(!ByteBuffer|boolean)=} buffer ByteBuffer to encode to. Will create a new one and flip it if omitted.
8042 * @param {boolean=} noVerify Whether to not verify field values, defaults to `false`
8043 * @return {!ByteBuffer} Encoded message as a ByteBuffer
8044 * @expose
8045 */
8046 Message.encode = function(data, buffer, noVerify) {
8047 return new Message(data).encode(buffer, noVerify);
8048 };
8049
8050 /**
8051 * Calculates the byte length of the message.
8052 * @name ProtoBuf.Builder.Message#calculate
8053 * @function
8054 * @returns {number} Byte length
8055 * @throws {Error} If the message cannot be calculated or if required fields are missing.
8056 * @expose
8057 */
8058 MessagePrototype.calculate = function() {
8059 return T.calculate(this);
8060 };
8061
8062 /**
8063 * Encodes the varint32 length-delimited message.
8064 * @name ProtoBuf.Builder.Message#encodeDelimited
8065 * @function
8066 * @param {(!ByteBuffer|boolean)=} buffer ByteBuffer to encode to. Will create a new one and flip it if omitted.
8067 * @param {boolean=} noVerify Whether to not verify field values, defaults to `false`
8068 * @return {!ByteBuffer} Encoded message as a ByteBuffer
8069 * @throws {Error} If the message cannot be encoded or if required fields are missing. The later still
8070 * returns the encoded ByteBuffer in the `encoded` property on the error.
8071 * @expose
8072 */
8073 MessagePrototype.encodeDelimited = function(buffer, noVerify) {
8074 var isNew = false;
8075 if (!buffer)
8076 buffer = new ByteBuffer(),
8077 isNew = true;
8078 var enc = new ByteBuffer().LE();
8079 T.encode(this, enc, noVerify).flip();
8080 buffer.writeVarint32(enc.remaining());
8081 buffer.append(enc);
8082 return isNew ? buffer.flip() : buffer;
8083 };
8084
8085 /**
8086 * Directly encodes the message to an ArrayBuffer.
8087 * @name ProtoBuf.Builder.Message#encodeAB
8088 * @function
8089 * @return {ArrayBuffer} Encoded message as ArrayBuffer
8090 * @throws {Error} If the message cannot be encoded or if required fields are missing. The later still
8091 * returns the encoded ArrayBuffer in the `encoded` property on the error.
8092 * @expose
8093 */
8094 MessagePrototype.encodeAB = function() {
8095 try {
8096 return this.encode().toArrayBuffer();
8097 } catch (e) {
8098 if (e["encoded"]) e["encoded"] = e["encoded"].toArrayBuffer();
8099 throw(e);
8100 }
8101 };
8102
8103 /**
8104 * Returns the message as an ArrayBuffer. This is an alias for {@link ProtoBuf.Builder.Message#encodeAB}.
8105 * @name ProtoBuf.Builder.Message#toArrayBuffer
8106 * @function
8107 * @return {ArrayBuffer} Encoded message as ArrayBuffer
8108 * @throws {Error} If the message cannot be encoded or if required fields are missing. The later still
8109 * returns the encoded ArrayBuffer in the `encoded` property on the error.
8110 * @expose
8111 */
8112 MessagePrototype.toArrayBuffer = MessagePrototype.encodeAB;
8113
8114 /**
8115 * Directly encodes the message to a node Buffer.
8116 * @name ProtoBuf.Builder.Message#encodeNB
8117 * @function
8118 * @return {!Buffer}
8119 * @throws {Error} If the message cannot be encoded, not running under node.js or if required fields are
8120 * missing. The later still returns the encoded node Buffer in the `encoded` property on the error.
8121 * @expose
8122 */
8123 MessagePrototype.encodeNB = function() {
8124 try {
8125 return this.encode().toBuffer();
8126 } catch (e) {
8127 if (e["encoded"]) e["encoded"] = e["encoded"].toBuffer();
8128 throw(e);
8129 }
8130 };
8131
8132 /**
8133 * Returns the message as a node Buffer. This is an alias for {@link ProtoBuf.Builder.Message#encodeNB}.
8134 * @name ProtoBuf.Builder.Message#toBuffer
8135 * @function
8136 * @return {!Buffer}
8137 * @throws {Error} If the message cannot be encoded or if required fields are missing. The later still
8138 * returns the encoded node Buffer in the `encoded` property on the error.
8139 * @expose
8140 */
8141 MessagePrototype.toBuffer = MessagePrototype.encodeNB;
8142
8143 /**
8144 * Directly encodes the message to a base64 encoded string.
8145 * @name ProtoBuf.Builder.Message#encode64
8146 * @function
8147 * @return {string} Base64 encoded string
8148 * @throws {Error} If the underlying buffer cannot be encoded or if required fields are missing. The later
8149 * still returns the encoded base64 string in the `encoded` property on the error.
8150 * @expose
8151 */
8152 MessagePrototype.encode64 = function() {
8153 try {
8154 return this.encode().toBase64();
8155 } catch (e) {
8156 if (e["encoded"]) e["encoded"] = e["encoded"].toBase64();
8157 throw(e);
8158 }
8159 };
8160
8161 /**
8162 * Returns the message as a base64 encoded string. This is an alias for {@link ProtoBuf.Builder.Message#encode64}.
8163 * @name ProtoBuf.Builder.Message#toBase64
8164 * @function
8165 * @return {string} Base64 encoded string
8166 * @throws {Error} If the message cannot be encoded or if required fields are missing. The later still
8167 * returns the encoded base64 string in the `encoded` property on the error.
8168 * @expose
8169 */
8170 MessagePrototype.toBase64 = MessagePrototype.encode64;
8171
8172 /**
8173 * Directly encodes the message to a hex encoded string.
8174 * @name ProtoBuf.Builder.Message#encodeHex
8175 * @function
8176 * @return {string} Hex encoded string
8177 * @throws {Error} If the underlying buffer cannot be encoded or if required fields are missing. The later
8178 * still returns the encoded hex string in the `encoded` property on the error.
8179 * @expose
8180 */
8181 MessagePrototype.encodeHex = function() {
8182 try {
8183 return this.encode().toHex();
8184 } catch (e) {
8185 if (e["encoded"]) e["encoded"] = e["encoded"].toHex();
8186 throw(e);
8187 }
8188 };
8189
8190 /**
8191 * Returns the message as a hex encoded string. This is an alias for {@link ProtoBuf.Builder.Message#encodeHex}.
8192 * @name ProtoBuf.Builder.Message#toHex
8193 * @function
8194 * @return {string} Hex encoded string
8195 * @throws {Error} If the message cannot be encoded or if required fields are missing. The later still
8196 * returns the encoded hex string in the `encoded` property on the error.
8197 * @expose
8198 */
8199 MessagePrototype.toHex = MessagePrototype.encodeHex;
8200
8201 /**
8202 * Clones a message object or field value to a raw object.
8203 * @param {*} obj Object to clone
8204 * @param {boolean} binaryAsBase64 Whether to include binary data as base64 strings or as a buffer otherwise
8205 * @param {boolean} longsAsStrings Whether to encode longs as strings
8206 * @param {!ProtoBuf.Reflect.T=} resolvedType The resolved field type if a field
8207 * @returns {*} Cloned object
8208 * @inner
8209 */
8210 function cloneRaw(obj, binaryAsBase64, longsAsStrings, resolvedType) {
8211 if (obj === null || typeof obj !== 'object') {
8212 // Convert enum values to their respective names
8213 if (resolvedType && resolvedType instanceof ProtoBuf.Reflect.Enum) {
8214 var name = ProtoBuf.Reflect.Enum.getName(resolvedType.object, obj);
8215 if (name !== null)
8216 return name;
8217 }
8218 // Pass-through string, number, boolean, null...
8219 return obj;
8220 }
8221 // Convert ByteBuffers to raw buffer or strings
8222 if (ByteBuffer.isByteBuffer(obj))
8223 return binaryAsBase64 ? obj.toBase64() : obj.toBuffer();
8224 // Convert Longs to proper objects or strings
8225 if (ProtoBuf.Long.isLong(obj))
8226 return longsAsStrings ? obj.toString() : ProtoBuf.Long.fromValue(obj);
8227 var clone;
8228 // Clone arrays
8229 if (Array.isArray(obj)) {
8230 clone = [];
8231 obj.forEach(function(v, k) {
8232 clone[k] = cloneRaw(v, binaryAsBase64, longsAsStrings, resolvedType);
8233 });
8234 return clone;
8235 }
8236 clone = {};
8237 // Convert maps to objects
8238 if (obj instanceof ProtoBuf.Map) {
8239 var it = obj.entries();
8240 for (var e = it.next(); !e.done; e = it.next())
8241 clone[obj.keyElem.valueToString(e.value[0])] = cloneRaw(e.value[1], binaryAsBase64, longsAsStrings, obj.valueElem.resolvedType);
8242 return clone;
8243 }
8244 // Everything else is a non-null object
8245 var type = obj.$type,
8246 field = undefined;
8247 for (var i in obj)
8248 if (obj.hasOwnProperty(i)) {
8249 if (type && (field = type.getChild(i)))
8250 clone[i] = cloneRaw(obj[i], binaryAsBase64, longsAsStrings, field.resolvedType);
8251 else
8252 clone[i] = cloneRaw(obj[i], binaryAsBase64, longsAsStrings);
8253 }
8254 return clone;
8255 }
8256
8257 /**
8258 * Returns the message's raw payload.
8259 * @param {boolean=} binaryAsBase64 Whether to include binary data as base64 strings instead of Buffers, defaults to `false`
8260 * @param {boolean} longsAsStrings Whether to encode longs as strings
8261 * @returns {Object.<string,*>} Raw payload
8262 * @expose
8263 */
8264 MessagePrototype.toRaw = function(binaryAsBase64, longsAsStrings) {
8265 return cloneRaw(this, !!binaryAsBase64, !!longsAsStrings, this.$type);
8266 };
8267
8268 /**
8269 * Encodes a message to JSON.
8270 * @returns {string} JSON string
8271 * @expose
8272 */
8273 MessagePrototype.encodeJSON = function() {
8274 return JSON.stringify(
8275 cloneRaw(this,
8276 /* binary-as-base64 */ true,
8277 /* longs-as-strings */ true,
8278 this.$type
8279 )
8280 );
8281 };
8282
8283 /**
8284 * Decodes a message from the specified buffer or string.
8285 * @name ProtoBuf.Builder.Message.decode
8286 * @function
8287 * @param {!ByteBuffer|!ArrayBuffer|!Buffer|string} buffer Buffer to decode from
8288 * @param {(number|string)=} length Message length. Defaults to decode all the remainig data.
8289 * @param {string=} enc Encoding if buffer is a string: hex, utf8 (not recommended), defaults to base64
8290 * @return {!ProtoBuf.Builder.Message} Decoded message
8291 * @throws {Error} If the message cannot be decoded or if required fields are missing. The later still
8292 * returns the decoded message with missing fields in the `decoded` property on the error.
8293 * @expose
8294 * @see ProtoBuf.Builder.Message.decode64
8295 * @see ProtoBuf.Builder.Message.decodeHex
8296 */
8297 Message.decode = function(buffer, length, enc) {
8298 if (typeof length === 'string')
8299 enc = length,
8300 length = -1;
8301 if (typeof buffer === 'string')
8302 buffer = ByteBuffer.wrap(buffer, enc ? enc : "base64");
8303 else if (!ByteBuffer.isByteBuffer(buffer))
8304 buffer = ByteBuffer.wrap(buffer); // May throw
8305 var le = buffer.littleEndian;
8306 try {
8307 var msg = T.decode(buffer.LE(), length);
8308 buffer.LE(le);
8309 return msg;
8310 } catch (e) {
8311 buffer.LE(le);
8312 throw(e);
8313 }
8314 };
8315
8316 /**
8317 * Decodes a varint32 length-delimited message from the specified buffer or string.
8318 * @name ProtoBuf.Builder.Message.decodeDelimited
8319 * @function
8320 * @param {!ByteBuffer|!ArrayBuffer|!Buffer|string} buffer Buffer to decode from
8321 * @param {string=} enc Encoding if buffer is a string: hex, utf8 (not recommended), defaults to base64
8322 * @return {ProtoBuf.Builder.Message} Decoded message or `null` if not enough bytes are available yet
8323 * @throws {Error} If the message cannot be decoded or if required fields are missing. The later still
8324 * returns the decoded message with missing fields in the `decoded` property on the error.
8325 * @expose
8326 */
8327 Message.decodeDelimited = function(buffer, enc) {
8328 if (typeof buffer === 'string')
8329 buffer = ByteBuffer.wrap(buffer, enc ? enc : "base64");
8330 else if (!ByteBuffer.isByteBuffer(buffer))
8331 buffer = ByteBuffer.wrap(buffer); // May throw
8332 if (buffer.remaining() < 1)
8333 return null;
8334 var off = buffer.offset,
8335 len = buffer.readVarint32();
8336 if (buffer.remaining() < len) {
8337 buffer.offset = off;
8338 return null;
8339 }
8340 try {
8341 var msg = T.decode(buffer.slice(buffer.offset, buffer.offset + len).LE());
8342 buffer.offset += len;
8343 return msg;
8344 } catch (err) {
8345 buffer.offset += len;
8346 throw err;
8347 }
8348 };
8349
8350 /**
8351 * Decodes the message from the specified base64 encoded string.
8352 * @name ProtoBuf.Builder.Message.decode64
8353 * @function
8354 * @param {string} str String to decode from
8355 * @return {!ProtoBuf.Builder.Message} Decoded message
8356 * @throws {Error} If the message cannot be decoded or if required fields are missing. The later still
8357 * returns the decoded message with missing fields in the `decoded` property on the error.
8358 * @expose
8359 */
8360 Message.decode64 = function(str) {
8361 return Message.decode(str, "base64");
8362 };
8363
8364 /**
8365 * Decodes the message from the specified hex encoded string.
8366 * @name ProtoBuf.Builder.Message.decodeHex
8367 * @function
8368 * @param {string} str String to decode from
8369 * @return {!ProtoBuf.Builder.Message} Decoded message
8370 * @throws {Error} If the message cannot be decoded or if required fields are missing. The later still
8371 * returns the decoded message with missing fields in the `decoded` property on the error.
8372 * @expose
8373 */
8374 Message.decodeHex = function(str) {
8375 return Message.decode(str, "hex");
8376 };
8377
8378 /**
8379 * Decodes the message from a JSON string.
8380 * @name ProtoBuf.Builder.Message.decodeJSON
8381 * @function
8382 * @param {string} str String to decode from
8383 * @return {!ProtoBuf.Builder.Message} Decoded message
8384 * @throws {Error} If the message cannot be decoded or if required fields are
8385 * missing.
8386 * @expose
8387 */
8388 Message.decodeJSON = function(str) {
8389 return new Message(JSON.parse(str));
8390 };
8391
8392 // Utility
8393
8394 /**
8395 * Returns a string representation of this Message.
8396 * @name ProtoBuf.Builder.Message#toString
8397 * @function
8398 * @return {string} String representation as of ".Fully.Qualified.MessageName"
8399 * @expose
8400 */
8401 MessagePrototype.toString = function() {
8402 return T.toString();
8403 };
8404
8405 if (Object.defineProperty)
8406 Object.defineProperty(Message, '$options', { "value": T.buildOpt() }),
8407 Object.defineProperty(MessagePrototype, "$options", { "value": Message["$options"] }),
8408 Object.defineProperty(Message, "$type", { "value": T }),
8409 Object.defineProperty(MessagePrototype, "$type", { "value": T });
8410
8411 return Message;
8412
8413 })(ProtoBuf, this);
8414
8415 // Static enums and prototyped sub-messages / cached collections
8416 this._fields = [];
8417 this._fieldsById = {};
8418 this._fieldsByName = {};
8419 this._oneofsByName = {};
8420 for (var i=0, k=this.children.length, child; i<k; i++) {
8421 child = this.children[i];
8422 if (child instanceof Enum || child instanceof Message || child instanceof Service) {
8423 if (clazz.hasOwnProperty(child.name))
8424 throw Error("Illegal reflect child of "+this.toString(true)+": "+child.toString(true)+" cannot override static property '"+child.name+"'");
8425 clazz[child.name] = child.build();
8426 } else if (child instanceof Message.Field)
8427 child.build(),
8428 this._fields.push(child),
8429 this._fieldsById[child.id] = child,
8430 this._fieldsByName[child.name] = child;
8431 else if (child instanceof Message.OneOf) {
8432 this._oneofsByName[child.name] = child;
8433 }
8434 else if (!(child instanceof Message.OneOf) && !(child instanceof Extension)) // Not built
8435 throw Error("Illegal reflect child of "+this.toString(true)+": "+this.children[i].toString(true));
8436 }
8437
8438 return this.clazz = clazz;
8439 };
8440
8441 /**
8442 * Encodes a runtime message's contents to the specified buffer.
8443 * @param {!ProtoBuf.Builder.Message} message Runtime message to encode
8444 * @param {ByteBuffer} buffer ByteBuffer to write to
8445 * @param {boolean=} noVerify Whether to not verify field values, defaults to `false`
8446 * @return {ByteBuffer} The ByteBuffer for chaining
8447 * @throws {Error} If required fields are missing or the message cannot be encoded for another reason
8448 * @expose
8449 */
8450 MessagePrototype.encode = function(message, buffer, noVerify) {
8451 var fieldMissing = null,
8452 field;
8453 for (var i=0, k=this._fields.length, val; i<k; ++i) {
8454 field = this._fields[i];
8455 val = message[field.name];
8456 if (field.required && val === null) {
8457 if (fieldMissing === null)
8458 fieldMissing = field;
8459 } else
8460 field.encode(noVerify ? val : field.verifyValue(val), buffer, message);
8461 }
8462 if (fieldMissing !== null) {
8463 var err = Error("Missing at least one required field for "+this.toString(true)+": "+fieldMissing);
8464 err["encoded"] = buffer; // Still expose what we got
8465 throw(err);
8466 }
8467 return buffer;
8468 };
8469
8470 /**
8471 * Calculates a runtime message's byte length.
8472 * @param {!ProtoBuf.Builder.Message} message Runtime message to encode
8473 * @returns {number} Byte length
8474 * @throws {Error} If required fields are missing or the message cannot be calculated for another reason
8475 * @expose
8476 */
8477 MessagePrototype.calculate = function(message) {
8478 for (var n=0, i=0, k=this._fields.length, field, val; i<k; ++i) {
8479 field = this._fields[i];
8480 val = message[field.name];
8481 if (field.required && val === null)
8482 throw Error("Missing at least one required field for "+this.toString(true)+": "+field);
8483 else
8484 n += field.calculate(val, message);
8485 }
8486 return n;
8487 };
8488
8489 /**
8490 * Skips all data until the end of the specified group has been reached.
8491 * @param {number} expectedId Expected GROUPEND id
8492 * @param {!ByteBuffer} buf ByteBuffer
8493 * @returns {boolean} `true` if a value as been skipped, `false` if the end has been reached
8494 * @throws {Error} If it wasn't possible to find the end of the group (buffer overrun or end tag mismatch)
8495 * @inner
8496 */
8497 function skipTillGroupEnd(expectedId, buf) {
8498 var tag = buf.readVarint32(), // Throws on OOB
8499 wireType = tag & 0x07,
8500 id = tag >>> 3;
8501 switch (wireType) {
8502 case ProtoBuf.WIRE_TYPES.VARINT:
8503 do tag = buf.readUint8();
8504 while ((tag & 0x80) === 0x80);
8505 break;
8506 case ProtoBuf.WIRE_TYPES.BITS64:
8507 buf.offset += 8;
8508 break;
8509 case ProtoBuf.WIRE_TYPES.LDELIM:
8510 tag = buf.readVarint32(); // reads the varint
8511 buf.offset += tag; // skips n bytes
8512 break;
8513 case ProtoBuf.WIRE_TYPES.STARTGROUP:
8514 skipTillGroupEnd(id, buf);
8515 break;
8516 case ProtoBuf.WIRE_TYPES.ENDGROUP:
8517 if (id === expectedId)
8518 return false;
8519 else
8520 throw Error("Illegal GROUPEND after unknown group: "+id+" ("+expectedId+" expected)");
8521 case ProtoBuf.WIRE_TYPES.BITS32:
8522 buf.offset += 4;
8523 break;
8524 default:
8525 throw Error("Illegal wire type in unknown group "+expectedId+": "+wireType);
8526 }
8527 return true;
8528 }
8529
8530 /**
8531 * Decodes an encoded message and returns the decoded message.
8532 * @param {ByteBuffer} buffer ByteBuffer to decode from
8533 * @param {number=} length Message length. Defaults to decode all remaining data.
8534 * @param {number=} expectedGroupEndId Expected GROUPEND id if this is a legacy group
8535 * @return {ProtoBuf.Builder.Message} Decoded message
8536 * @throws {Error} If the message cannot be decoded
8537 * @expose
8538 */
8539 MessagePrototype.decode = function(buffer, length, expectedGroupEndId) {
8540 if (typeof length !== 'number')
8541 length = -1;
8542 var start = buffer.offset,
8543 msg = new (this.clazz)(),
8544 tag, wireType, id, field;
8545 while (buffer.offset < start+length || (length === -1 && buffer.remaining() > 0)) {
8546 tag = buffer.readVarint32();
8547 wireType = tag & 0x07;
8548 id = tag >>> 3;
8549 if (wireType === ProtoBuf.WIRE_TYPES.ENDGROUP) {
8550 if (id !== expectedGroupEndId)
8551 throw Error("Illegal group end indicator for "+this.toString(true)+": "+id+" ("+(expectedGroupEndId ? expectedGroupEndId+" expected" : "not a group")+")");
8552 break;
8553 }
8554 if (!(field = this._fieldsById[id])) {
8555 // "messages created by your new code can be parsed by your old code: old binaries simply ignore the new field when parsing."
8556 switch (wireType) {
8557 case ProtoBuf.WIRE_TYPES.VARINT:
8558 buffer.readVarint32();
8559 break;
8560 case ProtoBuf.WIRE_TYPES.BITS32:
8561 buffer.offset += 4;
8562 break;
8563 case ProtoBuf.WIRE_TYPES.BITS64:
8564 buffer.offset += 8;
8565 break;
8566 case ProtoBuf.WIRE_TYPES.LDELIM:
8567 var len = buffer.readVarint32();
8568 buffer.offset += len;
8569 break;
8570 case ProtoBuf.WIRE_TYPES.STARTGROUP:
8571 while (skipTillGroupEnd(id, buffer)) {}
8572 break;
8573 default:
8574 throw Error("Illegal wire type for unknown field "+id+" in "+this.toString(true)+"#decode: "+wireType);
8575 }
8576 continue;
8577 }
8578 if (field.repeated && !field.options["packed"]) {
8579 msg[field.name].push(field.decode(wireType, buffer));
8580 } else if (field.map) {
8581 var keyval = field.decode(wireType, buffer);
8582 msg[field.name].set(keyval[0], keyval[1]);
8583 } else {
8584 msg[field.name] = field.decode(wireType, buffer);
8585 if (field.oneof) { // Field is part of an OneOf (not a virtual OneOf field)
8586 var currentField = msg[field.oneof.name]; // Virtual field references currently set field
8587 if (currentField !== null && currentField !== field.name)
8588 msg[currentField] = null; // Clear currently set field
8589 msg[field.oneof.name] = field.name; // Point virtual field at this field
8590 }
8591 }
8592 }
8593
8594 // Check if all required fields are present and set default values for optional fields that are not
8595 for (var i=0, k=this._fields.length; i<k; ++i) {
8596 field = this._fields[i];
8597 if (msg[field.name] === null) {
8598 if (this.syntax === "proto3") { // Proto3 sets default values by specification
8599 msg[field.name] = field.defaultValue;
8600 } else if (field.required) {
8601 var err = Error("Missing at least one required field for " + this.toString(true) + ": " + field.name);
8602 err["decoded"] = msg; // Still expose what we got
8603 throw(err);
8604 } else if (ProtoBuf.populateDefaults && field.defaultValue !== null)
8605 msg[field.name] = field.defaultValue;
8606 }
8607 }
8608 return msg;
8609 };
8610
8611 /**
8612 * @alias ProtoBuf.Reflect.Message
8613 * @expose
8614 */
8615 Reflect.Message = Message;
8616
8617 /**
8618 * Constructs a new Message Field.
8619 * @exports ProtoBuf.Reflect.Message.Field
8620 * @param {!ProtoBuf.Builder} builder Builder reference
8621 * @param {!ProtoBuf.Reflect.Message} message Message reference
8622 * @param {string} rule Rule, one of requried, optional, repeated
8623 * @param {string?} keytype Key data type, if any.
8624 * @param {string} type Data type, e.g. int32
8625 * @param {string} name Field name
8626 * @param {number} id Unique field id
8627 * @param {Object.<string,*>=} options Options
8628 * @param {!ProtoBuf.Reflect.Message.OneOf=} oneof Enclosing OneOf
8629 * @param {string?} syntax The syntax level of this definition (e.g., proto3)
8630 * @constructor
8631 * @extends ProtoBuf.Reflect.T
8632 */
8633 var Field = function(builder, message, rule, keytype, type, name, id, options, oneof, syntax) {
8634 T.call(this, builder, message, name);
8635
8636 /**
8637 * @override
8638 */
8639 this.className = "Message.Field";
8640
8641 /**
8642 * Message field required flag.
8643 * @type {boolean}
8644 * @expose
8645 */
8646 this.required = rule === "required";
8647
8648 /**
8649 * Message field repeated flag.
8650 * @type {boolean}
8651 * @expose
8652 */
8653 this.repeated = rule === "repeated";
8654
8655 /**
8656 * Message field map flag.
8657 * @type {boolean}
8658 * @expose
8659 */
8660 this.map = rule === "map";
8661
8662 /**
8663 * Message field key type. Type reference string if unresolved, protobuf
8664 * type if resolved. Valid only if this.map === true, null otherwise.
8665 * @type {string|{name: string, wireType: number}|null}
8666 * @expose
8667 */
8668 this.keyType = keytype || null;
8669
8670 /**
8671 * Message field type. Type reference string if unresolved, protobuf type if
8672 * resolved. In a map field, this is the value type.
8673 * @type {string|{name: string, wireType: number}}
8674 * @expose
8675 */
8676 this.type = type;
8677
8678 /**
8679 * Resolved type reference inside the global namespace.
8680 * @type {ProtoBuf.Reflect.T|null}
8681 * @expose
8682 */
8683 this.resolvedType = null;
8684
8685 /**
8686 * Unique message field id.
8687 * @type {number}
8688 * @expose
8689 */
8690 this.id = id;
8691
8692 /**
8693 * Message field options.
8694 * @type {!Object.<string,*>}
8695 * @dict
8696 * @expose
8697 */
8698 this.options = options || {};
8699
8700 /**
8701 * Default value.
8702 * @type {*}
8703 * @expose
8704 */
8705 this.defaultValue = null;
8706
8707 /**
8708 * Enclosing OneOf.
8709 * @type {?ProtoBuf.Reflect.Message.OneOf}
8710 * @expose
8711 */
8712 this.oneof = oneof || null;
8713
8714 /**
8715 * Syntax level of this definition (e.g., proto3).
8716 * @type {string}
8717 * @expose
8718 */
8719 this.syntax = syntax || 'proto2';
8720
8721 /**
8722 * Original field name.
8723 * @type {string}
8724 * @expose
8725 */
8726 this.originalName = this.name; // Used to revert camelcase transformation on naming collisions
8727
8728 /**
8729 * Element implementation. Created in build() after types are resolved.
8730 * @type {ProtoBuf.Element}
8731 * @expose
8732 */
8733 this.element = null;
8734
8735 /**
8736 * Key element implementation, for map fields. Created in build() after
8737 * types are resolved.
8738 * @type {ProtoBuf.Element}
8739 * @expose
8740 */
8741 this.keyElement = null;
8742
8743 // Convert field names to camel case notation if the override is set
8744 if (this.builder.options['convertFieldsToCamelCase'] && !(this instanceof Message.ExtensionField))
8745 this.name = ProtoBuf.Util.toCamelCase(this.name);
8746 };
8747
8748 /**
8749 * @alias ProtoBuf.Reflect.Message.Field.prototype
8750 * @inner
8751 */
8752 var FieldPrototype = Field.prototype = Object.create(T.prototype);
8753
8754 /**
8755 * Builds the field.
8756 * @override
8757 * @expose
8758 */
8759 FieldPrototype.build = function() {
8760 this.element = new Element(this.type, this.resolvedType, false, this.syntax, this.name);
8761 if (this.map)
8762 this.keyElement = new Element(this.keyType, undefined, true, this.syntax, this.name);
8763
8764 // In proto3, fields do not have field presence, and every field is set to
8765 // its type's default value ("", 0, 0.0, or false).
8766 if (this.syntax === 'proto3' && !this.repeated && !this.map)
8767 this.defaultValue = Element.defaultFieldValue(this.type);
8768
8769 // Otherwise, default values are present when explicitly specified
8770 else if (typeof this.options['default'] !== 'undefined')
8771 this.defaultValue = this.verifyValue(this.options['default']);
8772 };
8773
8774 /**
8775 * Checks if the given value can be set for this field.
8776 * @param {*} value Value to check
8777 * @param {boolean=} skipRepeated Whether to skip the repeated value check or not. Defaults to false.
8778 * @return {*} Verified, maybe adjusted, value
8779 * @throws {Error} If the value cannot be set for this field
8780 * @expose
8781 */
8782 FieldPrototype.verifyValue = function(value, skipRepeated) {
8783 skipRepeated = skipRepeated || false;
8784 var self = this;
8785 function fail(val, msg) {
8786 throw Error("Illegal value for "+self.toString(true)+" of type "+self.type.name+": "+val+" ("+msg+")");
8787 }
8788 if (value === null) { // NULL values for optional fields
8789 if (this.required)
8790 fail(typeof value, "required");
8791 if (this.syntax === 'proto3' && this.type !== ProtoBuf.TYPES["message"])
8792 fail(typeof value, "proto3 field without field presence cannot be null");
8793 return null;
8794 }
8795 var i;
8796 if (this.repeated && !skipRepeated) { // Repeated values as arrays
8797 if (!Array.isArray(value))
8798 value = [value];
8799 var res = [];
8800 for (i=0; i<value.length; i++)
8801 res.push(this.element.verifyValue(value[i]));
8802 return res;
8803 }
8804 if (this.map && !skipRepeated) { // Map values as objects
8805 if (!(value instanceof ProtoBuf.Map)) {
8806 // If not already a Map, attempt to convert.
8807 if (!(value instanceof Object)) {
8808 fail(typeof value,
8809 "expected ProtoBuf.Map or raw object for map field");
8810 }
8811 return new ProtoBuf.Map(this, value);
8812 } else {
8813 return value;
8814 }
8815 }
8816 // All non-repeated fields expect no array
8817 if (!this.repeated && Array.isArray(value))
8818 fail(typeof value, "no array expected");
8819
8820 return this.element.verifyValue(value);
8821 };
8822
8823 /**
8824 * Determines whether the field will have a presence on the wire given its
8825 * value.
8826 * @param {*} value Verified field value
8827 * @param {!ProtoBuf.Builder.Message} message Runtime message
8828 * @return {boolean} Whether the field will be present on the wire
8829 */
8830 FieldPrototype.hasWirePresence = function(value, message) {
8831 if (this.syntax !== 'proto3')
8832 return (value !== null);
8833 if (this.oneof && message[this.oneof.name] === this.name)
8834 return true;
8835 switch (this.type) {
8836 case ProtoBuf.TYPES["int32"]:
8837 case ProtoBuf.TYPES["sint32"]:
8838 case ProtoBuf.TYPES["sfixed32"]:
8839 case ProtoBuf.TYPES["uint32"]:
8840 case ProtoBuf.TYPES["fixed32"]:
8841 return value !== 0;
8842
8843 case ProtoBuf.TYPES["int64"]:
8844 case ProtoBuf.TYPES["sint64"]:
8845 case ProtoBuf.TYPES["sfixed64"]:
8846 case ProtoBuf.TYPES["uint64"]:
8847 case ProtoBuf.TYPES["fixed64"]:
8848 return value.low !== 0 || value.high !== 0;
8849
8850 case ProtoBuf.TYPES["bool"]:
8851 return value;
8852
8853 case ProtoBuf.TYPES["float"]:
8854 case ProtoBuf.TYPES["double"]:
8855 return value !== 0.0;
8856
8857 case ProtoBuf.TYPES["string"]:
8858 return value.length > 0;
8859
8860 case ProtoBuf.TYPES["bytes"]:
8861 return value.remaining() > 0;
8862
8863 case ProtoBuf.TYPES["enum"]:
8864 return value !== 0;
8865
8866 case ProtoBuf.TYPES["message"]:
8867 return value !== null;
8868 default:
8869 return true;
8870 }
8871 };
8872
8873 /**
8874 * Encodes the specified field value to the specified buffer.
8875 * @param {*} value Verified field value
8876 * @param {ByteBuffer} buffer ByteBuffer to encode to
8877 * @param {!ProtoBuf.Builder.Message} message Runtime message
8878 * @return {ByteBuffer} The ByteBuffer for chaining
8879 * @throws {Error} If the field cannot be encoded
8880 * @expose
8881 */
8882 FieldPrototype.encode = function(value, buffer, message) {
8883 if (this.type === null || typeof this.type !== 'object')
8884 throw Error("[INTERNAL] Unresolved type in "+this.toString(true)+": "+this.type);
8885 if (value === null || (this.repeated && value.length == 0))
8886 return buffer; // Optional omitted
8887 try {
8888 if (this.repeated) {
8889 var i;
8890 // "Only repeated fields of primitive numeric types (types which use the varint, 32-bit, or 64-bit wire
8891 // types) can be declared 'packed'."
8892 if (this.options["packed"] && ProtoBuf.PACKABLE_WIRE_TYPES.indexOf(this.type.wireType) >= 0) {
8893 // "All of the elements of the field are packed into a single key-value pair with wire type 2
8894 // (length-delimited). Each element is encoded the same way it would be normally, except without a
8895 // tag preceding it."
8896 buffer.writeVarint32((this.id << 3) | ProtoBuf.WIRE_TYPES.LDELIM);
8897 buffer.ensureCapacity(buffer.offset += 1); // We do not know the length yet, so let's assume a varint of length 1
8898 var start = buffer.offset; // Remember where the contents begin
8899 for (i=0; i<value.length; i++)
8900 this.element.encodeValue(this.id, value[i], buffer);
8901 var len = buffer.offset-start,
8902 varintLen = ByteBuffer.calculateVarint32(len);
8903 if (varintLen > 1) { // We need to move the contents
8904 var contents = buffer.slice(start, buffer.offset);
8905 start += varintLen-1;
8906 buffer.offset = start;
8907 buffer.append(contents);
8908 }
8909 buffer.writeVarint32(len, start-varintLen);
8910 } else {
8911 // "If your message definition has repeated elements (without the [packed=true] option), the encoded
8912 // message has zero or more key-value pairs with the same tag number"
8913 for (i=0; i<value.length; i++)
8914 buffer.writeVarint32((this.id << 3) | this.type.wireType),
8915 this.element.encodeValue(this.id, value[i], buffer);
8916 }
8917 } else if (this.map) {
8918 // Write out each map entry as a submessage.
8919 value.forEach(function(val, key, m) {
8920 // Compute the length of the submessage (key, val) pair.
8921 var length =
8922 ByteBuffer.calculateVarint32((1 << 3) | this.keyType.wireType) +
8923 this.keyElement.calculateLength(1, key) +
8924 ByteBuffer.calculateVarint32((2 << 3) | this.type.wireType) +
8925 this.element.calculateLength(2, val);
8926
8927 // Submessage with wire type of length-delimited.
8928 buffer.writeVarint32((this.id << 3) | ProtoBuf.WIRE_TYPES.LDELIM);
8929 buffer.writeVarint32(length);
8930
8931 // Write out the key and val.
8932 buffer.writeVarint32((1 << 3) | this.keyType.wireType);
8933 this.keyElement.encodeValue(1, key, buffer);
8934 buffer.writeVarint32((2 << 3) | this.type.wireType);
8935 this.element.encodeValue(2, val, buffer);
8936 }, this);
8937 } else {
8938 if (this.hasWirePresence(value, message)) {
8939 buffer.writeVarint32((this.id << 3) | this.type.wireType);
8940 this.element.encodeValue(this.id, value, buffer);
8941 }
8942 }
8943 } catch (e) {
8944 throw Error("Illegal value for "+this.toString(true)+": "+value+" ("+e+")");
8945 }
8946 return buffer;
8947 };
8948
8949 /**
8950 * Calculates the length of this field's value on the network level.
8951 * @param {*} value Field value
8952 * @param {!ProtoBuf.Builder.Message} message Runtime message
8953 * @returns {number} Byte length
8954 * @expose
8955 */
8956 FieldPrototype.calculate = function(value, message) {
8957 value = this.verifyValue(value); // May throw
8958 if (this.type === null || typeof this.type !== 'object')
8959 throw Error("[INTERNAL] Unresolved type in "+this.toString(true)+": "+this.type);
8960 if (value === null || (this.repeated && value.length == 0))
8961 return 0; // Optional omitted
8962 var n = 0;
8963 try {
8964 if (this.repeated) {
8965 var i, ni;
8966 if (this.options["packed"] && ProtoBuf.PACKABLE_WIRE_TYPES.indexOf(this.type.wireType) >= 0) {
8967 n += ByteBuffer.calculateVarint32((this.id << 3) | ProtoBuf.WIRE_TYPES.LDELIM);
8968 ni = 0;
8969 for (i=0; i<value.length; i++)
8970 ni += this.element.calculateLength(this.id, value[i]);
8971 n += ByteBuffer.calculateVarint32(ni);
8972 n += ni;
8973 } else {
8974 for (i=0; i<value.length; i++)
8975 n += ByteBuffer.calculateVarint32((this.id << 3) | this.type.wireType),
8976 n += this.element.calculateLength(this.id, value[i]);
8977 }
8978 } else if (this.map) {
8979 // Each map entry becomes a submessage.
8980 value.forEach(function(val, key, m) {
8981 // Compute the length of the submessage (key, val) pair.
8982 var length =
8983 ByteBuffer.calculateVarint32((1 << 3) | this.keyType.wireType) +
8984 this.keyElement.calculateLength(1, key) +
8985 ByteBuffer.calculateVarint32((2 << 3) | this.type.wireType) +
8986 this.element.calculateLength(2, val);
8987
8988 n += ByteBuffer.calculateVarint32((this.id << 3) | ProtoBuf.WIRE_TYPES.LDELIM);
8989 n += ByteBuffer.calculateVarint32(length);
8990 n += length;
8991 }, this);
8992 } else {
8993 if (this.hasWirePresence(value, message)) {
8994 n += ByteBuffer.calculateVarint32((this.id << 3) | this.type.wireType);
8995 n += this.element.calculateLength(this.id, value);
8996 }
8997 }
8998 } catch (e) {
8999 throw Error("Illegal value for "+this.toString(true)+": "+value+" ("+e+")");
9000 }
9001 return n;
9002 };
9003
9004 /**
9005 * Decode the field value from the specified buffer.
9006 * @param {number} wireType Leading wire type
9007 * @param {ByteBuffer} buffer ByteBuffer to decode from
9008 * @param {boolean=} skipRepeated Whether to skip the repeated check or not. Defaults to false.
9009 * @return {*} Decoded value: array for packed repeated fields, [key, value] for
9010 * map fields, or an individual value otherwise.
9011 * @throws {Error} If the field cannot be decoded
9012 * @expose
9013 */
9014 FieldPrototype.decode = function(wireType, buffer, skipRepeated) {
9015 var value, nBytes;
9016
9017 // We expect wireType to match the underlying type's wireType unless we see
9018 // a packed repeated field, or unless this is a map field.
9019 var wireTypeOK =
9020 (!this.map && wireType == this.type.wireType) ||
9021 (!skipRepeated && this.repeated && this.options["packed"] &&
9022 wireType == ProtoBuf.WIRE_TYPES.LDELIM) ||
9023 (this.map && wireType == ProtoBuf.WIRE_TYPES.LDELIM);
9024 if (!wireTypeOK)
9025 throw Error("Illegal wire type for field "+this.toString(true)+": "+wireType+" ("+this.type.wireType+" expected)");
9026
9027 // Handle packed repeated fields.
9028 if (wireType == ProtoBuf.WIRE_TYPES.LDELIM && this.repeated && this.options["packed"] && ProtoBuf.PACKABLE_WIRE_TYPES.indexOf(this.type.wireType) >= 0) {
9029 if (!skipRepeated) {
9030 nBytes = buffer.readVarint32();
9031 nBytes = buffer.offset + nBytes; // Limit
9032 var values = [];
9033 while (buffer.offset < nBytes)
9034 values.push(this.decode(this.type.wireType, buffer, true));
9035 return values;
9036 }
9037 // Read the next value otherwise...
9038 }
9039
9040 // Handle maps.
9041 if (this.map) {
9042 // Read one (key, value) submessage, and return [key, value]
9043 var key = Element.defaultFieldValue(this.keyType);
9044 value = Element.defaultFieldValue(this.type);
9045
9046 // Read the length
9047 nBytes = buffer.readVarint32();
9048 if (buffer.remaining() < nBytes)
9049 throw Error("Illegal number of bytes for "+this.toString(true)+": "+nBytes+" required but got only "+buffer.remaining());
9050
9051 // Get a sub-buffer of this key/value submessage
9052 var msgbuf = buffer.clone();
9053 msgbuf.limit = msgbuf.offset + nBytes;
9054 buffer.offset += nBytes;
9055
9056 while (msgbuf.remaining() > 0) {
9057 var tag = msgbuf.readVarint32();
9058 wireType = tag & 0x07;
9059 var id = tag >>> 3;
9060 if (id === 1) {
9061 key = this.keyElement.decode(msgbuf, wireType, id);
9062 } else if (id === 2) {
9063 value = this.element.decode(msgbuf, wireType, id);
9064 } else {
9065 throw Error("Unexpected tag in map field key/value submessage");
9066 }
9067 }
9068
9069 return [key, value];
9070 }
9071
9072 // Handle singular and non-packed repeated field values.
9073 return this.element.decode(buffer, wireType, this.id);
9074 };
9075
9076 /**
9077 * @alias ProtoBuf.Reflect.Message.Field
9078 * @expose
9079 */
9080 Reflect.Message.Field = Field;
9081
9082 /**
9083 * Constructs a new Message ExtensionField.
9084 * @exports ProtoBuf.Reflect.Message.ExtensionField
9085 * @param {!ProtoBuf.Builder} builder Builder reference
9086 * @param {!ProtoBuf.Reflect.Message} message Message reference
9087 * @param {string} rule Rule, one of requried, optional, repeated
9088 * @param {string} type Data type, e.g. int32
9089 * @param {string} name Field name
9090 * @param {number} id Unique field id
9091 * @param {!Object.<string,*>=} options Options
9092 * @constructor
9093 * @extends ProtoBuf.Reflect.Message.Field
9094 */
9095 var ExtensionField = function(builder, message, rule, type, name, id, options) {
9096 Field.call(this, builder, message, rule, /* keytype = */ null, type, name, id, options);
9097
9098 /**
9099 * Extension reference.
9100 * @type {!ProtoBuf.Reflect.Extension}
9101 * @expose
9102 */
9103 this.extension;
9104 };
9105
9106 // Extends Field
9107 ExtensionField.prototype = Object.create(Field.prototype);
9108
9109 /**
9110 * @alias ProtoBuf.Reflect.Message.ExtensionField
9111 * @expose
9112 */
9113 Reflect.Message.ExtensionField = ExtensionField;
9114
9115 /**
9116 * Constructs a new Message OneOf.
9117 * @exports ProtoBuf.Reflect.Message.OneOf
9118 * @param {!ProtoBuf.Builder} builder Builder reference
9119 * @param {!ProtoBuf.Reflect.Message} message Message reference
9120 * @param {string} name OneOf name
9121 * @constructor
9122 * @extends ProtoBuf.Reflect.T
9123 */
9124 var OneOf = function(builder, message, name) {
9125 T.call(this, builder, message, name);
9126
9127 /**
9128 * Enclosed fields.
9129 * @type {!Array.<!ProtoBuf.Reflect.Message.Field>}
9130 * @expose
9131 */
9132 this.fields = [];
9133 };
9134
9135 /**
9136 * @alias ProtoBuf.Reflect.Message.OneOf
9137 * @expose
9138 */
9139 Reflect.Message.OneOf = OneOf;
9140
9141 /**
9142 * Constructs a new Enum.
9143 * @exports ProtoBuf.Reflect.Enum
9144 * @param {!ProtoBuf.Builder} builder Builder reference
9145 * @param {!ProtoBuf.Reflect.T} parent Parent Reflect object
9146 * @param {string} name Enum name
9147 * @param {Object.<string,*>=} options Enum options
9148 * @param {string?} syntax The syntax level (e.g., proto3)
9149 * @constructor
9150 * @extends ProtoBuf.Reflect.Namespace
9151 */
9152 var Enum = function(builder, parent, name, options, syntax) {
9153 Namespace.call(this, builder, parent, name, options, syntax);
9154
9155 /**
9156 * @override
9157 */
9158 this.className = "Enum";
9159
9160 /**
9161 * Runtime enum object.
9162 * @type {Object.<string,number>|null}
9163 * @expose
9164 */
9165 this.object = null;
9166 };
9167
9168 /**
9169 * Gets the string name of an enum value.
9170 * @param {!ProtoBuf.Builder.Enum} enm Runtime enum
9171 * @param {number} value Enum value
9172 * @returns {?string} Name or `null` if not present
9173 * @expose
9174 */
9175 Enum.getName = function(enm, value) {
9176 var keys = Object.keys(enm);
9177 for (var i=0, key; i<keys.length; ++i)
9178 if (enm[key = keys[i]] === value)
9179 return key;
9180 return null;
9181 };
9182
9183 /**
9184 * @alias ProtoBuf.Reflect.Enum.prototype
9185 * @inner
9186 */
9187 var EnumPrototype = Enum.prototype = Object.create(Namespace.prototype);
9188
9189 /**
9190 * Builds this enum and returns the runtime counterpart.
9191 * @param {boolean} rebuild Whether to rebuild or not, defaults to false
9192 * @returns {!Object.<string,number>}
9193 * @expose
9194 */
9195 EnumPrototype.build = function(rebuild) {
9196 if (this.object && !rebuild)
9197 return this.object;
9198 var enm = new ProtoBuf.Builder.Enum(),
9199 values = this.getChildren(Enum.Value);
9200 for (var i=0, k=values.length; i<k; ++i)
9201 enm[values[i]['name']] = values[i]['id'];
9202 if (Object.defineProperty)
9203 Object.defineProperty(enm, '$options', {
9204 "value": this.buildOpt(),
9205 "enumerable": false
9206 });
9207 return this.object = enm;
9208 };
9209
9210 /**
9211 * @alias ProtoBuf.Reflect.Enum
9212 * @expose
9213 */
9214 Reflect.Enum = Enum;
9215
9216 /**
9217 * Constructs a new Enum Value.
9218 * @exports ProtoBuf.Reflect.Enum.Value
9219 * @param {!ProtoBuf.Builder} builder Builder reference
9220 * @param {!ProtoBuf.Reflect.Enum} enm Enum reference
9221 * @param {string} name Field name
9222 * @param {number} id Unique field id
9223 * @constructor
9224 * @extends ProtoBuf.Reflect.T
9225 */
9226 var Value = function(builder, enm, name, id) {
9227 T.call(this, builder, enm, name);
9228
9229 /**
9230 * @override
9231 */
9232 this.className = "Enum.Value";
9233
9234 /**
9235 * Unique enum value id.
9236 * @type {number}
9237 * @expose
9238 */
9239 this.id = id;
9240 };
9241
9242 // Extends T
9243 Value.prototype = Object.create(T.prototype);
9244
9245 /**
9246 * @alias ProtoBuf.Reflect.Enum.Value
9247 * @expose
9248 */
9249 Reflect.Enum.Value = Value;
9250
9251 /**
9252 * An extension (field).
9253 * @exports ProtoBuf.Reflect.Extension
9254 * @constructor
9255 * @param {!ProtoBuf.Builder} builder Builder reference
9256 * @param {!ProtoBuf.Reflect.T} parent Parent object
9257 * @param {string} name Object name
9258 * @param {!ProtoBuf.Reflect.Message.Field} field Extension field
9259 */
9260 var Extension = function(builder, parent, name, field) {
9261 T.call(this, builder, parent, name);
9262
9263 /**
9264 * Extended message field.
9265 * @type {!ProtoBuf.Reflect.Message.Field}
9266 * @expose
9267 */
9268 this.field = field;
9269 };
9270
9271 // Extends T
9272 Extension.prototype = Object.create(T.prototype);
9273
9274 /**
9275 * @alias ProtoBuf.Reflect.Extension
9276 * @expose
9277 */
9278 Reflect.Extension = Extension;
9279
9280 /**
9281 * Constructs a new Service.
9282 * @exports ProtoBuf.Reflect.Service
9283 * @param {!ProtoBuf.Builder} builder Builder reference
9284 * @param {!ProtoBuf.Reflect.Namespace} root Root
9285 * @param {string} name Service name
9286 * @param {Object.<string,*>=} options Options
9287 * @constructor
9288 * @extends ProtoBuf.Reflect.Namespace
9289 */
9290 var Service = function(builder, root, name, options) {
9291 Namespace.call(this, builder, root, name, options);
9292
9293 /**
9294 * @override
9295 */
9296 this.className = "Service";
9297
9298 /**
9299 * Built runtime service class.
9300 * @type {?function(new:ProtoBuf.Builder.Service)}
9301 */
9302 this.clazz = null;
9303 };
9304
9305 /**
9306 * @alias ProtoBuf.Reflect.Service.prototype
9307 * @inner
9308 */
9309 var ServicePrototype = Service.prototype = Object.create(Namespace.prototype);
9310
9311 /**
9312 * Builds the service and returns the runtime counterpart, which is a fully functional class.
9313 * @see ProtoBuf.Builder.Service
9314 * @param {boolean=} rebuild Whether to rebuild or not
9315 * @return {Function} Service class
9316 * @throws {Error} If the message cannot be built
9317 * @expose
9318 */
9319 ServicePrototype.build = function(rebuild) {
9320 if (this.clazz && !rebuild)
9321 return this.clazz;
9322
9323 // Create the runtime Service class in its own scope
9324 return this.clazz = (function(ProtoBuf, T) {
9325
9326 /**
9327 * Constructs a new runtime Service.
9328 * @name ProtoBuf.Builder.Service
9329 * @param {function(string, ProtoBuf.Builder.Message, function(Error, ProtoBuf.Builder.Message=))=} rpcImpl RPC implementation receiving the method name and the message
9330 * @class Barebone of all runtime services.
9331 * @constructor
9332 * @throws {Error} If the service cannot be created
9333 */
9334 var Service = function(rpcImpl) {
9335 ProtoBuf.Builder.Service.call(this);
9336
9337 /**
9338 * Service implementation.
9339 * @name ProtoBuf.Builder.Service#rpcImpl
9340 * @type {!function(string, ProtoBuf.Builder.Message, function(Error, ProtoBuf.Builder.Message=))}
9341 * @expose
9342 */
9343 this.rpcImpl = rpcImpl || function(name, msg, callback) {
9344 // This is what a user has to implement: A function receiving the method name, the actual message to
9345 // send (type checked) and the callback that's either provided with the error as its first
9346 // argument or null and the actual response message.
9347 setTimeout(callback.bind(this, Error("Not implemented, see: https://github.com/dcodeIO/ProtoBuf.js/wiki/Services")), 0); // Must be async!
9348 };
9349 };
9350
9351 /**
9352 * @alias ProtoBuf.Builder.Service.prototype
9353 * @inner
9354 */
9355 var ServicePrototype = Service.prototype = Object.create(ProtoBuf.Builder.Service.prototype);
9356
9357 /**
9358 * Asynchronously performs an RPC call using the given RPC implementation.
9359 * @name ProtoBuf.Builder.Service.[Method]
9360 * @function
9361 * @param {!function(string, ProtoBuf.Builder.Message, function(Error, ProtoBuf.Builder.Message=))} rpcImpl RPC implementation
9362 * @param {ProtoBuf.Builder.Message} req Request
9363 * @param {function(Error, (ProtoBuf.Builder.Message|ByteBuffer|Buffer|string)=)} callback Callback receiving
9364 * the error if any and the response either as a pre-parsed message or as its raw bytes
9365 * @abstract
9366 */
9367
9368 /**
9369 * Asynchronously performs an RPC call using the instance's RPC implementation.
9370 * @name ProtoBuf.Builder.Service#[Method]
9371 * @function
9372 * @param {ProtoBuf.Builder.Message} req Request
9373 * @param {function(Error, (ProtoBuf.Builder.Message|ByteBuffer|Buffer|string)=)} callback Callback receiving
9374 * the error if any and the response either as a pre-parsed message or as its raw bytes
9375 * @abstract
9376 */
9377
9378 var rpc = T.getChildren(ProtoBuf.Reflect.Service.RPCMethod);
9379 for (var i=0; i<rpc.length; i++) {
9380 (function(method) {
9381
9382 // service#Method(message, callback)
9383 ServicePrototype[method.name] = function(req, callback) {
9384 try {
9385 try {
9386 // If given as a buffer, decode the request. Will throw a TypeError if not a valid buffer.
9387 req = method.resolvedRequestType.clazz.decode(ByteBuffer.wrap(req));
9388 } catch (err) {
9389 if (!(err instanceof TypeError))
9390 throw err;
9391 }
9392 if (req === null || typeof req !== 'object')
9393 throw Error("Illegal arguments");
9394 if (!(req instanceof method.resolvedRequestType.clazz))
9395 req = new method.resolvedRequestType.clazz(req);
9396 this.rpcImpl(method.fqn(), req, function(err, res) { // Assumes that this is properly async
9397 if (err) {
9398 callback(err);
9399 return;
9400 }
9401 // Coalesce to empty string when service response has empty content
9402 if (res === null)
9403 res = '';
9404 try { res = method.resolvedResponseType.clazz.decode(res); } catch (notABuffer) {}
9405 if (!res || !(res instanceof method.resolvedResponseType.clazz)) {
9406 callback(Error("Illegal response type received in service method "+ T.name+"#"+method.name));
9407 return;
9408 }
9409 callback(null, res);
9410 });
9411 } catch (err) {
9412 setTimeout(callback.bind(this, err), 0);
9413 }
9414 };
9415
9416 // Service.Method(rpcImpl, message, callback)
9417 Service[method.name] = function(rpcImpl, req, callback) {
9418 new Service(rpcImpl)[method.name](req, callback);
9419 };
9420
9421 if (Object.defineProperty)
9422 Object.defineProperty(Service[method.name], "$options", { "value": method.buildOpt() }),
9423 Object.defineProperty(ServicePrototype[method.name], "$options", { "value": Service[method.name]["$options"] });
9424 })(rpc[i]);
9425 }
9426
9427 if (Object.defineProperty)
9428 Object.defineProperty(Service, "$options", { "value": T.buildOpt() }),
9429 Object.defineProperty(ServicePrototype, "$options", { "value": Service["$options"] }),
9430 Object.defineProperty(Service, "$type", { "value": T }),
9431 Object.defineProperty(ServicePrototype, "$type", { "value": T });
9432
9433 return Service;
9434
9435 })(ProtoBuf, this);
9436 };
9437
9438 /**
9439 * @alias ProtoBuf.Reflect.Service
9440 * @expose
9441 */
9442 Reflect.Service = Service;
9443
9444 /**
9445 * Abstract service method.
9446 * @exports ProtoBuf.Reflect.Service.Method
9447 * @param {!ProtoBuf.Builder} builder Builder reference
9448 * @param {!ProtoBuf.Reflect.Service} svc Service
9449 * @param {string} name Method name
9450 * @param {Object.<string,*>=} options Options
9451 * @constructor
9452 * @extends ProtoBuf.Reflect.T
9453 */
9454 var Method = function(builder, svc, name, options) {
9455 T.call(this, builder, svc, name);
9456
9457 /**
9458 * @override
9459 */
9460 this.className = "Service.Method";
9461
9462 /**
9463 * Options.
9464 * @type {Object.<string, *>}
9465 * @expose
9466 */
9467 this.options = options || {};
9468 };
9469
9470 /**
9471 * @alias ProtoBuf.Reflect.Service.Method.prototype
9472 * @inner
9473 */
9474 var MethodPrototype = Method.prototype = Object.create(T.prototype);
9475
9476 /**
9477 * Builds the method's '$options' property.
9478 * @name ProtoBuf.Reflect.Service.Method#buildOpt
9479 * @function
9480 * @return {Object.<string,*>}
9481 */
9482 MethodPrototype.buildOpt = NamespacePrototype.buildOpt;
9483
9484 /**
9485 * @alias ProtoBuf.Reflect.Service.Method
9486 * @expose
9487 */
9488 Reflect.Service.Method = Method;
9489
9490 /**
9491 * RPC service method.
9492 * @exports ProtoBuf.Reflect.Service.RPCMethod
9493 * @param {!ProtoBuf.Builder} builder Builder reference
9494 * @param {!ProtoBuf.Reflect.Service} svc Service
9495 * @param {string} name Method name
9496 * @param {string} request Request message name
9497 * @param {string} response Response message name
9498 * @param {boolean} request_stream Whether requests are streamed
9499 * @param {boolean} response_stream Whether responses are streamed
9500 * @param {Object.<string,*>=} options Options
9501 * @constructor
9502 * @extends ProtoBuf.Reflect.Service.Method
9503 */
9504 var RPCMethod = function(builder, svc, name, request, response, request_stream, response_stream, options) {
9505 Method.call(this, builder, svc, name, options);
9506
9507 /**
9508 * @override
9509 */
9510 this.className = "Service.RPCMethod";
9511
9512 /**
9513 * Request message name.
9514 * @type {string}
9515 * @expose
9516 */
9517 this.requestName = request;
9518
9519 /**
9520 * Response message name.
9521 * @type {string}
9522 * @expose
9523 */
9524 this.responseName = response;
9525
9526 /**
9527 * Whether requests are streamed
9528 * @type {bool}
9529 * @expose
9530 */
9531 this.requestStream = request_stream;
9532
9533 /**
9534 * Whether responses are streamed
9535 * @type {bool}
9536 * @expose
9537 */
9538 this.responseStream = response_stream;
9539
9540 /**
9541 * Resolved request message type.
9542 * @type {ProtoBuf.Reflect.Message}
9543 * @expose
9544 */
9545 this.resolvedRequestType = null;
9546
9547 /**
9548 * Resolved response message type.
9549 * @type {ProtoBuf.Reflect.Message}
9550 * @expose
9551 */
9552 this.resolvedResponseType = null;
9553 };
9554
9555 // Extends Method
9556 RPCMethod.prototype = Object.create(Method.prototype);
9557
9558 /**
9559 * @alias ProtoBuf.Reflect.Service.RPCMethod
9560 * @expose
9561 */
9562 Reflect.Service.RPCMethod = RPCMethod;
9563
9564 return Reflect;
9565
9566 })(ProtoBuf);
9567
9568 /**
9569 * @alias ProtoBuf.Builder
9570 * @expose
9571 */
9572 ProtoBuf.Builder = (function(ProtoBuf, Lang, Reflect) {
9573
9574 /**
9575 * Constructs a new Builder.
9576 * @exports ProtoBuf.Builder
9577 * @class Provides the functionality to build protocol messages.
9578 * @param {Object.<string,*>=} options Options
9579 * @constructor
9580 */
9581 var Builder = function(options) {
9582
9583 /**
9584 * Namespace.
9585 * @type {ProtoBuf.Reflect.Namespace}
9586 * @expose
9587 */
9588 this.ns = new Reflect.Namespace(this, null, ""); // Global namespace
9589
9590 /**
9591 * Namespace pointer.
9592 * @type {ProtoBuf.Reflect.T}
9593 * @expose
9594 */
9595 this.ptr = this.ns;
9596
9597 /**
9598 * Resolved flag.
9599 * @type {boolean}
9600 * @expose
9601 */
9602 this.resolved = false;
9603
9604 /**
9605 * The current building result.
9606 * @type {Object.<string,ProtoBuf.Builder.Message|Object>|null}
9607 * @expose
9608 */
9609 this.result = null;
9610
9611 /**
9612 * Imported files.
9613 * @type {Array.<string>}
9614 * @expose
9615 */
9616 this.files = {};
9617
9618 /**
9619 * Import root override.
9620 * @type {?string}
9621 * @expose
9622 */
9623 this.importRoot = null;
9624
9625 /**
9626 * Options.
9627 * @type {!Object.<string, *>}
9628 * @expose
9629 */
9630 this.options = options || {};
9631 };
9632
9633 /**
9634 * @alias ProtoBuf.Builder.prototype
9635 * @inner
9636 */
9637 var BuilderPrototype = Builder.prototype;
9638
9639 // ----- Definition tests -----
9640
9641 /**
9642 * Tests if a definition most likely describes a message.
9643 * @param {!Object} def
9644 * @returns {boolean}
9645 * @expose
9646 */
9647 Builder.isMessage = function(def) {
9648 // Messages require a string name
9649 if (typeof def["name"] !== 'string')
9650 return false;
9651 // Messages do not contain values (enum) or rpc methods (service)
9652 if (typeof def["values"] !== 'undefined' || typeof def["rpc"] !== 'undefined')
9653 return false;
9654 return true;
9655 };
9656
9657 /**
9658 * Tests if a definition most likely describes a message field.
9659 * @param {!Object} def
9660 * @returns {boolean}
9661 * @expose
9662 */
9663 Builder.isMessageField = function(def) {
9664 // Message fields require a string rule, name and type and an id
9665 if (typeof def["rule"] !== 'string' || typeof def["name"] !== 'string' || typeof def["type"] !== 'string' || typeof def["id"] === 'undefined')
9666 return false;
9667 return true;
9668 };
9669
9670 /**
9671 * Tests if a definition most likely describes an enum.
9672 * @param {!Object} def
9673 * @returns {boolean}
9674 * @expose
9675 */
9676 Builder.isEnum = function(def) {
9677 // Enums require a string name
9678 if (typeof def["name"] !== 'string')
9679 return false;
9680 // Enums require at least one value
9681 if (typeof def["values"] === 'undefined' || !Array.isArray(def["values"]) || def["values"].length === 0)
9682 return false;
9683 return true;
9684 };
9685
9686 /**
9687 * Tests if a definition most likely describes a service.
9688 * @param {!Object} def
9689 * @returns {boolean}
9690 * @expose
9691 */
9692 Builder.isService = function(def) {
9693 // Services require a string name and an rpc object
9694 if (typeof def["name"] !== 'string' || typeof def["rpc"] !== 'object' || !def["rpc"])
9695 return false;
9696 return true;
9697 };
9698
9699 /**
9700 * Tests if a definition most likely describes an extended message
9701 * @param {!Object} def
9702 * @returns {boolean}
9703 * @expose
9704 */
9705 Builder.isExtend = function(def) {
9706 // Extends rquire a string ref
9707 if (typeof def["ref"] !== 'string')
9708 return false;
9709 return true;
9710 };
9711
9712 // ----- Building -----
9713
9714 /**
9715 * Resets the pointer to the root namespace.
9716 * @returns {!ProtoBuf.Builder} this
9717 * @expose
9718 */
9719 BuilderPrototype.reset = function() {
9720 this.ptr = this.ns;
9721 return this;
9722 };
9723
9724 /**
9725 * Defines a namespace on top of the current pointer position and places the pointer on it.
9726 * @param {string} namespace
9727 * @return {!ProtoBuf.Builder} this
9728 * @expose
9729 */
9730 BuilderPrototype.define = function(namespace) {
9731 if (typeof namespace !== 'string' || !Lang.TYPEREF.test(namespace))
9732 throw Error("illegal namespace: "+namespace);
9733 namespace.split(".").forEach(function(part) {
9734 var ns = this.ptr.getChild(part);
9735 if (ns === null) // Keep existing
9736 this.ptr.addChild(ns = new Reflect.Namespace(this, this.ptr, part));
9737 this.ptr = ns;
9738 }, this);
9739 return this;
9740 };
9741
9742 /**
9743 * Creates the specified definitions at the current pointer position.
9744 * @param {!Array.<!Object>} defs Messages, enums or services to create
9745 * @returns {!ProtoBuf.Builder} this
9746 * @throws {Error} If a message definition is invalid
9747 * @expose
9748 */
9749 BuilderPrototype.create = function(defs) {
9750 if (!defs)
9751 return this; // Nothing to create
9752 if (!Array.isArray(defs))
9753 defs = [defs];
9754 else {
9755 if (defs.length === 0)
9756 return this;
9757 defs = defs.slice();
9758 }
9759
9760 // It's quite hard to keep track of scopes and memory here, so let's do this iteratively.
9761 var stack = [defs];
9762 while (stack.length > 0) {
9763 defs = stack.pop();
9764
9765 if (!Array.isArray(defs)) // Stack always contains entire namespaces
9766 throw Error("not a valid namespace: "+JSON.stringify(defs));
9767
9768 while (defs.length > 0) {
9769 var def = defs.shift(); // Namespaces always contain an array of messages, enums and services
9770
9771 if (Builder.isMessage(def)) {
9772 var obj = new Reflect.Message(this, this.ptr, def["name"], def["options"], def["isGroup"], def["syntax"]);
9773
9774 // Create OneOfs
9775 var oneofs = {};
9776 if (def["oneofs"])
9777 Object.keys(def["oneofs"]).forEach(function(name) {
9778 obj.addChild(oneofs[name] = new Reflect.Message.OneOf(this, obj, name));
9779 }, this);
9780
9781 // Create fields
9782 if (def["fields"])
9783 def["fields"].forEach(function(fld) {
9784 if (obj.getChild(fld["id"]|0) !== null)
9785 throw Error("duplicate or invalid field id in "+obj.name+": "+fld['id']);
9786 if (fld["options"] && typeof fld["options"] !== 'object')
9787 throw Error("illegal field options in "+obj.name+"#"+fld["name"]);
9788 var oneof = null;
9789 if (typeof fld["oneof"] === 'string' && !(oneof = oneofs[fld["oneof"]]))
9790 throw Error("illegal oneof in "+obj.name+"#"+fld["name"]+": "+fld["oneof"]);
9791 fld = new Reflect.Message.Field(this, obj, fld["rule"], fld["keytype"], fld["type"], fld["name"], fld["id"], fld["options"], oneof, def["syntax"]);
9792 if (oneof)
9793 oneof.fields.push(fld);
9794 obj.addChild(fld);
9795 }, this);
9796
9797 // Push children to stack
9798 var subObj = [];
9799 if (def["enums"])
9800 def["enums"].forEach(function(enm) {
9801 subObj.push(enm);
9802 });
9803 if (def["messages"])
9804 def["messages"].forEach(function(msg) {
9805 subObj.push(msg);
9806 });
9807 if (def["services"])
9808 def["services"].forEach(function(svc) {
9809 subObj.push(svc);
9810 });
9811
9812 // Set extension ranges
9813 if (def["extensions"]) {
9814 if (typeof def["extensions"][0] === 'number') // pre 5.0.1
9815 obj.extensions = [ def["extensions"] ];
9816 else
9817 obj.extensions = def["extensions"];
9818 }
9819
9820 // Create on top of current namespace
9821 this.ptr.addChild(obj);
9822 if (subObj.length > 0) {
9823 stack.push(defs); // Push the current level back
9824 defs = subObj; // Continue processing sub level
9825 subObj = null;
9826 this.ptr = obj; // And move the pointer to this namespace
9827 obj = null;
9828 continue;
9829 }
9830 subObj = null;
9831
9832 } else if (Builder.isEnum(def)) {
9833
9834 obj = new Reflect.Enum(this, this.ptr, def["name"], def["options"], def["syntax"]);
9835 def["values"].forEach(function(val) {
9836 obj.addChild(new Reflect.Enum.Value(this, obj, val["name"], val["id"]));
9837 }, this);
9838 this.ptr.addChild(obj);
9839
9840 } else if (Builder.isService(def)) {
9841
9842 obj = new Reflect.Service(this, this.ptr, def["name"], def["options"]);
9843 Object.keys(def["rpc"]).forEach(function(name) {
9844 var mtd = def["rpc"][name];
9845 obj.addChild(new Reflect.Service.RPCMethod(this, obj, name, mtd["request"], mtd["response"], !!mtd["request_stream"], !!mtd["response_stream"], mtd["options"]));
9846 }, this);
9847 this.ptr.addChild(obj);
9848
9849 } else if (Builder.isExtend(def)) {
9850
9851 obj = this.ptr.resolve(def["ref"], true);
9852 if (obj) {
9853 def["fields"].forEach(function(fld) {
9854 if (obj.getChild(fld['id']|0) !== null)
9855 throw Error("duplicate extended field id in "+obj.name+": "+fld['id']);
9856 // Check if field id is allowed to be extended
9857 if (obj.extensions) {
9858 var valid = false;
9859 obj.extensions.forEach(function(range) {
9860 if (fld["id"] >= range[0] && fld["id"] <= range[1])
9861 valid = true;
9862 });
9863 if (!valid)
9864 throw Error("illegal extended field id in "+obj.name+": "+fld['id']+" (not within valid ranges)");
9865 }
9866 // Convert extension field names to camel case notation if the override is set
9867 var name = fld["name"];
9868 if (this.options['convertFieldsToCamelCase'])
9869 name = ProtoBuf.Util.toCamelCase(name);
9870 // see #161: Extensions use their fully qualified name as their runtime key and...
9871 var field = new Reflect.Message.ExtensionField(this, obj, fld["rule"], fld["type"], this.ptr.fqn()+'.'+name, fld["id"], fld["options"]);
9872 // ...are added on top of the current namespace as an extension which is used for
9873 // resolving their type later on (the extension always keeps the original name to
9874 // prevent naming collisions)
9875 var ext = new Reflect.Extension(this, this.ptr, fld["name"], field);
9876 field.extension = ext;
9877 this.ptr.addChild(ext);
9878 obj.addChild(field);
9879 }, this);
9880
9881 } else if (!/\.?google\.protobuf\./.test(def["ref"])) // Silently skip internal extensions
9882 throw Error("extended message "+def["ref"]+" is not defined");
9883
9884 } else
9885 throw Error("not a valid definition: "+JSON.stringify(def));
9886
9887 def = null;
9888 obj = null;
9889 }
9890 // Break goes here
9891 defs = null;
9892 this.ptr = this.ptr.parent; // Namespace done, continue at parent
9893 }
9894 this.resolved = false; // Require re-resolve
9895 this.result = null; // Require re-build
9896 return this;
9897 };
9898
9899 /**
9900 * Propagates syntax to all children.
9901 * @param {!Object} parent
9902 * @inner
9903 */
9904 function propagateSyntax(parent) {
9905 if (parent['messages']) {
9906 parent['messages'].forEach(function(child) {
9907 child["syntax"] = parent["syntax"];
9908 propagateSyntax(child);
9909 });
9910 }
9911 if (parent['enums']) {
9912 parent['enums'].forEach(function(child) {
9913 child["syntax"] = parent["syntax"];
9914 });
9915 }
9916 }
9917
9918 /**
9919 * Imports another definition into this builder.
9920 * @param {Object.<string,*>} json Parsed import
9921 * @param {(string|{root: string, file: string})=} filename Imported file name
9922 * @returns {!ProtoBuf.Builder} this
9923 * @throws {Error} If the definition or file cannot be imported
9924 * @expose
9925 */
9926 BuilderPrototype["import"] = function(json, filename) {
9927 var delim = '/';
9928
9929 // Make sure to skip duplicate imports
9930
9931 if (typeof filename === 'string') {
9932
9933 if (ProtoBuf.Util.IS_NODE)
9934 filename = require$$2['resolve'](filename);
9935 if (this.files[filename] === true)
9936 return this.reset();
9937 this.files[filename] = true;
9938
9939 } else if (typeof filename === 'object') { // Object with root, file.
9940
9941 var root = filename.root;
9942 if (ProtoBuf.Util.IS_NODE)
9943 root = require$$2['resolve'](root);
9944 if (root.indexOf("\\") >= 0 || filename.file.indexOf("\\") >= 0)
9945 delim = '\\';
9946 var fname;
9947 if (ProtoBuf.Util.IS_NODE)
9948 fname = require$$2['join'](root, filename.file);
9949 else
9950 fname = root + delim + filename.file;
9951 if (this.files[fname] === true)
9952 return this.reset();
9953 this.files[fname] = true;
9954 }
9955
9956 // Import imports
9957
9958 if (json['imports'] && json['imports'].length > 0) {
9959 var importRoot,
9960 resetRoot = false;
9961
9962 if (typeof filename === 'object') { // If an import root is specified, override
9963
9964 this.importRoot = filename["root"]; resetRoot = true; // ... and reset afterwards
9965 importRoot = this.importRoot;
9966 filename = filename["file"];
9967 if (importRoot.indexOf("\\") >= 0 || filename.indexOf("\\") >= 0)
9968 delim = '\\';
9969
9970 } else if (typeof filename === 'string') {
9971
9972 if (this.importRoot) // If import root is overridden, use it
9973 importRoot = this.importRoot;
9974 else { // Otherwise compute from filename
9975 if (filename.indexOf("/") >= 0) { // Unix
9976 importRoot = filename.replace(/\/[^\/]*$/, "");
9977 if (/* /file.proto */ importRoot === "")
9978 importRoot = "/";
9979 } else if (filename.indexOf("\\") >= 0) { // Windows
9980 importRoot = filename.replace(/\\[^\\]*$/, "");
9981 delim = '\\';
9982 } else
9983 importRoot = ".";
9984 }
9985
9986 } else
9987 importRoot = null;
9988
9989 for (var i=0; i<json['imports'].length; i++) {
9990 if (typeof json['imports'][i] === 'string') { // Import file
9991 if (!importRoot)
9992 throw Error("cannot determine import root");
9993 var importFilename = json['imports'][i];
9994 if (importFilename === "google/protobuf/descriptor.proto")
9995 continue; // Not needed and therefore not used
9996 if (ProtoBuf.Util.IS_NODE)
9997 importFilename = require$$2['join'](importRoot, importFilename);
9998 else
9999 importFilename = importRoot + delim + importFilename;
10000 if (this.files[importFilename] === true)
10001 continue; // Already imported
10002 if (/\.proto$/i.test(importFilename) && !ProtoBuf.DotProto) // If this is a light build
10003 importFilename = importFilename.replace(/\.proto$/, ".json"); // always load the JSON file
10004 var contents = ProtoBuf.Util.fetch(importFilename);
10005 if (contents === null)
10006 throw Error("failed to import '"+importFilename+"' in '"+filename+"': file not found");
10007 if (/\.json$/i.test(importFilename)) // Always possible
10008 this["import"](JSON.parse(contents+""), importFilename); // May throw
10009 else
10010 this["import"](ProtoBuf.DotProto.Parser.parse(contents), importFilename); // May throw
10011 } else // Import structure
10012 if (!filename)
10013 this["import"](json['imports'][i]);
10014 else if (/\.(\w+)$/.test(filename)) // With extension: Append _importN to the name portion to make it unique
10015 this["import"](json['imports'][i], filename.replace(/^(.+)\.(\w+)$/, function($0, $1, $2) { return $1+"_import"+i+"."+$2; }));
10016 else // Without extension: Append _importN to make it unique
10017 this["import"](json['imports'][i], filename+"_import"+i);
10018 }
10019 if (resetRoot) // Reset import root override when all imports are done
10020 this.importRoot = null;
10021 }
10022
10023 // Import structures
10024
10025 if (json['package'])
10026 this.define(json['package']);
10027 if (json['syntax'])
10028 propagateSyntax(json);
10029 var base = this.ptr;
10030 if (json['options'])
10031 Object.keys(json['options']).forEach(function(key) {
10032 base.options[key] = json['options'][key];
10033 });
10034 if (json['messages'])
10035 this.create(json['messages']),
10036 this.ptr = base;
10037 if (json['enums'])
10038 this.create(json['enums']),
10039 this.ptr = base;
10040 if (json['services'])
10041 this.create(json['services']),
10042 this.ptr = base;
10043 if (json['extends'])
10044 this.create(json['extends']);
10045
10046 return this.reset();
10047 };
10048
10049 /**
10050 * Resolves all namespace objects.
10051 * @throws {Error} If a type cannot be resolved
10052 * @returns {!ProtoBuf.Builder} this
10053 * @expose
10054 */
10055 BuilderPrototype.resolveAll = function() {
10056 // Resolve all reflected objects
10057 var res;
10058 if (this.ptr == null || typeof this.ptr.type === 'object')
10059 return this; // Done (already resolved)
10060
10061 if (this.ptr instanceof Reflect.Namespace) { // Resolve children
10062
10063 this.ptr.children.forEach(function(child) {
10064 this.ptr = child;
10065 this.resolveAll();
10066 }, this);
10067
10068 } else if (this.ptr instanceof Reflect.Message.Field) { // Resolve type
10069
10070 if (!Lang.TYPE.test(this.ptr.type)) {
10071 if (!Lang.TYPEREF.test(this.ptr.type))
10072 throw Error("illegal type reference in "+this.ptr.toString(true)+": "+this.ptr.type);
10073 res = (this.ptr instanceof Reflect.Message.ExtensionField ? this.ptr.extension.parent : this.ptr.parent).resolve(this.ptr.type, true);
10074 if (!res)
10075 throw Error("unresolvable type reference in "+this.ptr.toString(true)+": "+this.ptr.type);
10076 this.ptr.resolvedType = res;
10077 if (res instanceof Reflect.Enum) {
10078 this.ptr.type = ProtoBuf.TYPES["enum"];
10079 if (this.ptr.syntax === 'proto3' && res.syntax !== 'proto3')
10080 throw Error("proto3 message cannot reference proto2 enum");
10081 }
10082 else if (res instanceof Reflect.Message)
10083 this.ptr.type = res.isGroup ? ProtoBuf.TYPES["group"] : ProtoBuf.TYPES["message"];
10084 else
10085 throw Error("illegal type reference in "+this.ptr.toString(true)+": "+this.ptr.type);
10086 } else
10087 this.ptr.type = ProtoBuf.TYPES[this.ptr.type];
10088
10089 // If it's a map field, also resolve the key type. The key type can be only a numeric, string, or bool type
10090 // (i.e., no enums or messages), so we don't need to resolve against the current namespace.
10091 if (this.ptr.map) {
10092 if (!Lang.TYPE.test(this.ptr.keyType))
10093 throw Error("illegal key type for map field in "+this.ptr.toString(true)+": "+this.ptr.keyType);
10094 this.ptr.keyType = ProtoBuf.TYPES[this.ptr.keyType];
10095 }
10096
10097 // If it's a repeated and packable field then proto3 mandates it should be packed by
10098 // default
10099 if (
10100 this.ptr.syntax === 'proto3' &&
10101 this.ptr.repeated && this.ptr.options.packed === undefined &&
10102 ProtoBuf.PACKABLE_WIRE_TYPES.indexOf(this.ptr.type.wireType) !== -1
10103 ) {
10104 this.ptr.options.packed = true;
10105 }
10106
10107 } else if (this.ptr instanceof ProtoBuf.Reflect.Service.Method) {
10108
10109 if (this.ptr instanceof ProtoBuf.Reflect.Service.RPCMethod) {
10110 res = this.ptr.parent.resolve(this.ptr.requestName, true);
10111 if (!res || !(res instanceof ProtoBuf.Reflect.Message))
10112 throw Error("Illegal type reference in "+this.ptr.toString(true)+": "+this.ptr.requestName);
10113 this.ptr.resolvedRequestType = res;
10114 res = this.ptr.parent.resolve(this.ptr.responseName, true);
10115 if (!res || !(res instanceof ProtoBuf.Reflect.Message))
10116 throw Error("Illegal type reference in "+this.ptr.toString(true)+": "+this.ptr.responseName);
10117 this.ptr.resolvedResponseType = res;
10118 } else // Should not happen as nothing else is implemented
10119 throw Error("illegal service type in "+this.ptr.toString(true));
10120
10121 } else if (
10122 !(this.ptr instanceof ProtoBuf.Reflect.Message.OneOf) && // Not built
10123 !(this.ptr instanceof ProtoBuf.Reflect.Extension) && // Not built
10124 !(this.ptr instanceof ProtoBuf.Reflect.Enum.Value) // Built in enum
10125 )
10126 throw Error("illegal object in namespace: "+typeof(this.ptr)+": "+this.ptr);
10127
10128 return this.reset();
10129 };
10130
10131 /**
10132 * Builds the protocol. This will first try to resolve all definitions and, if this has been successful,
10133 * return the built package.
10134 * @param {(string|Array.<string>)=} path Specifies what to return. If omitted, the entire namespace will be returned.
10135 * @returns {!ProtoBuf.Builder.Message|!Object.<string,*>}
10136 * @throws {Error} If a type could not be resolved
10137 * @expose
10138 */
10139 BuilderPrototype.build = function(path) {
10140 this.reset();
10141 if (!this.resolved)
10142 this.resolveAll(),
10143 this.resolved = true,
10144 this.result = null; // Require re-build
10145 if (this.result === null) // (Re-)Build
10146 this.result = this.ns.build();
10147 if (!path)
10148 return this.result;
10149 var part = typeof path === 'string' ? path.split(".") : path,
10150 ptr = this.result; // Build namespace pointer (no hasChild etc.)
10151 for (var i=0; i<part.length; i++)
10152 if (ptr[part[i]])
10153 ptr = ptr[part[i]];
10154 else {
10155 ptr = null;
10156 break;
10157 }
10158 return ptr;
10159 };
10160
10161 /**
10162 * Similar to {@link ProtoBuf.Builder#build}, but looks up the internal reflection descriptor.
10163 * @param {string=} path Specifies what to return. If omitted, the entire namespace wiil be returned.
10164 * @param {boolean=} excludeNonNamespace Excludes non-namespace types like fields, defaults to `false`
10165 * @returns {?ProtoBuf.Reflect.T} Reflection descriptor or `null` if not found
10166 */
10167 BuilderPrototype.lookup = function(path, excludeNonNamespace) {
10168 return path ? this.ns.resolve(path, excludeNonNamespace) : this.ns;
10169 };
10170
10171 /**
10172 * Returns a string representation of this object.
10173 * @return {string} String representation as of "Builder"
10174 * @expose
10175 */
10176 BuilderPrototype.toString = function() {
10177 return "Builder";
10178 };
10179
10180 // ----- Base classes -----
10181 // Exist for the sole purpose of being able to "... instanceof ProtoBuf.Builder.Message" etc.
10182
10183 /**
10184 * @alias ProtoBuf.Builder.Message
10185 */
10186 Builder.Message = function() {};
10187
10188 /**
10189 * @alias ProtoBuf.Builder.Enum
10190 */
10191 Builder.Enum = function() {};
10192
10193 /**
10194 * @alias ProtoBuf.Builder.Message
10195 */
10196 Builder.Service = function() {};
10197
10198 return Builder;
10199
10200 })(ProtoBuf, ProtoBuf.Lang, ProtoBuf.Reflect);
10201
10202 /**
10203 * @alias ProtoBuf.Map
10204 * @expose
10205 */
10206 ProtoBuf.Map = (function(ProtoBuf, Reflect) {
10207
10208 /**
10209 * Constructs a new Map. A Map is a container that is used to implement map
10210 * fields on message objects. It closely follows the ES6 Map API; however,
10211 * it is distinct because we do not want to depend on external polyfills or
10212 * on ES6 itself.
10213 *
10214 * @exports ProtoBuf.Map
10215 * @param {!ProtoBuf.Reflect.Field} field Map field
10216 * @param {Object.<string,*>=} contents Initial contents
10217 * @constructor
10218 */
10219 var Map = function(field, contents) {
10220 if (!field.map)
10221 throw Error("field is not a map");
10222
10223 /**
10224 * The field corresponding to this map.
10225 * @type {!ProtoBuf.Reflect.Field}
10226 */
10227 this.field = field;
10228
10229 /**
10230 * Element instance corresponding to key type.
10231 * @type {!ProtoBuf.Reflect.Element}
10232 */
10233 this.keyElem = new Reflect.Element(field.keyType, null, true, field.syntax);
10234
10235 /**
10236 * Element instance corresponding to value type.
10237 * @type {!ProtoBuf.Reflect.Element}
10238 */
10239 this.valueElem = new Reflect.Element(field.type, field.resolvedType, false, field.syntax);
10240
10241 /**
10242 * Internal map: stores mapping of (string form of key) -> (key, value)
10243 * pair.
10244 *
10245 * We provide map semantics for arbitrary key types, but we build on top
10246 * of an Object, which has only string keys. In order to avoid the need
10247 * to convert a string key back to its native type in many situations,
10248 * we store the native key value alongside the value. Thus, we only need
10249 * a one-way mapping from a key type to its string form that guarantees
10250 * uniqueness and equality (i.e., str(K1) === str(K2) if and only if K1
10251 * === K2).
10252 *
10253 * @type {!Object<string, {key: *, value: *}>}
10254 */
10255 this.map = {};
10256
10257 /**
10258 * Returns the number of elements in the map.
10259 */
10260 Object.defineProperty(this, "size", {
10261 get: function() { return Object.keys(this.map).length; }
10262 });
10263
10264 // Fill initial contents from a raw object.
10265 if (contents) {
10266 var keys = Object.keys(contents);
10267 for (var i = 0; i < keys.length; i++) {
10268 var key = this.keyElem.valueFromString(keys[i]);
10269 var val = this.valueElem.verifyValue(contents[keys[i]]);
10270 this.map[this.keyElem.valueToString(key)] =
10271 { key: key, value: val };
10272 }
10273 }
10274 };
10275
10276 var MapPrototype = Map.prototype;
10277
10278 /**
10279 * Helper: return an iterator over an array.
10280 * @param {!Array<*>} arr the array
10281 * @returns {!Object} an iterator
10282 * @inner
10283 */
10284 function arrayIterator(arr) {
10285 var idx = 0;
10286 return {
10287 next: function() {
10288 if (idx < arr.length)
10289 return { done: false, value: arr[idx++] };
10290 return { done: true };
10291 }
10292 }
10293 }
10294
10295 /**
10296 * Clears the map.
10297 */
10298 MapPrototype.clear = function() {
10299 this.map = {};
10300 };
10301
10302 /**
10303 * Deletes a particular key from the map.
10304 * @returns {boolean} Whether any entry with this key was deleted.
10305 */
10306 MapPrototype["delete"] = function(key) {
10307 var keyValue = this.keyElem.valueToString(this.keyElem.verifyValue(key));
10308 var hadKey = keyValue in this.map;
10309 delete this.map[keyValue];
10310 return hadKey;
10311 };
10312
10313 /**
10314 * Returns an iterator over [key, value] pairs in the map.
10315 * @returns {Object} The iterator
10316 */
10317 MapPrototype.entries = function() {
10318 var entries = [];
10319 var strKeys = Object.keys(this.map);
10320 for (var i = 0, entry; i < strKeys.length; i++)
10321 entries.push([(entry=this.map[strKeys[i]]).key, entry.value]);
10322 return arrayIterator(entries);
10323 };
10324
10325 /**
10326 * Returns an iterator over keys in the map.
10327 * @returns {Object} The iterator
10328 */
10329 MapPrototype.keys = function() {
10330 var keys = [];
10331 var strKeys = Object.keys(this.map);
10332 for (var i = 0; i < strKeys.length; i++)
10333 keys.push(this.map[strKeys[i]].key);
10334 return arrayIterator(keys);
10335 };
10336
10337 /**
10338 * Returns an iterator over values in the map.
10339 * @returns {!Object} The iterator
10340 */
10341 MapPrototype.values = function() {
10342 var values = [];
10343 var strKeys = Object.keys(this.map);
10344 for (var i = 0; i < strKeys.length; i++)
10345 values.push(this.map[strKeys[i]].value);
10346 return arrayIterator(values);
10347 };
10348
10349 /**
10350 * Iterates over entries in the map, calling a function on each.
10351 * @param {function(this:*, *, *, *)} cb The callback to invoke with value, key, and map arguments.
10352 * @param {Object=} thisArg The `this` value for the callback
10353 */
10354 MapPrototype.forEach = function(cb, thisArg) {
10355 var strKeys = Object.keys(this.map);
10356 for (var i = 0, entry; i < strKeys.length; i++)
10357 cb.call(thisArg, (entry=this.map[strKeys[i]]).value, entry.key, this);
10358 };
10359
10360 /**
10361 * Sets a key in the map to the given value.
10362 * @param {*} key The key
10363 * @param {*} value The value
10364 * @returns {!ProtoBuf.Map} The map instance
10365 */
10366 MapPrototype.set = function(key, value) {
10367 var keyValue = this.keyElem.verifyValue(key);
10368 var valValue = this.valueElem.verifyValue(value);
10369 this.map[this.keyElem.valueToString(keyValue)] =
10370 { key: keyValue, value: valValue };
10371 return this;
10372 };
10373
10374 /**
10375 * Gets the value corresponding to a key in the map.
10376 * @param {*} key The key
10377 * @returns {*|undefined} The value, or `undefined` if key not present
10378 */
10379 MapPrototype.get = function(key) {
10380 var keyValue = this.keyElem.valueToString(this.keyElem.verifyValue(key));
10381 if (!(keyValue in this.map))
10382 return undefined;
10383 return this.map[keyValue].value;
10384 };
10385
10386 /**
10387 * Determines whether the given key is present in the map.
10388 * @param {*} key The key
10389 * @returns {boolean} `true` if the key is present
10390 */
10391 MapPrototype.has = function(key) {
10392 var keyValue = this.keyElem.valueToString(this.keyElem.verifyValue(key));
10393 return (keyValue in this.map);
10394 };
10395
10396 return Map;
10397 })(ProtoBuf, ProtoBuf.Reflect);
10398
10399
10400 /**
10401 * Constructs a new empty Builder.
10402 * @param {Object.<string,*>=} options Builder options, defaults to global options set on ProtoBuf
10403 * @return {!ProtoBuf.Builder} Builder
10404 * @expose
10405 */
10406 ProtoBuf.newBuilder = function(options) {
10407 options = options || {};
10408 if (typeof options['convertFieldsToCamelCase'] === 'undefined')
10409 options['convertFieldsToCamelCase'] = ProtoBuf.convertFieldsToCamelCase;
10410 if (typeof options['populateAccessors'] === 'undefined')
10411 options['populateAccessors'] = ProtoBuf.populateAccessors;
10412 return new ProtoBuf.Builder(options);
10413 };
10414
10415 /**
10416 * Loads a .json definition and returns the Builder.
10417 * @param {!*|string} json JSON definition
10418 * @param {(ProtoBuf.Builder|string|{root: string, file: string})=} builder Builder to append to. Will create a new one if omitted.
10419 * @param {(string|{root: string, file: string})=} filename The corresponding file name if known. Must be specified for imports.
10420 * @return {ProtoBuf.Builder} Builder to create new messages
10421 * @throws {Error} If the definition cannot be parsed or built
10422 * @expose
10423 */
10424 ProtoBuf.loadJson = function(json, builder, filename) {
10425 if (typeof builder === 'string' || (builder && typeof builder["file"] === 'string' && typeof builder["root"] === 'string'))
10426 filename = builder,
10427 builder = null;
10428 if (!builder || typeof builder !== 'object')
10429 builder = ProtoBuf.newBuilder();
10430 if (typeof json === 'string')
10431 json = JSON.parse(json);
10432 builder["import"](json, filename);
10433 builder.resolveAll();
10434 return builder;
10435 };
10436
10437 /**
10438 * Loads a .json file and returns the Builder.
10439 * @param {string|!{root: string, file: string}} filename Path to json file or an object specifying 'file' with
10440 * an overridden 'root' path for all imported files.
10441 * @param {function(?Error, !ProtoBuf.Builder=)=} callback Callback that will receive `null` as the first and
10442 * the Builder as its second argument on success, otherwise the error as its first argument. If omitted, the
10443 * file will be read synchronously and this function will return the Builder.
10444 * @param {ProtoBuf.Builder=} builder Builder to append to. Will create a new one if omitted.
10445 * @return {?ProtoBuf.Builder|undefined} The Builder if synchronous (no callback specified, will be NULL if the
10446 * request has failed), else undefined
10447 * @expose
10448 */
10449 ProtoBuf.loadJsonFile = function(filename, callback, builder) {
10450 if (callback && typeof callback === 'object')
10451 builder = callback,
10452 callback = null;
10453 else if (!callback || typeof callback !== 'function')
10454 callback = null;
10455 if (callback)
10456 return ProtoBuf.Util.fetch(typeof filename === 'string' ? filename : filename["root"]+"/"+filename["file"], function(contents) {
10457 if (contents === null) {
10458 callback(Error("Failed to fetch file"));
10459 return;
10460 }
10461 try {
10462 callback(null, ProtoBuf.loadJson(JSON.parse(contents), builder, filename));
10463 } catch (e) {
10464 callback(e);
10465 }
10466 });
10467 var contents = ProtoBuf.Util.fetch(typeof filename === 'object' ? filename["root"]+"/"+filename["file"] : filename);
10468 return contents === null ? null : ProtoBuf.loadJson(JSON.parse(contents), builder, filename);
10469 };
10470
10471 return ProtoBuf;
10472 });
10473 });
10474
10475 var messageCompiled = protobufLight.newBuilder({})['import']({
10476 "package": 'push_server.messages2',
10477 syntax: 'proto2',
10478 options: {
10479 objc_class_prefix: 'AVIM'
10480 },
10481 messages: [{
10482 name: 'JsonObjectMessage',
10483 syntax: 'proto2',
10484 fields: [{
10485 rule: 'required',
10486 type: 'string',
10487 name: 'data',
10488 id: 1
10489 }]
10490 }, {
10491 name: 'UnreadTuple',
10492 syntax: 'proto2',
10493 fields: [{
10494 rule: 'required',
10495 type: 'string',
10496 name: 'cid',
10497 id: 1
10498 }, {
10499 rule: 'required',
10500 type: 'int32',
10501 name: 'unread',
10502 id: 2
10503 }, {
10504 rule: 'optional',
10505 type: 'string',
10506 name: 'mid',
10507 id: 3
10508 }, {
10509 rule: 'optional',
10510 type: 'int64',
10511 name: 'timestamp',
10512 id: 4
10513 }, {
10514 rule: 'optional',
10515 type: 'string',
10516 name: 'from',
10517 id: 5
10518 }, {
10519 rule: 'optional',
10520 type: 'string',
10521 name: 'data',
10522 id: 6
10523 }, {
10524 rule: 'optional',
10525 type: 'int64',
10526 name: 'patchTimestamp',
10527 id: 7
10528 }, {
10529 rule: 'optional',
10530 type: 'bool',
10531 name: 'mentioned',
10532 id: 8
10533 }, {
10534 rule: 'optional',
10535 type: 'bytes',
10536 name: 'binaryMsg',
10537 id: 9
10538 }, {
10539 rule: 'optional',
10540 type: 'int32',
10541 name: 'convType',
10542 id: 10
10543 }]
10544 }, {
10545 name: 'LogItem',
10546 syntax: 'proto2',
10547 fields: [{
10548 rule: 'optional',
10549 type: 'string',
10550 name: 'from',
10551 id: 1
10552 }, {
10553 rule: 'optional',
10554 type: 'string',
10555 name: 'data',
10556 id: 2
10557 }, {
10558 rule: 'optional',
10559 type: 'int64',
10560 name: 'timestamp',
10561 id: 3
10562 }, {
10563 rule: 'optional',
10564 type: 'string',
10565 name: 'msgId',
10566 id: 4
10567 }, {
10568 rule: 'optional',
10569 type: 'int64',
10570 name: 'ackAt',
10571 id: 5
10572 }, {
10573 rule: 'optional',
10574 type: 'int64',
10575 name: 'readAt',
10576 id: 6
10577 }, {
10578 rule: 'optional',
10579 type: 'int64',
10580 name: 'patchTimestamp',
10581 id: 7
10582 }, {
10583 rule: 'optional',
10584 type: 'bool',
10585 name: 'mentionAll',
10586 id: 8
10587 }, {
10588 rule: 'repeated',
10589 type: 'string',
10590 name: 'mentionPids',
10591 id: 9
10592 }, {
10593 rule: 'optional',
10594 type: 'bool',
10595 name: 'bin',
10596 id: 10
10597 }, {
10598 rule: 'optional',
10599 type: 'int32',
10600 name: 'convType',
10601 id: 11
10602 }]
10603 }, {
10604 name: 'ConvMemberInfo',
10605 syntax: 'proto2',
10606 fields: [{
10607 rule: 'optional',
10608 type: 'string',
10609 name: 'pid',
10610 id: 1
10611 }, {
10612 rule: 'optional',
10613 type: 'string',
10614 name: 'role',
10615 id: 2
10616 }, {
10617 rule: 'optional',
10618 type: 'string',
10619 name: 'infoId',
10620 id: 3
10621 }]
10622 }, {
10623 name: 'DataCommand',
10624 syntax: 'proto2',
10625 fields: [{
10626 rule: 'repeated',
10627 type: 'string',
10628 name: 'ids',
10629 id: 1
10630 }, {
10631 rule: 'repeated',
10632 type: 'JsonObjectMessage',
10633 name: 'msg',
10634 id: 2
10635 }, {
10636 rule: 'optional',
10637 type: 'bool',
10638 name: 'offline',
10639 id: 3
10640 }]
10641 }, {
10642 name: 'SessionCommand',
10643 syntax: 'proto2',
10644 fields: [{
10645 rule: 'optional',
10646 type: 'int64',
10647 name: 't',
10648 id: 1
10649 }, {
10650 rule: 'optional',
10651 type: 'string',
10652 name: 'n',
10653 id: 2
10654 }, {
10655 rule: 'optional',
10656 type: 'string',
10657 name: 's',
10658 id: 3
10659 }, {
10660 rule: 'optional',
10661 type: 'string',
10662 name: 'ua',
10663 id: 4
10664 }, {
10665 rule: 'optional',
10666 type: 'bool',
10667 name: 'r',
10668 id: 5
10669 }, {
10670 rule: 'optional',
10671 type: 'string',
10672 name: 'tag',
10673 id: 6
10674 }, {
10675 rule: 'optional',
10676 type: 'string',
10677 name: 'deviceId',
10678 id: 7
10679 }, {
10680 rule: 'repeated',
10681 type: 'string',
10682 name: 'sessionPeerIds',
10683 id: 8
10684 }, {
10685 rule: 'repeated',
10686 type: 'string',
10687 name: 'onlineSessionPeerIds',
10688 id: 9
10689 }, {
10690 rule: 'optional',
10691 type: 'string',
10692 name: 'st',
10693 id: 10
10694 }, {
10695 rule: 'optional',
10696 type: 'int32',
10697 name: 'stTtl',
10698 id: 11
10699 }, {
10700 rule: 'optional',
10701 type: 'int32',
10702 name: 'code',
10703 id: 12
10704 }, {
10705 rule: 'optional',
10706 type: 'string',
10707 name: 'reason',
10708 id: 13
10709 }, {
10710 rule: 'optional',
10711 type: 'string',
10712 name: 'deviceToken',
10713 id: 14
10714 }, {
10715 rule: 'optional',
10716 type: 'bool',
10717 name: 'sp',
10718 id: 15
10719 }, {
10720 rule: 'optional',
10721 type: 'string',
10722 name: 'detail',
10723 id: 16
10724 }, {
10725 rule: 'optional',
10726 type: 'int64',
10727 name: 'lastUnreadNotifTime',
10728 id: 17
10729 }, {
10730 rule: 'optional',
10731 type: 'int64',
10732 name: 'lastPatchTime',
10733 id: 18
10734 }, {
10735 rule: 'optional',
10736 type: 'int64',
10737 name: 'configBitmap',
10738 id: 19
10739 }]
10740 }, {
10741 name: 'ErrorCommand',
10742 syntax: 'proto2',
10743 fields: [{
10744 rule: 'required',
10745 type: 'int32',
10746 name: 'code',
10747 id: 1
10748 }, {
10749 rule: 'required',
10750 type: 'string',
10751 name: 'reason',
10752 id: 2
10753 }, {
10754 rule: 'optional',
10755 type: 'int32',
10756 name: 'appCode',
10757 id: 3
10758 }, {
10759 rule: 'optional',
10760 type: 'string',
10761 name: 'detail',
10762 id: 4
10763 }, {
10764 rule: 'repeated',
10765 type: 'string',
10766 name: 'pids',
10767 id: 5
10768 }, {
10769 rule: 'optional',
10770 type: 'string',
10771 name: 'appMsg',
10772 id: 6
10773 }]
10774 }, {
10775 name: 'DirectCommand',
10776 syntax: 'proto2',
10777 fields: [{
10778 rule: 'optional',
10779 type: 'string',
10780 name: 'msg',
10781 id: 1
10782 }, {
10783 rule: 'optional',
10784 type: 'string',
10785 name: 'uid',
10786 id: 2
10787 }, {
10788 rule: 'optional',
10789 type: 'string',
10790 name: 'fromPeerId',
10791 id: 3
10792 }, {
10793 rule: 'optional',
10794 type: 'int64',
10795 name: 'timestamp',
10796 id: 4
10797 }, {
10798 rule: 'optional',
10799 type: 'bool',
10800 name: 'offline',
10801 id: 5
10802 }, {
10803 rule: 'optional',
10804 type: 'bool',
10805 name: 'hasMore',
10806 id: 6
10807 }, {
10808 rule: 'repeated',
10809 type: 'string',
10810 name: 'toPeerIds',
10811 id: 7
10812 }, {
10813 rule: 'optional',
10814 type: 'bool',
10815 name: 'r',
10816 id: 10
10817 }, {
10818 rule: 'optional',
10819 type: 'string',
10820 name: 'cid',
10821 id: 11
10822 }, {
10823 rule: 'optional',
10824 type: 'string',
10825 name: 'id',
10826 id: 12
10827 }, {
10828 rule: 'optional',
10829 type: 'bool',
10830 name: 'transient',
10831 id: 13
10832 }, {
10833 rule: 'optional',
10834 type: 'string',
10835 name: 'dt',
10836 id: 14
10837 }, {
10838 rule: 'optional',
10839 type: 'string',
10840 name: 'roomId',
10841 id: 15
10842 }, {
10843 rule: 'optional',
10844 type: 'string',
10845 name: 'pushData',
10846 id: 16
10847 }, {
10848 rule: 'optional',
10849 type: 'bool',
10850 name: 'will',
10851 id: 17
10852 }, {
10853 rule: 'optional',
10854 type: 'int64',
10855 name: 'patchTimestamp',
10856 id: 18
10857 }, {
10858 rule: 'optional',
10859 type: 'bytes',
10860 name: 'binaryMsg',
10861 id: 19
10862 }, {
10863 rule: 'repeated',
10864 type: 'string',
10865 name: 'mentionPids',
10866 id: 20
10867 }, {
10868 rule: 'optional',
10869 type: 'bool',
10870 name: 'mentionAll',
10871 id: 21
10872 }, {
10873 rule: 'optional',
10874 type: 'int32',
10875 name: 'convType',
10876 id: 22
10877 }]
10878 }, {
10879 name: 'AckCommand',
10880 syntax: 'proto2',
10881 fields: [{
10882 rule: 'optional',
10883 type: 'int32',
10884 name: 'code',
10885 id: 1
10886 }, {
10887 rule: 'optional',
10888 type: 'string',
10889 name: 'reason',
10890 id: 2
10891 }, {
10892 rule: 'optional',
10893 type: 'string',
10894 name: 'mid',
10895 id: 3
10896 }, {
10897 rule: 'optional',
10898 type: 'string',
10899 name: 'cid',
10900 id: 4
10901 }, {
10902 rule: 'optional',
10903 type: 'int64',
10904 name: 't',
10905 id: 5
10906 }, {
10907 rule: 'optional',
10908 type: 'string',
10909 name: 'uid',
10910 id: 6
10911 }, {
10912 rule: 'optional',
10913 type: 'int64',
10914 name: 'fromts',
10915 id: 7
10916 }, {
10917 rule: 'optional',
10918 type: 'int64',
10919 name: 'tots',
10920 id: 8
10921 }, {
10922 rule: 'optional',
10923 type: 'string',
10924 name: 'type',
10925 id: 9
10926 }, {
10927 rule: 'repeated',
10928 type: 'string',
10929 name: 'ids',
10930 id: 10
10931 }, {
10932 rule: 'optional',
10933 type: 'int32',
10934 name: 'appCode',
10935 id: 11
10936 }, {
10937 rule: 'optional',
10938 type: 'string',
10939 name: 'appMsg',
10940 id: 12
10941 }]
10942 }, {
10943 name: 'UnreadCommand',
10944 syntax: 'proto2',
10945 fields: [{
10946 rule: 'repeated',
10947 type: 'UnreadTuple',
10948 name: 'convs',
10949 id: 1
10950 }, {
10951 rule: 'optional',
10952 type: 'int64',
10953 name: 'notifTime',
10954 id: 2
10955 }]
10956 }, {
10957 name: 'ConvCommand',
10958 syntax: 'proto2',
10959 fields: [{
10960 rule: 'repeated',
10961 type: 'string',
10962 name: 'm',
10963 id: 1
10964 }, {
10965 rule: 'optional',
10966 type: 'bool',
10967 name: 'transient',
10968 id: 2
10969 }, {
10970 rule: 'optional',
10971 type: 'bool',
10972 name: 'unique',
10973 id: 3
10974 }, {
10975 rule: 'optional',
10976 type: 'string',
10977 name: 'cid',
10978 id: 4
10979 }, {
10980 rule: 'optional',
10981 type: 'string',
10982 name: 'cdate',
10983 id: 5
10984 }, {
10985 rule: 'optional',
10986 type: 'string',
10987 name: 'initBy',
10988 id: 6
10989 }, {
10990 rule: 'optional',
10991 type: 'string',
10992 name: 'sort',
10993 id: 7
10994 }, {
10995 rule: 'optional',
10996 type: 'int32',
10997 name: 'limit',
10998 id: 8
10999 }, {
11000 rule: 'optional',
11001 type: 'int32',
11002 name: 'skip',
11003 id: 9
11004 }, {
11005 rule: 'optional',
11006 type: 'int32',
11007 name: 'flag',
11008 id: 10
11009 }, {
11010 rule: 'optional',
11011 type: 'int32',
11012 name: 'count',
11013 id: 11
11014 }, {
11015 rule: 'optional',
11016 type: 'string',
11017 name: 'udate',
11018 id: 12
11019 }, {
11020 rule: 'optional',
11021 type: 'int64',
11022 name: 't',
11023 id: 13
11024 }, {
11025 rule: 'optional',
11026 type: 'string',
11027 name: 'n',
11028 id: 14
11029 }, {
11030 rule: 'optional',
11031 type: 'string',
11032 name: 's',
11033 id: 15
11034 }, {
11035 rule: 'optional',
11036 type: 'bool',
11037 name: 'statusSub',
11038 id: 16
11039 }, {
11040 rule: 'optional',
11041 type: 'bool',
11042 name: 'statusPub',
11043 id: 17
11044 }, {
11045 rule: 'optional',
11046 type: 'int32',
11047 name: 'statusTTL',
11048 id: 18
11049 }, {
11050 rule: 'optional',
11051 type: 'string',
11052 name: 'uniqueId',
11053 id: 19
11054 }, {
11055 rule: 'optional',
11056 type: 'string',
11057 name: 'targetClientId',
11058 id: 20
11059 }, {
11060 rule: 'optional',
11061 type: 'int64',
11062 name: 'maxReadTimestamp',
11063 id: 21
11064 }, {
11065 rule: 'optional',
11066 type: 'int64',
11067 name: 'maxAckTimestamp',
11068 id: 22
11069 }, {
11070 rule: 'optional',
11071 type: 'bool',
11072 name: 'queryAllMembers',
11073 id: 23
11074 }, {
11075 rule: 'repeated',
11076 type: 'MaxReadTuple',
11077 name: 'maxReadTuples',
11078 id: 24
11079 }, {
11080 rule: 'repeated',
11081 type: 'string',
11082 name: 'cids',
11083 id: 25
11084 }, {
11085 rule: 'optional',
11086 type: 'ConvMemberInfo',
11087 name: 'info',
11088 id: 26
11089 }, {
11090 rule: 'optional',
11091 type: 'bool',
11092 name: 'tempConv',
11093 id: 27
11094 }, {
11095 rule: 'optional',
11096 type: 'int32',
11097 name: 'tempConvTTL',
11098 id: 28
11099 }, {
11100 rule: 'repeated',
11101 type: 'string',
11102 name: 'tempConvIds',
11103 id: 29
11104 }, {
11105 rule: 'repeated',
11106 type: 'string',
11107 name: 'allowedPids',
11108 id: 30
11109 }, {
11110 rule: 'repeated',
11111 type: 'ErrorCommand',
11112 name: 'failedPids',
11113 id: 31
11114 }, {
11115 rule: 'optional',
11116 type: 'string',
11117 name: 'next',
11118 id: 40
11119 }, {
11120 rule: 'optional',
11121 type: 'JsonObjectMessage',
11122 name: 'results',
11123 id: 100
11124 }, {
11125 rule: 'optional',
11126 type: 'JsonObjectMessage',
11127 name: 'where',
11128 id: 101
11129 }, {
11130 rule: 'optional',
11131 type: 'JsonObjectMessage',
11132 name: 'attr',
11133 id: 103
11134 }, {
11135 rule: 'optional',
11136 type: 'JsonObjectMessage',
11137 name: 'attrModified',
11138 id: 104
11139 }]
11140 }, {
11141 name: 'RoomCommand',
11142 syntax: 'proto2',
11143 fields: [{
11144 rule: 'optional',
11145 type: 'string',
11146 name: 'roomId',
11147 id: 1
11148 }, {
11149 rule: 'optional',
11150 type: 'string',
11151 name: 's',
11152 id: 2
11153 }, {
11154 rule: 'optional',
11155 type: 'int64',
11156 name: 't',
11157 id: 3
11158 }, {
11159 rule: 'optional',
11160 type: 'string',
11161 name: 'n',
11162 id: 4
11163 }, {
11164 rule: 'optional',
11165 type: 'bool',
11166 name: 'transient',
11167 id: 5
11168 }, {
11169 rule: 'repeated',
11170 type: 'string',
11171 name: 'roomPeerIds',
11172 id: 6
11173 }, {
11174 rule: 'optional',
11175 type: 'string',
11176 name: 'byPeerId',
11177 id: 7
11178 }]
11179 }, {
11180 name: 'LogsCommand',
11181 syntax: 'proto2',
11182 fields: [{
11183 rule: 'optional',
11184 type: 'string',
11185 name: 'cid',
11186 id: 1
11187 }, {
11188 rule: 'optional',
11189 type: 'int32',
11190 name: 'l',
11191 id: 2
11192 }, {
11193 rule: 'optional',
11194 type: 'int32',
11195 name: 'limit',
11196 id: 3
11197 }, {
11198 rule: 'optional',
11199 type: 'int64',
11200 name: 't',
11201 id: 4
11202 }, {
11203 rule: 'optional',
11204 type: 'int64',
11205 name: 'tt',
11206 id: 5
11207 }, {
11208 rule: 'optional',
11209 type: 'string',
11210 name: 'tmid',
11211 id: 6
11212 }, {
11213 rule: 'optional',
11214 type: 'string',
11215 name: 'mid',
11216 id: 7
11217 }, {
11218 rule: 'optional',
11219 type: 'string',
11220 name: 'checksum',
11221 id: 8
11222 }, {
11223 rule: 'optional',
11224 type: 'bool',
11225 name: 'stored',
11226 id: 9
11227 }, {
11228 rule: 'optional',
11229 type: 'QueryDirection',
11230 name: 'direction',
11231 id: 10,
11232 options: {
11233 "default": 'OLD'
11234 }
11235 }, {
11236 rule: 'optional',
11237 type: 'bool',
11238 name: 'tIncluded',
11239 id: 11
11240 }, {
11241 rule: 'optional',
11242 type: 'bool',
11243 name: 'ttIncluded',
11244 id: 12
11245 }, {
11246 rule: 'optional',
11247 type: 'int32',
11248 name: 'lctype',
11249 id: 13
11250 }, {
11251 rule: 'repeated',
11252 type: 'LogItem',
11253 name: 'logs',
11254 id: 105
11255 }],
11256 enums: [{
11257 name: 'QueryDirection',
11258 syntax: 'proto2',
11259 values: [{
11260 name: 'OLD',
11261 id: 1
11262 }, {
11263 name: 'NEW',
11264 id: 2
11265 }]
11266 }]
11267 }, {
11268 name: 'RcpCommand',
11269 syntax: 'proto2',
11270 fields: [{
11271 rule: 'optional',
11272 type: 'string',
11273 name: 'id',
11274 id: 1
11275 }, {
11276 rule: 'optional',
11277 type: 'string',
11278 name: 'cid',
11279 id: 2
11280 }, {
11281 rule: 'optional',
11282 type: 'int64',
11283 name: 't',
11284 id: 3
11285 }, {
11286 rule: 'optional',
11287 type: 'bool',
11288 name: 'read',
11289 id: 4
11290 }, {
11291 rule: 'optional',
11292 type: 'string',
11293 name: 'from',
11294 id: 5
11295 }]
11296 }, {
11297 name: 'ReadTuple',
11298 syntax: 'proto2',
11299 fields: [{
11300 rule: 'required',
11301 type: 'string',
11302 name: 'cid',
11303 id: 1
11304 }, {
11305 rule: 'optional',
11306 type: 'int64',
11307 name: 'timestamp',
11308 id: 2
11309 }, {
11310 rule: 'optional',
11311 type: 'string',
11312 name: 'mid',
11313 id: 3
11314 }]
11315 }, {
11316 name: 'MaxReadTuple',
11317 syntax: 'proto2',
11318 fields: [{
11319 rule: 'optional',
11320 type: 'string',
11321 name: 'pid',
11322 id: 1
11323 }, {
11324 rule: 'optional',
11325 type: 'int64',
11326 name: 'maxAckTimestamp',
11327 id: 2
11328 }, {
11329 rule: 'optional',
11330 type: 'int64',
11331 name: 'maxReadTimestamp',
11332 id: 3
11333 }]
11334 }, {
11335 name: 'ReadCommand',
11336 syntax: 'proto2',
11337 fields: [{
11338 rule: 'optional',
11339 type: 'string',
11340 name: 'cid',
11341 id: 1
11342 }, {
11343 rule: 'repeated',
11344 type: 'string',
11345 name: 'cids',
11346 id: 2
11347 }, {
11348 rule: 'repeated',
11349 type: 'ReadTuple',
11350 name: 'convs',
11351 id: 3
11352 }]
11353 }, {
11354 name: 'PresenceCommand',
11355 syntax: 'proto2',
11356 fields: [{
11357 rule: 'optional',
11358 type: 'StatusType',
11359 name: 'status',
11360 id: 1
11361 }, {
11362 rule: 'repeated',
11363 type: 'string',
11364 name: 'sessionPeerIds',
11365 id: 2
11366 }, {
11367 rule: 'optional',
11368 type: 'string',
11369 name: 'cid',
11370 id: 3
11371 }]
11372 }, {
11373 name: 'ReportCommand',
11374 syntax: 'proto2',
11375 fields: [{
11376 rule: 'optional',
11377 type: 'bool',
11378 name: 'initiative',
11379 id: 1
11380 }, {
11381 rule: 'optional',
11382 type: 'string',
11383 name: 'type',
11384 id: 2
11385 }, {
11386 rule: 'optional',
11387 type: 'string',
11388 name: 'data',
11389 id: 3
11390 }]
11391 }, {
11392 name: 'PatchItem',
11393 syntax: 'proto2',
11394 fields: [{
11395 rule: 'optional',
11396 type: 'string',
11397 name: 'cid',
11398 id: 1
11399 }, {
11400 rule: 'optional',
11401 type: 'string',
11402 name: 'mid',
11403 id: 2
11404 }, {
11405 rule: 'optional',
11406 type: 'int64',
11407 name: 'timestamp',
11408 id: 3
11409 }, {
11410 rule: 'optional',
11411 type: 'bool',
11412 name: 'recall',
11413 id: 4
11414 }, {
11415 rule: 'optional',
11416 type: 'string',
11417 name: 'data',
11418 id: 5
11419 }, {
11420 rule: 'optional',
11421 type: 'int64',
11422 name: 'patchTimestamp',
11423 id: 6
11424 }, {
11425 rule: 'optional',
11426 type: 'string',
11427 name: 'from',
11428 id: 7
11429 }, {
11430 rule: 'optional',
11431 type: 'bytes',
11432 name: 'binaryMsg',
11433 id: 8
11434 }, {
11435 rule: 'optional',
11436 type: 'bool',
11437 name: 'mentionAll',
11438 id: 9
11439 }, {
11440 rule: 'repeated',
11441 type: 'string',
11442 name: 'mentionPids',
11443 id: 10
11444 }, {
11445 rule: 'optional',
11446 type: 'int64',
11447 name: 'patchCode',
11448 id: 11
11449 }, {
11450 rule: 'optional',
11451 type: 'string',
11452 name: 'patchReason',
11453 id: 12
11454 }]
11455 }, {
11456 name: 'PatchCommand',
11457 syntax: 'proto2',
11458 fields: [{
11459 rule: 'repeated',
11460 type: 'PatchItem',
11461 name: 'patches',
11462 id: 1
11463 }, {
11464 rule: 'optional',
11465 type: 'int64',
11466 name: 'lastPatchTime',
11467 id: 2
11468 }]
11469 }, {
11470 name: 'PubsubCommand',
11471 syntax: 'proto2',
11472 fields: [{
11473 rule: 'optional',
11474 type: 'string',
11475 name: 'cid',
11476 id: 1
11477 }, {
11478 rule: 'repeated',
11479 type: 'string',
11480 name: 'cids',
11481 id: 2
11482 }, {
11483 rule: 'optional',
11484 type: 'string',
11485 name: 'topic',
11486 id: 3
11487 }, {
11488 rule: 'optional',
11489 type: 'string',
11490 name: 'subtopic',
11491 id: 4
11492 }, {
11493 rule: 'repeated',
11494 type: 'string',
11495 name: 'topics',
11496 id: 5
11497 }, {
11498 rule: 'repeated',
11499 type: 'string',
11500 name: 'subtopics',
11501 id: 6
11502 }, {
11503 rule: 'optional',
11504 type: 'JsonObjectMessage',
11505 name: 'results',
11506 id: 7
11507 }]
11508 }, {
11509 name: 'BlacklistCommand',
11510 syntax: 'proto2',
11511 fields: [{
11512 rule: 'optional',
11513 type: 'string',
11514 name: 'srcCid',
11515 id: 1
11516 }, {
11517 rule: 'repeated',
11518 type: 'string',
11519 name: 'toPids',
11520 id: 2
11521 }, {
11522 rule: 'optional',
11523 type: 'string',
11524 name: 'srcPid',
11525 id: 3
11526 }, {
11527 rule: 'repeated',
11528 type: 'string',
11529 name: 'toCids',
11530 id: 4
11531 }, {
11532 rule: 'optional',
11533 type: 'int32',
11534 name: 'limit',
11535 id: 5
11536 }, {
11537 rule: 'optional',
11538 type: 'string',
11539 name: 'next',
11540 id: 6
11541 }, {
11542 rule: 'repeated',
11543 type: 'string',
11544 name: 'blockedPids',
11545 id: 8
11546 }, {
11547 rule: 'repeated',
11548 type: 'string',
11549 name: 'blockedCids',
11550 id: 9
11551 }, {
11552 rule: 'repeated',
11553 type: 'string',
11554 name: 'allowedPids',
11555 id: 10
11556 }, {
11557 rule: 'repeated',
11558 type: 'ErrorCommand',
11559 name: 'failedPids',
11560 id: 11
11561 }, {
11562 rule: 'optional',
11563 type: 'int64',
11564 name: 't',
11565 id: 12
11566 }, {
11567 rule: 'optional',
11568 type: 'string',
11569 name: 'n',
11570 id: 13
11571 }, {
11572 rule: 'optional',
11573 type: 'string',
11574 name: 's',
11575 id: 14
11576 }]
11577 }, {
11578 name: 'GenericCommand',
11579 syntax: 'proto2',
11580 fields: [{
11581 rule: 'optional',
11582 type: 'CommandType',
11583 name: 'cmd',
11584 id: 1
11585 }, {
11586 rule: 'optional',
11587 type: 'OpType',
11588 name: 'op',
11589 id: 2
11590 }, {
11591 rule: 'optional',
11592 type: 'string',
11593 name: 'appId',
11594 id: 3
11595 }, {
11596 rule: 'optional',
11597 type: 'string',
11598 name: 'peerId',
11599 id: 4
11600 }, {
11601 rule: 'optional',
11602 type: 'int32',
11603 name: 'i',
11604 id: 5
11605 }, {
11606 rule: 'optional',
11607 type: 'string',
11608 name: 'installationId',
11609 id: 6
11610 }, {
11611 rule: 'optional',
11612 type: 'int32',
11613 name: 'priority',
11614 id: 7
11615 }, {
11616 rule: 'optional',
11617 type: 'int32',
11618 name: 'service',
11619 id: 8
11620 }, {
11621 rule: 'optional',
11622 type: 'int64',
11623 name: 'serverTs',
11624 id: 9
11625 }, {
11626 rule: 'optional',
11627 type: 'int64',
11628 name: 'clientTs',
11629 id: 10
11630 }, {
11631 rule: 'optional',
11632 type: 'int32',
11633 name: 'notificationType',
11634 id: 11
11635 }, {
11636 rule: 'optional',
11637 type: 'DataCommand',
11638 name: 'dataMessage',
11639 id: 101
11640 }, {
11641 rule: 'optional',
11642 type: 'SessionCommand',
11643 name: 'sessionMessage',
11644 id: 102
11645 }, {
11646 rule: 'optional',
11647 type: 'ErrorCommand',
11648 name: 'errorMessage',
11649 id: 103
11650 }, {
11651 rule: 'optional',
11652 type: 'DirectCommand',
11653 name: 'directMessage',
11654 id: 104
11655 }, {
11656 rule: 'optional',
11657 type: 'AckCommand',
11658 name: 'ackMessage',
11659 id: 105
11660 }, {
11661 rule: 'optional',
11662 type: 'UnreadCommand',
11663 name: 'unreadMessage',
11664 id: 106
11665 }, {
11666 rule: 'optional',
11667 type: 'ReadCommand',
11668 name: 'readMessage',
11669 id: 107
11670 }, {
11671 rule: 'optional',
11672 type: 'RcpCommand',
11673 name: 'rcpMessage',
11674 id: 108
11675 }, {
11676 rule: 'optional',
11677 type: 'LogsCommand',
11678 name: 'logsMessage',
11679 id: 109
11680 }, {
11681 rule: 'optional',
11682 type: 'ConvCommand',
11683 name: 'convMessage',
11684 id: 110
11685 }, {
11686 rule: 'optional',
11687 type: 'RoomCommand',
11688 name: 'roomMessage',
11689 id: 111
11690 }, {
11691 rule: 'optional',
11692 type: 'PresenceCommand',
11693 name: 'presenceMessage',
11694 id: 112
11695 }, {
11696 rule: 'optional',
11697 type: 'ReportCommand',
11698 name: 'reportMessage',
11699 id: 113
11700 }, {
11701 rule: 'optional',
11702 type: 'PatchCommand',
11703 name: 'patchMessage',
11704 id: 114
11705 }, {
11706 rule: 'optional',
11707 type: 'PubsubCommand',
11708 name: 'pubsubMessage',
11709 id: 115
11710 }, {
11711 rule: 'optional',
11712 type: 'BlacklistCommand',
11713 name: 'blacklistMessage',
11714 id: 116
11715 }]
11716 }],
11717 enums: [{
11718 name: 'CommandType',
11719 syntax: 'proto2',
11720 values: [{
11721 name: 'session',
11722 id: 0
11723 }, {
11724 name: 'conv',
11725 id: 1
11726 }, {
11727 name: 'direct',
11728 id: 2
11729 }, {
11730 name: 'ack',
11731 id: 3
11732 }, {
11733 name: 'rcp',
11734 id: 4
11735 }, {
11736 name: 'unread',
11737 id: 5
11738 }, {
11739 name: 'logs',
11740 id: 6
11741 }, {
11742 name: 'error',
11743 id: 7
11744 }, {
11745 name: 'login',
11746 id: 8
11747 }, {
11748 name: 'data',
11749 id: 9
11750 }, {
11751 name: 'room',
11752 id: 10
11753 }, {
11754 name: 'read',
11755 id: 11
11756 }, {
11757 name: 'presence',
11758 id: 12
11759 }, {
11760 name: 'report',
11761 id: 13
11762 }, {
11763 name: 'echo',
11764 id: 14
11765 }, {
11766 name: 'loggedin',
11767 id: 15
11768 }, {
11769 name: 'logout',
11770 id: 16
11771 }, {
11772 name: 'loggedout',
11773 id: 17
11774 }, {
11775 name: 'patch',
11776 id: 18
11777 }, {
11778 name: 'pubsub',
11779 id: 19
11780 }, {
11781 name: 'blacklist',
11782 id: 20
11783 }, {
11784 name: 'goaway',
11785 id: 21
11786 }]
11787 }, {
11788 name: 'OpType',
11789 syntax: 'proto2',
11790 values: [{
11791 name: 'open',
11792 id: 1
11793 }, {
11794 name: 'add',
11795 id: 2
11796 }, {
11797 name: 'remove',
11798 id: 3
11799 }, {
11800 name: 'close',
11801 id: 4
11802 }, {
11803 name: 'opened',
11804 id: 5
11805 }, {
11806 name: 'closed',
11807 id: 6
11808 }, {
11809 name: 'query',
11810 id: 7
11811 }, {
11812 name: 'query_result',
11813 id: 8
11814 }, {
11815 name: 'conflict',
11816 id: 9
11817 }, {
11818 name: 'added',
11819 id: 10
11820 }, {
11821 name: 'removed',
11822 id: 11
11823 }, {
11824 name: 'refresh',
11825 id: 12
11826 }, {
11827 name: 'refreshed',
11828 id: 13
11829 }, {
11830 name: 'start',
11831 id: 30
11832 }, {
11833 name: 'started',
11834 id: 31
11835 }, {
11836 name: 'joined',
11837 id: 32
11838 }, {
11839 name: 'members_joined',
11840 id: 33
11841 }, {
11842 name: 'left',
11843 id: 39
11844 }, {
11845 name: 'members_left',
11846 id: 40
11847 }, {
11848 name: 'results',
11849 id: 42
11850 }, {
11851 name: 'count',
11852 id: 43
11853 }, {
11854 name: 'result',
11855 id: 44
11856 }, {
11857 name: 'update',
11858 id: 45
11859 }, {
11860 name: 'updated',
11861 id: 46
11862 }, {
11863 name: 'mute',
11864 id: 47
11865 }, {
11866 name: 'unmute',
11867 id: 48
11868 }, {
11869 name: 'status',
11870 id: 49
11871 }, {
11872 name: 'members',
11873 id: 50
11874 }, {
11875 name: 'max_read',
11876 id: 51
11877 }, {
11878 name: 'is_member',
11879 id: 52
11880 }, {
11881 name: 'member_info_update',
11882 id: 53
11883 }, {
11884 name: 'member_info_updated',
11885 id: 54
11886 }, {
11887 name: 'member_info_changed',
11888 id: 55
11889 }, {
11890 name: 'join',
11891 id: 80
11892 }, {
11893 name: 'invite',
11894 id: 81
11895 }, {
11896 name: 'leave',
11897 id: 82
11898 }, {
11899 name: 'kick',
11900 id: 83
11901 }, {
11902 name: 'reject',
11903 id: 84
11904 }, {
11905 name: 'invited',
11906 id: 85
11907 }, {
11908 name: 'kicked',
11909 id: 86
11910 }, {
11911 name: 'upload',
11912 id: 100
11913 }, {
11914 name: 'uploaded',
11915 id: 101
11916 }, {
11917 name: 'subscribe',
11918 id: 120
11919 }, {
11920 name: 'subscribed',
11921 id: 121
11922 }, {
11923 name: 'unsubscribe',
11924 id: 122
11925 }, {
11926 name: 'unsubscribed',
11927 id: 123
11928 }, {
11929 name: 'is_subscribed',
11930 id: 124
11931 }, {
11932 name: 'modify',
11933 id: 150
11934 }, {
11935 name: 'modified',
11936 id: 151
11937 }, {
11938 name: 'block',
11939 id: 170
11940 }, {
11941 name: 'unblock',
11942 id: 171
11943 }, {
11944 name: 'blocked',
11945 id: 172
11946 }, {
11947 name: 'unblocked',
11948 id: 173
11949 }, {
11950 name: 'members_blocked',
11951 id: 174
11952 }, {
11953 name: 'members_unblocked',
11954 id: 175
11955 }, {
11956 name: 'check_block',
11957 id: 176
11958 }, {
11959 name: 'check_result',
11960 id: 177
11961 }, {
11962 name: 'add_shutup',
11963 id: 180
11964 }, {
11965 name: 'remove_shutup',
11966 id: 181
11967 }, {
11968 name: 'query_shutup',
11969 id: 182
11970 }, {
11971 name: 'shutup_added',
11972 id: 183
11973 }, {
11974 name: 'shutup_removed',
11975 id: 184
11976 }, {
11977 name: 'shutup_result',
11978 id: 185
11979 }, {
11980 name: 'shutuped',
11981 id: 186
11982 }, {
11983 name: 'unshutuped',
11984 id: 187
11985 }, {
11986 name: 'members_shutuped',
11987 id: 188
11988 }, {
11989 name: 'members_unshutuped',
11990 id: 189
11991 }, {
11992 name: 'check_shutup',
11993 id: 190
11994 }]
11995 }, {
11996 name: 'StatusType',
11997 syntax: 'proto2',
11998 values: [{
11999 name: 'on',
12000 id: 1
12001 }, {
12002 name: 'off',
12003 id: 2
12004 }]
12005 }],
12006 isNamespace: true
12007 }).build();
12008
12009 var _messages$push_server = messageCompiled.push_server.messages2,
12010 JsonObjectMessage = _messages$push_server.JsonObjectMessage,
12011 UnreadTuple = _messages$push_server.UnreadTuple,
12012 LogItem = _messages$push_server.LogItem,
12013 DataCommand = _messages$push_server.DataCommand,
12014 SessionCommand = _messages$push_server.SessionCommand,
12015 ErrorCommand = _messages$push_server.ErrorCommand,
12016 DirectCommand = _messages$push_server.DirectCommand,
12017 AckCommand = _messages$push_server.AckCommand,
12018 UnreadCommand = _messages$push_server.UnreadCommand,
12019 ConvCommand = _messages$push_server.ConvCommand,
12020 RoomCommand = _messages$push_server.RoomCommand,
12021 LogsCommand = _messages$push_server.LogsCommand,
12022 RcpCommand = _messages$push_server.RcpCommand,
12023 ReadTuple = _messages$push_server.ReadTuple,
12024 MaxReadTuple = _messages$push_server.MaxReadTuple,
12025 ReadCommand = _messages$push_server.ReadCommand,
12026 PresenceCommand = _messages$push_server.PresenceCommand,
12027 ReportCommand = _messages$push_server.ReportCommand,
12028 GenericCommand = _messages$push_server.GenericCommand,
12029 BlacklistCommand = _messages$push_server.BlacklistCommand,
12030 PatchCommand = _messages$push_server.PatchCommand,
12031 PatchItem = _messages$push_server.PatchItem,
12032 ConvMemberInfo = _messages$push_server.ConvMemberInfo,
12033 CommandType = _messages$push_server.CommandType,
12034 OpType = _messages$push_server.OpType,
12035 StatusType = _messages$push_server.StatusType;
12036
12037 var message = /*#__PURE__*/Object.freeze({
12038 __proto__: null,
12039 JsonObjectMessage: JsonObjectMessage,
12040 UnreadTuple: UnreadTuple,
12041 LogItem: LogItem,
12042 DataCommand: DataCommand,
12043 SessionCommand: SessionCommand,
12044 ErrorCommand: ErrorCommand,
12045 DirectCommand: DirectCommand,
12046 AckCommand: AckCommand,
12047 UnreadCommand: UnreadCommand,
12048 ConvCommand: ConvCommand,
12049 RoomCommand: RoomCommand,
12050 LogsCommand: LogsCommand,
12051 RcpCommand: RcpCommand,
12052 ReadTuple: ReadTuple,
12053 MaxReadTuple: MaxReadTuple,
12054 ReadCommand: ReadCommand,
12055 PresenceCommand: PresenceCommand,
12056 ReportCommand: ReportCommand,
12057 GenericCommand: GenericCommand,
12058 BlacklistCommand: BlacklistCommand,
12059 PatchCommand: PatchCommand,
12060 PatchItem: PatchItem,
12061 ConvMemberInfo: ConvMemberInfo,
12062 CommandType: CommandType,
12063 OpType: OpType,
12064 StatusType: StatusType
12065 });
12066
12067 var eventemitter3 = createCommonjsModule(function (module) {
12068
12069 var has = Object.prototype.hasOwnProperty
12070 , prefix = '~';
12071
12072 /**
12073 * Constructor to create a storage for our `EE` objects.
12074 * An `Events` instance is a plain object whose properties are event names.
12075 *
12076 * @constructor
12077 * @private
12078 */
12079 function Events() {}
12080
12081 //
12082 // We try to not inherit from `Object.prototype`. In some engines creating an
12083 // instance in this way is faster than calling `Object.create(null)` directly.
12084 // If `Object.create(null)` is not supported we prefix the event names with a
12085 // character to make sure that the built-in object properties are not
12086 // overridden or used as an attack vector.
12087 //
12088 if (Object.create) {
12089 Events.prototype = Object.create(null);
12090
12091 //
12092 // This hack is needed because the `__proto__` property is still inherited in
12093 // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.
12094 //
12095 if (!new Events().__proto__) prefix = false;
12096 }
12097
12098 /**
12099 * Representation of a single event listener.
12100 *
12101 * @param {Function} fn The listener function.
12102 * @param {*} context The context to invoke the listener with.
12103 * @param {Boolean} [once=false] Specify if the listener is a one-time listener.
12104 * @constructor
12105 * @private
12106 */
12107 function EE(fn, context, once) {
12108 this.fn = fn;
12109 this.context = context;
12110 this.once = once || false;
12111 }
12112
12113 /**
12114 * Add a listener for a given event.
12115 *
12116 * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
12117 * @param {(String|Symbol)} event The event name.
12118 * @param {Function} fn The listener function.
12119 * @param {*} context The context to invoke the listener with.
12120 * @param {Boolean} once Specify if the listener is a one-time listener.
12121 * @returns {EventEmitter}
12122 * @private
12123 */
12124 function addListener(emitter, event, fn, context, once) {
12125 if (typeof fn !== 'function') {
12126 throw new TypeError('The listener must be a function');
12127 }
12128
12129 var listener = new EE(fn, context || emitter, once)
12130 , evt = prefix ? prefix + event : event;
12131
12132 if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;
12133 else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);
12134 else emitter._events[evt] = [emitter._events[evt], listener];
12135
12136 return emitter;
12137 }
12138
12139 /**
12140 * Clear event by name.
12141 *
12142 * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
12143 * @param {(String|Symbol)} evt The Event name.
12144 * @private
12145 */
12146 function clearEvent(emitter, evt) {
12147 if (--emitter._eventsCount === 0) emitter._events = new Events();
12148 else delete emitter._events[evt];
12149 }
12150
12151 /**
12152 * Minimal `EventEmitter` interface that is molded against the Node.js
12153 * `EventEmitter` interface.
12154 *
12155 * @constructor
12156 * @public
12157 */
12158 function EventEmitter() {
12159 this._events = new Events();
12160 this._eventsCount = 0;
12161 }
12162
12163 /**
12164 * Return an array listing the events for which the emitter has registered
12165 * listeners.
12166 *
12167 * @returns {Array}
12168 * @public
12169 */
12170 EventEmitter.prototype.eventNames = function eventNames() {
12171 var names = []
12172 , events
12173 , name;
12174
12175 if (this._eventsCount === 0) return names;
12176
12177 for (name in (events = this._events)) {
12178 if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);
12179 }
12180
12181 if (Object.getOwnPropertySymbols) {
12182 return names.concat(Object.getOwnPropertySymbols(events));
12183 }
12184
12185 return names;
12186 };
12187
12188 /**
12189 * Return the listeners registered for a given event.
12190 *
12191 * @param {(String|Symbol)} event The event name.
12192 * @returns {Array} The registered listeners.
12193 * @public
12194 */
12195 EventEmitter.prototype.listeners = function listeners(event) {
12196 var evt = prefix ? prefix + event : event
12197 , handlers = this._events[evt];
12198
12199 if (!handlers) return [];
12200 if (handlers.fn) return [handlers.fn];
12201
12202 for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {
12203 ee[i] = handlers[i].fn;
12204 }
12205
12206 return ee;
12207 };
12208
12209 /**
12210 * Return the number of listeners listening to a given event.
12211 *
12212 * @param {(String|Symbol)} event The event name.
12213 * @returns {Number} The number of listeners.
12214 * @public
12215 */
12216 EventEmitter.prototype.listenerCount = function listenerCount(event) {
12217 var evt = prefix ? prefix + event : event
12218 , listeners = this._events[evt];
12219
12220 if (!listeners) return 0;
12221 if (listeners.fn) return 1;
12222 return listeners.length;
12223 };
12224
12225 /**
12226 * Calls each of the listeners registered for a given event.
12227 *
12228 * @param {(String|Symbol)} event The event name.
12229 * @returns {Boolean} `true` if the event had listeners, else `false`.
12230 * @public
12231 */
12232 EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {
12233 var evt = prefix ? prefix + event : event;
12234
12235 if (!this._events[evt]) return false;
12236
12237 var listeners = this._events[evt]
12238 , len = arguments.length
12239 , args
12240 , i;
12241
12242 if (listeners.fn) {
12243 if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);
12244
12245 switch (len) {
12246 case 1: return listeners.fn.call(listeners.context), true;
12247 case 2: return listeners.fn.call(listeners.context, a1), true;
12248 case 3: return listeners.fn.call(listeners.context, a1, a2), true;
12249 case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;
12250 case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;
12251 case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;
12252 }
12253
12254 for (i = 1, args = new Array(len -1); i < len; i++) {
12255 args[i - 1] = arguments[i];
12256 }
12257
12258 listeners.fn.apply(listeners.context, args);
12259 } else {
12260 var length = listeners.length
12261 , j;
12262
12263 for (i = 0; i < length; i++) {
12264 if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);
12265
12266 switch (len) {
12267 case 1: listeners[i].fn.call(listeners[i].context); break;
12268 case 2: listeners[i].fn.call(listeners[i].context, a1); break;
12269 case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;
12270 case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;
12271 default:
12272 if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {
12273 args[j - 1] = arguments[j];
12274 }
12275
12276 listeners[i].fn.apply(listeners[i].context, args);
12277 }
12278 }
12279 }
12280
12281 return true;
12282 };
12283
12284 /**
12285 * Add a listener for a given event.
12286 *
12287 * @param {(String|Symbol)} event The event name.
12288 * @param {Function} fn The listener function.
12289 * @param {*} [context=this] The context to invoke the listener with.
12290 * @returns {EventEmitter} `this`.
12291 * @public
12292 */
12293 EventEmitter.prototype.on = function on(event, fn, context) {
12294 return addListener(this, event, fn, context, false);
12295 };
12296
12297 /**
12298 * Add a one-time listener for a given event.
12299 *
12300 * @param {(String|Symbol)} event The event name.
12301 * @param {Function} fn The listener function.
12302 * @param {*} [context=this] The context to invoke the listener with.
12303 * @returns {EventEmitter} `this`.
12304 * @public
12305 */
12306 EventEmitter.prototype.once = function once(event, fn, context) {
12307 return addListener(this, event, fn, context, true);
12308 };
12309
12310 /**
12311 * Remove the listeners of a given event.
12312 *
12313 * @param {(String|Symbol)} event The event name.
12314 * @param {Function} fn Only remove the listeners that match this function.
12315 * @param {*} context Only remove the listeners that have this context.
12316 * @param {Boolean} once Only remove one-time listeners.
12317 * @returns {EventEmitter} `this`.
12318 * @public
12319 */
12320 EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {
12321 var evt = prefix ? prefix + event : event;
12322
12323 if (!this._events[evt]) return this;
12324 if (!fn) {
12325 clearEvent(this, evt);
12326 return this;
12327 }
12328
12329 var listeners = this._events[evt];
12330
12331 if (listeners.fn) {
12332 if (
12333 listeners.fn === fn &&
12334 (!once || listeners.once) &&
12335 (!context || listeners.context === context)
12336 ) {
12337 clearEvent(this, evt);
12338 }
12339 } else {
12340 for (var i = 0, events = [], length = listeners.length; i < length; i++) {
12341 if (
12342 listeners[i].fn !== fn ||
12343 (once && !listeners[i].once) ||
12344 (context && listeners[i].context !== context)
12345 ) {
12346 events.push(listeners[i]);
12347 }
12348 }
12349
12350 //
12351 // Reset the array, or remove it completely if we have no more listeners.
12352 //
12353 if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;
12354 else clearEvent(this, evt);
12355 }
12356
12357 return this;
12358 };
12359
12360 /**
12361 * Remove all listeners, or those of the specified event.
12362 *
12363 * @param {(String|Symbol)} [event] The event name.
12364 * @returns {EventEmitter} `this`.
12365 * @public
12366 */
12367 EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {
12368 var evt;
12369
12370 if (event) {
12371 evt = prefix ? prefix + event : event;
12372 if (this._events[evt]) clearEvent(this, evt);
12373 } else {
12374 this._events = new Events();
12375 this._eventsCount = 0;
12376 }
12377
12378 return this;
12379 };
12380
12381 //
12382 // Alias methods names because people roll like that.
12383 //
12384 EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
12385 EventEmitter.prototype.addListener = EventEmitter.prototype.on;
12386
12387 //
12388 // Expose the prefix.
12389 //
12390 EventEmitter.prefixed = prefix;
12391
12392 //
12393 // Allow `EventEmitter` to be imported as module namespace.
12394 //
12395 EventEmitter.EventEmitter = EventEmitter;
12396
12397 //
12398 // Expose the module.
12399 //
12400 {
12401 module.exports = EventEmitter;
12402 }
12403 });
12404
12405 var asyncToGenerator = createCommonjsModule(function (module) {
12406 function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
12407 try {
12408 var info = gen[key](arg);
12409 var value = info.value;
12410 } catch (error) {
12411 reject(error);
12412 return;
12413 }
12414 if (info.done) {
12415 resolve(value);
12416 } else {
12417 Promise.resolve(value).then(_next, _throw);
12418 }
12419 }
12420 function _asyncToGenerator(fn) {
12421 return function () {
12422 var self = this,
12423 args = arguments;
12424 return new Promise(function (resolve, reject) {
12425 var gen = fn.apply(self, args);
12426 function _next(value) {
12427 asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
12428 }
12429 function _throw(err) {
12430 asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
12431 }
12432 _next(undefined);
12433 });
12434 };
12435 }
12436 module.exports = _asyncToGenerator, module.exports.__esModule = true, module.exports["default"] = module.exports;
12437 });
12438
12439 var _asyncToGenerator = unwrapExports(asyncToGenerator);
12440
12441 var arrayLikeToArray = createCommonjsModule(function (module) {
12442 function _arrayLikeToArray(arr, len) {
12443 if (len == null || len > arr.length) len = arr.length;
12444 for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
12445 return arr2;
12446 }
12447 module.exports = _arrayLikeToArray, module.exports.__esModule = true, module.exports["default"] = module.exports;
12448 });
12449
12450 unwrapExports(arrayLikeToArray);
12451
12452 var arrayWithoutHoles = createCommonjsModule(function (module) {
12453 function _arrayWithoutHoles(arr) {
12454 if (Array.isArray(arr)) return arrayLikeToArray(arr);
12455 }
12456 module.exports = _arrayWithoutHoles, module.exports.__esModule = true, module.exports["default"] = module.exports;
12457 });
12458
12459 unwrapExports(arrayWithoutHoles);
12460
12461 var iterableToArray = createCommonjsModule(function (module) {
12462 function _iterableToArray(iter) {
12463 if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
12464 }
12465 module.exports = _iterableToArray, module.exports.__esModule = true, module.exports["default"] = module.exports;
12466 });
12467
12468 unwrapExports(iterableToArray);
12469
12470 var unsupportedIterableToArray = createCommonjsModule(function (module) {
12471 function _unsupportedIterableToArray(o, minLen) {
12472 if (!o) return;
12473 if (typeof o === "string") return arrayLikeToArray(o, minLen);
12474 var n = Object.prototype.toString.call(o).slice(8, -1);
12475 if (n === "Object" && o.constructor) n = o.constructor.name;
12476 if (n === "Map" || n === "Set") return Array.from(o);
12477 if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return arrayLikeToArray(o, minLen);
12478 }
12479 module.exports = _unsupportedIterableToArray, module.exports.__esModule = true, module.exports["default"] = module.exports;
12480 });
12481
12482 unwrapExports(unsupportedIterableToArray);
12483
12484 var nonIterableSpread = createCommonjsModule(function (module) {
12485 function _nonIterableSpread() {
12486 throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
12487 }
12488 module.exports = _nonIterableSpread, module.exports.__esModule = true, module.exports["default"] = module.exports;
12489 });
12490
12491 unwrapExports(nonIterableSpread);
12492
12493 var toConsumableArray = createCommonjsModule(function (module) {
12494 function _toConsumableArray(arr) {
12495 return arrayWithoutHoles(arr) || iterableToArray(arr) || unsupportedIterableToArray(arr) || nonIterableSpread();
12496 }
12497 module.exports = _toConsumableArray, module.exports.__esModule = true, module.exports["default"] = module.exports;
12498 });
12499
12500 var _toConsumableArray = unwrapExports(toConsumableArray);
12501
12502 var objectWithoutPropertiesLoose = createCommonjsModule(function (module) {
12503 function _objectWithoutPropertiesLoose(source, excluded) {
12504 if (source == null) return {};
12505 var target = {};
12506 var sourceKeys = Object.keys(source);
12507 var key, i;
12508 for (i = 0; i < sourceKeys.length; i++) {
12509 key = sourceKeys[i];
12510 if (excluded.indexOf(key) >= 0) continue;
12511 target[key] = source[key];
12512 }
12513 return target;
12514 }
12515 module.exports = _objectWithoutPropertiesLoose, module.exports.__esModule = true, module.exports["default"] = module.exports;
12516 });
12517
12518 unwrapExports(objectWithoutPropertiesLoose);
12519
12520 var objectWithoutProperties = createCommonjsModule(function (module) {
12521 function _objectWithoutProperties(source, excluded) {
12522 if (source == null) return {};
12523 var target = objectWithoutPropertiesLoose(source, excluded);
12524 var key, i;
12525 if (Object.getOwnPropertySymbols) {
12526 var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
12527 for (i = 0; i < sourceSymbolKeys.length; i++) {
12528 key = sourceSymbolKeys[i];
12529 if (excluded.indexOf(key) >= 0) continue;
12530 if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
12531 target[key] = source[key];
12532 }
12533 }
12534 return target;
12535 }
12536 module.exports = _objectWithoutProperties, module.exports.__esModule = true, module.exports["default"] = module.exports;
12537 });
12538
12539 var _objectWithoutProperties = unwrapExports(objectWithoutProperties);
12540
12541 var assertThisInitialized = createCommonjsModule(function (module) {
12542 function _assertThisInitialized(self) {
12543 if (self === void 0) {
12544 throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
12545 }
12546 return self;
12547 }
12548 module.exports = _assertThisInitialized, module.exports.__esModule = true, module.exports["default"] = module.exports;
12549 });
12550
12551 var _assertThisInitialized = unwrapExports(assertThisInitialized);
12552
12553 var setPrototypeOf = createCommonjsModule(function (module) {
12554 function _setPrototypeOf(o, p) {
12555 module.exports = _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
12556 o.__proto__ = p;
12557 return o;
12558 }, module.exports.__esModule = true, module.exports["default"] = module.exports;
12559 return _setPrototypeOf(o, p);
12560 }
12561 module.exports = _setPrototypeOf, module.exports.__esModule = true, module.exports["default"] = module.exports;
12562 });
12563
12564 unwrapExports(setPrototypeOf);
12565
12566 var inheritsLoose = createCommonjsModule(function (module) {
12567 function _inheritsLoose(subClass, superClass) {
12568 subClass.prototype = Object.create(superClass.prototype);
12569 subClass.prototype.constructor = subClass;
12570 setPrototypeOf(subClass, superClass);
12571 }
12572 module.exports = _inheritsLoose, module.exports.__esModule = true, module.exports["default"] = module.exports;
12573 });
12574
12575 var _inheritsLoose = unwrapExports(inheritsLoose);
12576
12577 var regeneratorRuntime$1 = createCommonjsModule(function (module) {
12578 var _typeof = _typeof_1["default"];
12579 function _regeneratorRuntime() {
12580 module.exports = _regeneratorRuntime = function _regeneratorRuntime() {
12581 return exports;
12582 }, module.exports.__esModule = true, module.exports["default"] = module.exports;
12583 var exports = {},
12584 Op = Object.prototype,
12585 hasOwn = Op.hasOwnProperty,
12586 defineProperty = Object.defineProperty || function (obj, key, desc) {
12587 obj[key] = desc.value;
12588 },
12589 $Symbol = "function" == typeof Symbol ? Symbol : {},
12590 iteratorSymbol = $Symbol.iterator || "@@iterator",
12591 asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator",
12592 toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";
12593 function define(obj, key, value) {
12594 return Object.defineProperty(obj, key, {
12595 value: value,
12596 enumerable: !0,
12597 configurable: !0,
12598 writable: !0
12599 }), obj[key];
12600 }
12601 try {
12602 define({}, "");
12603 } catch (err) {
12604 define = function define(obj, key, value) {
12605 return obj[key] = value;
12606 };
12607 }
12608 function wrap(innerFn, outerFn, self, tryLocsList) {
12609 var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator,
12610 generator = Object.create(protoGenerator.prototype),
12611 context = new Context(tryLocsList || []);
12612 return defineProperty(generator, "_invoke", {
12613 value: makeInvokeMethod(innerFn, self, context)
12614 }), generator;
12615 }
12616 function tryCatch(fn, obj, arg) {
12617 try {
12618 return {
12619 type: "normal",
12620 arg: fn.call(obj, arg)
12621 };
12622 } catch (err) {
12623 return {
12624 type: "throw",
12625 arg: err
12626 };
12627 }
12628 }
12629 exports.wrap = wrap;
12630 var ContinueSentinel = {};
12631 function Generator() {}
12632 function GeneratorFunction() {}
12633 function GeneratorFunctionPrototype() {}
12634 var IteratorPrototype = {};
12635 define(IteratorPrototype, iteratorSymbol, function () {
12636 return this;
12637 });
12638 var getProto = Object.getPrototypeOf,
12639 NativeIteratorPrototype = getProto && getProto(getProto(values([])));
12640 NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype);
12641 var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype);
12642 function defineIteratorMethods(prototype) {
12643 ["next", "throw", "return"].forEach(function (method) {
12644 define(prototype, method, function (arg) {
12645 return this._invoke(method, arg);
12646 });
12647 });
12648 }
12649 function AsyncIterator(generator, PromiseImpl) {
12650 function invoke(method, arg, resolve, reject) {
12651 var record = tryCatch(generator[method], generator, arg);
12652 if ("throw" !== record.type) {
12653 var result = record.arg,
12654 value = result.value;
12655 return value && "object" == _typeof(value) && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function (value) {
12656 invoke("next", value, resolve, reject);
12657 }, function (err) {
12658 invoke("throw", err, resolve, reject);
12659 }) : PromiseImpl.resolve(value).then(function (unwrapped) {
12660 result.value = unwrapped, resolve(result);
12661 }, function (error) {
12662 return invoke("throw", error, resolve, reject);
12663 });
12664 }
12665 reject(record.arg);
12666 }
12667 var previousPromise;
12668 defineProperty(this, "_invoke", {
12669 value: function value(method, arg) {
12670 function callInvokeWithMethodAndArg() {
12671 return new PromiseImpl(function (resolve, reject) {
12672 invoke(method, arg, resolve, reject);
12673 });
12674 }
12675 return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg();
12676 }
12677 });
12678 }
12679 function makeInvokeMethod(innerFn, self, context) {
12680 var state = "suspendedStart";
12681 return function (method, arg) {
12682 if ("executing" === state) throw new Error("Generator is already running");
12683 if ("completed" === state) {
12684 if ("throw" === method) throw arg;
12685 return doneResult();
12686 }
12687 for (context.method = method, context.arg = arg;;) {
12688 var delegate = context.delegate;
12689 if (delegate) {
12690 var delegateResult = maybeInvokeDelegate(delegate, context);
12691 if (delegateResult) {
12692 if (delegateResult === ContinueSentinel) continue;
12693 return delegateResult;
12694 }
12695 }
12696 if ("next" === context.method) context.sent = context._sent = context.arg;else if ("throw" === context.method) {
12697 if ("suspendedStart" === state) throw state = "completed", context.arg;
12698 context.dispatchException(context.arg);
12699 } else "return" === context.method && context.abrupt("return", context.arg);
12700 state = "executing";
12701 var record = tryCatch(innerFn, self, context);
12702 if ("normal" === record.type) {
12703 if (state = context.done ? "completed" : "suspendedYield", record.arg === ContinueSentinel) continue;
12704 return {
12705 value: record.arg,
12706 done: context.done
12707 };
12708 }
12709 "throw" === record.type && (state = "completed", context.method = "throw", context.arg = record.arg);
12710 }
12711 };
12712 }
12713 function maybeInvokeDelegate(delegate, context) {
12714 var methodName = context.method,
12715 method = delegate.iterator[methodName];
12716 if (undefined === method) return context.delegate = null, "throw" === methodName && delegate.iterator["return"] && (context.method = "return", context.arg = undefined, maybeInvokeDelegate(delegate, context), "throw" === context.method) || "return" !== methodName && (context.method = "throw", context.arg = new TypeError("The iterator does not provide a '" + methodName + "' method")), ContinueSentinel;
12717 var record = tryCatch(method, delegate.iterator, context.arg);
12718 if ("throw" === record.type) return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel;
12719 var info = record.arg;
12720 return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, "return" !== context.method && (context.method = "next", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = "throw", context.arg = new TypeError("iterator result is not an object"), context.delegate = null, ContinueSentinel);
12721 }
12722 function pushTryEntry(locs) {
12723 var entry = {
12724 tryLoc: locs[0]
12725 };
12726 1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry);
12727 }
12728 function resetTryEntry(entry) {
12729 var record = entry.completion || {};
12730 record.type = "normal", delete record.arg, entry.completion = record;
12731 }
12732 function Context(tryLocsList) {
12733 this.tryEntries = [{
12734 tryLoc: "root"
12735 }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0);
12736 }
12737 function values(iterable) {
12738 if (iterable) {
12739 var iteratorMethod = iterable[iteratorSymbol];
12740 if (iteratorMethod) return iteratorMethod.call(iterable);
12741 if ("function" == typeof iterable.next) return iterable;
12742 if (!isNaN(iterable.length)) {
12743 var i = -1,
12744 next = function next() {
12745 for (; ++i < iterable.length;) if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next;
12746 return next.value = undefined, next.done = !0, next;
12747 };
12748 return next.next = next;
12749 }
12750 }
12751 return {
12752 next: doneResult
12753 };
12754 }
12755 function doneResult() {
12756 return {
12757 value: undefined,
12758 done: !0
12759 };
12760 }
12761 return GeneratorFunction.prototype = GeneratorFunctionPrototype, defineProperty(Gp, "constructor", {
12762 value: GeneratorFunctionPrototype,
12763 configurable: !0
12764 }), defineProperty(GeneratorFunctionPrototype, "constructor", {
12765 value: GeneratorFunction,
12766 configurable: !0
12767 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"), exports.isGeneratorFunction = function (genFun) {
12768 var ctor = "function" == typeof genFun && genFun.constructor;
12769 return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === (ctor.displayName || ctor.name));
12770 }, exports.mark = function (genFun) {
12771 return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, "GeneratorFunction")), genFun.prototype = Object.create(Gp), genFun;
12772 }, exports.awrap = function (arg) {
12773 return {
12774 __await: arg
12775 };
12776 }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () {
12777 return this;
12778 }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) {
12779 void 0 === PromiseImpl && (PromiseImpl = Promise);
12780 var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl);
12781 return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) {
12782 return result.done ? result.value : iter.next();
12783 });
12784 }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, "Generator"), define(Gp, iteratorSymbol, function () {
12785 return this;
12786 }), define(Gp, "toString", function () {
12787 return "[object Generator]";
12788 }), exports.keys = function (val) {
12789 var object = Object(val),
12790 keys = [];
12791 for (var key in object) keys.push(key);
12792 return keys.reverse(), function next() {
12793 for (; keys.length;) {
12794 var key = keys.pop();
12795 if (key in object) return next.value = key, next.done = !1, next;
12796 }
12797 return next.done = !0, next;
12798 };
12799 }, exports.values = values, Context.prototype = {
12800 constructor: Context,
12801 reset: function reset(skipTempReset) {
12802 if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = "next", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) "t" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined);
12803 },
12804 stop: function stop() {
12805 this.done = !0;
12806 var rootRecord = this.tryEntries[0].completion;
12807 if ("throw" === rootRecord.type) throw rootRecord.arg;
12808 return this.rval;
12809 },
12810 dispatchException: function dispatchException(exception) {
12811 if (this.done) throw exception;
12812 var context = this;
12813 function handle(loc, caught) {
12814 return record.type = "throw", record.arg = exception, context.next = loc, caught && (context.method = "next", context.arg = undefined), !!caught;
12815 }
12816 for (var i = this.tryEntries.length - 1; i >= 0; --i) {
12817 var entry = this.tryEntries[i],
12818 record = entry.completion;
12819 if ("root" === entry.tryLoc) return handle("end");
12820 if (entry.tryLoc <= this.prev) {
12821 var hasCatch = hasOwn.call(entry, "catchLoc"),
12822 hasFinally = hasOwn.call(entry, "finallyLoc");
12823 if (hasCatch && hasFinally) {
12824 if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0);
12825 if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc);
12826 } else if (hasCatch) {
12827 if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0);
12828 } else {
12829 if (!hasFinally) throw new Error("try statement without catch or finally");
12830 if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc);
12831 }
12832 }
12833 }
12834 },
12835 abrupt: function abrupt(type, arg) {
12836 for (var i = this.tryEntries.length - 1; i >= 0; --i) {
12837 var entry = this.tryEntries[i];
12838 if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) {
12839 var finallyEntry = entry;
12840 break;
12841 }
12842 }
12843 finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null);
12844 var record = finallyEntry ? finallyEntry.completion : {};
12845 return record.type = type, record.arg = arg, finallyEntry ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record);
12846 },
12847 complete: function complete(record, afterLoc) {
12848 if ("throw" === record.type) throw record.arg;
12849 return "break" === record.type || "continue" === record.type ? this.next = record.arg : "return" === record.type ? (this.rval = this.arg = record.arg, this.method = "return", this.next = "end") : "normal" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel;
12850 },
12851 finish: function finish(finallyLoc) {
12852 for (var i = this.tryEntries.length - 1; i >= 0; --i) {
12853 var entry = this.tryEntries[i];
12854 if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel;
12855 }
12856 },
12857 "catch": function _catch(tryLoc) {
12858 for (var i = this.tryEntries.length - 1; i >= 0; --i) {
12859 var entry = this.tryEntries[i];
12860 if (entry.tryLoc === tryLoc) {
12861 var record = entry.completion;
12862 if ("throw" === record.type) {
12863 var thrown = record.arg;
12864 resetTryEntry(entry);
12865 }
12866 return thrown;
12867 }
12868 }
12869 throw new Error("illegal catch attempt");
12870 },
12871 delegateYield: function delegateYield(iterable, resultName, nextLoc) {
12872 return this.delegate = {
12873 iterator: values(iterable),
12874 resultName: resultName,
12875 nextLoc: nextLoc
12876 }, "next" === this.method && (this.arg = undefined), ContinueSentinel;
12877 }
12878 }, exports;
12879 }
12880 module.exports = _regeneratorRuntime, module.exports.__esModule = true, module.exports["default"] = module.exports;
12881 });
12882
12883 unwrapExports(regeneratorRuntime$1);
12884
12885 // TODO(Babel 8): Remove this file.
12886
12887 var runtime = regeneratorRuntime$1();
12888 var regenerator = runtime;
12889
12890 // Copied from https://github.com/facebook/regenerator/blob/main/packages/runtime/runtime.js#L736=
12891 try {
12892 regeneratorRuntime = runtime;
12893 } catch (accidentalStrictMode) {
12894 if (typeof globalThis === "object") {
12895 globalThis.regeneratorRuntime = runtime;
12896 } else {
12897 Function("r", "regeneratorRuntime = r")(runtime);
12898 }
12899 }
12900
12901 /**
12902 * Helpers.
12903 */
12904
12905 var s = 1000;
12906 var m = s * 60;
12907 var h = m * 60;
12908 var d = h * 24;
12909 var w = d * 7;
12910 var y = d * 365.25;
12911
12912 /**
12913 * Parse or format the given `val`.
12914 *
12915 * Options:
12916 *
12917 * - `long` verbose formatting [false]
12918 *
12919 * @param {String|Number} val
12920 * @param {Object} [options]
12921 * @throws {Error} throw an error if val is not a non-empty string or a number
12922 * @return {String|Number}
12923 * @api public
12924 */
12925
12926 var ms = function(val, options) {
12927 options = options || {};
12928 var type = typeof val;
12929 if (type === 'string' && val.length > 0) {
12930 return parse(val);
12931 } else if (type === 'number' && isNaN(val) === false) {
12932 return options.long ? fmtLong(val) : fmtShort(val);
12933 }
12934 throw new Error(
12935 'val is not a non-empty string or a valid number. val=' +
12936 JSON.stringify(val)
12937 );
12938 };
12939
12940 /**
12941 * Parse the given `str` and return milliseconds.
12942 *
12943 * @param {String} str
12944 * @return {Number}
12945 * @api private
12946 */
12947
12948 function parse(str) {
12949 str = String(str);
12950 if (str.length > 100) {
12951 return;
12952 }
12953 var match = /^((?:\d+)?\-?\d?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
12954 str
12955 );
12956 if (!match) {
12957 return;
12958 }
12959 var n = parseFloat(match[1]);
12960 var type = (match[2] || 'ms').toLowerCase();
12961 switch (type) {
12962 case 'years':
12963 case 'year':
12964 case 'yrs':
12965 case 'yr':
12966 case 'y':
12967 return n * y;
12968 case 'weeks':
12969 case 'week':
12970 case 'w':
12971 return n * w;
12972 case 'days':
12973 case 'day':
12974 case 'd':
12975 return n * d;
12976 case 'hours':
12977 case 'hour':
12978 case 'hrs':
12979 case 'hr':
12980 case 'h':
12981 return n * h;
12982 case 'minutes':
12983 case 'minute':
12984 case 'mins':
12985 case 'min':
12986 case 'm':
12987 return n * m;
12988 case 'seconds':
12989 case 'second':
12990 case 'secs':
12991 case 'sec':
12992 case 's':
12993 return n * s;
12994 case 'milliseconds':
12995 case 'millisecond':
12996 case 'msecs':
12997 case 'msec':
12998 case 'ms':
12999 return n;
13000 default:
13001 return undefined;
13002 }
13003 }
13004
13005 /**
13006 * Short format for `ms`.
13007 *
13008 * @param {Number} ms
13009 * @return {String}
13010 * @api private
13011 */
13012
13013 function fmtShort(ms) {
13014 var msAbs = Math.abs(ms);
13015 if (msAbs >= d) {
13016 return Math.round(ms / d) + 'd';
13017 }
13018 if (msAbs >= h) {
13019 return Math.round(ms / h) + 'h';
13020 }
13021 if (msAbs >= m) {
13022 return Math.round(ms / m) + 'm';
13023 }
13024 if (msAbs >= s) {
13025 return Math.round(ms / s) + 's';
13026 }
13027 return ms + 'ms';
13028 }
13029
13030 /**
13031 * Long format for `ms`.
13032 *
13033 * @param {Number} ms
13034 * @return {String}
13035 * @api private
13036 */
13037
13038 function fmtLong(ms) {
13039 var msAbs = Math.abs(ms);
13040 if (msAbs >= d) {
13041 return plural(ms, msAbs, d, 'day');
13042 }
13043 if (msAbs >= h) {
13044 return plural(ms, msAbs, h, 'hour');
13045 }
13046 if (msAbs >= m) {
13047 return plural(ms, msAbs, m, 'minute');
13048 }
13049 if (msAbs >= s) {
13050 return plural(ms, msAbs, s, 'second');
13051 }
13052 return ms + ' ms';
13053 }
13054
13055 /**
13056 * Pluralization helper.
13057 */
13058
13059 function plural(ms, msAbs, n, name) {
13060 var isPlural = msAbs >= n * 1.5;
13061 return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');
13062 }
13063
13064 /**
13065 * This is the common logic for both the Node.js and web browser
13066 * implementations of `debug()`.
13067 */
13068 function setup(env) {
13069 createDebug.debug = createDebug;
13070 createDebug.default = createDebug;
13071 createDebug.coerce = coerce;
13072 createDebug.disable = disable;
13073 createDebug.enable = enable;
13074 createDebug.enabled = enabled;
13075 createDebug.humanize = ms;
13076 Object.keys(env).forEach(function (key) {
13077 createDebug[key] = env[key];
13078 });
13079 /**
13080 * Active `debug` instances.
13081 */
13082
13083 createDebug.instances = [];
13084 /**
13085 * The currently active debug mode names, and names to skip.
13086 */
13087
13088 createDebug.names = [];
13089 createDebug.skips = [];
13090 /**
13091 * Map of special "%n" handling functions, for the debug "format" argument.
13092 *
13093 * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
13094 */
13095
13096 createDebug.formatters = {};
13097 /**
13098 * Selects a color for a debug namespace
13099 * @param {String} namespace The namespace string for the for the debug instance to be colored
13100 * @return {Number|String} An ANSI color code for the given namespace
13101 * @api private
13102 */
13103
13104 function selectColor(namespace) {
13105 var hash = 0;
13106
13107 for (var i = 0; i < namespace.length; i++) {
13108 hash = (hash << 5) - hash + namespace.charCodeAt(i);
13109 hash |= 0; // Convert to 32bit integer
13110 }
13111
13112 return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
13113 }
13114
13115 createDebug.selectColor = selectColor;
13116 /**
13117 * Create a debugger with the given `namespace`.
13118 *
13119 * @param {String} namespace
13120 * @return {Function}
13121 * @api public
13122 */
13123
13124 function createDebug(namespace) {
13125 var prevTime;
13126
13127 function debug() {
13128 // Disabled?
13129 if (!debug.enabled) {
13130 return;
13131 }
13132
13133 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
13134 args[_key] = arguments[_key];
13135 }
13136
13137 var self = debug; // Set `diff` timestamp
13138
13139 var curr = Number(new Date());
13140 var ms = curr - (prevTime || curr);
13141 self.diff = ms;
13142 self.prev = prevTime;
13143 self.curr = curr;
13144 prevTime = curr;
13145 args[0] = createDebug.coerce(args[0]);
13146
13147 if (typeof args[0] !== 'string') {
13148 // Anything else let's inspect with %O
13149 args.unshift('%O');
13150 } // Apply any `formatters` transformations
13151
13152
13153 var index = 0;
13154 args[0] = args[0].replace(/%([a-zA-Z%])/g, function (match, format) {
13155 // If we encounter an escaped % then don't increase the array index
13156 if (match === '%%') {
13157 return match;
13158 }
13159
13160 index++;
13161 var formatter = createDebug.formatters[format];
13162
13163 if (typeof formatter === 'function') {
13164 var val = args[index];
13165 match = formatter.call(self, val); // Now we need to remove `args[index]` since it's inlined in the `format`
13166
13167 args.splice(index, 1);
13168 index--;
13169 }
13170
13171 return match;
13172 }); // Apply env-specific formatting (colors, etc.)
13173
13174 createDebug.formatArgs.call(self, args);
13175 var logFn = self.log || createDebug.log;
13176 logFn.apply(self, args);
13177 }
13178
13179 debug.namespace = namespace;
13180 debug.enabled = createDebug.enabled(namespace);
13181 debug.useColors = createDebug.useColors();
13182 debug.color = selectColor(namespace);
13183 debug.destroy = destroy;
13184 debug.extend = extend; // Debug.formatArgs = formatArgs;
13185 // debug.rawLog = rawLog;
13186 // env-specific initialization logic for debug instances
13187
13188 if (typeof createDebug.init === 'function') {
13189 createDebug.init(debug);
13190 }
13191
13192 createDebug.instances.push(debug);
13193 return debug;
13194 }
13195
13196 function destroy() {
13197 var index = createDebug.instances.indexOf(this);
13198
13199 if (index !== -1) {
13200 createDebug.instances.splice(index, 1);
13201 return true;
13202 }
13203
13204 return false;
13205 }
13206
13207 function extend(namespace, delimiter) {
13208 return createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);
13209 }
13210 /**
13211 * Enables a debug mode by namespaces. This can include modes
13212 * separated by a colon and wildcards.
13213 *
13214 * @param {String} namespaces
13215 * @api public
13216 */
13217
13218
13219 function enable(namespaces) {
13220 createDebug.save(namespaces);
13221 createDebug.names = [];
13222 createDebug.skips = [];
13223 var i;
13224 var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
13225 var len = split.length;
13226
13227 for (i = 0; i < len; i++) {
13228 if (!split[i]) {
13229 // ignore empty strings
13230 continue;
13231 }
13232
13233 namespaces = split[i].replace(/\*/g, '.*?');
13234
13235 if (namespaces[0] === '-') {
13236 createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
13237 } else {
13238 createDebug.names.push(new RegExp('^' + namespaces + '$'));
13239 }
13240 }
13241
13242 for (i = 0; i < createDebug.instances.length; i++) {
13243 var instance = createDebug.instances[i];
13244 instance.enabled = createDebug.enabled(instance.namespace);
13245 }
13246 }
13247 /**
13248 * Disable debug output.
13249 *
13250 * @api public
13251 */
13252
13253
13254 function disable() {
13255 createDebug.enable('');
13256 }
13257 /**
13258 * Returns true if the given mode name is enabled, false otherwise.
13259 *
13260 * @param {String} name
13261 * @return {Boolean}
13262 * @api public
13263 */
13264
13265
13266 function enabled(name) {
13267 if (name[name.length - 1] === '*') {
13268 return true;
13269 }
13270
13271 var i;
13272 var len;
13273
13274 for (i = 0, len = createDebug.skips.length; i < len; i++) {
13275 if (createDebug.skips[i].test(name)) {
13276 return false;
13277 }
13278 }
13279
13280 for (i = 0, len = createDebug.names.length; i < len; i++) {
13281 if (createDebug.names[i].test(name)) {
13282 return true;
13283 }
13284 }
13285
13286 return false;
13287 }
13288 /**
13289 * Coerce `val`.
13290 *
13291 * @param {Mixed} val
13292 * @return {Mixed}
13293 * @api private
13294 */
13295
13296
13297 function coerce(val) {
13298 if (val instanceof Error) {
13299 return val.stack || val.message;
13300 }
13301
13302 return val;
13303 }
13304
13305 createDebug.enable(createDebug.load());
13306 return createDebug;
13307 }
13308
13309 var common = setup;
13310
13311 var browser = createCommonjsModule(function (module, exports) {
13312
13313 function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
13314
13315 /* eslint-env browser */
13316
13317 /**
13318 * This is the web browser implementation of `debug()`.
13319 */
13320 exports.log = log;
13321 exports.formatArgs = formatArgs;
13322 exports.save = save;
13323 exports.load = load;
13324 exports.useColors = useColors;
13325 exports.storage = localstorage();
13326 /**
13327 * Colors.
13328 */
13329
13330 exports.colors = ['#0000CC', '#0000FF', '#0033CC', '#0033FF', '#0066CC', '#0066FF', '#0099CC', '#0099FF', '#00CC00', '#00CC33', '#00CC66', '#00CC99', '#00CCCC', '#00CCFF', '#3300CC', '#3300FF', '#3333CC', '#3333FF', '#3366CC', '#3366FF', '#3399CC', '#3399FF', '#33CC00', '#33CC33', '#33CC66', '#33CC99', '#33CCCC', '#33CCFF', '#6600CC', '#6600FF', '#6633CC', '#6633FF', '#66CC00', '#66CC33', '#9900CC', '#9900FF', '#9933CC', '#9933FF', '#99CC00', '#99CC33', '#CC0000', '#CC0033', '#CC0066', '#CC0099', '#CC00CC', '#CC00FF', '#CC3300', '#CC3333', '#CC3366', '#CC3399', '#CC33CC', '#CC33FF', '#CC6600', '#CC6633', '#CC9900', '#CC9933', '#CCCC00', '#CCCC33', '#FF0000', '#FF0033', '#FF0066', '#FF0099', '#FF00CC', '#FF00FF', '#FF3300', '#FF3333', '#FF3366', '#FF3399', '#FF33CC', '#FF33FF', '#FF6600', '#FF6633', '#FF9900', '#FF9933', '#FFCC00', '#FFCC33'];
13331 /**
13332 * Currently only WebKit-based Web Inspectors, Firefox >= v31,
13333 * and the Firebug extension (any Firefox version) are known
13334 * to support "%c" CSS customizations.
13335 *
13336 * TODO: add a `localStorage` variable to explicitly enable/disable colors
13337 */
13338 // eslint-disable-next-line complexity
13339
13340 function useColors() {
13341 // NB: In an Electron preload script, document will be defined but not fully
13342 // initialized. Since we know we're in Chrome, we'll just detect this case
13343 // explicitly
13344 if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {
13345 return true;
13346 } // Internet Explorer and Edge do not support colors.
13347
13348
13349 if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
13350 return false;
13351 } // Is webkit? http://stackoverflow.com/a/16459606/376773
13352 // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
13353
13354
13355 return typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || // Is firebug? http://stackoverflow.com/a/398120/376773
13356 typeof window !== 'undefined' && window.console && (window.console.firebug || window.console.exception && window.console.table) || // Is firefox >= v31?
13357 // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
13358 typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31 || // Double check webkit in userAgent just in case we are in a worker
13359 typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/);
13360 }
13361 /**
13362 * Colorize log arguments if enabled.
13363 *
13364 * @api public
13365 */
13366
13367
13368 function formatArgs(args) {
13369 args[0] = (this.useColors ? '%c' : '') + this.namespace + (this.useColors ? ' %c' : ' ') + args[0] + (this.useColors ? '%c ' : ' ') + '+' + module.exports.humanize(this.diff);
13370
13371 if (!this.useColors) {
13372 return;
13373 }
13374
13375 var c = 'color: ' + this.color;
13376 args.splice(1, 0, c, 'color: inherit'); // The final "%c" is somewhat tricky, because there could be other
13377 // arguments passed either before or after the %c, so we need to
13378 // figure out the correct index to insert the CSS into
13379
13380 var index = 0;
13381 var lastC = 0;
13382 args[0].replace(/%[a-zA-Z%]/g, function (match) {
13383 if (match === '%%') {
13384 return;
13385 }
13386
13387 index++;
13388
13389 if (match === '%c') {
13390 // We only are interested in the *last* %c
13391 // (the user may have provided their own)
13392 lastC = index;
13393 }
13394 });
13395 args.splice(lastC, 0, c);
13396 }
13397 /**
13398 * Invokes `console.log()` when available.
13399 * No-op when `console.log` is not a "function".
13400 *
13401 * @api public
13402 */
13403
13404
13405 function log() {
13406 var _console;
13407
13408 // This hackery is required for IE8/9, where
13409 // the `console.log` function doesn't have 'apply'
13410 return (typeof console === "undefined" ? "undefined" : _typeof(console)) === 'object' && console.log && (_console = console).log.apply(_console, arguments);
13411 }
13412 /**
13413 * Save `namespaces`.
13414 *
13415 * @param {String} namespaces
13416 * @api private
13417 */
13418
13419
13420 function save(namespaces) {
13421 try {
13422 if (namespaces) {
13423 exports.storage.setItem('debug', namespaces);
13424 } else {
13425 exports.storage.removeItem('debug');
13426 }
13427 } catch (error) {// Swallow
13428 // XXX (@Qix-) should we be logging these?
13429 }
13430 }
13431 /**
13432 * Load `namespaces`.
13433 *
13434 * @return {String} returns the previously persisted debug modes
13435 * @api private
13436 */
13437
13438
13439 function load() {
13440 var r;
13441
13442 try {
13443 r = exports.storage.getItem('debug');
13444 } catch (error) {} // Swallow
13445 // XXX (@Qix-) should we be logging these?
13446 // If debug isn't set in LS, and we're in Electron, try to load $DEBUG
13447
13448
13449 if (!r && typeof process !== 'undefined' && 'env' in process) {
13450 r = process.env.DEBUG;
13451 }
13452
13453 return r;
13454 }
13455 /**
13456 * Localstorage attempts to return the localstorage.
13457 *
13458 * This is necessary because safari throws
13459 * when a user disables cookies/localstorage
13460 * and you attempt to access it.
13461 *
13462 * @return {LocalStorage}
13463 * @api private
13464 */
13465
13466
13467 function localstorage() {
13468 try {
13469 // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context
13470 // The Browser also has localStorage in the global context.
13471 return localStorage;
13472 } catch (error) {// Swallow
13473 // XXX (@Qix-) should we be logging these?
13474 }
13475 }
13476
13477 module.exports = common(exports);
13478 var formatters = module.exports.formatters;
13479 /**
13480 * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
13481 */
13482
13483 formatters.j = function (v) {
13484 try {
13485 return JSON.stringify(v);
13486 } catch (error) {
13487 return '[UnexpectedJSONParseError]: ' + error.message;
13488 }
13489 };
13490 });
13491 var browser_1 = browser.log;
13492 var browser_2 = browser.formatArgs;
13493 var browser_3 = browser.save;
13494 var browser_4 = browser.load;
13495 var browser_5 = browser.useColors;
13496 var browser_6 = browser.storage;
13497 var browser_7 = browser.colors;
13498
13499 /**
13500 * Copies the values of `source` to `array`.
13501 *
13502 * @private
13503 * @param {Array} source The array to copy values from.
13504 * @param {Array} [array=[]] The array to copy values to.
13505 * @returns {Array} Returns `array`.
13506 */
13507 function copyArray(source, array) {
13508 var index = -1,
13509 length = source.length;
13510
13511 array || (array = Array(length));
13512 while (++index < length) {
13513 array[index] = source[index];
13514 }
13515 return array;
13516 }
13517
13518 var _copyArray = copyArray;
13519
13520 /* Built-in method references for those with the same name as other `lodash` methods. */
13521 var nativeFloor = Math.floor,
13522 nativeRandom = Math.random;
13523
13524 /**
13525 * The base implementation of `_.random` without support for returning
13526 * floating-point numbers.
13527 *
13528 * @private
13529 * @param {number} lower The lower bound.
13530 * @param {number} upper The upper bound.
13531 * @returns {number} Returns the random number.
13532 */
13533 function baseRandom(lower, upper) {
13534 return lower + nativeFloor(nativeRandom() * (upper - lower + 1));
13535 }
13536
13537 var _baseRandom = baseRandom;
13538
13539 /**
13540 * A specialized version of `_.shuffle` which mutates and sets the size of `array`.
13541 *
13542 * @private
13543 * @param {Array} array The array to shuffle.
13544 * @param {number} [size=array.length] The size of `array`.
13545 * @returns {Array} Returns `array`.
13546 */
13547 function shuffleSelf(array, size) {
13548 var index = -1,
13549 length = array.length,
13550 lastIndex = length - 1;
13551
13552 size = size === undefined ? length : size;
13553 while (++index < size) {
13554 var rand = _baseRandom(index, lastIndex),
13555 value = array[rand];
13556
13557 array[rand] = array[index];
13558 array[index] = value;
13559 }
13560 array.length = size;
13561 return array;
13562 }
13563
13564 var _shuffleSelf = shuffleSelf;
13565
13566 /**
13567 * A specialized version of `_.shuffle` for arrays.
13568 *
13569 * @private
13570 * @param {Array} array The array to shuffle.
13571 * @returns {Array} Returns the new shuffled array.
13572 */
13573 function arrayShuffle(array) {
13574 return _shuffleSelf(_copyArray(array));
13575 }
13576
13577 var _arrayShuffle = arrayShuffle;
13578
13579 /**
13580 * A specialized version of `_.map` for arrays without support for iteratee
13581 * shorthands.
13582 *
13583 * @private
13584 * @param {Array} [array] The array to iterate over.
13585 * @param {Function} iteratee The function invoked per iteration.
13586 * @returns {Array} Returns the new mapped array.
13587 */
13588 function arrayMap(array, iteratee) {
13589 var index = -1,
13590 length = array == null ? 0 : array.length,
13591 result = Array(length);
13592
13593 while (++index < length) {
13594 result[index] = iteratee(array[index], index, array);
13595 }
13596 return result;
13597 }
13598
13599 var _arrayMap = arrayMap;
13600
13601 /**
13602 * The base implementation of `_.values` and `_.valuesIn` which creates an
13603 * array of `object` property values corresponding to the property names
13604 * of `props`.
13605 *
13606 * @private
13607 * @param {Object} object The object to query.
13608 * @param {Array} props The property names to get values for.
13609 * @returns {Object} Returns the array of property values.
13610 */
13611 function baseValues(object, props) {
13612 return _arrayMap(props, function(key) {
13613 return object[key];
13614 });
13615 }
13616
13617 var _baseValues = baseValues;
13618
13619 /**
13620 * The base implementation of `_.times` without support for iteratee shorthands
13621 * or max array length checks.
13622 *
13623 * @private
13624 * @param {number} n The number of times to invoke `iteratee`.
13625 * @param {Function} iteratee The function invoked per iteration.
13626 * @returns {Array} Returns the array of results.
13627 */
13628 function baseTimes(n, iteratee) {
13629 var index = -1,
13630 result = Array(n);
13631
13632 while (++index < n) {
13633 result[index] = iteratee(index);
13634 }
13635 return result;
13636 }
13637
13638 var _baseTimes = baseTimes;
13639
13640 /** Detect free variable `global` from Node.js. */
13641 var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal;
13642
13643 var _freeGlobal = freeGlobal;
13644
13645 /** Detect free variable `self`. */
13646 var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
13647
13648 /** Used as a reference to the global object. */
13649 var root = _freeGlobal || freeSelf || Function('return this')();
13650
13651 var _root = root;
13652
13653 /** Built-in value references. */
13654 var Symbol$1 = _root.Symbol;
13655
13656 var _Symbol = Symbol$1;
13657
13658 /** Used for built-in method references. */
13659 var objectProto = Object.prototype;
13660
13661 /** Used to check objects for own properties. */
13662 var hasOwnProperty = objectProto.hasOwnProperty;
13663
13664 /**
13665 * Used to resolve the
13666 * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
13667 * of values.
13668 */
13669 var nativeObjectToString = objectProto.toString;
13670
13671 /** Built-in value references. */
13672 var symToStringTag = _Symbol ? _Symbol.toStringTag : undefined;
13673
13674 /**
13675 * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
13676 *
13677 * @private
13678 * @param {*} value The value to query.
13679 * @returns {string} Returns the raw `toStringTag`.
13680 */
13681 function getRawTag(value) {
13682 var isOwn = hasOwnProperty.call(value, symToStringTag),
13683 tag = value[symToStringTag];
13684
13685 try {
13686 value[symToStringTag] = undefined;
13687 var unmasked = true;
13688 } catch (e) {}
13689
13690 var result = nativeObjectToString.call(value);
13691 if (unmasked) {
13692 if (isOwn) {
13693 value[symToStringTag] = tag;
13694 } else {
13695 delete value[symToStringTag];
13696 }
13697 }
13698 return result;
13699 }
13700
13701 var _getRawTag = getRawTag;
13702
13703 /** Used for built-in method references. */
13704 var objectProto$1 = Object.prototype;
13705
13706 /**
13707 * Used to resolve the
13708 * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
13709 * of values.
13710 */
13711 var nativeObjectToString$1 = objectProto$1.toString;
13712
13713 /**
13714 * Converts `value` to a string using `Object.prototype.toString`.
13715 *
13716 * @private
13717 * @param {*} value The value to convert.
13718 * @returns {string} Returns the converted string.
13719 */
13720 function objectToString(value) {
13721 return nativeObjectToString$1.call(value);
13722 }
13723
13724 var _objectToString = objectToString;
13725
13726 /** `Object#toString` result references. */
13727 var nullTag = '[object Null]',
13728 undefinedTag = '[object Undefined]';
13729
13730 /** Built-in value references. */
13731 var symToStringTag$1 = _Symbol ? _Symbol.toStringTag : undefined;
13732
13733 /**
13734 * The base implementation of `getTag` without fallbacks for buggy environments.
13735 *
13736 * @private
13737 * @param {*} value The value to query.
13738 * @returns {string} Returns the `toStringTag`.
13739 */
13740 function baseGetTag(value) {
13741 if (value == null) {
13742 return value === undefined ? undefinedTag : nullTag;
13743 }
13744 return (symToStringTag$1 && symToStringTag$1 in Object(value))
13745 ? _getRawTag(value)
13746 : _objectToString(value);
13747 }
13748
13749 var _baseGetTag = baseGetTag;
13750
13751 /**
13752 * Checks if `value` is object-like. A value is object-like if it's not `null`
13753 * and has a `typeof` result of "object".
13754 *
13755 * @static
13756 * @memberOf _
13757 * @since 4.0.0
13758 * @category Lang
13759 * @param {*} value The value to check.
13760 * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
13761 * @example
13762 *
13763 * _.isObjectLike({});
13764 * // => true
13765 *
13766 * _.isObjectLike([1, 2, 3]);
13767 * // => true
13768 *
13769 * _.isObjectLike(_.noop);
13770 * // => false
13771 *
13772 * _.isObjectLike(null);
13773 * // => false
13774 */
13775 function isObjectLike(value) {
13776 return value != null && typeof value == 'object';
13777 }
13778
13779 var isObjectLike_1 = isObjectLike;
13780
13781 /** `Object#toString` result references. */
13782 var argsTag = '[object Arguments]';
13783
13784 /**
13785 * The base implementation of `_.isArguments`.
13786 *
13787 * @private
13788 * @param {*} value The value to check.
13789 * @returns {boolean} Returns `true` if `value` is an `arguments` object,
13790 */
13791 function baseIsArguments(value) {
13792 return isObjectLike_1(value) && _baseGetTag(value) == argsTag;
13793 }
13794
13795 var _baseIsArguments = baseIsArguments;
13796
13797 /** Used for built-in method references. */
13798 var objectProto$2 = Object.prototype;
13799
13800 /** Used to check objects for own properties. */
13801 var hasOwnProperty$1 = objectProto$2.hasOwnProperty;
13802
13803 /** Built-in value references. */
13804 var propertyIsEnumerable = objectProto$2.propertyIsEnumerable;
13805
13806 /**
13807 * Checks if `value` is likely an `arguments` object.
13808 *
13809 * @static
13810 * @memberOf _
13811 * @since 0.1.0
13812 * @category Lang
13813 * @param {*} value The value to check.
13814 * @returns {boolean} Returns `true` if `value` is an `arguments` object,
13815 * else `false`.
13816 * @example
13817 *
13818 * _.isArguments(function() { return arguments; }());
13819 * // => true
13820 *
13821 * _.isArguments([1, 2, 3]);
13822 * // => false
13823 */
13824 var isArguments = _baseIsArguments(function() { return arguments; }()) ? _baseIsArguments : function(value) {
13825 return isObjectLike_1(value) && hasOwnProperty$1.call(value, 'callee') &&
13826 !propertyIsEnumerable.call(value, 'callee');
13827 };
13828
13829 var isArguments_1 = isArguments;
13830
13831 /**
13832 * Checks if `value` is classified as an `Array` object.
13833 *
13834 * @static
13835 * @memberOf _
13836 * @since 0.1.0
13837 * @category Lang
13838 * @param {*} value The value to check.
13839 * @returns {boolean} Returns `true` if `value` is an array, else `false`.
13840 * @example
13841 *
13842 * _.isArray([1, 2, 3]);
13843 * // => true
13844 *
13845 * _.isArray(document.body.children);
13846 * // => false
13847 *
13848 * _.isArray('abc');
13849 * // => false
13850 *
13851 * _.isArray(_.noop);
13852 * // => false
13853 */
13854 var isArray = Array.isArray;
13855
13856 var isArray_1 = isArray;
13857
13858 /**
13859 * This method returns `false`.
13860 *
13861 * @static
13862 * @memberOf _
13863 * @since 4.13.0
13864 * @category Util
13865 * @returns {boolean} Returns `false`.
13866 * @example
13867 *
13868 * _.times(2, _.stubFalse);
13869 * // => [false, false]
13870 */
13871 function stubFalse() {
13872 return false;
13873 }
13874
13875 var stubFalse_1 = stubFalse;
13876
13877 var isBuffer_1 = createCommonjsModule(function (module, exports) {
13878 /** Detect free variable `exports`. */
13879 var freeExports = exports && !exports.nodeType && exports;
13880
13881 /** Detect free variable `module`. */
13882 var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module;
13883
13884 /** Detect the popular CommonJS extension `module.exports`. */
13885 var moduleExports = freeModule && freeModule.exports === freeExports;
13886
13887 /** Built-in value references. */
13888 var Buffer = moduleExports ? _root.Buffer : undefined;
13889
13890 /* Built-in method references for those with the same name as other `lodash` methods. */
13891 var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined;
13892
13893 /**
13894 * Checks if `value` is a buffer.
13895 *
13896 * @static
13897 * @memberOf _
13898 * @since 4.3.0
13899 * @category Lang
13900 * @param {*} value The value to check.
13901 * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.
13902 * @example
13903 *
13904 * _.isBuffer(new Buffer(2));
13905 * // => true
13906 *
13907 * _.isBuffer(new Uint8Array(2));
13908 * // => false
13909 */
13910 var isBuffer = nativeIsBuffer || stubFalse_1;
13911
13912 module.exports = isBuffer;
13913 });
13914
13915 /** Used as references for various `Number` constants. */
13916 var MAX_SAFE_INTEGER = 9007199254740991;
13917
13918 /** Used to detect unsigned integer values. */
13919 var reIsUint = /^(?:0|[1-9]\d*)$/;
13920
13921 /**
13922 * Checks if `value` is a valid array-like index.
13923 *
13924 * @private
13925 * @param {*} value The value to check.
13926 * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
13927 * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
13928 */
13929 function isIndex(value, length) {
13930 var type = typeof value;
13931 length = length == null ? MAX_SAFE_INTEGER : length;
13932
13933 return !!length &&
13934 (type == 'number' ||
13935 (type != 'symbol' && reIsUint.test(value))) &&
13936 (value > -1 && value % 1 == 0 && value < length);
13937 }
13938
13939 var _isIndex = isIndex;
13940
13941 /** Used as references for various `Number` constants. */
13942 var MAX_SAFE_INTEGER$1 = 9007199254740991;
13943
13944 /**
13945 * Checks if `value` is a valid array-like length.
13946 *
13947 * **Note:** This method is loosely based on
13948 * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
13949 *
13950 * @static
13951 * @memberOf _
13952 * @since 4.0.0
13953 * @category Lang
13954 * @param {*} value The value to check.
13955 * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
13956 * @example
13957 *
13958 * _.isLength(3);
13959 * // => true
13960 *
13961 * _.isLength(Number.MIN_VALUE);
13962 * // => false
13963 *
13964 * _.isLength(Infinity);
13965 * // => false
13966 *
13967 * _.isLength('3');
13968 * // => false
13969 */
13970 function isLength(value) {
13971 return typeof value == 'number' &&
13972 value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER$1;
13973 }
13974
13975 var isLength_1 = isLength;
13976
13977 /** `Object#toString` result references. */
13978 var argsTag$1 = '[object Arguments]',
13979 arrayTag = '[object Array]',
13980 boolTag = '[object Boolean]',
13981 dateTag = '[object Date]',
13982 errorTag = '[object Error]',
13983 funcTag = '[object Function]',
13984 mapTag = '[object Map]',
13985 numberTag = '[object Number]',
13986 objectTag = '[object Object]',
13987 regexpTag = '[object RegExp]',
13988 setTag = '[object Set]',
13989 stringTag = '[object String]',
13990 weakMapTag = '[object WeakMap]';
13991
13992 var arrayBufferTag = '[object ArrayBuffer]',
13993 dataViewTag = '[object DataView]',
13994 float32Tag = '[object Float32Array]',
13995 float64Tag = '[object Float64Array]',
13996 int8Tag = '[object Int8Array]',
13997 int16Tag = '[object Int16Array]',
13998 int32Tag = '[object Int32Array]',
13999 uint8Tag = '[object Uint8Array]',
14000 uint8ClampedTag = '[object Uint8ClampedArray]',
14001 uint16Tag = '[object Uint16Array]',
14002 uint32Tag = '[object Uint32Array]';
14003
14004 /** Used to identify `toStringTag` values of typed arrays. */
14005 var typedArrayTags = {};
14006 typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =
14007 typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =
14008 typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =
14009 typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =
14010 typedArrayTags[uint32Tag] = true;
14011 typedArrayTags[argsTag$1] = typedArrayTags[arrayTag] =
14012 typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =
14013 typedArrayTags[dataViewTag] = typedArrayTags[dateTag] =
14014 typedArrayTags[errorTag] = typedArrayTags[funcTag] =
14015 typedArrayTags[mapTag] = typedArrayTags[numberTag] =
14016 typedArrayTags[objectTag] = typedArrayTags[regexpTag] =
14017 typedArrayTags[setTag] = typedArrayTags[stringTag] =
14018 typedArrayTags[weakMapTag] = false;
14019
14020 /**
14021 * The base implementation of `_.isTypedArray` without Node.js optimizations.
14022 *
14023 * @private
14024 * @param {*} value The value to check.
14025 * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
14026 */
14027 function baseIsTypedArray(value) {
14028 return isObjectLike_1(value) &&
14029 isLength_1(value.length) && !!typedArrayTags[_baseGetTag(value)];
14030 }
14031
14032 var _baseIsTypedArray = baseIsTypedArray;
14033
14034 /**
14035 * The base implementation of `_.unary` without support for storing metadata.
14036 *
14037 * @private
14038 * @param {Function} func The function to cap arguments for.
14039 * @returns {Function} Returns the new capped function.
14040 */
14041 function baseUnary(func) {
14042 return function(value) {
14043 return func(value);
14044 };
14045 }
14046
14047 var _baseUnary = baseUnary;
14048
14049 var _nodeUtil = createCommonjsModule(function (module, exports) {
14050 /** Detect free variable `exports`. */
14051 var freeExports = exports && !exports.nodeType && exports;
14052
14053 /** Detect free variable `module`. */
14054 var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module;
14055
14056 /** Detect the popular CommonJS extension `module.exports`. */
14057 var moduleExports = freeModule && freeModule.exports === freeExports;
14058
14059 /** Detect free variable `process` from Node.js. */
14060 var freeProcess = moduleExports && _freeGlobal.process;
14061
14062 /** Used to access faster Node.js helpers. */
14063 var nodeUtil = (function() {
14064 try {
14065 // Use `util.types` for Node.js 10+.
14066 var types = freeModule && freeModule.require && freeModule.require('util').types;
14067
14068 if (types) {
14069 return types;
14070 }
14071
14072 // Legacy `process.binding('util')` for Node.js < 10.
14073 return freeProcess && freeProcess.binding && freeProcess.binding('util');
14074 } catch (e) {}
14075 }());
14076
14077 module.exports = nodeUtil;
14078 });
14079
14080 /* Node.js helper references. */
14081 var nodeIsTypedArray = _nodeUtil && _nodeUtil.isTypedArray;
14082
14083 /**
14084 * Checks if `value` is classified as a typed array.
14085 *
14086 * @static
14087 * @memberOf _
14088 * @since 3.0.0
14089 * @category Lang
14090 * @param {*} value The value to check.
14091 * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
14092 * @example
14093 *
14094 * _.isTypedArray(new Uint8Array);
14095 * // => true
14096 *
14097 * _.isTypedArray([]);
14098 * // => false
14099 */
14100 var isTypedArray = nodeIsTypedArray ? _baseUnary(nodeIsTypedArray) : _baseIsTypedArray;
14101
14102 var isTypedArray_1 = isTypedArray;
14103
14104 /** Used for built-in method references. */
14105 var objectProto$3 = Object.prototype;
14106
14107 /** Used to check objects for own properties. */
14108 var hasOwnProperty$2 = objectProto$3.hasOwnProperty;
14109
14110 /**
14111 * Creates an array of the enumerable property names of the array-like `value`.
14112 *
14113 * @private
14114 * @param {*} value The value to query.
14115 * @param {boolean} inherited Specify returning inherited property names.
14116 * @returns {Array} Returns the array of property names.
14117 */
14118 function arrayLikeKeys(value, inherited) {
14119 var isArr = isArray_1(value),
14120 isArg = !isArr && isArguments_1(value),
14121 isBuff = !isArr && !isArg && isBuffer_1(value),
14122 isType = !isArr && !isArg && !isBuff && isTypedArray_1(value),
14123 skipIndexes = isArr || isArg || isBuff || isType,
14124 result = skipIndexes ? _baseTimes(value.length, String) : [],
14125 length = result.length;
14126
14127 for (var key in value) {
14128 if ((inherited || hasOwnProperty$2.call(value, key)) &&
14129 !(skipIndexes && (
14130 // Safari 9 has enumerable `arguments.length` in strict mode.
14131 key == 'length' ||
14132 // Node.js 0.10 has enumerable non-index properties on buffers.
14133 (isBuff && (key == 'offset' || key == 'parent')) ||
14134 // PhantomJS 2 has enumerable non-index properties on typed arrays.
14135 (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) ||
14136 // Skip index properties.
14137 _isIndex(key, length)
14138 ))) {
14139 result.push(key);
14140 }
14141 }
14142 return result;
14143 }
14144
14145 var _arrayLikeKeys = arrayLikeKeys;
14146
14147 /** Used for built-in method references. */
14148 var objectProto$4 = Object.prototype;
14149
14150 /**
14151 * Checks if `value` is likely a prototype object.
14152 *
14153 * @private
14154 * @param {*} value The value to check.
14155 * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
14156 */
14157 function isPrototype(value) {
14158 var Ctor = value && value.constructor,
14159 proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto$4;
14160
14161 return value === proto;
14162 }
14163
14164 var _isPrototype = isPrototype;
14165
14166 /**
14167 * Creates a unary function that invokes `func` with its argument transformed.
14168 *
14169 * @private
14170 * @param {Function} func The function to wrap.
14171 * @param {Function} transform The argument transform.
14172 * @returns {Function} Returns the new function.
14173 */
14174 function overArg(func, transform) {
14175 return function(arg) {
14176 return func(transform(arg));
14177 };
14178 }
14179
14180 var _overArg = overArg;
14181
14182 /* Built-in method references for those with the same name as other `lodash` methods. */
14183 var nativeKeys = _overArg(Object.keys, Object);
14184
14185 var _nativeKeys = nativeKeys;
14186
14187 /** Used for built-in method references. */
14188 var objectProto$5 = Object.prototype;
14189
14190 /** Used to check objects for own properties. */
14191 var hasOwnProperty$3 = objectProto$5.hasOwnProperty;
14192
14193 /**
14194 * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
14195 *
14196 * @private
14197 * @param {Object} object The object to query.
14198 * @returns {Array} Returns the array of property names.
14199 */
14200 function baseKeys(object) {
14201 if (!_isPrototype(object)) {
14202 return _nativeKeys(object);
14203 }
14204 var result = [];
14205 for (var key in Object(object)) {
14206 if (hasOwnProperty$3.call(object, key) && key != 'constructor') {
14207 result.push(key);
14208 }
14209 }
14210 return result;
14211 }
14212
14213 var _baseKeys = baseKeys;
14214
14215 /**
14216 * Checks if `value` is the
14217 * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
14218 * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
14219 *
14220 * @static
14221 * @memberOf _
14222 * @since 0.1.0
14223 * @category Lang
14224 * @param {*} value The value to check.
14225 * @returns {boolean} Returns `true` if `value` is an object, else `false`.
14226 * @example
14227 *
14228 * _.isObject({});
14229 * // => true
14230 *
14231 * _.isObject([1, 2, 3]);
14232 * // => true
14233 *
14234 * _.isObject(_.noop);
14235 * // => true
14236 *
14237 * _.isObject(null);
14238 * // => false
14239 */
14240 function isObject(value) {
14241 var type = typeof value;
14242 return value != null && (type == 'object' || type == 'function');
14243 }
14244
14245 var isObject_1 = isObject;
14246
14247 /** `Object#toString` result references. */
14248 var asyncTag = '[object AsyncFunction]',
14249 funcTag$1 = '[object Function]',
14250 genTag = '[object GeneratorFunction]',
14251 proxyTag = '[object Proxy]';
14252
14253 /**
14254 * Checks if `value` is classified as a `Function` object.
14255 *
14256 * @static
14257 * @memberOf _
14258 * @since 0.1.0
14259 * @category Lang
14260 * @param {*} value The value to check.
14261 * @returns {boolean} Returns `true` if `value` is a function, else `false`.
14262 * @example
14263 *
14264 * _.isFunction(_);
14265 * // => true
14266 *
14267 * _.isFunction(/abc/);
14268 * // => false
14269 */
14270 function isFunction(value) {
14271 if (!isObject_1(value)) {
14272 return false;
14273 }
14274 // The use of `Object#toString` avoids issues with the `typeof` operator
14275 // in Safari 9 which returns 'object' for typed arrays and other constructors.
14276 var tag = _baseGetTag(value);
14277 return tag == funcTag$1 || tag == genTag || tag == asyncTag || tag == proxyTag;
14278 }
14279
14280 var isFunction_1 = isFunction;
14281
14282 /**
14283 * Checks if `value` is array-like. A value is considered array-like if it's
14284 * not a function and has a `value.length` that's an integer greater than or
14285 * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
14286 *
14287 * @static
14288 * @memberOf _
14289 * @since 4.0.0
14290 * @category Lang
14291 * @param {*} value The value to check.
14292 * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
14293 * @example
14294 *
14295 * _.isArrayLike([1, 2, 3]);
14296 * // => true
14297 *
14298 * _.isArrayLike(document.body.children);
14299 * // => true
14300 *
14301 * _.isArrayLike('abc');
14302 * // => true
14303 *
14304 * _.isArrayLike(_.noop);
14305 * // => false
14306 */
14307 function isArrayLike(value) {
14308 return value != null && isLength_1(value.length) && !isFunction_1(value);
14309 }
14310
14311 var isArrayLike_1 = isArrayLike;
14312
14313 /**
14314 * Creates an array of the own enumerable property names of `object`.
14315 *
14316 * **Note:** Non-object values are coerced to objects. See the
14317 * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
14318 * for more details.
14319 *
14320 * @static
14321 * @since 0.1.0
14322 * @memberOf _
14323 * @category Object
14324 * @param {Object} object The object to query.
14325 * @returns {Array} Returns the array of property names.
14326 * @example
14327 *
14328 * function Foo() {
14329 * this.a = 1;
14330 * this.b = 2;
14331 * }
14332 *
14333 * Foo.prototype.c = 3;
14334 *
14335 * _.keys(new Foo);
14336 * // => ['a', 'b'] (iteration order is not guaranteed)
14337 *
14338 * _.keys('hi');
14339 * // => ['0', '1']
14340 */
14341 function keys(object) {
14342 return isArrayLike_1(object) ? _arrayLikeKeys(object) : _baseKeys(object);
14343 }
14344
14345 var keys_1 = keys;
14346
14347 /**
14348 * Creates an array of the own enumerable string keyed property values of `object`.
14349 *
14350 * **Note:** Non-object values are coerced to objects.
14351 *
14352 * @static
14353 * @since 0.1.0
14354 * @memberOf _
14355 * @category Object
14356 * @param {Object} object The object to query.
14357 * @returns {Array} Returns the array of property values.
14358 * @example
14359 *
14360 * function Foo() {
14361 * this.a = 1;
14362 * this.b = 2;
14363 * }
14364 *
14365 * Foo.prototype.c = 3;
14366 *
14367 * _.values(new Foo);
14368 * // => [1, 2] (iteration order is not guaranteed)
14369 *
14370 * _.values('hi');
14371 * // => ['h', 'i']
14372 */
14373 function values(object) {
14374 return object == null ? [] : _baseValues(object, keys_1(object));
14375 }
14376
14377 var values_1 = values;
14378
14379 /**
14380 * The base implementation of `_.shuffle`.
14381 *
14382 * @private
14383 * @param {Array|Object} collection The collection to shuffle.
14384 * @returns {Array} Returns the new shuffled array.
14385 */
14386 function baseShuffle(collection) {
14387 return _shuffleSelf(values_1(collection));
14388 }
14389
14390 var _baseShuffle = baseShuffle;
14391
14392 /**
14393 * Creates an array of shuffled values, using a version of the
14394 * [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle).
14395 *
14396 * @static
14397 * @memberOf _
14398 * @since 0.1.0
14399 * @category Collection
14400 * @param {Array|Object} collection The collection to shuffle.
14401 * @returns {Array} Returns the new shuffled array.
14402 * @example
14403 *
14404 * _.shuffle([1, 2, 3, 4]);
14405 * // => [4, 1, 3, 2]
14406 */
14407 function shuffle(collection) {
14408 var func = isArray_1(collection) ? _arrayShuffle : _baseShuffle;
14409 return func(collection);
14410 }
14411
14412 var shuffle_1 = shuffle;
14413
14414 var arrayWithHoles = createCommonjsModule(function (module) {
14415 function _arrayWithHoles(arr) {
14416 if (Array.isArray(arr)) return arr;
14417 }
14418 module.exports = _arrayWithHoles, module.exports.__esModule = true, module.exports["default"] = module.exports;
14419 });
14420
14421 unwrapExports(arrayWithHoles);
14422
14423 var nonIterableRest = createCommonjsModule(function (module) {
14424 function _nonIterableRest() {
14425 throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
14426 }
14427 module.exports = _nonIterableRest, module.exports.__esModule = true, module.exports["default"] = module.exports;
14428 });
14429
14430 unwrapExports(nonIterableRest);
14431
14432 var toArray = createCommonjsModule(function (module) {
14433 function _toArray(arr) {
14434 return arrayWithHoles(arr) || iterableToArray(arr) || unsupportedIterableToArray(arr) || nonIterableRest();
14435 }
14436 module.exports = _toArray, module.exports.__esModule = true, module.exports["default"] = module.exports;
14437 });
14438
14439 var _toArray = unwrapExports(toArray);
14440
14441 var createClass = createCommonjsModule(function (module) {
14442 function _defineProperties(target, props) {
14443 for (var i = 0; i < props.length; i++) {
14444 var descriptor = props[i];
14445 descriptor.enumerable = descriptor.enumerable || false;
14446 descriptor.configurable = true;
14447 if ("value" in descriptor) descriptor.writable = true;
14448 Object.defineProperty(target, toPropertyKey(descriptor.key), descriptor);
14449 }
14450 }
14451 function _createClass(Constructor, protoProps, staticProps) {
14452 if (protoProps) _defineProperties(Constructor.prototype, protoProps);
14453 if (staticProps) _defineProperties(Constructor, staticProps);
14454 Object.defineProperty(Constructor, "prototype", {
14455 writable: false
14456 });
14457 return Constructor;
14458 }
14459 module.exports = _createClass, module.exports.__esModule = true, module.exports["default"] = module.exports;
14460 });
14461
14462 var _createClass = unwrapExports(createClass);
14463
14464 var applyDecoratedDescriptor = createCommonjsModule(function (module) {
14465 function _applyDecoratedDescriptor(target, property, decorators, descriptor, context) {
14466 var desc = {};
14467 Object.keys(descriptor).forEach(function (key) {
14468 desc[key] = descriptor[key];
14469 });
14470 desc.enumerable = !!desc.enumerable;
14471 desc.configurable = !!desc.configurable;
14472 if ('value' in desc || desc.initializer) {
14473 desc.writable = true;
14474 }
14475 desc = decorators.slice().reverse().reduce(function (desc, decorator) {
14476 return decorator(target, property, desc) || desc;
14477 }, desc);
14478 if (context && desc.initializer !== void 0) {
14479 desc.value = desc.initializer ? desc.initializer.call(context) : void 0;
14480 desc.initializer = undefined;
14481 }
14482 if (desc.initializer === void 0) {
14483 Object.defineProperty(target, property, desc);
14484 desc = null;
14485 }
14486 return desc;
14487 }
14488 module.exports = _applyDecoratedDescriptor, module.exports.__esModule = true, module.exports["default"] = module.exports;
14489 });
14490
14491 var _applyDecoratedDescriptor = unwrapExports(applyDecoratedDescriptor);
14492
14493 var stateMachine = createCommonjsModule(function (module, exports) {
14494 /*
14495
14496 Javascript State Machine Library - https://github.com/jakesgordon/javascript-state-machine
14497
14498 Copyright (c) 2012, 2013, 2014, 2015, Jake Gordon and contributors
14499 Released under the MIT license - https://github.com/jakesgordon/javascript-state-machine/blob/master/LICENSE
14500
14501 */
14502
14503 (function () {
14504
14505 var StateMachine = {
14506
14507 //---------------------------------------------------------------------------
14508
14509 VERSION: "2.4.0",
14510
14511 //---------------------------------------------------------------------------
14512
14513 Result: {
14514 SUCCEEDED: 1, // the event transitioned successfully from one state to another
14515 NOTRANSITION: 2, // the event was successfull but no state transition was necessary
14516 CANCELLED: 3, // the event was cancelled by the caller in a beforeEvent callback
14517 PENDING: 4 // the event is asynchronous and the caller is in control of when the transition occurs
14518 },
14519
14520 Error: {
14521 INVALID_TRANSITION: 100, // caller tried to fire an event that was innapropriate in the current state
14522 PENDING_TRANSITION: 200, // caller tried to fire an event while an async transition was still pending
14523 INVALID_CALLBACK: 300 // caller provided callback function threw an exception
14524 },
14525
14526 WILDCARD: '*',
14527 ASYNC: 'async',
14528
14529 //---------------------------------------------------------------------------
14530
14531 create: function(cfg, target) {
14532
14533 var initial = (typeof cfg.initial == 'string') ? { state: cfg.initial } : cfg.initial; // allow for a simple string, or an object with { state: 'foo', event: 'setup', defer: true|false }
14534 var terminal = cfg.terminal || cfg['final'];
14535 var fsm = target || cfg.target || {};
14536 var events = cfg.events || [];
14537 var callbacks = cfg.callbacks || {};
14538 var map = {}; // track state transitions allowed for an event { event: { from: [ to ] } }
14539 var transitions = {}; // track events allowed from a state { state: [ event ] }
14540
14541 var add = function(e) {
14542 var from = Array.isArray(e.from) ? e.from : (e.from ? [e.from] : [StateMachine.WILDCARD]); // allow 'wildcard' transition if 'from' is not specified
14543 map[e.name] = map[e.name] || {};
14544 for (var n = 0 ; n < from.length ; n++) {
14545 transitions[from[n]] = transitions[from[n]] || [];
14546 transitions[from[n]].push(e.name);
14547
14548 map[e.name][from[n]] = e.to || from[n]; // allow no-op transition if 'to' is not specified
14549 }
14550 if (e.to)
14551 transitions[e.to] = transitions[e.to] || [];
14552 };
14553
14554 if (initial) {
14555 initial.event = initial.event || 'startup';
14556 add({ name: initial.event, from: 'none', to: initial.state });
14557 }
14558
14559 for(var n = 0 ; n < events.length ; n++)
14560 add(events[n]);
14561
14562 for(var name in map) {
14563 if (map.hasOwnProperty(name))
14564 fsm[name] = StateMachine.buildEvent(name, map[name]);
14565 }
14566
14567 for(var name in callbacks) {
14568 if (callbacks.hasOwnProperty(name))
14569 fsm[name] = callbacks[name];
14570 }
14571
14572 fsm.current = 'none';
14573 fsm.is = function(state) { return Array.isArray(state) ? (state.indexOf(this.current) >= 0) : (this.current === state); };
14574 fsm.can = function(event) { return !this.transition && (map[event] !== undefined) && (map[event].hasOwnProperty(this.current) || map[event].hasOwnProperty(StateMachine.WILDCARD)); };
14575 fsm.cannot = function(event) { return !this.can(event); };
14576 fsm.transitions = function() { return (transitions[this.current] || []).concat(transitions[StateMachine.WILDCARD] || []); };
14577 fsm.isFinished = function() { return this.is(terminal); };
14578 fsm.error = cfg.error || function(name, from, to, args, error, msg, e) { throw e || msg; }; // default behavior when something unexpected happens is to throw an exception, but caller can override this behavior if desired (see github issue #3 and #17)
14579 fsm.states = function() { return Object.keys(transitions).sort() };
14580
14581 if (initial && !initial.defer)
14582 fsm[initial.event]();
14583
14584 return fsm;
14585
14586 },
14587
14588 //===========================================================================
14589
14590 doCallback: function(fsm, func, name, from, to, args) {
14591 if (func) {
14592 try {
14593 return func.apply(fsm, [name, from, to].concat(args));
14594 }
14595 catch(e) {
14596 return fsm.error(name, from, to, args, StateMachine.Error.INVALID_CALLBACK, "an exception occurred in a caller-provided callback function", e);
14597 }
14598 }
14599 },
14600
14601 beforeAnyEvent: function(fsm, name, from, to, args) { return StateMachine.doCallback(fsm, fsm['onbeforeevent'], name, from, to, args); },
14602 afterAnyEvent: function(fsm, name, from, to, args) { return StateMachine.doCallback(fsm, fsm['onafterevent'] || fsm['onevent'], name, from, to, args); },
14603 leaveAnyState: function(fsm, name, from, to, args) { return StateMachine.doCallback(fsm, fsm['onleavestate'], name, from, to, args); },
14604 enterAnyState: function(fsm, name, from, to, args) { return StateMachine.doCallback(fsm, fsm['onenterstate'] || fsm['onstate'], name, from, to, args); },
14605 changeState: function(fsm, name, from, to, args) { return StateMachine.doCallback(fsm, fsm['onchangestate'], name, from, to, args); },
14606
14607 beforeThisEvent: function(fsm, name, from, to, args) { return StateMachine.doCallback(fsm, fsm['onbefore' + name], name, from, to, args); },
14608 afterThisEvent: function(fsm, name, from, to, args) { return StateMachine.doCallback(fsm, fsm['onafter' + name] || fsm['on' + name], name, from, to, args); },
14609 leaveThisState: function(fsm, name, from, to, args) { return StateMachine.doCallback(fsm, fsm['onleave' + from], name, from, to, args); },
14610 enterThisState: function(fsm, name, from, to, args) { return StateMachine.doCallback(fsm, fsm['onenter' + to] || fsm['on' + to], name, from, to, args); },
14611
14612 beforeEvent: function(fsm, name, from, to, args) {
14613 if ((false === StateMachine.beforeThisEvent(fsm, name, from, to, args)) ||
14614 (false === StateMachine.beforeAnyEvent( fsm, name, from, to, args)))
14615 return false;
14616 },
14617
14618 afterEvent: function(fsm, name, from, to, args) {
14619 StateMachine.afterThisEvent(fsm, name, from, to, args);
14620 StateMachine.afterAnyEvent( fsm, name, from, to, args);
14621 },
14622
14623 leaveState: function(fsm, name, from, to, args) {
14624 var specific = StateMachine.leaveThisState(fsm, name, from, to, args),
14625 general = StateMachine.leaveAnyState( fsm, name, from, to, args);
14626 if ((false === specific) || (false === general))
14627 return false;
14628 else if ((StateMachine.ASYNC === specific) || (StateMachine.ASYNC === general))
14629 return StateMachine.ASYNC;
14630 },
14631
14632 enterState: function(fsm, name, from, to, args) {
14633 StateMachine.enterThisState(fsm, name, from, to, args);
14634 StateMachine.enterAnyState( fsm, name, from, to, args);
14635 },
14636
14637 //===========================================================================
14638
14639 buildEvent: function(name, map) {
14640 return function() {
14641
14642 var from = this.current;
14643 var to = map[from] || (map[StateMachine.WILDCARD] != StateMachine.WILDCARD ? map[StateMachine.WILDCARD] : from) || from;
14644 var args = Array.prototype.slice.call(arguments); // turn arguments into pure array
14645
14646 if (this.transition)
14647 return this.error(name, from, to, args, StateMachine.Error.PENDING_TRANSITION, "event " + name + " inappropriate because previous transition did not complete");
14648
14649 if (this.cannot(name))
14650 return this.error(name, from, to, args, StateMachine.Error.INVALID_TRANSITION, "event " + name + " inappropriate in current state " + this.current);
14651
14652 if (false === StateMachine.beforeEvent(this, name, from, to, args))
14653 return StateMachine.Result.CANCELLED;
14654
14655 if (from === to) {
14656 StateMachine.afterEvent(this, name, from, to, args);
14657 return StateMachine.Result.NOTRANSITION;
14658 }
14659
14660 // prepare a transition method for use EITHER lower down, or by caller if they want an async transition (indicated by an ASYNC return value from leaveState)
14661 var fsm = this;
14662 this.transition = function() {
14663 fsm.transition = null; // this method should only ever be called once
14664 fsm.current = to;
14665 StateMachine.enterState( fsm, name, from, to, args);
14666 StateMachine.changeState(fsm, name, from, to, args);
14667 StateMachine.afterEvent( fsm, name, from, to, args);
14668 return StateMachine.Result.SUCCEEDED;
14669 };
14670 this.transition.cancel = function() { // provide a way for caller to cancel async transition if desired (issue #22)
14671 fsm.transition = null;
14672 StateMachine.afterEvent(fsm, name, from, to, args);
14673 };
14674
14675 var leave = StateMachine.leaveState(this, name, from, to, args);
14676 if (false === leave) {
14677 this.transition = null;
14678 return StateMachine.Result.CANCELLED;
14679 }
14680 else if (StateMachine.ASYNC === leave) {
14681 return StateMachine.Result.PENDING;
14682 }
14683 else {
14684 if (this.transition) // need to check in case user manually called transition() but forgot to return StateMachine.ASYNC
14685 return this.transition();
14686 }
14687
14688 };
14689 }
14690
14691 }; // StateMachine
14692
14693 //===========================================================================
14694
14695 //======
14696 // NODE
14697 //======
14698 {
14699 if ( module.exports) {
14700 exports = module.exports = StateMachine;
14701 }
14702 exports.StateMachine = StateMachine;
14703 }
14704
14705 }());
14706 });
14707 var stateMachine_1 = stateMachine.StateMachine;
14708
14709 var adapters = {};
14710 var getAdapter = function getAdapter(name) {
14711 var adapter = adapters[name];
14712 if (adapter === undefined) {
14713 throw new Error("".concat(name, " adapter is not configured"));
14714 }
14715 return adapter;
14716 };
14717
14718 /**
14719 * 指定 Adapters
14720 * @function
14721 * @memberof module:leancloud-realtime
14722 * @param {Adapters} newAdapters Adapters 的类型请参考 {@link https://url.leanapp.cn/adapter-type-definitions @leancloud/adapter-types} 中的定义
14723 */
14724 var setAdapters = function setAdapters(newAdapters) {
14725 Object.assign(adapters, newAdapters);
14726 };
14727
14728 /** Built-in value references. */
14729 var getPrototype = _overArg(Object.getPrototypeOf, Object);
14730
14731 var _getPrototype = getPrototype;
14732
14733 /** `Object#toString` result references. */
14734 var objectTag$1 = '[object Object]';
14735
14736 /** Used for built-in method references. */
14737 var funcProto = Function.prototype,
14738 objectProto$6 = Object.prototype;
14739
14740 /** Used to resolve the decompiled source of functions. */
14741 var funcToString = funcProto.toString;
14742
14743 /** Used to check objects for own properties. */
14744 var hasOwnProperty$4 = objectProto$6.hasOwnProperty;
14745
14746 /** Used to infer the `Object` constructor. */
14747 var objectCtorString = funcToString.call(Object);
14748
14749 /**
14750 * Checks if `value` is a plain object, that is, an object created by the
14751 * `Object` constructor or one with a `[[Prototype]]` of `null`.
14752 *
14753 * @static
14754 * @memberOf _
14755 * @since 0.8.0
14756 * @category Lang
14757 * @param {*} value The value to check.
14758 * @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
14759 * @example
14760 *
14761 * function Foo() {
14762 * this.a = 1;
14763 * }
14764 *
14765 * _.isPlainObject(new Foo);
14766 * // => false
14767 *
14768 * _.isPlainObject([1, 2, 3]);
14769 * // => false
14770 *
14771 * _.isPlainObject({ 'x': 0, 'y': 0 });
14772 * // => true
14773 *
14774 * _.isPlainObject(Object.create(null));
14775 * // => true
14776 */
14777 function isPlainObject(value) {
14778 if (!isObjectLike_1(value) || _baseGetTag(value) != objectTag$1) {
14779 return false;
14780 }
14781 var proto = _getPrototype(value);
14782 if (proto === null) {
14783 return true;
14784 }
14785 var Ctor = hasOwnProperty$4.call(proto, 'constructor') && proto.constructor;
14786 return typeof Ctor == 'function' && Ctor instanceof Ctor &&
14787 funcToString.call(Ctor) == objectCtorString;
14788 }
14789
14790 var isPlainObject_1 = isPlainObject;
14791
14792 /* eslint-disable */
14793 var global$1 = typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : {};
14794
14795 var EXPIRED = Symbol('expired');
14796 var debug = browser('LC:Expirable');
14797 var Expirable = /*#__PURE__*/function () {
14798 function Expirable(value, ttl) {
14799 this.originalValue = value;
14800 if (typeof ttl === 'number') {
14801 this.expiredAt = Date.now() + ttl;
14802 }
14803 }
14804 _createClass(Expirable, [{
14805 key: "value",
14806 get: function get() {
14807 var expired = this.expiredAt && this.expiredAt <= Date.now();
14808 if (expired) debug("expired: ".concat(this.originalValue));
14809 return expired ? EXPIRED : this.originalValue;
14810 }
14811 }]);
14812 return Expirable;
14813 }();
14814 Expirable.EXPIRED = EXPIRED;
14815
14816 var debug$1 = browser('LC:Cache');
14817 var Cache = /*#__PURE__*/function () {
14818 function Cache() {
14819 var name = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'anonymous';
14820 this.name = name;
14821 this._map = {};
14822 }
14823 var _proto = Cache.prototype;
14824 _proto.get = function get(key) {
14825 var cache = this._map[key];
14826 if (cache) {
14827 var value = cache.value;
14828 if (value !== Expirable.EXPIRED) {
14829 debug$1('[%s] hit: %s', this.name, key);
14830 return value;
14831 }
14832 delete this._map[key];
14833 }
14834 debug$1("[".concat(this.name, "] missed: ").concat(key));
14835 return null;
14836 };
14837 _proto.set = function set(key, value, ttl) {
14838 debug$1('[%s] set: %s %d', this.name, key, ttl);
14839 this._map[key] = new Expirable(value, ttl);
14840 };
14841 return Cache;
14842 }();
14843
14844 function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
14845 function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
14846
14847 /**
14848 * 调试日志控制器
14849 * @const
14850 * @memberof module:leancloud-realtime
14851 * @example
14852 * debug.enable(); // 启用调试日志
14853 * debug.disable(); // 关闭调试日志
14854 */
14855 var debug$2 = {
14856 enable: function enable() {
14857 var namespaces = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'LC*';
14858 return browser.enable(namespaces);
14859 },
14860 disable: browser.disable
14861 };
14862 var tryAll = function tryAll(promiseConstructors) {
14863 var promise = new Promise(promiseConstructors[0]);
14864 if (promiseConstructors.length === 1) {
14865 return promise;
14866 }
14867 return promise["catch"](function () {
14868 return tryAll(promiseConstructors.slice(1));
14869 });
14870 };
14871
14872 // eslint-disable-next-line no-sequences
14873 var tap = function tap(interceptor) {
14874 return function (value) {
14875 return interceptor(value), value;
14876 };
14877 };
14878 var finalize = function finalize(callback) {
14879 return [
14880 // eslint-disable-next-line no-sequences
14881 function (value) {
14882 return callback(), value;
14883 }, function (error) {
14884 callback();
14885 throw error;
14886 }];
14887 };
14888
14889 /**
14890 * 将对象转换为 Date,支持 string、number、ProtoBuf Long 以及 LeanCloud 的 Date 类型,
14891 * 其他情况下(包括对象为 falsy)返回原值。
14892 * @private
14893 */
14894 var decodeDate = function decodeDate(date) {
14895 if (!date) return date;
14896 if (typeof date === 'string' || typeof date === 'number') {
14897 return new Date(date);
14898 }
14899 if (date.__type === 'Date' && date.iso) {
14900 return new Date(date.iso);
14901 }
14902 // Long
14903 if (typeof date.toNumber === 'function') {
14904 return new Date(date.toNumber());
14905 }
14906 return date;
14907 };
14908 /**
14909 * 获取 Date 的毫秒数,如果不是一个 Date 返回 undefined。
14910 * @private
14911 */
14912 var getTime = function getTime(date) {
14913 return date && date.getTime ? date.getTime() : undefined;
14914 };
14915
14916 /**
14917 * 解码对象中的 LeanCloud 数据结构。
14918 * 目前仅会处理 Date 类型。
14919 * @private
14920 */
14921 var decode = function decode(value) {
14922 if (!value) return value;
14923 if (value.__type === 'Date' && value.iso) {
14924 return new Date(value.iso);
14925 }
14926 if (Array.isArray(value)) {
14927 return value.map(decode);
14928 }
14929 if (isPlainObject_1(value)) {
14930 return Object.keys(value).reduce(function (result, key) {
14931 return _objectSpread(_objectSpread({}, result), {}, _defineProperty({}, key, decode(value[key])));
14932 }, {});
14933 }
14934 return value;
14935 };
14936 /**
14937 * 将对象中的特殊类型编码为 LeanCloud 数据结构。
14938 * 目前仅会处理 Date 类型。
14939 * @private
14940 */
14941 var encode = function encode(value) {
14942 if (value instanceof Date) return {
14943 __type: 'Date',
14944 iso: value.toJSON()
14945 };
14946 if (Array.isArray(value)) {
14947 return value.map(encode);
14948 }
14949 if (isPlainObject_1(value)) {
14950 return Object.keys(value).reduce(function (result, key) {
14951 return _objectSpread(_objectSpread({}, result), {}, _defineProperty({}, key, encode(value[key])));
14952 }, {});
14953 }
14954 return value;
14955 };
14956 var keyRemap = function keyRemap(keymap, obj) {
14957 return Object.keys(obj).reduce(function (newObj, key) {
14958 var newKey = keymap[key] || key;
14959 return Object.assign(newObj, _defineProperty({}, newKey, obj[key]));
14960 }, {});
14961 };
14962 var isIE10 = global$1.navigator && global$1.navigator.userAgent && global$1.navigator.userAgent.indexOf('MSIE 10.') !== -1;
14963
14964 /* eslint-disable no-proto */
14965 var getStaticProperty = function getStaticProperty(klass, property) {
14966 return klass[property] || (klass.__proto__ ? getStaticProperty(klass.__proto__, property) : undefined);
14967 };
14968 /* eslint-enable no-proto */
14969
14970 var union = function union(a, b) {
14971 return Array.from(new Set([].concat(_toConsumableArray(a), _toConsumableArray(b))));
14972 };
14973 var difference = function difference(a, b) {
14974 return Array.from(function (bSet) {
14975 return new Set(a.filter(function (x) {
14976 return !bSet.has(x);
14977 }));
14978 }(new Set(b)));
14979 };
14980 var map = new WeakMap();
14981
14982 // protected property helper
14983 var internal = function internal(object) {
14984 if (!map.has(object)) {
14985 map.set(object, {});
14986 }
14987 return map.get(object);
14988 };
14989 var compact = function compact(obj, filter) {
14990 if (!isPlainObject_1(obj)) return obj;
14991 var object = _objectSpread({}, obj);
14992 Object.keys(object).forEach(function (prop) {
14993 var value = object[prop];
14994 if (value === filter) {
14995 delete object[prop];
14996 } else {
14997 object[prop] = compact(value, filter);
14998 }
14999 });
15000 return object;
15001 };
15002
15003 // debug utility
15004 var removeNull = function removeNull(obj) {
15005 return compact(obj, null);
15006 };
15007 var trim = function trim(message) {
15008 return removeNull(JSON.parse(JSON.stringify(message)));
15009 };
15010 var ensureArray = function ensureArray(target) {
15011 if (Array.isArray(target)) {
15012 return target;
15013 }
15014 if (target === undefined || target === null) {
15015 return [];
15016 }
15017 return [target];
15018 };
15019 var setValue = function setValue(target, key, value) {
15020 // '.' is not allowed in Class keys, escaping is not in concern now.
15021 var segs = key.split('.');
15022 var lastSeg = segs.pop();
15023 var currentTarget = target;
15024 segs.forEach(function (seg) {
15025 if (currentTarget[seg] === undefined) currentTarget[seg] = {};
15026 currentTarget = currentTarget[seg];
15027 });
15028 currentTarget[lastSeg] = value;
15029 return target;
15030 };
15031 var isWeapp =
15032 // eslint-disable-next-line no-undef
15033 (typeof wx === "undefined" ? "undefined" : _typeof(wx)) === 'object' && typeof wx.connectSocket === 'function';
15034
15035 // throttle decorator
15036 var throttle = function throttle(wait) {
15037 return function (target, property, descriptor) {
15038 var callback = descriptor.value;
15039 // very naive, internal use only
15040 if (callback.length) {
15041 throw new Error('throttled function should not accept any arguments');
15042 }
15043 return _objectSpread(_objectSpread({}, descriptor), {}, {
15044 value: function value() {
15045 var _this = this;
15046 var _internal = internal(this),
15047 throttleMeta = _internal.throttleMeta;
15048 if (!throttleMeta) {
15049 throttleMeta = {};
15050 internal(this).throttleMeta = throttleMeta;
15051 }
15052 var _throttleMeta = throttleMeta,
15053 propertyMeta = _throttleMeta[property];
15054 if (!propertyMeta) {
15055 propertyMeta = {};
15056 throttleMeta[property] = propertyMeta;
15057 }
15058 var _propertyMeta = propertyMeta,
15059 _propertyMeta$previou = _propertyMeta.previouseTimestamp,
15060 previouseTimestamp = _propertyMeta$previou === void 0 ? 0 : _propertyMeta$previou,
15061 timeout = _propertyMeta.timeout;
15062 var now = Date.now();
15063 var remainingTime = wait - (now - previouseTimestamp);
15064 if (remainingTime <= 0) {
15065 throttleMeta[property].previouseTimestamp = now;
15066 callback.apply(this);
15067 } else if (!timeout) {
15068 propertyMeta.timeout = setTimeout(function () {
15069 propertyMeta.previouseTimestamp = Date.now();
15070 delete propertyMeta.timeout;
15071 callback.apply(_this);
15072 }, remainingTime);
15073 }
15074 }
15075 });
15076 };
15077 };
15078 var isCNApp = function isCNApp(appId) {
15079 return appId.slice(-9) !== '-MdYXbMMI';
15080 };
15081 var equalBuffer = function equalBuffer(buffer1, buffer2) {
15082 if (!buffer1 || !buffer2) return false;
15083 if (buffer1.byteLength !== buffer2.byteLength) return false;
15084 var a = new Uint8Array(buffer1);
15085 var b = new Uint8Array(buffer2);
15086 return !a.some(function (value, index) {
15087 return value !== b[index];
15088 });
15089 };
15090
15091 var _class;
15092 function ownKeys$1(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
15093 function _objectSpread$1(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys$1(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$1(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
15094 var debug$3 = browser('LC:WebSocketPlus');
15095 var OPEN = 'open';
15096 var DISCONNECT = 'disconnect';
15097 var RECONNECT = 'reconnect';
15098 var RETRY = 'retry';
15099 var SCHEDULE = 'schedule';
15100 var OFFLINE = 'offline';
15101 var ONLINE = 'online';
15102 var ERROR = 'error';
15103 var MESSAGE = 'message';
15104 var HEARTBEAT_TIME = 180000;
15105 var TIMEOUT_TIME = 380000;
15106 var DEFAULT_RETRY_STRATEGY = function DEFAULT_RETRY_STRATEGY(attempt) {
15107 return Math.min(1000 * Math.pow(2, attempt), 300000);
15108 };
15109 var requireConnected = function requireConnected(target, name, descriptor) {
15110 return _objectSpread$1(_objectSpread$1({}, descriptor), {}, {
15111 value: function requireConnectedWrapper() {
15112 var _descriptor$value;
15113 this.checkConnectionAvailability(name);
15114 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
15115 args[_key] = arguments[_key];
15116 }
15117 return (_descriptor$value = descriptor.value).call.apply(_descriptor$value, [this].concat(args));
15118 }
15119 });
15120 };
15121 var WebSocketPlus = (_class = /*#__PURE__*/function (_EventEmitter) {
15122 _inheritsLoose(WebSocketPlus, _EventEmitter);
15123 function WebSocketPlus(getUrls, protocol) {
15124 var _this;
15125 _this = _EventEmitter.call(this) || this;
15126 _this.init();
15127 _this._protocol = protocol;
15128 Promise.resolve(typeof getUrls === 'function' ? getUrls() : getUrls).then(ensureArray).then(function (urls) {
15129 _this._urls = urls;
15130 return _this._open();
15131 }).then(function () {
15132 _this.__postponeTimeoutTimer = _this._postponeTimeoutTimer.bind(_assertThisInitialized(_this));
15133 if (global$1.addEventListener) {
15134 _this.__pause = function () {
15135 if (_this.can('pause')) _this.pause();
15136 };
15137 _this.__resume = function () {
15138 if (_this.can('resume')) _this.resume();
15139 };
15140 global$1.addEventListener('offline', _this.__pause);
15141 global$1.addEventListener('online', _this.__resume);
15142 }
15143 _this.open();
15144 })["catch"](_this["throw"].bind(_assertThisInitialized(_this)));
15145 return _this;
15146 }
15147 var _proto = WebSocketPlus.prototype;
15148 _proto._open = function _open() {
15149 var _this2 = this;
15150 return this._createWs(this._urls, this._protocol).then(function (ws) {
15151 var _this2$_urls = _toArray(_this2._urls),
15152 first = _this2$_urls[0],
15153 reset = _this2$_urls.slice(1);
15154 _this2._urls = [].concat(_toConsumableArray(reset), [first]);
15155 return ws;
15156 });
15157 };
15158 _proto._createWs = function _createWs(urls, protocol) {
15159 var _this3 = this;
15160 return tryAll(urls.map(function (url) {
15161 return function (resolve, reject) {
15162 debug$3("connect [".concat(url, "] ").concat(protocol));
15163 var WebSocket = getAdapter('WebSocket');
15164 var ws = protocol ? new WebSocket(url, protocol) : new WebSocket(url);
15165 ws.binaryType = _this3.binaryType || 'arraybuffer';
15166 ws.onopen = function () {
15167 return resolve(ws);
15168 };
15169 ws.onclose = function (error) {
15170 if (error instanceof Error) {
15171 return reject(error);
15172 }
15173 // in browser, error event is useless
15174 return reject(new Error("Failed to connect [".concat(url, "]")));
15175 };
15176 ws.onerror = ws.onclose;
15177 };
15178 })).then(function (ws) {
15179 _this3._ws = ws;
15180 _this3._ws.onclose = _this3._handleClose.bind(_this3);
15181 _this3._ws.onmessage = _this3._handleMessage.bind(_this3);
15182 return ws;
15183 });
15184 };
15185 _proto._destroyWs = function _destroyWs() {
15186 var ws = this._ws;
15187 if (!ws) return;
15188 ws.onopen = null;
15189 ws.onclose = null;
15190 ws.onerror = null;
15191 ws.onmessage = null;
15192 this._ws = null;
15193 ws.close();
15194 }
15195
15196 // eslint-disable-next-line class-methods-use-this
15197 ;
15198 _proto.onbeforeevent = function onbeforeevent(event, from, to) {
15199 for (var _len2 = arguments.length, payload = new Array(_len2 > 3 ? _len2 - 3 : 0), _key2 = 3; _key2 < _len2; _key2++) {
15200 payload[_key2 - 3] = arguments[_key2];
15201 }
15202 debug$3("".concat(event, ": ").concat(from, " -> ").concat(to, " %o"), payload);
15203 };
15204 _proto.onopen = function onopen() {
15205 this.emit(OPEN);
15206 };
15207 _proto.onconnected = function onconnected() {
15208 this._startConnectionKeeper();
15209 };
15210 _proto.onleaveconnected = function onleaveconnected(event, from, to) {
15211 this._stopConnectionKeeper();
15212 this._destroyWs();
15213 if (to === 'offline' || to === 'disconnected') {
15214 this.emit(DISCONNECT);
15215 }
15216 };
15217 _proto.onpause = function onpause() {
15218 this.emit(OFFLINE);
15219 };
15220 _proto.onbeforeresume = function onbeforeresume() {
15221 this.emit(ONLINE);
15222 };
15223 _proto.onreconnect = function onreconnect() {
15224 this.emit(RECONNECT);
15225 };
15226 _proto.ondisconnected = function ondisconnected(event, from, to) {
15227 var _this4 = this;
15228 var attempt = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;
15229 var delay = from === OFFLINE ? 0 : DEFAULT_RETRY_STRATEGY.call(null, attempt);
15230 debug$3("schedule attempt=".concat(attempt, " delay=").concat(delay));
15231 this.emit(SCHEDULE, attempt, delay);
15232 if (this.__scheduledRetry) {
15233 clearTimeout(this.__scheduledRetry);
15234 }
15235 this.__scheduledRetry = setTimeout(function () {
15236 if (_this4.is('disconnected')) {
15237 _this4.retry(attempt);
15238 }
15239 }, delay);
15240 };
15241 _proto.onretry = function onretry(event, from, to) {
15242 var _this5 = this;
15243 var attempt = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;
15244 this.emit(RETRY, attempt);
15245 this._open().then(function () {
15246 return _this5.can('reconnect') && _this5.reconnect();
15247 }, function () {
15248 return _this5.can('fail') && _this5.fail(attempt + 1);
15249 });
15250 };
15251 _proto.onerror = function onerror(event, from, to, error) {
15252 this.emit(ERROR, error);
15253 };
15254 _proto.onclose = function onclose() {
15255 if (global$1.removeEventListener) {
15256 if (this.__pause) global$1.removeEventListener('offline', this.__pause);
15257 if (this.__resume) global$1.removeEventListener('online', this.__resume);
15258 }
15259 };
15260 _proto.checkConnectionAvailability = function checkConnectionAvailability() {
15261 var name = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'API';
15262 if (!this.is('connected')) {
15263 var currentState = this.current;
15264 console.warn("".concat(name, " should not be called when the connection is ").concat(currentState));
15265 if (this.is('disconnected') || this.is('reconnecting')) {
15266 console.warn('disconnect and reconnect event should be handled to avoid such calls.');
15267 }
15268 throw new Error('Connection unavailable');
15269 }
15270 }
15271
15272 // jsdoc-ignore-start
15273 ;
15274 _proto.
15275 // jsdoc-ignore-end
15276 _ping = function _ping() {
15277 debug$3('ping');
15278 try {
15279 this.ping();
15280 } catch (error) {
15281 console.warn("websocket ping error: ".concat(error.message));
15282 }
15283 };
15284 _proto.ping = function ping() {
15285 if (this._ws.ping) {
15286 this._ws.ping();
15287 } else {
15288 console.warn("The WebSocket implement does not support sending ping frame.\n Override ping method to use application defined ping/pong mechanism.");
15289 }
15290 };
15291 _proto._postponeTimeoutTimer = function _postponeTimeoutTimer() {
15292 var _this6 = this;
15293 debug$3('_postponeTimeoutTimer');
15294 this._clearTimeoutTimers();
15295 this._timeoutTimer = setTimeout(function () {
15296 debug$3('timeout');
15297 _this6.disconnect();
15298 }, TIMEOUT_TIME);
15299 };
15300 _proto._clearTimeoutTimers = function _clearTimeoutTimers() {
15301 if (this._timeoutTimer) {
15302 clearTimeout(this._timeoutTimer);
15303 }
15304 };
15305 _proto._startConnectionKeeper = function _startConnectionKeeper() {
15306 debug$3('start connection keeper');
15307 this._heartbeatTimer = setInterval(this._ping.bind(this), HEARTBEAT_TIME);
15308 var addListener = this._ws.addListener || this._ws.addEventListener;
15309 if (!addListener) {
15310 debug$3('connection keeper disabled due to the lack of #addEventListener.');
15311 return;
15312 }
15313 addListener.call(this._ws, 'message', this.__postponeTimeoutTimer);
15314 addListener.call(this._ws, 'pong', this.__postponeTimeoutTimer);
15315 this._postponeTimeoutTimer();
15316 };
15317 _proto._stopConnectionKeeper = function _stopConnectionKeeper() {
15318 debug$3('stop connection keeper');
15319 // websockets/ws#489
15320 var removeListener = this._ws.removeListener || this._ws.removeEventListener;
15321 if (removeListener) {
15322 removeListener.call(this._ws, 'message', this.__postponeTimeoutTimer);
15323 removeListener.call(this._ws, 'pong', this.__postponeTimeoutTimer);
15324 this._clearTimeoutTimers();
15325 }
15326 if (this._heartbeatTimer) {
15327 clearInterval(this._heartbeatTimer);
15328 }
15329 };
15330 _proto._handleClose = function _handleClose(event) {
15331 debug$3("ws closed [".concat(event.code, "] ").concat(event.reason));
15332 // socket closed manually, ignore close event.
15333 if (this.isFinished()) return;
15334 this.handleClose(event);
15335 };
15336 _proto.handleClose = function handleClose() {
15337 // reconnect
15338 this.disconnect();
15339 }
15340
15341 // jsdoc-ignore-start
15342 ;
15343 _proto.
15344 // jsdoc-ignore-end
15345 send = function send(data) {
15346 debug$3('send', data);
15347 this._ws.send(data);
15348 };
15349 _proto._handleMessage = function _handleMessage(event) {
15350 debug$3('message', event.data);
15351 this.handleMessage(event.data);
15352 };
15353 _proto.handleMessage = function handleMessage(message) {
15354 this.emit(MESSAGE, message);
15355 };
15356 _createClass(WebSocketPlus, [{
15357 key: "urls",
15358 get: function get() {
15359 return this._urls;
15360 },
15361 set: function set(urls) {
15362 this._urls = ensureArray(urls);
15363 }
15364 }]);
15365 return WebSocketPlus;
15366 }(eventemitter3), (_applyDecoratedDescriptor(_class.prototype, "_ping", [requireConnected], Object.getOwnPropertyDescriptor(_class.prototype, "_ping"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "send", [requireConnected], Object.getOwnPropertyDescriptor(_class.prototype, "send"), _class.prototype)), _class);
15367 stateMachine.create({
15368 target: WebSocketPlus.prototype,
15369 initial: {
15370 state: 'initialized',
15371 event: 'init',
15372 defer: true
15373 },
15374 terminal: 'closed',
15375 events: [{
15376 name: 'open',
15377 from: 'initialized',
15378 to: 'connected'
15379 }, {
15380 name: 'disconnect',
15381 from: 'connected',
15382 to: 'disconnected'
15383 }, {
15384 name: 'retry',
15385 from: 'disconnected',
15386 to: 'reconnecting'
15387 }, {
15388 name: 'fail',
15389 from: 'reconnecting',
15390 to: 'disconnected'
15391 }, {
15392 name: 'reconnect',
15393 from: 'reconnecting',
15394 to: 'connected'
15395 }, {
15396 name: 'pause',
15397 from: ['connected', 'disconnected', 'reconnecting'],
15398 to: 'offline'
15399 }, {}, {
15400 name: 'resume',
15401 from: 'offline',
15402 to: 'disconnected'
15403 }, {
15404 name: 'close',
15405 from: ['connected', 'disconnected', 'reconnecting', 'offline'],
15406 to: 'closed'
15407 }, {
15408 name: 'throw',
15409 from: '*',
15410 to: 'error'
15411 }]
15412 });
15413
15414 var error = Object.freeze({
15415 1000: {
15416 name: 'CLOSE_NORMAL'
15417 },
15418 1006: {
15419 name: 'CLOSE_ABNORMAL'
15420 },
15421 4100: {
15422 name: 'APP_NOT_AVAILABLE',
15423 message: 'App not exists or realtime message service is disabled.'
15424 },
15425 4102: {
15426 name: 'SIGNATURE_FAILED',
15427 message: 'Login signature mismatch.'
15428 },
15429 4103: {
15430 name: 'INVALID_LOGIN',
15431 message: 'Malformed clientId.'
15432 },
15433 4105: {
15434 name: 'SESSION_REQUIRED',
15435 message: 'Message sent before session opened.'
15436 },
15437 4107: {
15438 name: 'READ_TIMEOUT'
15439 },
15440 4108: {
15441 name: 'LOGIN_TIMEOUT'
15442 },
15443 4109: {
15444 name: 'FRAME_TOO_LONG'
15445 },
15446 4110: {
15447 name: 'INVALID_ORIGIN',
15448 message: 'Access denied by domain whitelist.'
15449 },
15450 4111: {
15451 name: 'SESSION_CONFLICT'
15452 },
15453 4112: {
15454 name: 'SESSION_TOKEN_EXPIRED'
15455 },
15456 4113: {
15457 name: 'APP_QUOTA_EXCEEDED',
15458 message: 'The daily active users limit exceeded.'
15459 },
15460 4116: {
15461 name: 'MESSAGE_SENT_QUOTA_EXCEEDED',
15462 message: 'Command sent too fast.'
15463 },
15464 4200: {
15465 name: 'INTERNAL_ERROR',
15466 message: 'Internal error, please contact LeanCloud for support.'
15467 },
15468 4301: {
15469 name: 'CONVERSATION_API_FAILED',
15470 message: 'Upstream Conversatoin API failed, see error.detail for details.'
15471 },
15472 4302: {
15473 name: 'CONVERSATION_SIGNATURE_FAILED',
15474 message: 'Conversation action signature mismatch.'
15475 },
15476 4303: {
15477 name: 'CONVERSATION_NOT_FOUND'
15478 },
15479 4304: {
15480 name: 'CONVERSATION_FULL'
15481 },
15482 4305: {
15483 name: 'CONVERSATION_REJECTED_BY_APP',
15484 message: 'Conversation action rejected by hook.'
15485 },
15486 4306: {
15487 name: 'CONVERSATION_UPDATE_FAILED'
15488 },
15489 4307: {
15490 name: 'CONVERSATION_READ_ONLY'
15491 },
15492 4308: {
15493 name: 'CONVERSATION_NOT_ALLOWED'
15494 },
15495 4309: {
15496 name: 'CONVERSATION_UPDATE_REJECTED',
15497 message: 'Conversation update rejected because the client is not a member.'
15498 },
15499 4310: {
15500 name: 'CONVERSATION_QUERY_FAILED',
15501 message: 'Conversation query failed because it is too expansive.'
15502 },
15503 4311: {
15504 name: 'CONVERSATION_LOG_FAILED'
15505 },
15506 4312: {
15507 name: 'CONVERSATION_LOG_REJECTED',
15508 message: 'Message query rejected because the client is not a member of the conversation.'
15509 },
15510 4313: {
15511 name: 'SYSTEM_CONVERSATION_REQUIRED'
15512 },
15513 4314: {
15514 name: 'NORMAL_CONVERSATION_REQUIRED'
15515 },
15516 4315: {
15517 name: 'CONVERSATION_BLACKLISTED',
15518 message: 'Blacklisted in the conversation.'
15519 },
15520 4316: {
15521 name: 'TRANSIENT_CONVERSATION_REQUIRED'
15522 },
15523 4317: {
15524 name: 'CONVERSATION_MEMBERSHIP_REQUIRED'
15525 },
15526 4318: {
15527 name: 'CONVERSATION_API_QUOTA_EXCEEDED',
15528 message: 'LeanCloud API quota exceeded. You may upgrade your plan.'
15529 },
15530 4323: {
15531 name: 'TEMPORARY_CONVERSATION_EXPIRED',
15532 message: 'Temporary conversation expired or does not exist.'
15533 },
15534 4401: {
15535 name: 'INVALID_MESSAGING_TARGET',
15536 message: 'Conversation does not exist or client is not a member.'
15537 },
15538 4402: {
15539 name: 'MESSAGE_REJECTED_BY_APP',
15540 message: 'Message rejected by hook.'
15541 },
15542 4403: {
15543 name: 'MESSAGE_OWNERSHIP_REQUIRED'
15544 },
15545 4404: {
15546 name: 'MESSAGE_NOT_FOUND'
15547 },
15548 4405: {
15549 name: 'MESSAGE_UPDATE_REJECTED_BY_APP',
15550 message: 'Message update rejected by hook.'
15551 },
15552 4406: {
15553 name: 'MESSAGE_EDIT_DISABLED'
15554 },
15555 4407: {
15556 name: 'MESSAGE_RECALL_DISABLED'
15557 },
15558 5130: {
15559 name: 'OWNER_PROMOTION_NOT_ALLOWED',
15560 message: "Updating a member's role to owner is not allowed."
15561 }
15562 });
15563 var ErrorCode = Object.freeze(Object.keys(error).reduce(function (result, code) {
15564 return Object.assign(result, _defineProperty({}, error[code].name, Number(code)));
15565 }, {}));
15566 var createError = function createError(_ref) {
15567 var code = _ref.code,
15568 reason = _ref.reason,
15569 appCode = _ref.appCode,
15570 detail = _ref.detail,
15571 errorMessage = _ref.error;
15572 var message = reason || detail || errorMessage;
15573 var name = reason;
15574 if (!message && error[code]) {
15575 name = error[code].name;
15576 message = error[code].message || name;
15577 }
15578 if (!message) {
15579 message = "Unknow Error: ".concat(code);
15580 }
15581 var err = new Error(message);
15582 return Object.assign(err, {
15583 code: code,
15584 appCode: appCode,
15585 detail: detail,
15586 name: name
15587 });
15588 };
15589
15590 var debug$4 = browser('LC:Connection');
15591 var COMMAND_TIMEOUT = 20000;
15592 var EXPIRE = Symbol('expire');
15593 var isIdempotentCommand = function isIdempotentCommand(command) {
15594 return !(command.cmd === CommandType.direct || command.cmd === CommandType.session && command.op === OpType.open || command.cmd === CommandType.conv && (command.op === OpType.start || command.op === OpType.update || command.op === OpType.members));
15595 };
15596 var Connection = /*#__PURE__*/function (_WebSocketPlus) {
15597 _inheritsLoose(Connection, _WebSocketPlus);
15598 function Connection(getUrl, _ref) {
15599 var _this;
15600 var format = _ref.format,
15601 version = _ref.version;
15602 debug$4('initializing Connection');
15603 var protocolString = "lc.".concat(format, ".").concat(version);
15604 _this = _WebSocketPlus.call(this, getUrl, protocolString) || this;
15605 _this._protocolFormat = format;
15606 _this._commands = {};
15607 _this._serialId = 0;
15608 return _this;
15609 }
15610 var _proto = Connection.prototype;
15611 _proto.send = /*#__PURE__*/function () {
15612 var _send = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee(command) {
15613 var _this2 = this;
15614 var waitingForRespond,
15615 buffer,
15616 serialId,
15617 duplicatedCommand,
15618 message,
15619 promise,
15620 _args = arguments;
15621 return regenerator.wrap(function _callee$(_context) {
15622 while (1) switch (_context.prev = _context.next) {
15623 case 0:
15624 waitingForRespond = _args.length > 1 && _args[1] !== undefined ? _args[1] : true;
15625 if (!waitingForRespond) {
15626 _context.next = 11;
15627 break;
15628 }
15629 if (!isIdempotentCommand(command)) {
15630 _context.next = 8;
15631 break;
15632 }
15633 buffer = command.toArrayBuffer();
15634 duplicatedCommand = values_1(this._commands).find(function (_ref2) {
15635 var targetBuffer = _ref2.buffer,
15636 targetCommand = _ref2.command;
15637 return targetCommand.cmd === command.cmd && targetCommand.op === command.op && equalBuffer(targetBuffer, buffer);
15638 });
15639 if (!duplicatedCommand) {
15640 _context.next = 8;
15641 break;
15642 }
15643 console.warn("Duplicated command [cmd:".concat(command.cmd, " op:").concat(command.op, "] is throttled."));
15644 return _context.abrupt("return", duplicatedCommand.promise);
15645 case 8:
15646 this._serialId += 1;
15647 serialId = this._serialId;
15648 command.i = serialId; // eslint-disable-line no-param-reassign
15649 case 11:
15650 if (debug$4.enabled) debug$4('↑ %O sent', trim(command));
15651 if (this._protocolFormat === 'proto2base64') {
15652 message = command.toBase64();
15653 } else if (command.toArrayBuffer) {
15654 message = command.toArrayBuffer();
15655 }
15656 if (message) {
15657 _context.next = 15;
15658 break;
15659 }
15660 throw new TypeError("".concat(command, " is not a GenericCommand"));
15661 case 15:
15662 _WebSocketPlus.prototype.send.call(this, message);
15663 if (waitingForRespond) {
15664 _context.next = 18;
15665 break;
15666 }
15667 return _context.abrupt("return", undefined);
15668 case 18:
15669 promise = new Promise(function (resolve, reject) {
15670 _this2._commands[serialId] = {
15671 command: command,
15672 buffer: buffer,
15673 resolve: resolve,
15674 reject: reject,
15675 timeout: setTimeout(function () {
15676 if (_this2._commands[serialId]) {
15677 if (debug$4.enabled) debug$4('✗ %O timeout', trim(command));
15678 reject(createError({
15679 error: "Command Timeout [cmd:".concat(command.cmd, " op:").concat(command.op, "]"),
15680 name: 'COMMAND_TIMEOUT'
15681 }));
15682 delete _this2._commands[serialId];
15683 }
15684 }, COMMAND_TIMEOUT)
15685 };
15686 });
15687 this._commands[serialId].promise = promise;
15688 return _context.abrupt("return", promise);
15689 case 21:
15690 case "end":
15691 return _context.stop();
15692 }
15693 }, _callee, this);
15694 }));
15695 function send(_x) {
15696 return _send.apply(this, arguments);
15697 }
15698 return send;
15699 }();
15700 _proto.handleMessage = function handleMessage(msg) {
15701 var message;
15702 try {
15703 message = GenericCommand.decode(msg);
15704 if (debug$4.enabled) debug$4('↓ %O received', trim(message));
15705 } catch (e) {
15706 console.warn('Decode message failed:', e.message, msg);
15707 return;
15708 }
15709 var serialId = message.i;
15710 if (serialId) {
15711 if (this._commands[serialId]) {
15712 clearTimeout(this._commands[serialId].timeout);
15713 if (message.cmd === CommandType.error) {
15714 this._commands[serialId].reject(createError(message.errorMessage));
15715 } else {
15716 this._commands[serialId].resolve(message);
15717 }
15718 delete this._commands[serialId];
15719 } else {
15720 console.warn("Unexpected command received with serialId [".concat(serialId, "],\n which have timed out or never been requested."));
15721 }
15722 } else {
15723 switch (message.cmd) {
15724 case CommandType.error:
15725 {
15726 this.emit(ERROR, createError(message.errorMessage));
15727 return;
15728 }
15729 case CommandType.goaway:
15730 {
15731 this.emit(EXPIRE);
15732 return;
15733 }
15734 default:
15735 {
15736 this.emit(MESSAGE, message);
15737 }
15738 }
15739 }
15740 };
15741 _proto.ping = function ping() {
15742 return this.send(new GenericCommand({
15743 cmd: CommandType.echo
15744 }))["catch"](function (error) {
15745 return debug$4('ping failed:', error);
15746 });
15747 };
15748 return Connection;
15749 }(WebSocketPlus);
15750
15751 var promiseTimeout = createCommonjsModule(function (module) {
15752
15753 /**
15754 * Local reference to TimeoutError
15755 * @private
15756 */
15757 var TimeoutError;
15758
15759 /**
15760 * Rejects a promise with a {@link TimeoutError} if it does not settle within
15761 * the specified timeout.
15762 *
15763 * @param {Promise} promise The promise.
15764 * @param {number} timeoutMillis Number of milliseconds to wait on settling.
15765 * @returns {Promise} Either resolves/rejects with `promise`, or rejects with
15766 * `TimeoutError`, whichever settles first.
15767 */
15768 var timeout = module.exports.timeout = function (promise, timeoutMillis) {
15769 var error = new TimeoutError(),
15770 timeout;
15771 return Promise.race([promise, new Promise(function (resolve, reject) {
15772 timeout = setTimeout(function () {
15773 reject(error);
15774 }, timeoutMillis);
15775 })]).then(function (v) {
15776 clearTimeout(timeout);
15777 return v;
15778 }, function (err) {
15779 clearTimeout(timeout);
15780 throw err;
15781 });
15782 };
15783
15784 /**
15785 * Exception indicating that the timeout expired.
15786 */
15787 TimeoutError = module.exports.TimeoutError = function () {
15788 Error.call(this);
15789 this.stack = Error().stack;
15790 this.message = 'Timeout';
15791 };
15792 TimeoutError.prototype = Object.create(Error.prototype);
15793 TimeoutError.prototype.name = "TimeoutError";
15794 });
15795 var promiseTimeout_1 = promiseTimeout.timeout;
15796 var promiseTimeout_2 = promiseTimeout.TimeoutError;
15797
15798 var debug$5 = browser('LC:request');
15799 var request = (function (_ref) {
15800 var _ref$method = _ref.method,
15801 method = _ref$method === void 0 ? 'GET' : _ref$method,
15802 _url = _ref.url,
15803 query = _ref.query,
15804 headers = _ref.headers,
15805 data = _ref.data,
15806 time = _ref.timeout;
15807 var url = _url;
15808 if (query) {
15809 var queryString = Object.keys(query).map(function (key) {
15810 var value = query[key];
15811 if (value === undefined) return undefined;
15812 var v = isPlainObject_1(value) ? JSON.stringify(value) : value;
15813 return "".concat(encodeURIComponent(key), "=").concat(encodeURIComponent(v));
15814 }).filter(function (qs) {
15815 return qs;
15816 }).join('&');
15817 url = "".concat(url, "?").concat(queryString);
15818 }
15819 debug$5('Req: %O %O %O', method, url, {
15820 headers: headers,
15821 data: data
15822 });
15823 var request = getAdapter('request');
15824 var promise = request(url, {
15825 method: method,
15826 headers: headers,
15827 data: data
15828 }).then(function (response) {
15829 if (response.ok === false) {
15830 var error = createError(response.data);
15831 error.response = response;
15832 throw error;
15833 }
15834 debug$5('Res: %O %O %O', url, response.status, response.data);
15835 return response.data;
15836 })["catch"](function (error) {
15837 if (error.response) {
15838 debug$5('Error: %O %O %O', url, error.response.status, error.response.data);
15839 }
15840 throw error;
15841 });
15842 return time ? promiseTimeout_1(promise, time) : promise;
15843 });
15844
15845 var checkType = function checkType(middleware) {
15846 return function (param) {
15847 var constructor = param.constructor;
15848 return Promise.resolve(param).then(middleware).then(tap(function (result) {
15849 if (result === undefined || result === null) {
15850 // eslint-disable-next-line max-len
15851 return console.warn("Middleware[".concat(middleware._pluginName || 'anonymous plugin', ":").concat(middleware.name || 'anonymous middleware', "] param/return types not match. It returns ").concat(result, " while a ").concat(param.constructor.name, " expected."));
15852 }
15853 if (!(result instanceof constructor)) {
15854 // eslint-disable-next-line max-len
15855 return console.warn("Middleware[".concat(middleware._pluginName || 'anonymous plugin', ":").concat(middleware.name || 'anonymous middleware', "] param/return types not match. It returns a ").concat(result.constructor.name, " while a ").concat(param.constructor.name, " expected."));
15856 }
15857 return 0;
15858 }));
15859 };
15860 };
15861 var applyDecorators = function applyDecorators(decorators, target) {
15862 if (decorators) {
15863 decorators.forEach(function (decorator) {
15864 try {
15865 decorator(target);
15866 } catch (error) {
15867 if (decorator._pluginName) {
15868 error.message += "[".concat(decorator._pluginName, "]");
15869 }
15870 throw error;
15871 }
15872 });
15873 }
15874 };
15875 var applyMiddlewares = function applyMiddlewares(middlewares) {
15876 return function (target) {
15877 return ensureArray(middlewares).reduce(function (previousPromise, middleware) {
15878 return previousPromise.then(checkType(middleware))["catch"](function (error) {
15879 if (middleware._pluginName) {
15880 // eslint-disable-next-line no-param-reassign
15881 error.message += "[".concat(middleware._pluginName, "]");
15882 }
15883 throw error;
15884 });
15885 }, Promise.resolve(target));
15886 };
15887 };
15888 var applyDispatcher = function applyDispatcher(dispatchers, payload) {
15889 return ensureArray(dispatchers).reduce(function (resultPromise, dispatcher) {
15890 return resultPromise.then(function (shouldDispatch) {
15891 return shouldDispatch === false ? false : dispatcher.apply(void 0, _toConsumableArray(payload));
15892 })["catch"](function (error) {
15893 if (dispatcher._pluginName) {
15894 // eslint-disable-next-line no-param-reassign
15895 error.message += "[".concat(dispatcher._pluginName, "]");
15896 }
15897 throw error;
15898 });
15899 }, Promise.resolve(true));
15900 };
15901
15902 var version = "5.0.0-rc.8";
15903
15904 var _excluded = ["plugins"];
15905 function ownKeys$2(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
15906 function _objectSpread$2(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys$2(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$2(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
15907 var debug$6 = browser('LC:Realtime');
15908 var routerCache = new Cache('push-router');
15909 var initializedApp = {};
15910 var Realtime = /*#__PURE__*/function (_EventEmitter) {
15911 _inheritsLoose(Realtime, _EventEmitter);
15912 /**
15913 * @extends EventEmitter
15914 * @param {Object} options
15915 * @param {String} options.appId
15916 * @param {String} options.appKey (since 4.0.0)
15917 * @param {String|Object} [options.server] 指定服务器域名,中国节点应用此参数必填(since 4.0.0)
15918 * @param {Boolean} [options.noBinary=false] 设置 WebSocket 使用字符串格式收发消息(默认为二进制格式)。
15919 * 适用于 WebSocket 实现不支持二进制数据格式的情况
15920 * @param {Boolean} [options.ssl=true] 使用 wss 进行连接
15921 * @param {String|String[]} [options.RTMServers] 指定私有部署的 RTM 服务器地址(since 4.0.0)
15922 * @param {Plugin[]} [options.plugins] 加载插件(since 3.1.0)
15923 */
15924 function Realtime(_ref) {
15925 var _this2;
15926 var plugins = _ref.plugins,
15927 options = _objectWithoutProperties(_ref, _excluded);
15928 debug$6('initializing Realtime %s %O', version, options);
15929 _this2 = _EventEmitter.call(this) || this;
15930 var appId = options.appId;
15931 if (typeof appId !== 'string') {
15932 throw new TypeError("appId [".concat(appId, "] is not a string"));
15933 }
15934 if (initializedApp[appId]) {
15935 throw new Error("App [".concat(appId, "] is already initialized."));
15936 }
15937 initializedApp[appId] = true;
15938 if (typeof options.appKey !== 'string') {
15939 throw new TypeError("appKey [".concat(options.appKey, "] is not a string"));
15940 }
15941 if (isCNApp(appId)) {
15942 if (!options.server) {
15943 throw new TypeError("server option is required for apps from CN region");
15944 }
15945 }
15946 _this2._options = _objectSpread$2({
15947 appId: undefined,
15948 appKey: undefined,
15949 noBinary: false,
15950 ssl: true,
15951 RTMServerName: typeof process !== 'undefined' ? process.env.RTM_SERVER_NAME : undefined
15952 }, options);
15953 _this2._cache = new Cache('endpoints');
15954 var _this = internal(_assertThisInitialized(_this2));
15955 _this.clients = new Set();
15956 _this.pendingClients = new Set();
15957 var mergedPlugins = [].concat(_toConsumableArray(ensureArray(Realtime.__preRegisteredPlugins)), _toConsumableArray(ensureArray(plugins)));
15958 debug$6('Using plugins %o', mergedPlugins.map(function (plugin) {
15959 return plugin.name;
15960 }));
15961 _this2._plugins = mergedPlugins.reduce(function (result, plugin) {
15962 Object.keys(plugin).forEach(function (hook) {
15963 if ({}.hasOwnProperty.call(plugin, hook) && hook !== 'name') {
15964 if (plugin.name) {
15965 ensureArray(plugin[hook]).forEach(function (value) {
15966 // eslint-disable-next-line no-param-reassign
15967 value._pluginName = plugin.name;
15968 });
15969 }
15970 // eslint-disable-next-line no-param-reassign
15971 result[hook] = ensureArray(result[hook]).concat(plugin[hook]);
15972 }
15973 });
15974 return result;
15975 }, {});
15976 // onRealtimeCreate hook
15977 applyDecorators(_this2._plugins.onRealtimeCreate, _assertThisInitialized(_this2));
15978 return _this2;
15979 }
15980 var _proto = Realtime.prototype;
15981 _proto._request = /*#__PURE__*/function () {
15982 var _request2 = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee(_ref2) {
15983 var method, _url, _ref2$version, version, path, query, headers, data, url, _this$_options, appId, server, _yield$this$construct, api;
15984 return regenerator.wrap(function _callee$(_context) {
15985 while (1) switch (_context.prev = _context.next) {
15986 case 0:
15987 method = _ref2.method, _url = _ref2.url, _ref2$version = _ref2.version, version = _ref2$version === void 0 ? '1.1' : _ref2$version, path = _ref2.path, query = _ref2.query, headers = _ref2.headers, data = _ref2.data;
15988 url = _url;
15989 if (url) {
15990 _context.next = 9;
15991 break;
15992 }
15993 _this$_options = this._options, appId = _this$_options.appId, server = _this$_options.server;
15994 _context.next = 6;
15995 return this.constructor._getServerUrls({
15996 appId: appId,
15997 server: server
15998 });
15999 case 6:
16000 _yield$this$construct = _context.sent;
16001 api = _yield$this$construct.api;
16002 url = "".concat(api, "/").concat(version).concat(path);
16003 case 9:
16004 return _context.abrupt("return", request({
16005 url: url,
16006 method: method,
16007 query: query,
16008 headers: _objectSpread$2({
16009 'X-LC-Id': this._options.appId,
16010 'X-LC-Key': this._options.appKey
16011 }, headers),
16012 data: data
16013 }));
16014 case 10:
16015 case "end":
16016 return _context.stop();
16017 }
16018 }, _callee, this);
16019 }));
16020 function _request(_x) {
16021 return _request2.apply(this, arguments);
16022 }
16023 return _request;
16024 }();
16025 _proto._open = function _open() {
16026 var _this3 = this;
16027 if (this._openPromise) return this._openPromise;
16028 var format = 'protobuf2';
16029 if (this._options.noBinary) {
16030 // 不发送 binary data,fallback to base64 string
16031 format = 'proto2base64';
16032 }
16033 var version = 3;
16034 var protocol = {
16035 format: format,
16036 version: version
16037 };
16038 this._openPromise = new Promise(function (resolve, reject) {
16039 debug$6('No connection established, create a new one.');
16040 var connection = new Connection(function () {
16041 return _this3._getRTMServers(_this3._options);
16042 }, protocol);
16043 connection.on(OPEN, function () {
16044 return resolve(connection);
16045 }).on(ERROR, function (error) {
16046 delete _this3._openPromise;
16047 reject(error);
16048 }).on(EXPIRE, /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee2() {
16049 return regenerator.wrap(function _callee2$(_context2) {
16050 while (1) switch (_context2.prev = _context2.next) {
16051 case 0:
16052 debug$6('Connection expired. Refresh endpoints.');
16053 _this3._cache.set('endpoints', null, 0);
16054 _context2.next = 4;
16055 return _this3._getRTMServers(_this3._options);
16056 case 4:
16057 connection.urls = _context2.sent;
16058 connection.disconnect();
16059 case 6:
16060 case "end":
16061 return _context2.stop();
16062 }
16063 }, _callee2);
16064 }))).on(MESSAGE, _this3._dispatchCommand.bind(_this3));
16065 /**
16066 * 连接断开。
16067 * 连接断开可能是因为 SDK 进入了离线状态(see {@link Realtime#event:OFFLINE}),或长时间没有收到服务器心跳。
16068 * 连接断开后所有的网络操作都会失败,请在连接断开后禁用相关的 UI 元素。
16069 * @event Realtime#DISCONNECT
16070 */
16071 /**
16072 * 计划在一段时间后尝试重新连接
16073 * @event Realtime#SCHEDULE
16074 * @param {Number} attempt 尝试重连的次数
16075 * @param {Number} delay 延迟的毫秒数
16076 */
16077 /**
16078 * 正在尝试重新连接
16079 * @event Realtime#RETRY
16080 * @param {Number} attempt 尝试重连的次数
16081 */
16082 /**
16083 * 连接恢复正常。
16084 * 请重新启用在 {@link Realtime#event:DISCONNECT} 事件中禁用的相关 UI 元素
16085 * @event Realtime#RECONNECT
16086 */
16087
16088 /**
16089 * 客户端连接断开
16090 * @event IMClient#DISCONNECT
16091 * @see Realtime#event:DISCONNECT
16092 * @since 3.2.0
16093 */
16094 /**
16095 * 计划在一段时间后尝试重新连接
16096 * @event IMClient#SCHEDULE
16097 * @param {Number} attempt 尝试重连的次数
16098 * @param {Number} delay 延迟的毫秒数
16099 * @since 3.2.0
16100 */
16101 /**
16102 * 正在尝试重新连接
16103 * @event IMClient#RETRY
16104 * @param {Number} attempt 尝试重连的次数
16105 * @since 3.2.0
16106 */
16107
16108 /**
16109 * 客户端进入离线状态。
16110 * 这通常意味着网络已断开,或者 {@link Realtime#pause} 被调用
16111 * @event Realtime#OFFLINE
16112 * @since 3.4.0
16113 */
16114 /**
16115 * 客户端恢复在线状态
16116 * 这通常意味着网络已恢复,或者 {@link Realtime#resume} 被调用
16117 * @event Realtime#ONLINE
16118 * @since 3.4.0
16119 */
16120 /**
16121 * 进入离线状态。
16122 * 这通常意味着网络已断开,或者 {@link Realtime#pause} 被调用
16123 * @event IMClient#OFFLINE
16124 * @since 3.4.0
16125 */
16126 /**
16127 * 恢复在线状态
16128 * 这通常意味着网络已恢复,或者 {@link Realtime#resume} 被调用
16129 * @event IMClient#ONLINE
16130 * @since 3.4.0
16131 */
16132
16133 // event proxy
16134 [DISCONNECT, RECONNECT, RETRY, SCHEDULE, OFFLINE, ONLINE].forEach(function (event) {
16135 return connection.on(event, function () {
16136 for (var _len = arguments.length, payload = new Array(_len), _key = 0; _key < _len; _key++) {
16137 payload[_key] = arguments[_key];
16138 }
16139 debug$6("".concat(event, " event emitted. %o"), payload);
16140 _this3.emit.apply(_this3, [event].concat(payload));
16141 if (event !== RECONNECT) {
16142 internal(_this3).clients.forEach(function (client) {
16143 client.emit.apply(client, [event].concat(payload));
16144 });
16145 }
16146 });
16147 });
16148 // override handleClose
16149 connection.handleClose = function handleClose(event) {
16150 var isFatal = [ErrorCode.APP_NOT_AVAILABLE, ErrorCode.INVALID_LOGIN, ErrorCode.INVALID_ORIGIN].some(function (errorCode) {
16151 return errorCode === event.code;
16152 });
16153 if (isFatal) {
16154 // in these cases, SDK should throw.
16155 this["throw"](createError(event));
16156 } else {
16157 // reconnect
16158 this.disconnect();
16159 }
16160 };
16161 internal(_this3).connection = connection;
16162 });
16163 return this._openPromise;
16164 };
16165 _proto._getRTMServers = /*#__PURE__*/function () {
16166 var _getRTMServers2 = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee3(options) {
16167 var info, cachedEndPoints, _info, server, secondary, ttl;
16168 return regenerator.wrap(function _callee3$(_context3) {
16169 while (1) switch (_context3.prev = _context3.next) {
16170 case 0:
16171 if (!options.RTMServers) {
16172 _context3.next = 2;
16173 break;
16174 }
16175 return _context3.abrupt("return", shuffle_1(ensureArray(options.RTMServers)));
16176 case 2:
16177 cachedEndPoints = this._cache.get('endpoints');
16178 if (!cachedEndPoints) {
16179 _context3.next = 7;
16180 break;
16181 }
16182 info = cachedEndPoints;
16183 _context3.next = 14;
16184 break;
16185 case 7:
16186 _context3.next = 9;
16187 return this.constructor._fetchRTMServers(options);
16188 case 9:
16189 info = _context3.sent;
16190 _info = info, server = _info.server, secondary = _info.secondary, ttl = _info.ttl;
16191 if (!(typeof server !== 'string' && typeof secondary !== 'string' && typeof ttl !== 'number')) {
16192 _context3.next = 13;
16193 break;
16194 }
16195 throw new Error("malformed RTM route response: ".concat(JSON.stringify(info)));
16196 case 13:
16197 this._cache.set('endpoints', info, info.ttl * 1000);
16198 case 14:
16199 debug$6('endpoint info: %O', info);
16200 return _context3.abrupt("return", [info.server, info.secondary]);
16201 case 16:
16202 case "end":
16203 return _context3.stop();
16204 }
16205 }, _callee3, this);
16206 }));
16207 function _getRTMServers(_x2) {
16208 return _getRTMServers2.apply(this, arguments);
16209 }
16210 return _getRTMServers;
16211 }();
16212 Realtime._getServerUrls = /*#__PURE__*/function () {
16213 var _getServerUrls2 = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee4(_ref4) {
16214 var appId, server, cachedRouter, defaultProtocol;
16215 return regenerator.wrap(function _callee4$(_context4) {
16216 while (1) switch (_context4.prev = _context4.next) {
16217 case 0:
16218 appId = _ref4.appId, server = _ref4.server;
16219 debug$6('fetch server urls');
16220 if (!server) {
16221 _context4.next = 6;
16222 break;
16223 }
16224 if (!(typeof server !== 'string')) {
16225 _context4.next = 5;
16226 break;
16227 }
16228 return _context4.abrupt("return", server);
16229 case 5:
16230 return _context4.abrupt("return", {
16231 RTMRouter: server,
16232 api: server
16233 });
16234 case 6:
16235 cachedRouter = routerCache.get(appId);
16236 if (!cachedRouter) {
16237 _context4.next = 9;
16238 break;
16239 }
16240 return _context4.abrupt("return", cachedRouter);
16241 case 9:
16242 defaultProtocol = 'https://';
16243 return _context4.abrupt("return", request({
16244 url: 'https://app-router.com/2/route',
16245 query: {
16246 appId: appId
16247 },
16248 timeout: 20000
16249 }).then(tap(debug$6)).then(function (_ref5) {
16250 var RTMRouterServer = _ref5.rtm_router_server,
16251 APIServer = _ref5.api_server,
16252 _ref5$ttl = _ref5.ttl,
16253 ttl = _ref5$ttl === void 0 ? 3600 : _ref5$ttl;
16254 if (!RTMRouterServer) {
16255 throw new Error('rtm router not exists');
16256 }
16257 var serverUrls = {
16258 RTMRouter: "".concat(defaultProtocol).concat(RTMRouterServer),
16259 api: "".concat(defaultProtocol).concat(APIServer)
16260 };
16261 routerCache.set(appId, serverUrls, ttl * 1000);
16262 return serverUrls;
16263 })["catch"](function () {
16264 var id = appId.slice(0, 8).toLowerCase();
16265 var domain = 'lncldglobal.com';
16266 return {
16267 RTMRouter: "".concat(defaultProtocol).concat(id, ".rtm.").concat(domain),
16268 api: "".concat(defaultProtocol).concat(id, ".api.").concat(domain)
16269 };
16270 }));
16271 case 11:
16272 case "end":
16273 return _context4.stop();
16274 }
16275 }, _callee4);
16276 }));
16277 function _getServerUrls(_x3) {
16278 return _getServerUrls2.apply(this, arguments);
16279 }
16280 return _getServerUrls;
16281 }();
16282 Realtime._fetchRTMServers = function _fetchRTMServers(_ref6) {
16283 var appId = _ref6.appId,
16284 ssl = _ref6.ssl,
16285 server = _ref6.server,
16286 RTMServerName = _ref6.RTMServerName;
16287 debug$6('fetch endpoint info');
16288 return this._getServerUrls({
16289 appId: appId,
16290 server: server
16291 }).then(tap(debug$6)).then(function (_ref7) {
16292 var RTMRouter = _ref7.RTMRouter;
16293 return request({
16294 url: "".concat(RTMRouter, "/v1/route"),
16295 query: {
16296 appId: appId,
16297 secure: ssl,
16298 features: isWeapp ? 'wechat' : undefined,
16299 server: RTMServerName,
16300 _t: Date.now()
16301 },
16302 timeout: 20000
16303 }).then(tap(debug$6));
16304 });
16305 };
16306 _proto._close = function _close() {
16307 if (this._openPromise) {
16308 this._openPromise.then(function (connection) {
16309 return connection.close();
16310 });
16311 }
16312 delete this._openPromise;
16313 }
16314
16315 /**
16316 * 手动进行重连。
16317 * SDK 在网络出现异常时会自动按照一定的时间间隔尝试重连,调用该方法会立即尝试重连并重置重连尝试计数器。
16318 * 只能在 `SCHEDULE` 事件之后,`RETRY` 事件之前调用,如果当前网络正常或者正在进行重连,调用该方法会抛异常。
16319 */;
16320 _proto.retry = function retry() {
16321 var _internal = internal(this),
16322 connection = _internal.connection;
16323 if (!connection) {
16324 throw new Error('no connection established');
16325 }
16326 if (connection.cannot('retry')) {
16327 throw new Error("retrying not allowed when not disconnected. the connection is now ".concat(connection.current));
16328 }
16329 return connection.retry();
16330 }
16331
16332 /**
16333 * 暂停,使 SDK 进入离线状态。
16334 * 你可以在网络断开、应用进入后台等时刻调用该方法让 SDK 进入离线状态,离线状态下不会尝试重连。
16335 * 在浏览器中 SDK 会自动监听网络变化,因此无需手动调用该方法。
16336 *
16337 * @since 3.4.0
16338 * @see Realtime#event:OFFLINE
16339 */;
16340 _proto.pause = function pause() {
16341 // 这个方法常常在网络断开、进入后台时被调用,此时 connection 可能没有建立或者已经 close。
16342 // 因此不像 retry,这个方法应该尽可能 loose
16343 var _internal2 = internal(this),
16344 connection = _internal2.connection;
16345 if (!connection) return;
16346 if (connection.can('pause')) connection.pause();
16347 }
16348
16349 /**
16350 * 恢复在线状态。
16351 * 你可以在网络恢复、应用回到前台等时刻调用该方法让 SDK 恢复在线状态,恢复在线状态后 SDK 会开始尝试重连。
16352 *
16353 * @since 3.4.0
16354 * @see Realtime#event:ONLINE
16355 */;
16356 _proto.resume = function resume() {
16357 // 与 pause 一样,这个方法应该尽可能 loose
16358 var _internal3 = internal(this),
16359 connection = _internal3.connection;
16360 if (!connection) return;
16361 if (connection.can('resume')) connection.resume();
16362 };
16363 _proto._registerPending = function _registerPending(value) {
16364 internal(this).pendingClients.add(value);
16365 };
16366 _proto._deregisterPending = function _deregisterPending(client) {
16367 internal(this).pendingClients["delete"](client);
16368 };
16369 _proto._register = function _register(client) {
16370 internal(this).clients.add(client);
16371 };
16372 _proto._deregister = function _deregister(client) {
16373 var _this = internal(this);
16374 _this.clients["delete"](client);
16375 if (_this.clients.size + _this.pendingClients.size === 0) {
16376 this._close();
16377 }
16378 };
16379 _proto._dispatchCommand = function _dispatchCommand(command) {
16380 return applyDispatcher(this._plugins.beforeCommandDispatch, [command, this]).then(function (shouldDispatch) {
16381 // no plugin handled this command
16382 if (shouldDispatch) return debug$6('[WARN] Unexpected message received: %O', trim(command));
16383 return false;
16384 });
16385 };
16386 return Realtime;
16387 }(eventemitter3); // For test purpose only
16388
16389 var polyfilledPromise = Promise;
16390
16391 var rngBrowser = createCommonjsModule(function (module) {
16392 // Unique ID creation requires a high quality random # generator. In the
16393 // browser this is a little complicated due to unknown quality of Math.random()
16394 // and inconsistent support for the `crypto` API. We do the best we can via
16395 // feature-detection
16396
16397 // getRandomValues needs to be invoked in a context where "this" is a Crypto
16398 // implementation. Also, find the complete implementation of crypto on IE11.
16399 var getRandomValues = (typeof(crypto) != 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto)) ||
16400 (typeof(msCrypto) != 'undefined' && typeof window.msCrypto.getRandomValues == 'function' && msCrypto.getRandomValues.bind(msCrypto));
16401
16402 if (getRandomValues) {
16403 // WHATWG crypto RNG - http://wiki.whatwg.org/wiki/Crypto
16404 var rnds8 = new Uint8Array(16); // eslint-disable-line no-undef
16405
16406 module.exports = function whatwgRNG() {
16407 getRandomValues(rnds8);
16408 return rnds8;
16409 };
16410 } else {
16411 // Math.random()-based (RNG)
16412 //
16413 // If all else fails, use Math.random(). It's fast, but is of unspecified
16414 // quality.
16415 var rnds = new Array(16);
16416
16417 module.exports = function mathRNG() {
16418 for (var i = 0, r; i < 16; i++) {
16419 if ((i & 0x03) === 0) r = Math.random() * 0x100000000;
16420 rnds[i] = r >>> ((i & 0x03) << 3) & 0xff;
16421 }
16422
16423 return rnds;
16424 };
16425 }
16426 });
16427
16428 /**
16429 * Convert array of 16 byte values to UUID string format of the form:
16430 * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
16431 */
16432 var byteToHex = [];
16433 for (var i = 0; i < 256; ++i) {
16434 byteToHex[i] = (i + 0x100).toString(16).substr(1);
16435 }
16436
16437 function bytesToUuid(buf, offset) {
16438 var i = offset || 0;
16439 var bth = byteToHex;
16440 // join used to fix memory issue caused by concatenation: https://bugs.chromium.org/p/v8/issues/detail?id=3175#c4
16441 return ([bth[buf[i++]], bth[buf[i++]],
16442 bth[buf[i++]], bth[buf[i++]], '-',
16443 bth[buf[i++]], bth[buf[i++]], '-',
16444 bth[buf[i++]], bth[buf[i++]], '-',
16445 bth[buf[i++]], bth[buf[i++]], '-',
16446 bth[buf[i++]], bth[buf[i++]],
16447 bth[buf[i++]], bth[buf[i++]],
16448 bth[buf[i++]], bth[buf[i++]]]).join('');
16449 }
16450
16451 var bytesToUuid_1 = bytesToUuid;
16452
16453 function v4(options, buf, offset) {
16454 var i = buf && offset || 0;
16455
16456 if (typeof(options) == 'string') {
16457 buf = options === 'binary' ? new Array(16) : null;
16458 options = null;
16459 }
16460 options = options || {};
16461
16462 var rnds = options.random || (options.rng || rngBrowser)();
16463
16464 // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
16465 rnds[6] = (rnds[6] & 0x0f) | 0x40;
16466 rnds[8] = (rnds[8] & 0x3f) | 0x80;
16467
16468 // Copy bytes to buffer, if provided
16469 if (buf) {
16470 for (var ii = 0; ii < 16; ++ii) {
16471 buf[i + ii] = rnds[ii];
16472 }
16473 }
16474
16475 return buf || bytesToUuid_1(rnds);
16476 }
16477
16478 var v4_1 = v4;
16479
16480 var iterableToArrayLimit = createCommonjsModule(function (module) {
16481 function _iterableToArrayLimit(arr, i) {
16482 var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"];
16483 if (null != _i) {
16484 var _s,
16485 _e,
16486 _x,
16487 _r,
16488 _arr = [],
16489 _n = !0,
16490 _d = !1;
16491 try {
16492 if (_x = (_i = _i.call(arr)).next, 0 === i) {
16493 if (Object(_i) !== _i) return;
16494 _n = !1;
16495 } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0);
16496 } catch (err) {
16497 _d = !0, _e = err;
16498 } finally {
16499 try {
16500 if (!_n && null != _i["return"] && (_r = _i["return"](), Object(_r) !== _r)) return;
16501 } finally {
16502 if (_d) throw _e;
16503 }
16504 }
16505 return _arr;
16506 }
16507 }
16508 module.exports = _iterableToArrayLimit, module.exports.__esModule = true, module.exports["default"] = module.exports;
16509 });
16510
16511 unwrapExports(iterableToArrayLimit);
16512
16513 var slicedToArray = createCommonjsModule(function (module) {
16514 function _slicedToArray(arr, i) {
16515 return arrayWithHoles(arr) || iterableToArrayLimit(arr, i) || unsupportedIterableToArray(arr, i) || nonIterableRest();
16516 }
16517 module.exports = _slicedToArray, module.exports.__esModule = true, module.exports["default"] = module.exports;
16518 });
16519
16520 var _slicedToArray = unwrapExports(slicedToArray);
16521
16522 var base64Arraybuffer = createCommonjsModule(function (module, exports) {
16523 /*
16524 * base64-arraybuffer
16525 * https://github.com/niklasvh/base64-arraybuffer
16526 *
16527 * Copyright (c) 2012 Niklas von Hertzen
16528 * Licensed under the MIT license.
16529 */
16530 (function(){
16531
16532 var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
16533
16534 // Use a lookup table to find the index.
16535 var lookup = new Uint8Array(256);
16536 for (var i = 0; i < chars.length; i++) {
16537 lookup[chars.charCodeAt(i)] = i;
16538 }
16539
16540 exports.encode = function(arraybuffer) {
16541 var bytes = new Uint8Array(arraybuffer),
16542 i, len = bytes.length, base64 = "";
16543
16544 for (i = 0; i < len; i+=3) {
16545 base64 += chars[bytes[i] >> 2];
16546 base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];
16547 base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];
16548 base64 += chars[bytes[i + 2] & 63];
16549 }
16550
16551 if ((len % 3) === 2) {
16552 base64 = base64.substring(0, base64.length - 1) + "=";
16553 } else if (len % 3 === 1) {
16554 base64 = base64.substring(0, base64.length - 2) + "==";
16555 }
16556
16557 return base64;
16558 };
16559
16560 exports.decode = function(base64) {
16561 var bufferLength = base64.length * 0.75,
16562 len = base64.length, i, p = 0,
16563 encoded1, encoded2, encoded3, encoded4;
16564
16565 if (base64[base64.length - 1] === "=") {
16566 bufferLength--;
16567 if (base64[base64.length - 2] === "=") {
16568 bufferLength--;
16569 }
16570 }
16571
16572 var arraybuffer = new ArrayBuffer(bufferLength),
16573 bytes = new Uint8Array(arraybuffer);
16574
16575 for (i = 0; i < len; i+=4) {
16576 encoded1 = lookup[base64.charCodeAt(i)];
16577 encoded2 = lookup[base64.charCodeAt(i+1)];
16578 encoded3 = lookup[base64.charCodeAt(i+2)];
16579 encoded4 = lookup[base64.charCodeAt(i+3)];
16580
16581 bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);
16582 bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);
16583 bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);
16584 }
16585
16586 return arraybuffer;
16587 };
16588 })();
16589 });
16590 var base64Arraybuffer_1 = base64Arraybuffer.encode;
16591 var base64Arraybuffer_2 = base64Arraybuffer.decode;
16592
16593 /**
16594 * Removes all key-value entries from the list cache.
16595 *
16596 * @private
16597 * @name clear
16598 * @memberOf ListCache
16599 */
16600 function listCacheClear() {
16601 this.__data__ = [];
16602 this.size = 0;
16603 }
16604
16605 var _listCacheClear = listCacheClear;
16606
16607 /**
16608 * Performs a
16609 * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
16610 * comparison between two values to determine if they are equivalent.
16611 *
16612 * @static
16613 * @memberOf _
16614 * @since 4.0.0
16615 * @category Lang
16616 * @param {*} value The value to compare.
16617 * @param {*} other The other value to compare.
16618 * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
16619 * @example
16620 *
16621 * var object = { 'a': 1 };
16622 * var other = { 'a': 1 };
16623 *
16624 * _.eq(object, object);
16625 * // => true
16626 *
16627 * _.eq(object, other);
16628 * // => false
16629 *
16630 * _.eq('a', 'a');
16631 * // => true
16632 *
16633 * _.eq('a', Object('a'));
16634 * // => false
16635 *
16636 * _.eq(NaN, NaN);
16637 * // => true
16638 */
16639 function eq(value, other) {
16640 return value === other || (value !== value && other !== other);
16641 }
16642
16643 var eq_1 = eq;
16644
16645 /**
16646 * Gets the index at which the `key` is found in `array` of key-value pairs.
16647 *
16648 * @private
16649 * @param {Array} array The array to inspect.
16650 * @param {*} key The key to search for.
16651 * @returns {number} Returns the index of the matched value, else `-1`.
16652 */
16653 function assocIndexOf(array, key) {
16654 var length = array.length;
16655 while (length--) {
16656 if (eq_1(array[length][0], key)) {
16657 return length;
16658 }
16659 }
16660 return -1;
16661 }
16662
16663 var _assocIndexOf = assocIndexOf;
16664
16665 /** Used for built-in method references. */
16666 var arrayProto = Array.prototype;
16667
16668 /** Built-in value references. */
16669 var splice = arrayProto.splice;
16670
16671 /**
16672 * Removes `key` and its value from the list cache.
16673 *
16674 * @private
16675 * @name delete
16676 * @memberOf ListCache
16677 * @param {string} key The key of the value to remove.
16678 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
16679 */
16680 function listCacheDelete(key) {
16681 var data = this.__data__,
16682 index = _assocIndexOf(data, key);
16683
16684 if (index < 0) {
16685 return false;
16686 }
16687 var lastIndex = data.length - 1;
16688 if (index == lastIndex) {
16689 data.pop();
16690 } else {
16691 splice.call(data, index, 1);
16692 }
16693 --this.size;
16694 return true;
16695 }
16696
16697 var _listCacheDelete = listCacheDelete;
16698
16699 /**
16700 * Gets the list cache value for `key`.
16701 *
16702 * @private
16703 * @name get
16704 * @memberOf ListCache
16705 * @param {string} key The key of the value to get.
16706 * @returns {*} Returns the entry value.
16707 */
16708 function listCacheGet(key) {
16709 var data = this.__data__,
16710 index = _assocIndexOf(data, key);
16711
16712 return index < 0 ? undefined : data[index][1];
16713 }
16714
16715 var _listCacheGet = listCacheGet;
16716
16717 /**
16718 * Checks if a list cache value for `key` exists.
16719 *
16720 * @private
16721 * @name has
16722 * @memberOf ListCache
16723 * @param {string} key The key of the entry to check.
16724 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
16725 */
16726 function listCacheHas(key) {
16727 return _assocIndexOf(this.__data__, key) > -1;
16728 }
16729
16730 var _listCacheHas = listCacheHas;
16731
16732 /**
16733 * Sets the list cache `key` to `value`.
16734 *
16735 * @private
16736 * @name set
16737 * @memberOf ListCache
16738 * @param {string} key The key of the value to set.
16739 * @param {*} value The value to set.
16740 * @returns {Object} Returns the list cache instance.
16741 */
16742 function listCacheSet(key, value) {
16743 var data = this.__data__,
16744 index = _assocIndexOf(data, key);
16745
16746 if (index < 0) {
16747 ++this.size;
16748 data.push([key, value]);
16749 } else {
16750 data[index][1] = value;
16751 }
16752 return this;
16753 }
16754
16755 var _listCacheSet = listCacheSet;
16756
16757 /**
16758 * Creates an list cache object.
16759 *
16760 * @private
16761 * @constructor
16762 * @param {Array} [entries] The key-value pairs to cache.
16763 */
16764 function ListCache(entries) {
16765 var index = -1,
16766 length = entries == null ? 0 : entries.length;
16767
16768 this.clear();
16769 while (++index < length) {
16770 var entry = entries[index];
16771 this.set(entry[0], entry[1]);
16772 }
16773 }
16774
16775 // Add methods to `ListCache`.
16776 ListCache.prototype.clear = _listCacheClear;
16777 ListCache.prototype['delete'] = _listCacheDelete;
16778 ListCache.prototype.get = _listCacheGet;
16779 ListCache.prototype.has = _listCacheHas;
16780 ListCache.prototype.set = _listCacheSet;
16781
16782 var _ListCache = ListCache;
16783
16784 /**
16785 * Removes all key-value entries from the stack.
16786 *
16787 * @private
16788 * @name clear
16789 * @memberOf Stack
16790 */
16791 function stackClear() {
16792 this.__data__ = new _ListCache;
16793 this.size = 0;
16794 }
16795
16796 var _stackClear = stackClear;
16797
16798 /**
16799 * Removes `key` and its value from the stack.
16800 *
16801 * @private
16802 * @name delete
16803 * @memberOf Stack
16804 * @param {string} key The key of the value to remove.
16805 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
16806 */
16807 function stackDelete(key) {
16808 var data = this.__data__,
16809 result = data['delete'](key);
16810
16811 this.size = data.size;
16812 return result;
16813 }
16814
16815 var _stackDelete = stackDelete;
16816
16817 /**
16818 * Gets the stack value for `key`.
16819 *
16820 * @private
16821 * @name get
16822 * @memberOf Stack
16823 * @param {string} key The key of the value to get.
16824 * @returns {*} Returns the entry value.
16825 */
16826 function stackGet(key) {
16827 return this.__data__.get(key);
16828 }
16829
16830 var _stackGet = stackGet;
16831
16832 /**
16833 * Checks if a stack value for `key` exists.
16834 *
16835 * @private
16836 * @name has
16837 * @memberOf Stack
16838 * @param {string} key The key of the entry to check.
16839 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
16840 */
16841 function stackHas(key) {
16842 return this.__data__.has(key);
16843 }
16844
16845 var _stackHas = stackHas;
16846
16847 /** Used to detect overreaching core-js shims. */
16848 var coreJsData = _root['__core-js_shared__'];
16849
16850 var _coreJsData = coreJsData;
16851
16852 /** Used to detect methods masquerading as native. */
16853 var maskSrcKey = (function() {
16854 var uid = /[^.]+$/.exec(_coreJsData && _coreJsData.keys && _coreJsData.keys.IE_PROTO || '');
16855 return uid ? ('Symbol(src)_1.' + uid) : '';
16856 }());
16857
16858 /**
16859 * Checks if `func` has its source masked.
16860 *
16861 * @private
16862 * @param {Function} func The function to check.
16863 * @returns {boolean} Returns `true` if `func` is masked, else `false`.
16864 */
16865 function isMasked(func) {
16866 return !!maskSrcKey && (maskSrcKey in func);
16867 }
16868
16869 var _isMasked = isMasked;
16870
16871 /** Used for built-in method references. */
16872 var funcProto$1 = Function.prototype;
16873
16874 /** Used to resolve the decompiled source of functions. */
16875 var funcToString$1 = funcProto$1.toString;
16876
16877 /**
16878 * Converts `func` to its source code.
16879 *
16880 * @private
16881 * @param {Function} func The function to convert.
16882 * @returns {string} Returns the source code.
16883 */
16884 function toSource(func) {
16885 if (func != null) {
16886 try {
16887 return funcToString$1.call(func);
16888 } catch (e) {}
16889 try {
16890 return (func + '');
16891 } catch (e) {}
16892 }
16893 return '';
16894 }
16895
16896 var _toSource = toSource;
16897
16898 /**
16899 * Used to match `RegExp`
16900 * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
16901 */
16902 var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
16903
16904 /** Used to detect host constructors (Safari). */
16905 var reIsHostCtor = /^\[object .+?Constructor\]$/;
16906
16907 /** Used for built-in method references. */
16908 var funcProto$2 = Function.prototype,
16909 objectProto$7 = Object.prototype;
16910
16911 /** Used to resolve the decompiled source of functions. */
16912 var funcToString$2 = funcProto$2.toString;
16913
16914 /** Used to check objects for own properties. */
16915 var hasOwnProperty$5 = objectProto$7.hasOwnProperty;
16916
16917 /** Used to detect if a method is native. */
16918 var reIsNative = RegExp('^' +
16919 funcToString$2.call(hasOwnProperty$5).replace(reRegExpChar, '\\$&')
16920 .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
16921 );
16922
16923 /**
16924 * The base implementation of `_.isNative` without bad shim checks.
16925 *
16926 * @private
16927 * @param {*} value The value to check.
16928 * @returns {boolean} Returns `true` if `value` is a native function,
16929 * else `false`.
16930 */
16931 function baseIsNative(value) {
16932 if (!isObject_1(value) || _isMasked(value)) {
16933 return false;
16934 }
16935 var pattern = isFunction_1(value) ? reIsNative : reIsHostCtor;
16936 return pattern.test(_toSource(value));
16937 }
16938
16939 var _baseIsNative = baseIsNative;
16940
16941 /**
16942 * Gets the value at `key` of `object`.
16943 *
16944 * @private
16945 * @param {Object} [object] The object to query.
16946 * @param {string} key The key of the property to get.
16947 * @returns {*} Returns the property value.
16948 */
16949 function getValue(object, key) {
16950 return object == null ? undefined : object[key];
16951 }
16952
16953 var _getValue = getValue;
16954
16955 /**
16956 * Gets the native function at `key` of `object`.
16957 *
16958 * @private
16959 * @param {Object} object The object to query.
16960 * @param {string} key The key of the method to get.
16961 * @returns {*} Returns the function if it's native, else `undefined`.
16962 */
16963 function getNative(object, key) {
16964 var value = _getValue(object, key);
16965 return _baseIsNative(value) ? value : undefined;
16966 }
16967
16968 var _getNative = getNative;
16969
16970 /* Built-in method references that are verified to be native. */
16971 var Map$1 = _getNative(_root, 'Map');
16972
16973 var _Map = Map$1;
16974
16975 /* Built-in method references that are verified to be native. */
16976 var nativeCreate = _getNative(Object, 'create');
16977
16978 var _nativeCreate = nativeCreate;
16979
16980 /**
16981 * Removes all key-value entries from the hash.
16982 *
16983 * @private
16984 * @name clear
16985 * @memberOf Hash
16986 */
16987 function hashClear() {
16988 this.__data__ = _nativeCreate ? _nativeCreate(null) : {};
16989 this.size = 0;
16990 }
16991
16992 var _hashClear = hashClear;
16993
16994 /**
16995 * Removes `key` and its value from the hash.
16996 *
16997 * @private
16998 * @name delete
16999 * @memberOf Hash
17000 * @param {Object} hash The hash to modify.
17001 * @param {string} key The key of the value to remove.
17002 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
17003 */
17004 function hashDelete(key) {
17005 var result = this.has(key) && delete this.__data__[key];
17006 this.size -= result ? 1 : 0;
17007 return result;
17008 }
17009
17010 var _hashDelete = hashDelete;
17011
17012 /** Used to stand-in for `undefined` hash values. */
17013 var HASH_UNDEFINED = '__lodash_hash_undefined__';
17014
17015 /** Used for built-in method references. */
17016 var objectProto$8 = Object.prototype;
17017
17018 /** Used to check objects for own properties. */
17019 var hasOwnProperty$6 = objectProto$8.hasOwnProperty;
17020
17021 /**
17022 * Gets the hash value for `key`.
17023 *
17024 * @private
17025 * @name get
17026 * @memberOf Hash
17027 * @param {string} key The key of the value to get.
17028 * @returns {*} Returns the entry value.
17029 */
17030 function hashGet(key) {
17031 var data = this.__data__;
17032 if (_nativeCreate) {
17033 var result = data[key];
17034 return result === HASH_UNDEFINED ? undefined : result;
17035 }
17036 return hasOwnProperty$6.call(data, key) ? data[key] : undefined;
17037 }
17038
17039 var _hashGet = hashGet;
17040
17041 /** Used for built-in method references. */
17042 var objectProto$9 = Object.prototype;
17043
17044 /** Used to check objects for own properties. */
17045 var hasOwnProperty$7 = objectProto$9.hasOwnProperty;
17046
17047 /**
17048 * Checks if a hash value for `key` exists.
17049 *
17050 * @private
17051 * @name has
17052 * @memberOf Hash
17053 * @param {string} key The key of the entry to check.
17054 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
17055 */
17056 function hashHas(key) {
17057 var data = this.__data__;
17058 return _nativeCreate ? (data[key] !== undefined) : hasOwnProperty$7.call(data, key);
17059 }
17060
17061 var _hashHas = hashHas;
17062
17063 /** Used to stand-in for `undefined` hash values. */
17064 var HASH_UNDEFINED$1 = '__lodash_hash_undefined__';
17065
17066 /**
17067 * Sets the hash `key` to `value`.
17068 *
17069 * @private
17070 * @name set
17071 * @memberOf Hash
17072 * @param {string} key The key of the value to set.
17073 * @param {*} value The value to set.
17074 * @returns {Object} Returns the hash instance.
17075 */
17076 function hashSet(key, value) {
17077 var data = this.__data__;
17078 this.size += this.has(key) ? 0 : 1;
17079 data[key] = (_nativeCreate && value === undefined) ? HASH_UNDEFINED$1 : value;
17080 return this;
17081 }
17082
17083 var _hashSet = hashSet;
17084
17085 /**
17086 * Creates a hash object.
17087 *
17088 * @private
17089 * @constructor
17090 * @param {Array} [entries] The key-value pairs to cache.
17091 */
17092 function Hash(entries) {
17093 var index = -1,
17094 length = entries == null ? 0 : entries.length;
17095
17096 this.clear();
17097 while (++index < length) {
17098 var entry = entries[index];
17099 this.set(entry[0], entry[1]);
17100 }
17101 }
17102
17103 // Add methods to `Hash`.
17104 Hash.prototype.clear = _hashClear;
17105 Hash.prototype['delete'] = _hashDelete;
17106 Hash.prototype.get = _hashGet;
17107 Hash.prototype.has = _hashHas;
17108 Hash.prototype.set = _hashSet;
17109
17110 var _Hash = Hash;
17111
17112 /**
17113 * Removes all key-value entries from the map.
17114 *
17115 * @private
17116 * @name clear
17117 * @memberOf MapCache
17118 */
17119 function mapCacheClear() {
17120 this.size = 0;
17121 this.__data__ = {
17122 'hash': new _Hash,
17123 'map': new (_Map || _ListCache),
17124 'string': new _Hash
17125 };
17126 }
17127
17128 var _mapCacheClear = mapCacheClear;
17129
17130 /**
17131 * Checks if `value` is suitable for use as unique object key.
17132 *
17133 * @private
17134 * @param {*} value The value to check.
17135 * @returns {boolean} Returns `true` if `value` is suitable, else `false`.
17136 */
17137 function isKeyable(value) {
17138 var type = typeof value;
17139 return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')
17140 ? (value !== '__proto__')
17141 : (value === null);
17142 }
17143
17144 var _isKeyable = isKeyable;
17145
17146 /**
17147 * Gets the data for `map`.
17148 *
17149 * @private
17150 * @param {Object} map The map to query.
17151 * @param {string} key The reference key.
17152 * @returns {*} Returns the map data.
17153 */
17154 function getMapData(map, key) {
17155 var data = map.__data__;
17156 return _isKeyable(key)
17157 ? data[typeof key == 'string' ? 'string' : 'hash']
17158 : data.map;
17159 }
17160
17161 var _getMapData = getMapData;
17162
17163 /**
17164 * Removes `key` and its value from the map.
17165 *
17166 * @private
17167 * @name delete
17168 * @memberOf MapCache
17169 * @param {string} key The key of the value to remove.
17170 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
17171 */
17172 function mapCacheDelete(key) {
17173 var result = _getMapData(this, key)['delete'](key);
17174 this.size -= result ? 1 : 0;
17175 return result;
17176 }
17177
17178 var _mapCacheDelete = mapCacheDelete;
17179
17180 /**
17181 * Gets the map value for `key`.
17182 *
17183 * @private
17184 * @name get
17185 * @memberOf MapCache
17186 * @param {string} key The key of the value to get.
17187 * @returns {*} Returns the entry value.
17188 */
17189 function mapCacheGet(key) {
17190 return _getMapData(this, key).get(key);
17191 }
17192
17193 var _mapCacheGet = mapCacheGet;
17194
17195 /**
17196 * Checks if a map value for `key` exists.
17197 *
17198 * @private
17199 * @name has
17200 * @memberOf MapCache
17201 * @param {string} key The key of the entry to check.
17202 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
17203 */
17204 function mapCacheHas(key) {
17205 return _getMapData(this, key).has(key);
17206 }
17207
17208 var _mapCacheHas = mapCacheHas;
17209
17210 /**
17211 * Sets the map `key` to `value`.
17212 *
17213 * @private
17214 * @name set
17215 * @memberOf MapCache
17216 * @param {string} key The key of the value to set.
17217 * @param {*} value The value to set.
17218 * @returns {Object} Returns the map cache instance.
17219 */
17220 function mapCacheSet(key, value) {
17221 var data = _getMapData(this, key),
17222 size = data.size;
17223
17224 data.set(key, value);
17225 this.size += data.size == size ? 0 : 1;
17226 return this;
17227 }
17228
17229 var _mapCacheSet = mapCacheSet;
17230
17231 /**
17232 * Creates a map cache object to store key-value pairs.
17233 *
17234 * @private
17235 * @constructor
17236 * @param {Array} [entries] The key-value pairs to cache.
17237 */
17238 function MapCache(entries) {
17239 var index = -1,
17240 length = entries == null ? 0 : entries.length;
17241
17242 this.clear();
17243 while (++index < length) {
17244 var entry = entries[index];
17245 this.set(entry[0], entry[1]);
17246 }
17247 }
17248
17249 // Add methods to `MapCache`.
17250 MapCache.prototype.clear = _mapCacheClear;
17251 MapCache.prototype['delete'] = _mapCacheDelete;
17252 MapCache.prototype.get = _mapCacheGet;
17253 MapCache.prototype.has = _mapCacheHas;
17254 MapCache.prototype.set = _mapCacheSet;
17255
17256 var _MapCache = MapCache;
17257
17258 /** Used as the size to enable large array optimizations. */
17259 var LARGE_ARRAY_SIZE = 200;
17260
17261 /**
17262 * Sets the stack `key` to `value`.
17263 *
17264 * @private
17265 * @name set
17266 * @memberOf Stack
17267 * @param {string} key The key of the value to set.
17268 * @param {*} value The value to set.
17269 * @returns {Object} Returns the stack cache instance.
17270 */
17271 function stackSet(key, value) {
17272 var data = this.__data__;
17273 if (data instanceof _ListCache) {
17274 var pairs = data.__data__;
17275 if (!_Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) {
17276 pairs.push([key, value]);
17277 this.size = ++data.size;
17278 return this;
17279 }
17280 data = this.__data__ = new _MapCache(pairs);
17281 }
17282 data.set(key, value);
17283 this.size = data.size;
17284 return this;
17285 }
17286
17287 var _stackSet = stackSet;
17288
17289 /**
17290 * Creates a stack cache object to store key-value pairs.
17291 *
17292 * @private
17293 * @constructor
17294 * @param {Array} [entries] The key-value pairs to cache.
17295 */
17296 function Stack(entries) {
17297 var data = this.__data__ = new _ListCache(entries);
17298 this.size = data.size;
17299 }
17300
17301 // Add methods to `Stack`.
17302 Stack.prototype.clear = _stackClear;
17303 Stack.prototype['delete'] = _stackDelete;
17304 Stack.prototype.get = _stackGet;
17305 Stack.prototype.has = _stackHas;
17306 Stack.prototype.set = _stackSet;
17307
17308 var _Stack = Stack;
17309
17310 /** Used to stand-in for `undefined` hash values. */
17311 var HASH_UNDEFINED$2 = '__lodash_hash_undefined__';
17312
17313 /**
17314 * Adds `value` to the array cache.
17315 *
17316 * @private
17317 * @name add
17318 * @memberOf SetCache
17319 * @alias push
17320 * @param {*} value The value to cache.
17321 * @returns {Object} Returns the cache instance.
17322 */
17323 function setCacheAdd(value) {
17324 this.__data__.set(value, HASH_UNDEFINED$2);
17325 return this;
17326 }
17327
17328 var _setCacheAdd = setCacheAdd;
17329
17330 /**
17331 * Checks if `value` is in the array cache.
17332 *
17333 * @private
17334 * @name has
17335 * @memberOf SetCache
17336 * @param {*} value The value to search for.
17337 * @returns {number} Returns `true` if `value` is found, else `false`.
17338 */
17339 function setCacheHas(value) {
17340 return this.__data__.has(value);
17341 }
17342
17343 var _setCacheHas = setCacheHas;
17344
17345 /**
17346 *
17347 * Creates an array cache object to store unique values.
17348 *
17349 * @private
17350 * @constructor
17351 * @param {Array} [values] The values to cache.
17352 */
17353 function SetCache(values) {
17354 var index = -1,
17355 length = values == null ? 0 : values.length;
17356
17357 this.__data__ = new _MapCache;
17358 while (++index < length) {
17359 this.add(values[index]);
17360 }
17361 }
17362
17363 // Add methods to `SetCache`.
17364 SetCache.prototype.add = SetCache.prototype.push = _setCacheAdd;
17365 SetCache.prototype.has = _setCacheHas;
17366
17367 var _SetCache = SetCache;
17368
17369 /**
17370 * A specialized version of `_.some` for arrays without support for iteratee
17371 * shorthands.
17372 *
17373 * @private
17374 * @param {Array} [array] The array to iterate over.
17375 * @param {Function} predicate The function invoked per iteration.
17376 * @returns {boolean} Returns `true` if any element passes the predicate check,
17377 * else `false`.
17378 */
17379 function arraySome(array, predicate) {
17380 var index = -1,
17381 length = array == null ? 0 : array.length;
17382
17383 while (++index < length) {
17384 if (predicate(array[index], index, array)) {
17385 return true;
17386 }
17387 }
17388 return false;
17389 }
17390
17391 var _arraySome = arraySome;
17392
17393 /**
17394 * Checks if a `cache` value for `key` exists.
17395 *
17396 * @private
17397 * @param {Object} cache The cache to query.
17398 * @param {string} key The key of the entry to check.
17399 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
17400 */
17401 function cacheHas(cache, key) {
17402 return cache.has(key);
17403 }
17404
17405 var _cacheHas = cacheHas;
17406
17407 /** Used to compose bitmasks for value comparisons. */
17408 var COMPARE_PARTIAL_FLAG = 1,
17409 COMPARE_UNORDERED_FLAG = 2;
17410
17411 /**
17412 * A specialized version of `baseIsEqualDeep` for arrays with support for
17413 * partial deep comparisons.
17414 *
17415 * @private
17416 * @param {Array} array The array to compare.
17417 * @param {Array} other The other array to compare.
17418 * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
17419 * @param {Function} customizer The function to customize comparisons.
17420 * @param {Function} equalFunc The function to determine equivalents of values.
17421 * @param {Object} stack Tracks traversed `array` and `other` objects.
17422 * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.
17423 */
17424 function equalArrays(array, other, bitmask, customizer, equalFunc, stack) {
17425 var isPartial = bitmask & COMPARE_PARTIAL_FLAG,
17426 arrLength = array.length,
17427 othLength = other.length;
17428
17429 if (arrLength != othLength && !(isPartial && othLength > arrLength)) {
17430 return false;
17431 }
17432 // Check that cyclic values are equal.
17433 var arrStacked = stack.get(array);
17434 var othStacked = stack.get(other);
17435 if (arrStacked && othStacked) {
17436 return arrStacked == other && othStacked == array;
17437 }
17438 var index = -1,
17439 result = true,
17440 seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new _SetCache : undefined;
17441
17442 stack.set(array, other);
17443 stack.set(other, array);
17444
17445 // Ignore non-index properties.
17446 while (++index < arrLength) {
17447 var arrValue = array[index],
17448 othValue = other[index];
17449
17450 if (customizer) {
17451 var compared = isPartial
17452 ? customizer(othValue, arrValue, index, other, array, stack)
17453 : customizer(arrValue, othValue, index, array, other, stack);
17454 }
17455 if (compared !== undefined) {
17456 if (compared) {
17457 continue;
17458 }
17459 result = false;
17460 break;
17461 }
17462 // Recursively compare arrays (susceptible to call stack limits).
17463 if (seen) {
17464 if (!_arraySome(other, function(othValue, othIndex) {
17465 if (!_cacheHas(seen, othIndex) &&
17466 (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {
17467 return seen.push(othIndex);
17468 }
17469 })) {
17470 result = false;
17471 break;
17472 }
17473 } else if (!(
17474 arrValue === othValue ||
17475 equalFunc(arrValue, othValue, bitmask, customizer, stack)
17476 )) {
17477 result = false;
17478 break;
17479 }
17480 }
17481 stack['delete'](array);
17482 stack['delete'](other);
17483 return result;
17484 }
17485
17486 var _equalArrays = equalArrays;
17487
17488 /** Built-in value references. */
17489 var Uint8Array$1 = _root.Uint8Array;
17490
17491 var _Uint8Array = Uint8Array$1;
17492
17493 /**
17494 * Converts `map` to its key-value pairs.
17495 *
17496 * @private
17497 * @param {Object} map The map to convert.
17498 * @returns {Array} Returns the key-value pairs.
17499 */
17500 function mapToArray(map) {
17501 var index = -1,
17502 result = Array(map.size);
17503
17504 map.forEach(function(value, key) {
17505 result[++index] = [key, value];
17506 });
17507 return result;
17508 }
17509
17510 var _mapToArray = mapToArray;
17511
17512 /**
17513 * Converts `set` to an array of its values.
17514 *
17515 * @private
17516 * @param {Object} set The set to convert.
17517 * @returns {Array} Returns the values.
17518 */
17519 function setToArray(set) {
17520 var index = -1,
17521 result = Array(set.size);
17522
17523 set.forEach(function(value) {
17524 result[++index] = value;
17525 });
17526 return result;
17527 }
17528
17529 var _setToArray = setToArray;
17530
17531 /** Used to compose bitmasks for value comparisons. */
17532 var COMPARE_PARTIAL_FLAG$1 = 1,
17533 COMPARE_UNORDERED_FLAG$1 = 2;
17534
17535 /** `Object#toString` result references. */
17536 var boolTag$1 = '[object Boolean]',
17537 dateTag$1 = '[object Date]',
17538 errorTag$1 = '[object Error]',
17539 mapTag$1 = '[object Map]',
17540 numberTag$1 = '[object Number]',
17541 regexpTag$1 = '[object RegExp]',
17542 setTag$1 = '[object Set]',
17543 stringTag$1 = '[object String]',
17544 symbolTag = '[object Symbol]';
17545
17546 var arrayBufferTag$1 = '[object ArrayBuffer]',
17547 dataViewTag$1 = '[object DataView]';
17548
17549 /** Used to convert symbols to primitives and strings. */
17550 var symbolProto = _Symbol ? _Symbol.prototype : undefined,
17551 symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;
17552
17553 /**
17554 * A specialized version of `baseIsEqualDeep` for comparing objects of
17555 * the same `toStringTag`.
17556 *
17557 * **Note:** This function only supports comparing values with tags of
17558 * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
17559 *
17560 * @private
17561 * @param {Object} object The object to compare.
17562 * @param {Object} other The other object to compare.
17563 * @param {string} tag The `toStringTag` of the objects to compare.
17564 * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
17565 * @param {Function} customizer The function to customize comparisons.
17566 * @param {Function} equalFunc The function to determine equivalents of values.
17567 * @param {Object} stack Tracks traversed `object` and `other` objects.
17568 * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
17569 */
17570 function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {
17571 switch (tag) {
17572 case dataViewTag$1:
17573 if ((object.byteLength != other.byteLength) ||
17574 (object.byteOffset != other.byteOffset)) {
17575 return false;
17576 }
17577 object = object.buffer;
17578 other = other.buffer;
17579
17580 case arrayBufferTag$1:
17581 if ((object.byteLength != other.byteLength) ||
17582 !equalFunc(new _Uint8Array(object), new _Uint8Array(other))) {
17583 return false;
17584 }
17585 return true;
17586
17587 case boolTag$1:
17588 case dateTag$1:
17589 case numberTag$1:
17590 // Coerce booleans to `1` or `0` and dates to milliseconds.
17591 // Invalid dates are coerced to `NaN`.
17592 return eq_1(+object, +other);
17593
17594 case errorTag$1:
17595 return object.name == other.name && object.message == other.message;
17596
17597 case regexpTag$1:
17598 case stringTag$1:
17599 // Coerce regexes to strings and treat strings, primitives and objects,
17600 // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring
17601 // for more details.
17602 return object == (other + '');
17603
17604 case mapTag$1:
17605 var convert = _mapToArray;
17606
17607 case setTag$1:
17608 var isPartial = bitmask & COMPARE_PARTIAL_FLAG$1;
17609 convert || (convert = _setToArray);
17610
17611 if (object.size != other.size && !isPartial) {
17612 return false;
17613 }
17614 // Assume cyclic values are equal.
17615 var stacked = stack.get(object);
17616 if (stacked) {
17617 return stacked == other;
17618 }
17619 bitmask |= COMPARE_UNORDERED_FLAG$1;
17620
17621 // Recursively compare objects (susceptible to call stack limits).
17622 stack.set(object, other);
17623 var result = _equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack);
17624 stack['delete'](object);
17625 return result;
17626
17627 case symbolTag:
17628 if (symbolValueOf) {
17629 return symbolValueOf.call(object) == symbolValueOf.call(other);
17630 }
17631 }
17632 return false;
17633 }
17634
17635 var _equalByTag = equalByTag;
17636
17637 /**
17638 * Appends the elements of `values` to `array`.
17639 *
17640 * @private
17641 * @param {Array} array The array to modify.
17642 * @param {Array} values The values to append.
17643 * @returns {Array} Returns `array`.
17644 */
17645 function arrayPush(array, values) {
17646 var index = -1,
17647 length = values.length,
17648 offset = array.length;
17649
17650 while (++index < length) {
17651 array[offset + index] = values[index];
17652 }
17653 return array;
17654 }
17655
17656 var _arrayPush = arrayPush;
17657
17658 /**
17659 * The base implementation of `getAllKeys` and `getAllKeysIn` which uses
17660 * `keysFunc` and `symbolsFunc` to get the enumerable property names and
17661 * symbols of `object`.
17662 *
17663 * @private
17664 * @param {Object} object The object to query.
17665 * @param {Function} keysFunc The function to get the keys of `object`.
17666 * @param {Function} symbolsFunc The function to get the symbols of `object`.
17667 * @returns {Array} Returns the array of property names and symbols.
17668 */
17669 function baseGetAllKeys(object, keysFunc, symbolsFunc) {
17670 var result = keysFunc(object);
17671 return isArray_1(object) ? result : _arrayPush(result, symbolsFunc(object));
17672 }
17673
17674 var _baseGetAllKeys = baseGetAllKeys;
17675
17676 /**
17677 * A specialized version of `_.filter` for arrays without support for
17678 * iteratee shorthands.
17679 *
17680 * @private
17681 * @param {Array} [array] The array to iterate over.
17682 * @param {Function} predicate The function invoked per iteration.
17683 * @returns {Array} Returns the new filtered array.
17684 */
17685 function arrayFilter(array, predicate) {
17686 var index = -1,
17687 length = array == null ? 0 : array.length,
17688 resIndex = 0,
17689 result = [];
17690
17691 while (++index < length) {
17692 var value = array[index];
17693 if (predicate(value, index, array)) {
17694 result[resIndex++] = value;
17695 }
17696 }
17697 return result;
17698 }
17699
17700 var _arrayFilter = arrayFilter;
17701
17702 /**
17703 * This method returns a new empty array.
17704 *
17705 * @static
17706 * @memberOf _
17707 * @since 4.13.0
17708 * @category Util
17709 * @returns {Array} Returns the new empty array.
17710 * @example
17711 *
17712 * var arrays = _.times(2, _.stubArray);
17713 *
17714 * console.log(arrays);
17715 * // => [[], []]
17716 *
17717 * console.log(arrays[0] === arrays[1]);
17718 * // => false
17719 */
17720 function stubArray() {
17721 return [];
17722 }
17723
17724 var stubArray_1 = stubArray;
17725
17726 /** Used for built-in method references. */
17727 var objectProto$a = Object.prototype;
17728
17729 /** Built-in value references. */
17730 var propertyIsEnumerable$1 = objectProto$a.propertyIsEnumerable;
17731
17732 /* Built-in method references for those with the same name as other `lodash` methods. */
17733 var nativeGetSymbols = Object.getOwnPropertySymbols;
17734
17735 /**
17736 * Creates an array of the own enumerable symbols of `object`.
17737 *
17738 * @private
17739 * @param {Object} object The object to query.
17740 * @returns {Array} Returns the array of symbols.
17741 */
17742 var getSymbols = !nativeGetSymbols ? stubArray_1 : function(object) {
17743 if (object == null) {
17744 return [];
17745 }
17746 object = Object(object);
17747 return _arrayFilter(nativeGetSymbols(object), function(symbol) {
17748 return propertyIsEnumerable$1.call(object, symbol);
17749 });
17750 };
17751
17752 var _getSymbols = getSymbols;
17753
17754 /**
17755 * Creates an array of own enumerable property names and symbols of `object`.
17756 *
17757 * @private
17758 * @param {Object} object The object to query.
17759 * @returns {Array} Returns the array of property names and symbols.
17760 */
17761 function getAllKeys(object) {
17762 return _baseGetAllKeys(object, keys_1, _getSymbols);
17763 }
17764
17765 var _getAllKeys = getAllKeys;
17766
17767 /** Used to compose bitmasks for value comparisons. */
17768 var COMPARE_PARTIAL_FLAG$2 = 1;
17769
17770 /** Used for built-in method references. */
17771 var objectProto$b = Object.prototype;
17772
17773 /** Used to check objects for own properties. */
17774 var hasOwnProperty$8 = objectProto$b.hasOwnProperty;
17775
17776 /**
17777 * A specialized version of `baseIsEqualDeep` for objects with support for
17778 * partial deep comparisons.
17779 *
17780 * @private
17781 * @param {Object} object The object to compare.
17782 * @param {Object} other The other object to compare.
17783 * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
17784 * @param {Function} customizer The function to customize comparisons.
17785 * @param {Function} equalFunc The function to determine equivalents of values.
17786 * @param {Object} stack Tracks traversed `object` and `other` objects.
17787 * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
17788 */
17789 function equalObjects(object, other, bitmask, customizer, equalFunc, stack) {
17790 var isPartial = bitmask & COMPARE_PARTIAL_FLAG$2,
17791 objProps = _getAllKeys(object),
17792 objLength = objProps.length,
17793 othProps = _getAllKeys(other),
17794 othLength = othProps.length;
17795
17796 if (objLength != othLength && !isPartial) {
17797 return false;
17798 }
17799 var index = objLength;
17800 while (index--) {
17801 var key = objProps[index];
17802 if (!(isPartial ? key in other : hasOwnProperty$8.call(other, key))) {
17803 return false;
17804 }
17805 }
17806 // Check that cyclic values are equal.
17807 var objStacked = stack.get(object);
17808 var othStacked = stack.get(other);
17809 if (objStacked && othStacked) {
17810 return objStacked == other && othStacked == object;
17811 }
17812 var result = true;
17813 stack.set(object, other);
17814 stack.set(other, object);
17815
17816 var skipCtor = isPartial;
17817 while (++index < objLength) {
17818 key = objProps[index];
17819 var objValue = object[key],
17820 othValue = other[key];
17821
17822 if (customizer) {
17823 var compared = isPartial
17824 ? customizer(othValue, objValue, key, other, object, stack)
17825 : customizer(objValue, othValue, key, object, other, stack);
17826 }
17827 // Recursively compare objects (susceptible to call stack limits).
17828 if (!(compared === undefined
17829 ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack))
17830 : compared
17831 )) {
17832 result = false;
17833 break;
17834 }
17835 skipCtor || (skipCtor = key == 'constructor');
17836 }
17837 if (result && !skipCtor) {
17838 var objCtor = object.constructor,
17839 othCtor = other.constructor;
17840
17841 // Non `Object` object instances with different constructors are not equal.
17842 if (objCtor != othCtor &&
17843 ('constructor' in object && 'constructor' in other) &&
17844 !(typeof objCtor == 'function' && objCtor instanceof objCtor &&
17845 typeof othCtor == 'function' && othCtor instanceof othCtor)) {
17846 result = false;
17847 }
17848 }
17849 stack['delete'](object);
17850 stack['delete'](other);
17851 return result;
17852 }
17853
17854 var _equalObjects = equalObjects;
17855
17856 /* Built-in method references that are verified to be native. */
17857 var DataView = _getNative(_root, 'DataView');
17858
17859 var _DataView = DataView;
17860
17861 /* Built-in method references that are verified to be native. */
17862 var Promise$1 = _getNative(_root, 'Promise');
17863
17864 var _Promise = Promise$1;
17865
17866 /* Built-in method references that are verified to be native. */
17867 var Set$1 = _getNative(_root, 'Set');
17868
17869 var _Set = Set$1;
17870
17871 /* Built-in method references that are verified to be native. */
17872 var WeakMap$1 = _getNative(_root, 'WeakMap');
17873
17874 var _WeakMap = WeakMap$1;
17875
17876 /** `Object#toString` result references. */
17877 var mapTag$2 = '[object Map]',
17878 objectTag$2 = '[object Object]',
17879 promiseTag = '[object Promise]',
17880 setTag$2 = '[object Set]',
17881 weakMapTag$1 = '[object WeakMap]';
17882
17883 var dataViewTag$2 = '[object DataView]';
17884
17885 /** Used to detect maps, sets, and weakmaps. */
17886 var dataViewCtorString = _toSource(_DataView),
17887 mapCtorString = _toSource(_Map),
17888 promiseCtorString = _toSource(_Promise),
17889 setCtorString = _toSource(_Set),
17890 weakMapCtorString = _toSource(_WeakMap);
17891
17892 /**
17893 * Gets the `toStringTag` of `value`.
17894 *
17895 * @private
17896 * @param {*} value The value to query.
17897 * @returns {string} Returns the `toStringTag`.
17898 */
17899 var getTag = _baseGetTag;
17900
17901 // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.
17902 if ((_DataView && getTag(new _DataView(new ArrayBuffer(1))) != dataViewTag$2) ||
17903 (_Map && getTag(new _Map) != mapTag$2) ||
17904 (_Promise && getTag(_Promise.resolve()) != promiseTag) ||
17905 (_Set && getTag(new _Set) != setTag$2) ||
17906 (_WeakMap && getTag(new _WeakMap) != weakMapTag$1)) {
17907 getTag = function(value) {
17908 var result = _baseGetTag(value),
17909 Ctor = result == objectTag$2 ? value.constructor : undefined,
17910 ctorString = Ctor ? _toSource(Ctor) : '';
17911
17912 if (ctorString) {
17913 switch (ctorString) {
17914 case dataViewCtorString: return dataViewTag$2;
17915 case mapCtorString: return mapTag$2;
17916 case promiseCtorString: return promiseTag;
17917 case setCtorString: return setTag$2;
17918 case weakMapCtorString: return weakMapTag$1;
17919 }
17920 }
17921 return result;
17922 };
17923 }
17924
17925 var _getTag = getTag;
17926
17927 /** Used to compose bitmasks for value comparisons. */
17928 var COMPARE_PARTIAL_FLAG$3 = 1;
17929
17930 /** `Object#toString` result references. */
17931 var argsTag$2 = '[object Arguments]',
17932 arrayTag$1 = '[object Array]',
17933 objectTag$3 = '[object Object]';
17934
17935 /** Used for built-in method references. */
17936 var objectProto$c = Object.prototype;
17937
17938 /** Used to check objects for own properties. */
17939 var hasOwnProperty$9 = objectProto$c.hasOwnProperty;
17940
17941 /**
17942 * A specialized version of `baseIsEqual` for arrays and objects which performs
17943 * deep comparisons and tracks traversed objects enabling objects with circular
17944 * references to be compared.
17945 *
17946 * @private
17947 * @param {Object} object The object to compare.
17948 * @param {Object} other The other object to compare.
17949 * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
17950 * @param {Function} customizer The function to customize comparisons.
17951 * @param {Function} equalFunc The function to determine equivalents of values.
17952 * @param {Object} [stack] Tracks traversed `object` and `other` objects.
17953 * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
17954 */
17955 function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {
17956 var objIsArr = isArray_1(object),
17957 othIsArr = isArray_1(other),
17958 objTag = objIsArr ? arrayTag$1 : _getTag(object),
17959 othTag = othIsArr ? arrayTag$1 : _getTag(other);
17960
17961 objTag = objTag == argsTag$2 ? objectTag$3 : objTag;
17962 othTag = othTag == argsTag$2 ? objectTag$3 : othTag;
17963
17964 var objIsObj = objTag == objectTag$3,
17965 othIsObj = othTag == objectTag$3,
17966 isSameTag = objTag == othTag;
17967
17968 if (isSameTag && isBuffer_1(object)) {
17969 if (!isBuffer_1(other)) {
17970 return false;
17971 }
17972 objIsArr = true;
17973 objIsObj = false;
17974 }
17975 if (isSameTag && !objIsObj) {
17976 stack || (stack = new _Stack);
17977 return (objIsArr || isTypedArray_1(object))
17978 ? _equalArrays(object, other, bitmask, customizer, equalFunc, stack)
17979 : _equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);
17980 }
17981 if (!(bitmask & COMPARE_PARTIAL_FLAG$3)) {
17982 var objIsWrapped = objIsObj && hasOwnProperty$9.call(object, '__wrapped__'),
17983 othIsWrapped = othIsObj && hasOwnProperty$9.call(other, '__wrapped__');
17984
17985 if (objIsWrapped || othIsWrapped) {
17986 var objUnwrapped = objIsWrapped ? object.value() : object,
17987 othUnwrapped = othIsWrapped ? other.value() : other;
17988
17989 stack || (stack = new _Stack);
17990 return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);
17991 }
17992 }
17993 if (!isSameTag) {
17994 return false;
17995 }
17996 stack || (stack = new _Stack);
17997 return _equalObjects(object, other, bitmask, customizer, equalFunc, stack);
17998 }
17999
18000 var _baseIsEqualDeep = baseIsEqualDeep;
18001
18002 /**
18003 * The base implementation of `_.isEqual` which supports partial comparisons
18004 * and tracks traversed objects.
18005 *
18006 * @private
18007 * @param {*} value The value to compare.
18008 * @param {*} other The other value to compare.
18009 * @param {boolean} bitmask The bitmask flags.
18010 * 1 - Unordered comparison
18011 * 2 - Partial comparison
18012 * @param {Function} [customizer] The function to customize comparisons.
18013 * @param {Object} [stack] Tracks traversed `value` and `other` objects.
18014 * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
18015 */
18016 function baseIsEqual(value, other, bitmask, customizer, stack) {
18017 if (value === other) {
18018 return true;
18019 }
18020 if (value == null || other == null || (!isObjectLike_1(value) && !isObjectLike_1(other))) {
18021 return value !== value && other !== other;
18022 }
18023 return _baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);
18024 }
18025
18026 var _baseIsEqual = baseIsEqual;
18027
18028 /** Used to compose bitmasks for value comparisons. */
18029 var COMPARE_PARTIAL_FLAG$4 = 1,
18030 COMPARE_UNORDERED_FLAG$2 = 2;
18031
18032 /**
18033 * The base implementation of `_.isMatch` without support for iteratee shorthands.
18034 *
18035 * @private
18036 * @param {Object} object The object to inspect.
18037 * @param {Object} source The object of property values to match.
18038 * @param {Array} matchData The property names, values, and compare flags to match.
18039 * @param {Function} [customizer] The function to customize comparisons.
18040 * @returns {boolean} Returns `true` if `object` is a match, else `false`.
18041 */
18042 function baseIsMatch(object, source, matchData, customizer) {
18043 var index = matchData.length,
18044 length = index,
18045 noCustomizer = !customizer;
18046
18047 if (object == null) {
18048 return !length;
18049 }
18050 object = Object(object);
18051 while (index--) {
18052 var data = matchData[index];
18053 if ((noCustomizer && data[2])
18054 ? data[1] !== object[data[0]]
18055 : !(data[0] in object)
18056 ) {
18057 return false;
18058 }
18059 }
18060 while (++index < length) {
18061 data = matchData[index];
18062 var key = data[0],
18063 objValue = object[key],
18064 srcValue = data[1];
18065
18066 if (noCustomizer && data[2]) {
18067 if (objValue === undefined && !(key in object)) {
18068 return false;
18069 }
18070 } else {
18071 var stack = new _Stack;
18072 if (customizer) {
18073 var result = customizer(objValue, srcValue, key, object, source, stack);
18074 }
18075 if (!(result === undefined
18076 ? _baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG$4 | COMPARE_UNORDERED_FLAG$2, customizer, stack)
18077 : result
18078 )) {
18079 return false;
18080 }
18081 }
18082 }
18083 return true;
18084 }
18085
18086 var _baseIsMatch = baseIsMatch;
18087
18088 /**
18089 * Checks if `value` is suitable for strict equality comparisons, i.e. `===`.
18090 *
18091 * @private
18092 * @param {*} value The value to check.
18093 * @returns {boolean} Returns `true` if `value` if suitable for strict
18094 * equality comparisons, else `false`.
18095 */
18096 function isStrictComparable(value) {
18097 return value === value && !isObject_1(value);
18098 }
18099
18100 var _isStrictComparable = isStrictComparable;
18101
18102 /**
18103 * Gets the property names, values, and compare flags of `object`.
18104 *
18105 * @private
18106 * @param {Object} object The object to query.
18107 * @returns {Array} Returns the match data of `object`.
18108 */
18109 function getMatchData(object) {
18110 var result = keys_1(object),
18111 length = result.length;
18112
18113 while (length--) {
18114 var key = result[length],
18115 value = object[key];
18116
18117 result[length] = [key, value, _isStrictComparable(value)];
18118 }
18119 return result;
18120 }
18121
18122 var _getMatchData = getMatchData;
18123
18124 /**
18125 * A specialized version of `matchesProperty` for source values suitable
18126 * for strict equality comparisons, i.e. `===`.
18127 *
18128 * @private
18129 * @param {string} key The key of the property to get.
18130 * @param {*} srcValue The value to match.
18131 * @returns {Function} Returns the new spec function.
18132 */
18133 function matchesStrictComparable(key, srcValue) {
18134 return function(object) {
18135 if (object == null) {
18136 return false;
18137 }
18138 return object[key] === srcValue &&
18139 (srcValue !== undefined || (key in Object(object)));
18140 };
18141 }
18142
18143 var _matchesStrictComparable = matchesStrictComparable;
18144
18145 /**
18146 * The base implementation of `_.matches` which doesn't clone `source`.
18147 *
18148 * @private
18149 * @param {Object} source The object of property values to match.
18150 * @returns {Function} Returns the new spec function.
18151 */
18152 function baseMatches(source) {
18153 var matchData = _getMatchData(source);
18154 if (matchData.length == 1 && matchData[0][2]) {
18155 return _matchesStrictComparable(matchData[0][0], matchData[0][1]);
18156 }
18157 return function(object) {
18158 return object === source || _baseIsMatch(object, source, matchData);
18159 };
18160 }
18161
18162 var _baseMatches = baseMatches;
18163
18164 /** `Object#toString` result references. */
18165 var symbolTag$1 = '[object Symbol]';
18166
18167 /**
18168 * Checks if `value` is classified as a `Symbol` primitive or object.
18169 *
18170 * @static
18171 * @memberOf _
18172 * @since 4.0.0
18173 * @category Lang
18174 * @param {*} value The value to check.
18175 * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
18176 * @example
18177 *
18178 * _.isSymbol(Symbol.iterator);
18179 * // => true
18180 *
18181 * _.isSymbol('abc');
18182 * // => false
18183 */
18184 function isSymbol(value) {
18185 return typeof value == 'symbol' ||
18186 (isObjectLike_1(value) && _baseGetTag(value) == symbolTag$1);
18187 }
18188
18189 var isSymbol_1 = isSymbol;
18190
18191 /** Used to match property names within property paths. */
18192 var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,
18193 reIsPlainProp = /^\w*$/;
18194
18195 /**
18196 * Checks if `value` is a property name and not a property path.
18197 *
18198 * @private
18199 * @param {*} value The value to check.
18200 * @param {Object} [object] The object to query keys on.
18201 * @returns {boolean} Returns `true` if `value` is a property name, else `false`.
18202 */
18203 function isKey(value, object) {
18204 if (isArray_1(value)) {
18205 return false;
18206 }
18207 var type = typeof value;
18208 if (type == 'number' || type == 'symbol' || type == 'boolean' ||
18209 value == null || isSymbol_1(value)) {
18210 return true;
18211 }
18212 return reIsPlainProp.test(value) || !reIsDeepProp.test(value) ||
18213 (object != null && value in Object(object));
18214 }
18215
18216 var _isKey = isKey;
18217
18218 /** Error message constants. */
18219 var FUNC_ERROR_TEXT = 'Expected a function';
18220
18221 /**
18222 * Creates a function that memoizes the result of `func`. If `resolver` is
18223 * provided, it determines the cache key for storing the result based on the
18224 * arguments provided to the memoized function. By default, the first argument
18225 * provided to the memoized function is used as the map cache key. The `func`
18226 * is invoked with the `this` binding of the memoized function.
18227 *
18228 * **Note:** The cache is exposed as the `cache` property on the memoized
18229 * function. Its creation may be customized by replacing the `_.memoize.Cache`
18230 * constructor with one whose instances implement the
18231 * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)
18232 * method interface of `clear`, `delete`, `get`, `has`, and `set`.
18233 *
18234 * @static
18235 * @memberOf _
18236 * @since 0.1.0
18237 * @category Function
18238 * @param {Function} func The function to have its output memoized.
18239 * @param {Function} [resolver] The function to resolve the cache key.
18240 * @returns {Function} Returns the new memoized function.
18241 * @example
18242 *
18243 * var object = { 'a': 1, 'b': 2 };
18244 * var other = { 'c': 3, 'd': 4 };
18245 *
18246 * var values = _.memoize(_.values);
18247 * values(object);
18248 * // => [1, 2]
18249 *
18250 * values(other);
18251 * // => [3, 4]
18252 *
18253 * object.a = 2;
18254 * values(object);
18255 * // => [1, 2]
18256 *
18257 * // Modify the result cache.
18258 * values.cache.set(object, ['a', 'b']);
18259 * values(object);
18260 * // => ['a', 'b']
18261 *
18262 * // Replace `_.memoize.Cache`.
18263 * _.memoize.Cache = WeakMap;
18264 */
18265 function memoize(func, resolver) {
18266 if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) {
18267 throw new TypeError(FUNC_ERROR_TEXT);
18268 }
18269 var memoized = function() {
18270 var args = arguments,
18271 key = resolver ? resolver.apply(this, args) : args[0],
18272 cache = memoized.cache;
18273
18274 if (cache.has(key)) {
18275 return cache.get(key);
18276 }
18277 var result = func.apply(this, args);
18278 memoized.cache = cache.set(key, result) || cache;
18279 return result;
18280 };
18281 memoized.cache = new (memoize.Cache || _MapCache);
18282 return memoized;
18283 }
18284
18285 // Expose `MapCache`.
18286 memoize.Cache = _MapCache;
18287
18288 var memoize_1 = memoize;
18289
18290 /** Used as the maximum memoize cache size. */
18291 var MAX_MEMOIZE_SIZE = 500;
18292
18293 /**
18294 * A specialized version of `_.memoize` which clears the memoized function's
18295 * cache when it exceeds `MAX_MEMOIZE_SIZE`.
18296 *
18297 * @private
18298 * @param {Function} func The function to have its output memoized.
18299 * @returns {Function} Returns the new memoized function.
18300 */
18301 function memoizeCapped(func) {
18302 var result = memoize_1(func, function(key) {
18303 if (cache.size === MAX_MEMOIZE_SIZE) {
18304 cache.clear();
18305 }
18306 return key;
18307 });
18308
18309 var cache = result.cache;
18310 return result;
18311 }
18312
18313 var _memoizeCapped = memoizeCapped;
18314
18315 /** Used to match property names within property paths. */
18316 var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;
18317
18318 /** Used to match backslashes in property paths. */
18319 var reEscapeChar = /\\(\\)?/g;
18320
18321 /**
18322 * Converts `string` to a property path array.
18323 *
18324 * @private
18325 * @param {string} string The string to convert.
18326 * @returns {Array} Returns the property path array.
18327 */
18328 var stringToPath = _memoizeCapped(function(string) {
18329 var result = [];
18330 if (string.charCodeAt(0) === 46 /* . */) {
18331 result.push('');
18332 }
18333 string.replace(rePropName, function(match, number, quote, subString) {
18334 result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match));
18335 });
18336 return result;
18337 });
18338
18339 var _stringToPath = stringToPath;
18340
18341 /** Used as references for various `Number` constants. */
18342 var INFINITY = 1 / 0;
18343
18344 /** Used to convert symbols to primitives and strings. */
18345 var symbolProto$1 = _Symbol ? _Symbol.prototype : undefined,
18346 symbolToString = symbolProto$1 ? symbolProto$1.toString : undefined;
18347
18348 /**
18349 * The base implementation of `_.toString` which doesn't convert nullish
18350 * values to empty strings.
18351 *
18352 * @private
18353 * @param {*} value The value to process.
18354 * @returns {string} Returns the string.
18355 */
18356 function baseToString(value) {
18357 // Exit early for strings to avoid a performance hit in some environments.
18358 if (typeof value == 'string') {
18359 return value;
18360 }
18361 if (isArray_1(value)) {
18362 // Recursively convert values (susceptible to call stack limits).
18363 return _arrayMap(value, baseToString) + '';
18364 }
18365 if (isSymbol_1(value)) {
18366 return symbolToString ? symbolToString.call(value) : '';
18367 }
18368 var result = (value + '');
18369 return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;
18370 }
18371
18372 var _baseToString = baseToString;
18373
18374 /**
18375 * Converts `value` to a string. An empty string is returned for `null`
18376 * and `undefined` values. The sign of `-0` is preserved.
18377 *
18378 * @static
18379 * @memberOf _
18380 * @since 4.0.0
18381 * @category Lang
18382 * @param {*} value The value to convert.
18383 * @returns {string} Returns the converted string.
18384 * @example
18385 *
18386 * _.toString(null);
18387 * // => ''
18388 *
18389 * _.toString(-0);
18390 * // => '-0'
18391 *
18392 * _.toString([1, 2, 3]);
18393 * // => '1,2,3'
18394 */
18395 function toString(value) {
18396 return value == null ? '' : _baseToString(value);
18397 }
18398
18399 var toString_1 = toString;
18400
18401 /**
18402 * Casts `value` to a path array if it's not one.
18403 *
18404 * @private
18405 * @param {*} value The value to inspect.
18406 * @param {Object} [object] The object to query keys on.
18407 * @returns {Array} Returns the cast property path array.
18408 */
18409 function castPath(value, object) {
18410 if (isArray_1(value)) {
18411 return value;
18412 }
18413 return _isKey(value, object) ? [value] : _stringToPath(toString_1(value));
18414 }
18415
18416 var _castPath = castPath;
18417
18418 /** Used as references for various `Number` constants. */
18419 var INFINITY$1 = 1 / 0;
18420
18421 /**
18422 * Converts `value` to a string key if it's not a string or symbol.
18423 *
18424 * @private
18425 * @param {*} value The value to inspect.
18426 * @returns {string|symbol} Returns the key.
18427 */
18428 function toKey(value) {
18429 if (typeof value == 'string' || isSymbol_1(value)) {
18430 return value;
18431 }
18432 var result = (value + '');
18433 return (result == '0' && (1 / value) == -INFINITY$1) ? '-0' : result;
18434 }
18435
18436 var _toKey = toKey;
18437
18438 /**
18439 * The base implementation of `_.get` without support for default values.
18440 *
18441 * @private
18442 * @param {Object} object The object to query.
18443 * @param {Array|string} path The path of the property to get.
18444 * @returns {*} Returns the resolved value.
18445 */
18446 function baseGet(object, path) {
18447 path = _castPath(path, object);
18448
18449 var index = 0,
18450 length = path.length;
18451
18452 while (object != null && index < length) {
18453 object = object[_toKey(path[index++])];
18454 }
18455 return (index && index == length) ? object : undefined;
18456 }
18457
18458 var _baseGet = baseGet;
18459
18460 /**
18461 * Gets the value at `path` of `object`. If the resolved value is
18462 * `undefined`, the `defaultValue` is returned in its place.
18463 *
18464 * @static
18465 * @memberOf _
18466 * @since 3.7.0
18467 * @category Object
18468 * @param {Object} object The object to query.
18469 * @param {Array|string} path The path of the property to get.
18470 * @param {*} [defaultValue] The value returned for `undefined` resolved values.
18471 * @returns {*} Returns the resolved value.
18472 * @example
18473 *
18474 * var object = { 'a': [{ 'b': { 'c': 3 } }] };
18475 *
18476 * _.get(object, 'a[0].b.c');
18477 * // => 3
18478 *
18479 * _.get(object, ['a', '0', 'b', 'c']);
18480 * // => 3
18481 *
18482 * _.get(object, 'a.b.c', 'default');
18483 * // => 'default'
18484 */
18485 function get(object, path, defaultValue) {
18486 var result = object == null ? undefined : _baseGet(object, path);
18487 return result === undefined ? defaultValue : result;
18488 }
18489
18490 var get_1 = get;
18491
18492 /**
18493 * The base implementation of `_.hasIn` without support for deep paths.
18494 *
18495 * @private
18496 * @param {Object} [object] The object to query.
18497 * @param {Array|string} key The key to check.
18498 * @returns {boolean} Returns `true` if `key` exists, else `false`.
18499 */
18500 function baseHasIn(object, key) {
18501 return object != null && key in Object(object);
18502 }
18503
18504 var _baseHasIn = baseHasIn;
18505
18506 /**
18507 * Checks if `path` exists on `object`.
18508 *
18509 * @private
18510 * @param {Object} object The object to query.
18511 * @param {Array|string} path The path to check.
18512 * @param {Function} hasFunc The function to check properties.
18513 * @returns {boolean} Returns `true` if `path` exists, else `false`.
18514 */
18515 function hasPath(object, path, hasFunc) {
18516 path = _castPath(path, object);
18517
18518 var index = -1,
18519 length = path.length,
18520 result = false;
18521
18522 while (++index < length) {
18523 var key = _toKey(path[index]);
18524 if (!(result = object != null && hasFunc(object, key))) {
18525 break;
18526 }
18527 object = object[key];
18528 }
18529 if (result || ++index != length) {
18530 return result;
18531 }
18532 length = object == null ? 0 : object.length;
18533 return !!length && isLength_1(length) && _isIndex(key, length) &&
18534 (isArray_1(object) || isArguments_1(object));
18535 }
18536
18537 var _hasPath = hasPath;
18538
18539 /**
18540 * Checks if `path` is a direct or inherited property of `object`.
18541 *
18542 * @static
18543 * @memberOf _
18544 * @since 4.0.0
18545 * @category Object
18546 * @param {Object} object The object to query.
18547 * @param {Array|string} path The path to check.
18548 * @returns {boolean} Returns `true` if `path` exists, else `false`.
18549 * @example
18550 *
18551 * var object = _.create({ 'a': _.create({ 'b': 2 }) });
18552 *
18553 * _.hasIn(object, 'a');
18554 * // => true
18555 *
18556 * _.hasIn(object, 'a.b');
18557 * // => true
18558 *
18559 * _.hasIn(object, ['a', 'b']);
18560 * // => true
18561 *
18562 * _.hasIn(object, 'b');
18563 * // => false
18564 */
18565 function hasIn(object, path) {
18566 return object != null && _hasPath(object, path, _baseHasIn);
18567 }
18568
18569 var hasIn_1 = hasIn;
18570
18571 /** Used to compose bitmasks for value comparisons. */
18572 var COMPARE_PARTIAL_FLAG$5 = 1,
18573 COMPARE_UNORDERED_FLAG$3 = 2;
18574
18575 /**
18576 * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`.
18577 *
18578 * @private
18579 * @param {string} path The path of the property to get.
18580 * @param {*} srcValue The value to match.
18581 * @returns {Function} Returns the new spec function.
18582 */
18583 function baseMatchesProperty(path, srcValue) {
18584 if (_isKey(path) && _isStrictComparable(srcValue)) {
18585 return _matchesStrictComparable(_toKey(path), srcValue);
18586 }
18587 return function(object) {
18588 var objValue = get_1(object, path);
18589 return (objValue === undefined && objValue === srcValue)
18590 ? hasIn_1(object, path)
18591 : _baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG$5 | COMPARE_UNORDERED_FLAG$3);
18592 };
18593 }
18594
18595 var _baseMatchesProperty = baseMatchesProperty;
18596
18597 /**
18598 * This method returns the first argument it receives.
18599 *
18600 * @static
18601 * @since 0.1.0
18602 * @memberOf _
18603 * @category Util
18604 * @param {*} value Any value.
18605 * @returns {*} Returns `value`.
18606 * @example
18607 *
18608 * var object = { 'a': 1 };
18609 *
18610 * console.log(_.identity(object) === object);
18611 * // => true
18612 */
18613 function identity(value) {
18614 return value;
18615 }
18616
18617 var identity_1 = identity;
18618
18619 /**
18620 * The base implementation of `_.property` without support for deep paths.
18621 *
18622 * @private
18623 * @param {string} key The key of the property to get.
18624 * @returns {Function} Returns the new accessor function.
18625 */
18626 function baseProperty(key) {
18627 return function(object) {
18628 return object == null ? undefined : object[key];
18629 };
18630 }
18631
18632 var _baseProperty = baseProperty;
18633
18634 /**
18635 * A specialized version of `baseProperty` which supports deep paths.
18636 *
18637 * @private
18638 * @param {Array|string} path The path of the property to get.
18639 * @returns {Function} Returns the new accessor function.
18640 */
18641 function basePropertyDeep(path) {
18642 return function(object) {
18643 return _baseGet(object, path);
18644 };
18645 }
18646
18647 var _basePropertyDeep = basePropertyDeep;
18648
18649 /**
18650 * Creates a function that returns the value at `path` of a given object.
18651 *
18652 * @static
18653 * @memberOf _
18654 * @since 2.4.0
18655 * @category Util
18656 * @param {Array|string} path The path of the property to get.
18657 * @returns {Function} Returns the new accessor function.
18658 * @example
18659 *
18660 * var objects = [
18661 * { 'a': { 'b': 2 } },
18662 * { 'a': { 'b': 1 } }
18663 * ];
18664 *
18665 * _.map(objects, _.property('a.b'));
18666 * // => [2, 1]
18667 *
18668 * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b');
18669 * // => [1, 2]
18670 */
18671 function property(path) {
18672 return _isKey(path) ? _baseProperty(_toKey(path)) : _basePropertyDeep(path);
18673 }
18674
18675 var property_1 = property;
18676
18677 /**
18678 * The base implementation of `_.iteratee`.
18679 *
18680 * @private
18681 * @param {*} [value=_.identity] The value to convert to an iteratee.
18682 * @returns {Function} Returns the iteratee.
18683 */
18684 function baseIteratee(value) {
18685 // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9.
18686 // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details.
18687 if (typeof value == 'function') {
18688 return value;
18689 }
18690 if (value == null) {
18691 return identity_1;
18692 }
18693 if (typeof value == 'object') {
18694 return isArray_1(value)
18695 ? _baseMatchesProperty(value[0], value[1])
18696 : _baseMatches(value);
18697 }
18698 return property_1(value);
18699 }
18700
18701 var _baseIteratee = baseIteratee;
18702
18703 /**
18704 * Gets the last element of `array`.
18705 *
18706 * @static
18707 * @memberOf _
18708 * @since 0.1.0
18709 * @category Array
18710 * @param {Array} array The array to query.
18711 * @returns {*} Returns the last element of `array`.
18712 * @example
18713 *
18714 * _.last([1, 2, 3]);
18715 * // => 3
18716 */
18717 function last(array) {
18718 var length = array == null ? 0 : array.length;
18719 return length ? array[length - 1] : undefined;
18720 }
18721
18722 var last_1 = last;
18723
18724 /**
18725 * The base implementation of `_.slice` without an iteratee call guard.
18726 *
18727 * @private
18728 * @param {Array} array The array to slice.
18729 * @param {number} [start=0] The start position.
18730 * @param {number} [end=array.length] The end position.
18731 * @returns {Array} Returns the slice of `array`.
18732 */
18733 function baseSlice(array, start, end) {
18734 var index = -1,
18735 length = array.length;
18736
18737 if (start < 0) {
18738 start = -start > length ? 0 : (length + start);
18739 }
18740 end = end > length ? length : end;
18741 if (end < 0) {
18742 end += length;
18743 }
18744 length = start > end ? 0 : ((end - start) >>> 0);
18745 start >>>= 0;
18746
18747 var result = Array(length);
18748 while (++index < length) {
18749 result[index] = array[index + start];
18750 }
18751 return result;
18752 }
18753
18754 var _baseSlice = baseSlice;
18755
18756 /**
18757 * Gets the parent value at `path` of `object`.
18758 *
18759 * @private
18760 * @param {Object} object The object to query.
18761 * @param {Array} path The path to get the parent value of.
18762 * @returns {*} Returns the parent value.
18763 */
18764 function parent(object, path) {
18765 return path.length < 2 ? object : _baseGet(object, _baseSlice(path, 0, -1));
18766 }
18767
18768 var _parent = parent;
18769
18770 /**
18771 * The base implementation of `_.unset`.
18772 *
18773 * @private
18774 * @param {Object} object The object to modify.
18775 * @param {Array|string} path The property path to unset.
18776 * @returns {boolean} Returns `true` if the property is deleted, else `false`.
18777 */
18778 function baseUnset(object, path) {
18779 path = _castPath(path, object);
18780 object = _parent(object, path);
18781 return object == null || delete object[_toKey(last_1(path))];
18782 }
18783
18784 var _baseUnset = baseUnset;
18785
18786 /** Used for built-in method references. */
18787 var arrayProto$1 = Array.prototype;
18788
18789 /** Built-in value references. */
18790 var splice$1 = arrayProto$1.splice;
18791
18792 /**
18793 * The base implementation of `_.pullAt` without support for individual
18794 * indexes or capturing the removed elements.
18795 *
18796 * @private
18797 * @param {Array} array The array to modify.
18798 * @param {number[]} indexes The indexes of elements to remove.
18799 * @returns {Array} Returns `array`.
18800 */
18801 function basePullAt(array, indexes) {
18802 var length = array ? indexes.length : 0,
18803 lastIndex = length - 1;
18804
18805 while (length--) {
18806 var index = indexes[length];
18807 if (length == lastIndex || index !== previous) {
18808 var previous = index;
18809 if (_isIndex(index)) {
18810 splice$1.call(array, index, 1);
18811 } else {
18812 _baseUnset(array, index);
18813 }
18814 }
18815 }
18816 return array;
18817 }
18818
18819 var _basePullAt = basePullAt;
18820
18821 /**
18822 * Removes all elements from `array` that `predicate` returns truthy for
18823 * and returns an array of the removed elements. The predicate is invoked
18824 * with three arguments: (value, index, array).
18825 *
18826 * **Note:** Unlike `_.filter`, this method mutates `array`. Use `_.pull`
18827 * to pull elements from an array by value.
18828 *
18829 * @static
18830 * @memberOf _
18831 * @since 2.0.0
18832 * @category Array
18833 * @param {Array} array The array to modify.
18834 * @param {Function} [predicate=_.identity] The function invoked per iteration.
18835 * @returns {Array} Returns the new array of removed elements.
18836 * @example
18837 *
18838 * var array = [1, 2, 3, 4];
18839 * var evens = _.remove(array, function(n) {
18840 * return n % 2 == 0;
18841 * });
18842 *
18843 * console.log(array);
18844 * // => [1, 3]
18845 *
18846 * console.log(evens);
18847 * // => [2, 4]
18848 */
18849 function remove(array, predicate) {
18850 var result = [];
18851 if (!(array && array.length)) {
18852 return result;
18853 }
18854 var index = -1,
18855 indexes = [],
18856 length = array.length;
18857
18858 predicate = _baseIteratee(predicate);
18859 while (++index < length) {
18860 var value = array[index];
18861 if (predicate(value, index, array)) {
18862 result.push(value);
18863 indexes.push(index);
18864 }
18865 }
18866 _basePullAt(array, indexes);
18867 return result;
18868 }
18869
18870 var remove_1 = remove;
18871
18872 /** `Object#toString` result references. */
18873 var mapTag$3 = '[object Map]',
18874 setTag$3 = '[object Set]';
18875
18876 /** Used for built-in method references. */
18877 var objectProto$d = Object.prototype;
18878
18879 /** Used to check objects for own properties. */
18880 var hasOwnProperty$a = objectProto$d.hasOwnProperty;
18881
18882 /**
18883 * Checks if `value` is an empty object, collection, map, or set.
18884 *
18885 * Objects are considered empty if they have no own enumerable string keyed
18886 * properties.
18887 *
18888 * Array-like values such as `arguments` objects, arrays, buffers, strings, or
18889 * jQuery-like collections are considered empty if they have a `length` of `0`.
18890 * Similarly, maps and sets are considered empty if they have a `size` of `0`.
18891 *
18892 * @static
18893 * @memberOf _
18894 * @since 0.1.0
18895 * @category Lang
18896 * @param {*} value The value to check.
18897 * @returns {boolean} Returns `true` if `value` is empty, else `false`.
18898 * @example
18899 *
18900 * _.isEmpty(null);
18901 * // => true
18902 *
18903 * _.isEmpty(true);
18904 * // => true
18905 *
18906 * _.isEmpty(1);
18907 * // => true
18908 *
18909 * _.isEmpty([1, 2, 3]);
18910 * // => false
18911 *
18912 * _.isEmpty({ 'a': 1 });
18913 * // => false
18914 */
18915 function isEmpty(value) {
18916 if (value == null) {
18917 return true;
18918 }
18919 if (isArrayLike_1(value) &&
18920 (isArray_1(value) || typeof value == 'string' || typeof value.splice == 'function' ||
18921 isBuffer_1(value) || isTypedArray_1(value) || isArguments_1(value))) {
18922 return !value.length;
18923 }
18924 var tag = _getTag(value);
18925 if (tag == mapTag$3 || tag == setTag$3) {
18926 return !value.size;
18927 }
18928 if (_isPrototype(value)) {
18929 return !_baseKeys(value).length;
18930 }
18931 for (var key in value) {
18932 if (hasOwnProperty$a.call(value, key)) {
18933 return false;
18934 }
18935 }
18936 return true;
18937 }
18938
18939 var isEmpty_1 = isEmpty;
18940
18941 /**
18942 * A specialized version of `_.forEach` for arrays without support for
18943 * iteratee shorthands.
18944 *
18945 * @private
18946 * @param {Array} [array] The array to iterate over.
18947 * @param {Function} iteratee The function invoked per iteration.
18948 * @returns {Array} Returns `array`.
18949 */
18950 function arrayEach(array, iteratee) {
18951 var index = -1,
18952 length = array == null ? 0 : array.length;
18953
18954 while (++index < length) {
18955 if (iteratee(array[index], index, array) === false) {
18956 break;
18957 }
18958 }
18959 return array;
18960 }
18961
18962 var _arrayEach = arrayEach;
18963
18964 var defineProperty$1 = (function() {
18965 try {
18966 var func = _getNative(Object, 'defineProperty');
18967 func({}, '', {});
18968 return func;
18969 } catch (e) {}
18970 }());
18971
18972 var _defineProperty$1 = defineProperty$1;
18973
18974 /**
18975 * The base implementation of `assignValue` and `assignMergeValue` without
18976 * value checks.
18977 *
18978 * @private
18979 * @param {Object} object The object to modify.
18980 * @param {string} key The key of the property to assign.
18981 * @param {*} value The value to assign.
18982 */
18983 function baseAssignValue(object, key, value) {
18984 if (key == '__proto__' && _defineProperty$1) {
18985 _defineProperty$1(object, key, {
18986 'configurable': true,
18987 'enumerable': true,
18988 'value': value,
18989 'writable': true
18990 });
18991 } else {
18992 object[key] = value;
18993 }
18994 }
18995
18996 var _baseAssignValue = baseAssignValue;
18997
18998 /** Used for built-in method references. */
18999 var objectProto$e = Object.prototype;
19000
19001 /** Used to check objects for own properties. */
19002 var hasOwnProperty$b = objectProto$e.hasOwnProperty;
19003
19004 /**
19005 * Assigns `value` to `key` of `object` if the existing value is not equivalent
19006 * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
19007 * for equality comparisons.
19008 *
19009 * @private
19010 * @param {Object} object The object to modify.
19011 * @param {string} key The key of the property to assign.
19012 * @param {*} value The value to assign.
19013 */
19014 function assignValue(object, key, value) {
19015 var objValue = object[key];
19016 if (!(hasOwnProperty$b.call(object, key) && eq_1(objValue, value)) ||
19017 (value === undefined && !(key in object))) {
19018 _baseAssignValue(object, key, value);
19019 }
19020 }
19021
19022 var _assignValue = assignValue;
19023
19024 /**
19025 * Copies properties of `source` to `object`.
19026 *
19027 * @private
19028 * @param {Object} source The object to copy properties from.
19029 * @param {Array} props The property identifiers to copy.
19030 * @param {Object} [object={}] The object to copy properties to.
19031 * @param {Function} [customizer] The function to customize copied values.
19032 * @returns {Object} Returns `object`.
19033 */
19034 function copyObject(source, props, object, customizer) {
19035 var isNew = !object;
19036 object || (object = {});
19037
19038 var index = -1,
19039 length = props.length;
19040
19041 while (++index < length) {
19042 var key = props[index];
19043
19044 var newValue = customizer
19045 ? customizer(object[key], source[key], key, object, source)
19046 : undefined;
19047
19048 if (newValue === undefined) {
19049 newValue = source[key];
19050 }
19051 if (isNew) {
19052 _baseAssignValue(object, key, newValue);
19053 } else {
19054 _assignValue(object, key, newValue);
19055 }
19056 }
19057 return object;
19058 }
19059
19060 var _copyObject = copyObject;
19061
19062 /**
19063 * The base implementation of `_.assign` without support for multiple sources
19064 * or `customizer` functions.
19065 *
19066 * @private
19067 * @param {Object} object The destination object.
19068 * @param {Object} source The source object.
19069 * @returns {Object} Returns `object`.
19070 */
19071 function baseAssign(object, source) {
19072 return object && _copyObject(source, keys_1(source), object);
19073 }
19074
19075 var _baseAssign = baseAssign;
19076
19077 /**
19078 * This function is like
19079 * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
19080 * except that it includes inherited enumerable properties.
19081 *
19082 * @private
19083 * @param {Object} object The object to query.
19084 * @returns {Array} Returns the array of property names.
19085 */
19086 function nativeKeysIn(object) {
19087 var result = [];
19088 if (object != null) {
19089 for (var key in Object(object)) {
19090 result.push(key);
19091 }
19092 }
19093 return result;
19094 }
19095
19096 var _nativeKeysIn = nativeKeysIn;
19097
19098 /** Used for built-in method references. */
19099 var objectProto$f = Object.prototype;
19100
19101 /** Used to check objects for own properties. */
19102 var hasOwnProperty$c = objectProto$f.hasOwnProperty;
19103
19104 /**
19105 * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense.
19106 *
19107 * @private
19108 * @param {Object} object The object to query.
19109 * @returns {Array} Returns the array of property names.
19110 */
19111 function baseKeysIn(object) {
19112 if (!isObject_1(object)) {
19113 return _nativeKeysIn(object);
19114 }
19115 var isProto = _isPrototype(object),
19116 result = [];
19117
19118 for (var key in object) {
19119 if (!(key == 'constructor' && (isProto || !hasOwnProperty$c.call(object, key)))) {
19120 result.push(key);
19121 }
19122 }
19123 return result;
19124 }
19125
19126 var _baseKeysIn = baseKeysIn;
19127
19128 /**
19129 * Creates an array of the own and inherited enumerable property names of `object`.
19130 *
19131 * **Note:** Non-object values are coerced to objects.
19132 *
19133 * @static
19134 * @memberOf _
19135 * @since 3.0.0
19136 * @category Object
19137 * @param {Object} object The object to query.
19138 * @returns {Array} Returns the array of property names.
19139 * @example
19140 *
19141 * function Foo() {
19142 * this.a = 1;
19143 * this.b = 2;
19144 * }
19145 *
19146 * Foo.prototype.c = 3;
19147 *
19148 * _.keysIn(new Foo);
19149 * // => ['a', 'b', 'c'] (iteration order is not guaranteed)
19150 */
19151 function keysIn(object) {
19152 return isArrayLike_1(object) ? _arrayLikeKeys(object, true) : _baseKeysIn(object);
19153 }
19154
19155 var keysIn_1 = keysIn;
19156
19157 /**
19158 * The base implementation of `_.assignIn` without support for multiple sources
19159 * or `customizer` functions.
19160 *
19161 * @private
19162 * @param {Object} object The destination object.
19163 * @param {Object} source The source object.
19164 * @returns {Object} Returns `object`.
19165 */
19166 function baseAssignIn(object, source) {
19167 return object && _copyObject(source, keysIn_1(source), object);
19168 }
19169
19170 var _baseAssignIn = baseAssignIn;
19171
19172 var _cloneBuffer = createCommonjsModule(function (module, exports) {
19173 /** Detect free variable `exports`. */
19174 var freeExports = exports && !exports.nodeType && exports;
19175
19176 /** Detect free variable `module`. */
19177 var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module;
19178
19179 /** Detect the popular CommonJS extension `module.exports`. */
19180 var moduleExports = freeModule && freeModule.exports === freeExports;
19181
19182 /** Built-in value references. */
19183 var Buffer = moduleExports ? _root.Buffer : undefined,
19184 allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined;
19185
19186 /**
19187 * Creates a clone of `buffer`.
19188 *
19189 * @private
19190 * @param {Buffer} buffer The buffer to clone.
19191 * @param {boolean} [isDeep] Specify a deep clone.
19192 * @returns {Buffer} Returns the cloned buffer.
19193 */
19194 function cloneBuffer(buffer, isDeep) {
19195 if (isDeep) {
19196 return buffer.slice();
19197 }
19198 var length = buffer.length,
19199 result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length);
19200
19201 buffer.copy(result);
19202 return result;
19203 }
19204
19205 module.exports = cloneBuffer;
19206 });
19207
19208 /**
19209 * Copies own symbols of `source` to `object`.
19210 *
19211 * @private
19212 * @param {Object} source The object to copy symbols from.
19213 * @param {Object} [object={}] The object to copy symbols to.
19214 * @returns {Object} Returns `object`.
19215 */
19216 function copySymbols(source, object) {
19217 return _copyObject(source, _getSymbols(source), object);
19218 }
19219
19220 var _copySymbols = copySymbols;
19221
19222 /* Built-in method references for those with the same name as other `lodash` methods. */
19223 var nativeGetSymbols$1 = Object.getOwnPropertySymbols;
19224
19225 /**
19226 * Creates an array of the own and inherited enumerable symbols of `object`.
19227 *
19228 * @private
19229 * @param {Object} object The object to query.
19230 * @returns {Array} Returns the array of symbols.
19231 */
19232 var getSymbolsIn = !nativeGetSymbols$1 ? stubArray_1 : function(object) {
19233 var result = [];
19234 while (object) {
19235 _arrayPush(result, _getSymbols(object));
19236 object = _getPrototype(object);
19237 }
19238 return result;
19239 };
19240
19241 var _getSymbolsIn = getSymbolsIn;
19242
19243 /**
19244 * Copies own and inherited symbols of `source` to `object`.
19245 *
19246 * @private
19247 * @param {Object} source The object to copy symbols from.
19248 * @param {Object} [object={}] The object to copy symbols to.
19249 * @returns {Object} Returns `object`.
19250 */
19251 function copySymbolsIn(source, object) {
19252 return _copyObject(source, _getSymbolsIn(source), object);
19253 }
19254
19255 var _copySymbolsIn = copySymbolsIn;
19256
19257 /**
19258 * Creates an array of own and inherited enumerable property names and
19259 * symbols of `object`.
19260 *
19261 * @private
19262 * @param {Object} object The object to query.
19263 * @returns {Array} Returns the array of property names and symbols.
19264 */
19265 function getAllKeysIn(object) {
19266 return _baseGetAllKeys(object, keysIn_1, _getSymbolsIn);
19267 }
19268
19269 var _getAllKeysIn = getAllKeysIn;
19270
19271 /** Used for built-in method references. */
19272 var objectProto$g = Object.prototype;
19273
19274 /** Used to check objects for own properties. */
19275 var hasOwnProperty$d = objectProto$g.hasOwnProperty;
19276
19277 /**
19278 * Initializes an array clone.
19279 *
19280 * @private
19281 * @param {Array} array The array to clone.
19282 * @returns {Array} Returns the initialized clone.
19283 */
19284 function initCloneArray(array) {
19285 var length = array.length,
19286 result = new array.constructor(length);
19287
19288 // Add properties assigned by `RegExp#exec`.
19289 if (length && typeof array[0] == 'string' && hasOwnProperty$d.call(array, 'index')) {
19290 result.index = array.index;
19291 result.input = array.input;
19292 }
19293 return result;
19294 }
19295
19296 var _initCloneArray = initCloneArray;
19297
19298 /**
19299 * Creates a clone of `arrayBuffer`.
19300 *
19301 * @private
19302 * @param {ArrayBuffer} arrayBuffer The array buffer to clone.
19303 * @returns {ArrayBuffer} Returns the cloned array buffer.
19304 */
19305 function cloneArrayBuffer(arrayBuffer) {
19306 var result = new arrayBuffer.constructor(arrayBuffer.byteLength);
19307 new _Uint8Array(result).set(new _Uint8Array(arrayBuffer));
19308 return result;
19309 }
19310
19311 var _cloneArrayBuffer = cloneArrayBuffer;
19312
19313 /**
19314 * Creates a clone of `dataView`.
19315 *
19316 * @private
19317 * @param {Object} dataView The data view to clone.
19318 * @param {boolean} [isDeep] Specify a deep clone.
19319 * @returns {Object} Returns the cloned data view.
19320 */
19321 function cloneDataView(dataView, isDeep) {
19322 var buffer = isDeep ? _cloneArrayBuffer(dataView.buffer) : dataView.buffer;
19323 return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength);
19324 }
19325
19326 var _cloneDataView = cloneDataView;
19327
19328 /** Used to match `RegExp` flags from their coerced string values. */
19329 var reFlags = /\w*$/;
19330
19331 /**
19332 * Creates a clone of `regexp`.
19333 *
19334 * @private
19335 * @param {Object} regexp The regexp to clone.
19336 * @returns {Object} Returns the cloned regexp.
19337 */
19338 function cloneRegExp(regexp) {
19339 var result = new regexp.constructor(regexp.source, reFlags.exec(regexp));
19340 result.lastIndex = regexp.lastIndex;
19341 return result;
19342 }
19343
19344 var _cloneRegExp = cloneRegExp;
19345
19346 /** Used to convert symbols to primitives and strings. */
19347 var symbolProto$2 = _Symbol ? _Symbol.prototype : undefined,
19348 symbolValueOf$1 = symbolProto$2 ? symbolProto$2.valueOf : undefined;
19349
19350 /**
19351 * Creates a clone of the `symbol` object.
19352 *
19353 * @private
19354 * @param {Object} symbol The symbol object to clone.
19355 * @returns {Object} Returns the cloned symbol object.
19356 */
19357 function cloneSymbol(symbol) {
19358 return symbolValueOf$1 ? Object(symbolValueOf$1.call(symbol)) : {};
19359 }
19360
19361 var _cloneSymbol = cloneSymbol;
19362
19363 /**
19364 * Creates a clone of `typedArray`.
19365 *
19366 * @private
19367 * @param {Object} typedArray The typed array to clone.
19368 * @param {boolean} [isDeep] Specify a deep clone.
19369 * @returns {Object} Returns the cloned typed array.
19370 */
19371 function cloneTypedArray(typedArray, isDeep) {
19372 var buffer = isDeep ? _cloneArrayBuffer(typedArray.buffer) : typedArray.buffer;
19373 return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);
19374 }
19375
19376 var _cloneTypedArray = cloneTypedArray;
19377
19378 /** `Object#toString` result references. */
19379 var boolTag$2 = '[object Boolean]',
19380 dateTag$2 = '[object Date]',
19381 mapTag$4 = '[object Map]',
19382 numberTag$2 = '[object Number]',
19383 regexpTag$2 = '[object RegExp]',
19384 setTag$4 = '[object Set]',
19385 stringTag$2 = '[object String]',
19386 symbolTag$2 = '[object Symbol]';
19387
19388 var arrayBufferTag$2 = '[object ArrayBuffer]',
19389 dataViewTag$3 = '[object DataView]',
19390 float32Tag$1 = '[object Float32Array]',
19391 float64Tag$1 = '[object Float64Array]',
19392 int8Tag$1 = '[object Int8Array]',
19393 int16Tag$1 = '[object Int16Array]',
19394 int32Tag$1 = '[object Int32Array]',
19395 uint8Tag$1 = '[object Uint8Array]',
19396 uint8ClampedTag$1 = '[object Uint8ClampedArray]',
19397 uint16Tag$1 = '[object Uint16Array]',
19398 uint32Tag$1 = '[object Uint32Array]';
19399
19400 /**
19401 * Initializes an object clone based on its `toStringTag`.
19402 *
19403 * **Note:** This function only supports cloning values with tags of
19404 * `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`.
19405 *
19406 * @private
19407 * @param {Object} object The object to clone.
19408 * @param {string} tag The `toStringTag` of the object to clone.
19409 * @param {boolean} [isDeep] Specify a deep clone.
19410 * @returns {Object} Returns the initialized clone.
19411 */
19412 function initCloneByTag(object, tag, isDeep) {
19413 var Ctor = object.constructor;
19414 switch (tag) {
19415 case arrayBufferTag$2:
19416 return _cloneArrayBuffer(object);
19417
19418 case boolTag$2:
19419 case dateTag$2:
19420 return new Ctor(+object);
19421
19422 case dataViewTag$3:
19423 return _cloneDataView(object, isDeep);
19424
19425 case float32Tag$1: case float64Tag$1:
19426 case int8Tag$1: case int16Tag$1: case int32Tag$1:
19427 case uint8Tag$1: case uint8ClampedTag$1: case uint16Tag$1: case uint32Tag$1:
19428 return _cloneTypedArray(object, isDeep);
19429
19430 case mapTag$4:
19431 return new Ctor;
19432
19433 case numberTag$2:
19434 case stringTag$2:
19435 return new Ctor(object);
19436
19437 case regexpTag$2:
19438 return _cloneRegExp(object);
19439
19440 case setTag$4:
19441 return new Ctor;
19442
19443 case symbolTag$2:
19444 return _cloneSymbol(object);
19445 }
19446 }
19447
19448 var _initCloneByTag = initCloneByTag;
19449
19450 /** Built-in value references. */
19451 var objectCreate = Object.create;
19452
19453 /**
19454 * The base implementation of `_.create` without support for assigning
19455 * properties to the created object.
19456 *
19457 * @private
19458 * @param {Object} proto The object to inherit from.
19459 * @returns {Object} Returns the new object.
19460 */
19461 var baseCreate = (function() {
19462 function object() {}
19463 return function(proto) {
19464 if (!isObject_1(proto)) {
19465 return {};
19466 }
19467 if (objectCreate) {
19468 return objectCreate(proto);
19469 }
19470 object.prototype = proto;
19471 var result = new object;
19472 object.prototype = undefined;
19473 return result;
19474 };
19475 }());
19476
19477 var _baseCreate = baseCreate;
19478
19479 /**
19480 * Initializes an object clone.
19481 *
19482 * @private
19483 * @param {Object} object The object to clone.
19484 * @returns {Object} Returns the initialized clone.
19485 */
19486 function initCloneObject(object) {
19487 return (typeof object.constructor == 'function' && !_isPrototype(object))
19488 ? _baseCreate(_getPrototype(object))
19489 : {};
19490 }
19491
19492 var _initCloneObject = initCloneObject;
19493
19494 /** `Object#toString` result references. */
19495 var mapTag$5 = '[object Map]';
19496
19497 /**
19498 * The base implementation of `_.isMap` without Node.js optimizations.
19499 *
19500 * @private
19501 * @param {*} value The value to check.
19502 * @returns {boolean} Returns `true` if `value` is a map, else `false`.
19503 */
19504 function baseIsMap(value) {
19505 return isObjectLike_1(value) && _getTag(value) == mapTag$5;
19506 }
19507
19508 var _baseIsMap = baseIsMap;
19509
19510 /* Node.js helper references. */
19511 var nodeIsMap = _nodeUtil && _nodeUtil.isMap;
19512
19513 /**
19514 * Checks if `value` is classified as a `Map` object.
19515 *
19516 * @static
19517 * @memberOf _
19518 * @since 4.3.0
19519 * @category Lang
19520 * @param {*} value The value to check.
19521 * @returns {boolean} Returns `true` if `value` is a map, else `false`.
19522 * @example
19523 *
19524 * _.isMap(new Map);
19525 * // => true
19526 *
19527 * _.isMap(new WeakMap);
19528 * // => false
19529 */
19530 var isMap = nodeIsMap ? _baseUnary(nodeIsMap) : _baseIsMap;
19531
19532 var isMap_1 = isMap;
19533
19534 /** `Object#toString` result references. */
19535 var setTag$5 = '[object Set]';
19536
19537 /**
19538 * The base implementation of `_.isSet` without Node.js optimizations.
19539 *
19540 * @private
19541 * @param {*} value The value to check.
19542 * @returns {boolean} Returns `true` if `value` is a set, else `false`.
19543 */
19544 function baseIsSet(value) {
19545 return isObjectLike_1(value) && _getTag(value) == setTag$5;
19546 }
19547
19548 var _baseIsSet = baseIsSet;
19549
19550 /* Node.js helper references. */
19551 var nodeIsSet = _nodeUtil && _nodeUtil.isSet;
19552
19553 /**
19554 * Checks if `value` is classified as a `Set` object.
19555 *
19556 * @static
19557 * @memberOf _
19558 * @since 4.3.0
19559 * @category Lang
19560 * @param {*} value The value to check.
19561 * @returns {boolean} Returns `true` if `value` is a set, else `false`.
19562 * @example
19563 *
19564 * _.isSet(new Set);
19565 * // => true
19566 *
19567 * _.isSet(new WeakSet);
19568 * // => false
19569 */
19570 var isSet = nodeIsSet ? _baseUnary(nodeIsSet) : _baseIsSet;
19571
19572 var isSet_1 = isSet;
19573
19574 /** Used to compose bitmasks for cloning. */
19575 var CLONE_DEEP_FLAG = 1,
19576 CLONE_FLAT_FLAG = 2,
19577 CLONE_SYMBOLS_FLAG = 4;
19578
19579 /** `Object#toString` result references. */
19580 var argsTag$3 = '[object Arguments]',
19581 arrayTag$2 = '[object Array]',
19582 boolTag$3 = '[object Boolean]',
19583 dateTag$3 = '[object Date]',
19584 errorTag$2 = '[object Error]',
19585 funcTag$2 = '[object Function]',
19586 genTag$1 = '[object GeneratorFunction]',
19587 mapTag$6 = '[object Map]',
19588 numberTag$3 = '[object Number]',
19589 objectTag$4 = '[object Object]',
19590 regexpTag$3 = '[object RegExp]',
19591 setTag$6 = '[object Set]',
19592 stringTag$3 = '[object String]',
19593 symbolTag$3 = '[object Symbol]',
19594 weakMapTag$2 = '[object WeakMap]';
19595
19596 var arrayBufferTag$3 = '[object ArrayBuffer]',
19597 dataViewTag$4 = '[object DataView]',
19598 float32Tag$2 = '[object Float32Array]',
19599 float64Tag$2 = '[object Float64Array]',
19600 int8Tag$2 = '[object Int8Array]',
19601 int16Tag$2 = '[object Int16Array]',
19602 int32Tag$2 = '[object Int32Array]',
19603 uint8Tag$2 = '[object Uint8Array]',
19604 uint8ClampedTag$2 = '[object Uint8ClampedArray]',
19605 uint16Tag$2 = '[object Uint16Array]',
19606 uint32Tag$2 = '[object Uint32Array]';
19607
19608 /** Used to identify `toStringTag` values supported by `_.clone`. */
19609 var cloneableTags = {};
19610 cloneableTags[argsTag$3] = cloneableTags[arrayTag$2] =
19611 cloneableTags[arrayBufferTag$3] = cloneableTags[dataViewTag$4] =
19612 cloneableTags[boolTag$3] = cloneableTags[dateTag$3] =
19613 cloneableTags[float32Tag$2] = cloneableTags[float64Tag$2] =
19614 cloneableTags[int8Tag$2] = cloneableTags[int16Tag$2] =
19615 cloneableTags[int32Tag$2] = cloneableTags[mapTag$6] =
19616 cloneableTags[numberTag$3] = cloneableTags[objectTag$4] =
19617 cloneableTags[regexpTag$3] = cloneableTags[setTag$6] =
19618 cloneableTags[stringTag$3] = cloneableTags[symbolTag$3] =
19619 cloneableTags[uint8Tag$2] = cloneableTags[uint8ClampedTag$2] =
19620 cloneableTags[uint16Tag$2] = cloneableTags[uint32Tag$2] = true;
19621 cloneableTags[errorTag$2] = cloneableTags[funcTag$2] =
19622 cloneableTags[weakMapTag$2] = false;
19623
19624 /**
19625 * The base implementation of `_.clone` and `_.cloneDeep` which tracks
19626 * traversed objects.
19627 *
19628 * @private
19629 * @param {*} value The value to clone.
19630 * @param {boolean} bitmask The bitmask flags.
19631 * 1 - Deep clone
19632 * 2 - Flatten inherited properties
19633 * 4 - Clone symbols
19634 * @param {Function} [customizer] The function to customize cloning.
19635 * @param {string} [key] The key of `value`.
19636 * @param {Object} [object] The parent object of `value`.
19637 * @param {Object} [stack] Tracks traversed objects and their clone counterparts.
19638 * @returns {*} Returns the cloned value.
19639 */
19640 function baseClone(value, bitmask, customizer, key, object, stack) {
19641 var result,
19642 isDeep = bitmask & CLONE_DEEP_FLAG,
19643 isFlat = bitmask & CLONE_FLAT_FLAG,
19644 isFull = bitmask & CLONE_SYMBOLS_FLAG;
19645
19646 if (customizer) {
19647 result = object ? customizer(value, key, object, stack) : customizer(value);
19648 }
19649 if (result !== undefined) {
19650 return result;
19651 }
19652 if (!isObject_1(value)) {
19653 return value;
19654 }
19655 var isArr = isArray_1(value);
19656 if (isArr) {
19657 result = _initCloneArray(value);
19658 if (!isDeep) {
19659 return _copyArray(value, result);
19660 }
19661 } else {
19662 var tag = _getTag(value),
19663 isFunc = tag == funcTag$2 || tag == genTag$1;
19664
19665 if (isBuffer_1(value)) {
19666 return _cloneBuffer(value, isDeep);
19667 }
19668 if (tag == objectTag$4 || tag == argsTag$3 || (isFunc && !object)) {
19669 result = (isFlat || isFunc) ? {} : _initCloneObject(value);
19670 if (!isDeep) {
19671 return isFlat
19672 ? _copySymbolsIn(value, _baseAssignIn(result, value))
19673 : _copySymbols(value, _baseAssign(result, value));
19674 }
19675 } else {
19676 if (!cloneableTags[tag]) {
19677 return object ? value : {};
19678 }
19679 result = _initCloneByTag(value, tag, isDeep);
19680 }
19681 }
19682 // Check for circular references and return its corresponding clone.
19683 stack || (stack = new _Stack);
19684 var stacked = stack.get(value);
19685 if (stacked) {
19686 return stacked;
19687 }
19688 stack.set(value, result);
19689
19690 if (isSet_1(value)) {
19691 value.forEach(function(subValue) {
19692 result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack));
19693 });
19694 } else if (isMap_1(value)) {
19695 value.forEach(function(subValue, key) {
19696 result.set(key, baseClone(subValue, bitmask, customizer, key, value, stack));
19697 });
19698 }
19699
19700 var keysFunc = isFull
19701 ? (isFlat ? _getAllKeysIn : _getAllKeys)
19702 : (isFlat ? keysIn_1 : keys_1);
19703
19704 var props = isArr ? undefined : keysFunc(value);
19705 _arrayEach(props || value, function(subValue, key) {
19706 if (props) {
19707 key = subValue;
19708 subValue = value[key];
19709 }
19710 // Recursively populate clone (susceptible to call stack limits).
19711 _assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack));
19712 });
19713 return result;
19714 }
19715
19716 var _baseClone = baseClone;
19717
19718 /** Used to compose bitmasks for cloning. */
19719 var CLONE_DEEP_FLAG$1 = 1,
19720 CLONE_SYMBOLS_FLAG$1 = 4;
19721
19722 /**
19723 * This method is like `_.clone` except that it recursively clones `value`.
19724 *
19725 * @static
19726 * @memberOf _
19727 * @since 1.0.0
19728 * @category Lang
19729 * @param {*} value The value to recursively clone.
19730 * @returns {*} Returns the deep cloned value.
19731 * @see _.clone
19732 * @example
19733 *
19734 * var objects = [{ 'a': 1 }, { 'b': 2 }];
19735 *
19736 * var deep = _.cloneDeep(objects);
19737 * console.log(deep[0] === objects[0]);
19738 * // => false
19739 */
19740 function cloneDeep(value) {
19741 return _baseClone(value, CLONE_DEEP_FLAG$1 | CLONE_SYMBOLS_FLAG$1);
19742 }
19743
19744 var cloneDeep_1 = cloneDeep;
19745
19746 /**
19747 * Creates a `_.find` or `_.findLast` function.
19748 *
19749 * @private
19750 * @param {Function} findIndexFunc The function to find the collection index.
19751 * @returns {Function} Returns the new find function.
19752 */
19753 function createFind(findIndexFunc) {
19754 return function(collection, predicate, fromIndex) {
19755 var iterable = Object(collection);
19756 if (!isArrayLike_1(collection)) {
19757 var iteratee = _baseIteratee(predicate);
19758 collection = keys_1(collection);
19759 predicate = function(key) { return iteratee(iterable[key], key, iterable); };
19760 }
19761 var index = findIndexFunc(collection, predicate, fromIndex);
19762 return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined;
19763 };
19764 }
19765
19766 var _createFind = createFind;
19767
19768 /**
19769 * The base implementation of `_.findIndex` and `_.findLastIndex` without
19770 * support for iteratee shorthands.
19771 *
19772 * @private
19773 * @param {Array} array The array to inspect.
19774 * @param {Function} predicate The function invoked per iteration.
19775 * @param {number} fromIndex The index to search from.
19776 * @param {boolean} [fromRight] Specify iterating from right to left.
19777 * @returns {number} Returns the index of the matched value, else `-1`.
19778 */
19779 function baseFindIndex(array, predicate, fromIndex, fromRight) {
19780 var length = array.length,
19781 index = fromIndex + (fromRight ? 1 : -1);
19782
19783 while ((fromRight ? index-- : ++index < length)) {
19784 if (predicate(array[index], index, array)) {
19785 return index;
19786 }
19787 }
19788 return -1;
19789 }
19790
19791 var _baseFindIndex = baseFindIndex;
19792
19793 /** Used to match a single whitespace character. */
19794 var reWhitespace = /\s/;
19795
19796 /**
19797 * Used by `_.trim` and `_.trimEnd` to get the index of the last non-whitespace
19798 * character of `string`.
19799 *
19800 * @private
19801 * @param {string} string The string to inspect.
19802 * @returns {number} Returns the index of the last non-whitespace character.
19803 */
19804 function trimmedEndIndex(string) {
19805 var index = string.length;
19806
19807 while (index-- && reWhitespace.test(string.charAt(index))) {}
19808 return index;
19809 }
19810
19811 var _trimmedEndIndex = trimmedEndIndex;
19812
19813 /** Used to match leading whitespace. */
19814 var reTrimStart = /^\s+/;
19815
19816 /**
19817 * The base implementation of `_.trim`.
19818 *
19819 * @private
19820 * @param {string} string The string to trim.
19821 * @returns {string} Returns the trimmed string.
19822 */
19823 function baseTrim(string) {
19824 return string
19825 ? string.slice(0, _trimmedEndIndex(string) + 1).replace(reTrimStart, '')
19826 : string;
19827 }
19828
19829 var _baseTrim = baseTrim;
19830
19831 /** Used as references for various `Number` constants. */
19832 var NAN = 0 / 0;
19833
19834 /** Used to detect bad signed hexadecimal string values. */
19835 var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
19836
19837 /** Used to detect binary string values. */
19838 var reIsBinary = /^0b[01]+$/i;
19839
19840 /** Used to detect octal string values. */
19841 var reIsOctal = /^0o[0-7]+$/i;
19842
19843 /** Built-in method references without a dependency on `root`. */
19844 var freeParseInt = parseInt;
19845
19846 /**
19847 * Converts `value` to a number.
19848 *
19849 * @static
19850 * @memberOf _
19851 * @since 4.0.0
19852 * @category Lang
19853 * @param {*} value The value to process.
19854 * @returns {number} Returns the number.
19855 * @example
19856 *
19857 * _.toNumber(3.2);
19858 * // => 3.2
19859 *
19860 * _.toNumber(Number.MIN_VALUE);
19861 * // => 5e-324
19862 *
19863 * _.toNumber(Infinity);
19864 * // => Infinity
19865 *
19866 * _.toNumber('3.2');
19867 * // => 3.2
19868 */
19869 function toNumber(value) {
19870 if (typeof value == 'number') {
19871 return value;
19872 }
19873 if (isSymbol_1(value)) {
19874 return NAN;
19875 }
19876 if (isObject_1(value)) {
19877 var other = typeof value.valueOf == 'function' ? value.valueOf() : value;
19878 value = isObject_1(other) ? (other + '') : other;
19879 }
19880 if (typeof value != 'string') {
19881 return value === 0 ? value : +value;
19882 }
19883 value = _baseTrim(value);
19884 var isBinary = reIsBinary.test(value);
19885 return (isBinary || reIsOctal.test(value))
19886 ? freeParseInt(value.slice(2), isBinary ? 2 : 8)
19887 : (reIsBadHex.test(value) ? NAN : +value);
19888 }
19889
19890 var toNumber_1 = toNumber;
19891
19892 /** Used as references for various `Number` constants. */
19893 var INFINITY$2 = 1 / 0,
19894 MAX_INTEGER = 1.7976931348623157e+308;
19895
19896 /**
19897 * Converts `value` to a finite number.
19898 *
19899 * @static
19900 * @memberOf _
19901 * @since 4.12.0
19902 * @category Lang
19903 * @param {*} value The value to convert.
19904 * @returns {number} Returns the converted number.
19905 * @example
19906 *
19907 * _.toFinite(3.2);
19908 * // => 3.2
19909 *
19910 * _.toFinite(Number.MIN_VALUE);
19911 * // => 5e-324
19912 *
19913 * _.toFinite(Infinity);
19914 * // => 1.7976931348623157e+308
19915 *
19916 * _.toFinite('3.2');
19917 * // => 3.2
19918 */
19919 function toFinite(value) {
19920 if (!value) {
19921 return value === 0 ? value : 0;
19922 }
19923 value = toNumber_1(value);
19924 if (value === INFINITY$2 || value === -INFINITY$2) {
19925 var sign = (value < 0 ? -1 : 1);
19926 return sign * MAX_INTEGER;
19927 }
19928 return value === value ? value : 0;
19929 }
19930
19931 var toFinite_1 = toFinite;
19932
19933 /**
19934 * Converts `value` to an integer.
19935 *
19936 * **Note:** This method is loosely based on
19937 * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger).
19938 *
19939 * @static
19940 * @memberOf _
19941 * @since 4.0.0
19942 * @category Lang
19943 * @param {*} value The value to convert.
19944 * @returns {number} Returns the converted integer.
19945 * @example
19946 *
19947 * _.toInteger(3.2);
19948 * // => 3
19949 *
19950 * _.toInteger(Number.MIN_VALUE);
19951 * // => 0
19952 *
19953 * _.toInteger(Infinity);
19954 * // => 1.7976931348623157e+308
19955 *
19956 * _.toInteger('3.2');
19957 * // => 3
19958 */
19959 function toInteger(value) {
19960 var result = toFinite_1(value),
19961 remainder = result % 1;
19962
19963 return result === result ? (remainder ? result - remainder : result) : 0;
19964 }
19965
19966 var toInteger_1 = toInteger;
19967
19968 /* Built-in method references for those with the same name as other `lodash` methods. */
19969 var nativeMax = Math.max;
19970
19971 /**
19972 * This method is like `_.find` except that it returns the index of the first
19973 * element `predicate` returns truthy for instead of the element itself.
19974 *
19975 * @static
19976 * @memberOf _
19977 * @since 1.1.0
19978 * @category Array
19979 * @param {Array} array The array to inspect.
19980 * @param {Function} [predicate=_.identity] The function invoked per iteration.
19981 * @param {number} [fromIndex=0] The index to search from.
19982 * @returns {number} Returns the index of the found element, else `-1`.
19983 * @example
19984 *
19985 * var users = [
19986 * { 'user': 'barney', 'active': false },
19987 * { 'user': 'fred', 'active': false },
19988 * { 'user': 'pebbles', 'active': true }
19989 * ];
19990 *
19991 * _.findIndex(users, function(o) { return o.user == 'barney'; });
19992 * // => 0
19993 *
19994 * // The `_.matches` iteratee shorthand.
19995 * _.findIndex(users, { 'user': 'fred', 'active': false });
19996 * // => 1
19997 *
19998 * // The `_.matchesProperty` iteratee shorthand.
19999 * _.findIndex(users, ['active', false]);
20000 * // => 0
20001 *
20002 * // The `_.property` iteratee shorthand.
20003 * _.findIndex(users, 'active');
20004 * // => 2
20005 */
20006 function findIndex(array, predicate, fromIndex) {
20007 var length = array == null ? 0 : array.length;
20008 if (!length) {
20009 return -1;
20010 }
20011 var index = fromIndex == null ? 0 : toInteger_1(fromIndex);
20012 if (index < 0) {
20013 index = nativeMax(length + index, 0);
20014 }
20015 return _baseFindIndex(array, _baseIteratee(predicate), index);
20016 }
20017
20018 var findIndex_1 = findIndex;
20019
20020 /**
20021 * Iterates over elements of `collection`, returning the first element
20022 * `predicate` returns truthy for. The predicate is invoked with three
20023 * arguments: (value, index|key, collection).
20024 *
20025 * @static
20026 * @memberOf _
20027 * @since 0.1.0
20028 * @category Collection
20029 * @param {Array|Object} collection The collection to inspect.
20030 * @param {Function} [predicate=_.identity] The function invoked per iteration.
20031 * @param {number} [fromIndex=0] The index to search from.
20032 * @returns {*} Returns the matched element, else `undefined`.
20033 * @example
20034 *
20035 * var users = [
20036 * { 'user': 'barney', 'age': 36, 'active': true },
20037 * { 'user': 'fred', 'age': 40, 'active': false },
20038 * { 'user': 'pebbles', 'age': 1, 'active': true }
20039 * ];
20040 *
20041 * _.find(users, function(o) { return o.age < 40; });
20042 * // => object for 'barney'
20043 *
20044 * // The `_.matches` iteratee shorthand.
20045 * _.find(users, { 'age': 1, 'active': true });
20046 * // => object for 'pebbles'
20047 *
20048 * // The `_.matchesProperty` iteratee shorthand.
20049 * _.find(users, ['active', false]);
20050 * // => object for 'fred'
20051 *
20052 * // The `_.property` iteratee shorthand.
20053 * _.find(users, 'active');
20054 * // => object for 'barney'
20055 */
20056 var find = _createFind(findIndex_1);
20057
20058 var find_1 = find;
20059
20060 // IMClient
20061 var UNREAD_MESSAGES_COUNT_UPDATE = 'unreadmessagescountupdate';
20062 var CLOSE = 'close';
20063 var CONFLICT = 'conflict';
20064 var CONVERSATION_INFO_UPDATED = 'conversationinfoupdated';
20065 var UNHANDLED_MESSAGE = 'unhandledmessage';
20066
20067 // shared
20068 var INVITED = 'invited';
20069 var KICKED = 'kicked';
20070 var MEMBERS_JOINED = 'membersjoined';
20071 var MEMBERS_LEFT = 'membersleft';
20072 var MEMBER_INFO_UPDATED = 'memberinfoupdated';
20073 var BLOCKED = 'blocked';
20074 var UNBLOCKED = 'unblocked';
20075 var MEMBERS_BLOCKED = 'membersblocked';
20076 var MEMBERS_UNBLOCKED = 'membersunblocked';
20077 var MUTED = 'muted';
20078 var UNMUTED = 'unmuted';
20079 var MEMBERS_MUTED = 'membersmuted';
20080 var MEMBERS_UNMUTED = 'membersunmuted';
20081 var MESSAGE$1 = 'message';
20082 var MESSAGE_RECALL = 'messagerecall';
20083 var MESSAGE_UPDATE = 'messageupdate';
20084
20085 // Conversation
20086 var LAST_DELIVERED_AT_UPDATE = 'lastdeliveredatupdate';
20087 var LAST_READ_AT_UPDATE = 'lastreadatupdate';
20088 var INFO_UPDATED = 'infoupdated';
20089
20090 var IMEvent = /*#__PURE__*/Object.freeze({
20091 __proto__: null,
20092 UNREAD_MESSAGES_COUNT_UPDATE: UNREAD_MESSAGES_COUNT_UPDATE,
20093 CLOSE: CLOSE,
20094 CONFLICT: CONFLICT,
20095 CONVERSATION_INFO_UPDATED: CONVERSATION_INFO_UPDATED,
20096 UNHANDLED_MESSAGE: UNHANDLED_MESSAGE,
20097 INVITED: INVITED,
20098 KICKED: KICKED,
20099 MEMBERS_JOINED: MEMBERS_JOINED,
20100 MEMBERS_LEFT: MEMBERS_LEFT,
20101 MEMBER_INFO_UPDATED: MEMBER_INFO_UPDATED,
20102 BLOCKED: BLOCKED,
20103 UNBLOCKED: UNBLOCKED,
20104 MEMBERS_BLOCKED: MEMBERS_BLOCKED,
20105 MEMBERS_UNBLOCKED: MEMBERS_UNBLOCKED,
20106 MUTED: MUTED,
20107 UNMUTED: UNMUTED,
20108 MEMBERS_MUTED: MEMBERS_MUTED,
20109 MEMBERS_UNMUTED: MEMBERS_UNMUTED,
20110 MESSAGE: MESSAGE$1,
20111 MESSAGE_RECALL: MESSAGE_RECALL,
20112 MESSAGE_UPDATE: MESSAGE_UPDATE,
20113 LAST_DELIVERED_AT_UPDATE: LAST_DELIVERED_AT_UPDATE,
20114 LAST_READ_AT_UPDATE: LAST_READ_AT_UPDATE,
20115 INFO_UPDATED: INFO_UPDATED
20116 });
20117
20118 var _rMessageStatus;
20119 function ownKeys$3(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
20120 function _objectSpread$3(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys$3(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$3(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
20121
20122 /**
20123 * 消息状态枚举
20124 * @enum {Symbol}
20125 * @since 3.2.0
20126 * @memberof module:leancloud-realtime
20127 */
20128 var MessageStatus = {
20129 /** 初始状态、未知状态 */
20130 NONE: Symbol('none'),
20131 /** 正在发送 */
20132 SENDING: Symbol('sending'),
20133 /** 已发送 */
20134 SENT: Symbol('sent'),
20135 /** 已送达 */
20136 DELIVERED: Symbol('delivered'),
20137 /** 发送失败 */
20138 FAILED: Symbol('failed')
20139 };
20140 Object.freeze(MessageStatus);
20141 var rMessageStatus = (_rMessageStatus = {}, _defineProperty(_rMessageStatus, MessageStatus.NONE, true), _defineProperty(_rMessageStatus, MessageStatus.SENDING, true), _defineProperty(_rMessageStatus, MessageStatus.SENT, true), _defineProperty(_rMessageStatus, MessageStatus.DELIVERED, true), _defineProperty(_rMessageStatus, MessageStatus.READ, true), _defineProperty(_rMessageStatus, MessageStatus.FAILED, true), _rMessageStatus);
20142 var Message = /*#__PURE__*/function () {
20143 /**
20144 * @implements AVMessage
20145 * @param {Object|String|ArrayBuffer} content 消息内容
20146 */
20147 function Message(content) {
20148 Object.assign(this, {
20149 content: content
20150 }, {
20151 /**
20152 * @type {String}
20153 * @memberof Message#
20154 */
20155 id: v4_1(),
20156 /**
20157 * 消息所在的 conversation id
20158 * @memberof Message#
20159 * @type {String?}
20160 */
20161 cid: null,
20162 /**
20163 * 消息发送时间
20164 * @memberof Message#
20165 * @type {Date}
20166 */
20167 timestamp: new Date(),
20168 /**
20169 * 消息发送者
20170 * @memberof Message#
20171 * @type {String}
20172 */
20173 from: undefined,
20174 /**
20175 * 消息提及的用户
20176 * @since 4.0.0
20177 * @memberof Message#
20178 * @type {String[]}
20179 */
20180 mentionList: [],
20181 /**
20182 * 消息是否提及了所有人
20183 * @since 4.0.0
20184 * @memberof Message#
20185 * @type {Boolean}
20186 */
20187 mentionedAll: false,
20188 _mentioned: false
20189 });
20190 this._setStatus(MessageStatus.NONE);
20191 }
20192
20193 /**
20194 * 将当前消息的内容序列化为 JSON 对象
20195 * @private
20196 * @return {Object}
20197 */
20198 var _proto = Message.prototype;
20199 _proto.getPayload = function getPayload() {
20200 return this.content;
20201 };
20202 _proto._toJSON = function _toJSON() {
20203 var id = this.id,
20204 cid = this.cid,
20205 from = this.from,
20206 timestamp = this.timestamp,
20207 deliveredAt = this.deliveredAt,
20208 updatedAt = this.updatedAt,
20209 mentionList = this.mentionList,
20210 mentionedAll = this.mentionedAll,
20211 mentioned = this.mentioned;
20212 return {
20213 id: id,
20214 cid: cid,
20215 from: from,
20216 timestamp: timestamp,
20217 deliveredAt: deliveredAt,
20218 updatedAt: updatedAt,
20219 mentionList: mentionList,
20220 mentionedAll: mentionedAll,
20221 mentioned: mentioned
20222 };
20223 }
20224
20225 /**
20226 * 返回 JSON 格式的消息
20227 * @return {Object} 返回值是一个 plain Object
20228 */;
20229 _proto.toJSON = function toJSON() {
20230 return _objectSpread$3(_objectSpread$3({}, this._toJSON()), {}, {
20231 data: this.content
20232 });
20233 }
20234
20235 /**
20236 * 返回 JSON 格式的消息,与 toJSON 不同的是,该对象包含了完整的信息,可以通过 {@link IMClient#parseMessage} 反序列化。
20237 * @return {Object} 返回值是一个 plain Object
20238 * @since 4.0.0
20239 */;
20240 _proto.toFullJSON = function toFullJSON() {
20241 var content = this.content,
20242 id = this.id,
20243 cid = this.cid,
20244 from = this.from,
20245 timestamp = this.timestamp,
20246 deliveredAt = this.deliveredAt,
20247 _updatedAt = this._updatedAt,
20248 mentionList = this.mentionList,
20249 mentionedAll = this.mentionedAll;
20250 return {
20251 data: content,
20252 id: id,
20253 cid: cid,
20254 from: from,
20255 timestamp: getTime(timestamp),
20256 deliveredAt: getTime(deliveredAt),
20257 updatedAt: getTime(_updatedAt),
20258 mentionList: mentionList,
20259 mentionedAll: mentionedAll
20260 };
20261 }
20262
20263 /**
20264 * 消息状态,值为 {@link module:leancloud-realtime.MessageStatus} 之一
20265 * @type {Symbol}
20266 * @readonly
20267 * @since 3.2.0
20268 */;
20269 _proto._setStatus = function _setStatus(status) {
20270 if (!rMessageStatus[status]) {
20271 throw new Error('Invalid message status');
20272 }
20273 this._status = status;
20274 };
20275 _proto._updateMentioned = function _updateMentioned(client) {
20276 this._mentioned = this.from !== client && (this.mentionedAll || this.mentionList.indexOf(client) > -1);
20277 }
20278
20279 /**
20280 * 获取提及用户列表
20281 * @since 4.0.0
20282 * @return {String[]} 提及用户的 id 列表
20283 */;
20284 _proto.getMentionList = function getMentionList() {
20285 return this.mentionList;
20286 }
20287
20288 /**
20289 * 设置提及用户列表
20290 * @since 4.0.0
20291 * @param {String[]} clients 提及用户的 id 列表
20292 * @return {this} self
20293 */;
20294 _proto.setMentionList = function setMentionList(clients) {
20295 this.mentionList = ensureArray(clients);
20296 return this;
20297 }
20298
20299 /**
20300 * 设置是否提及所有人
20301 * @since 4.0.0
20302 * @param {Boolean} [value=true]
20303 * @return {this} self
20304 */;
20305 _proto.mentionAll = function mentionAll() {
20306 var value = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
20307 this.mentionedAll = Boolean(value);
20308 return this;
20309 }
20310
20311 /**
20312 * 判断给定的内容是否是有效的 Message,
20313 * 该方法始终返回 true
20314 * @private
20315 * @returns {Boolean}
20316 * @implements AVMessage.validate
20317 */;
20318 Message.validate = function validate() {
20319 return true;
20320 }
20321
20322 /**
20323 * 解析处理消息内容
20324 * <pre>
20325 * 如果子类提供了 message,返回该 message
20326 * 如果没有提供,将 json 作为 content 实例化一个 Message
20327 * @private
20328 * @param {Object} json json 格式的消息内容
20329 * @param {Message} message 子类提供的 message
20330 * @return {Message}
20331 * @implements AVMessage.parse
20332 */;
20333 Message.parse = function parse(json, message) {
20334 return message || new this(json);
20335 };
20336 _createClass(Message, [{
20337 key: "status",
20338 get: function get() {
20339 return this._status;
20340 }
20341 }, {
20342 key: "timestamp",
20343 get: function get() {
20344 return this._timestamp;
20345 },
20346 set: function set(value) {
20347 this._timestamp = decodeDate(value);
20348 }
20349
20350 /**
20351 * 消息送达时间
20352 * @type {?Date}
20353 */
20354 }, {
20355 key: "deliveredAt",
20356 get: function get() {
20357 return this._deliveredAt;
20358 },
20359 set: function set(value) {
20360 this._deliveredAt = decodeDate(value);
20361 }
20362
20363 /**
20364 * 消息修改或撤回时间,可以通过比较其与消息的 timestamp 是否相等判断消息是否被修改过或撤回过。
20365 * @type {Date}
20366 * @since 3.5.0
20367 */
20368 }, {
20369 key: "updatedAt",
20370 get: function get() {
20371 return this._updatedAt || this.timestamp;
20372 },
20373 set: function set(value) {
20374 this._updatedAt = decodeDate(value);
20375 }
20376
20377 /**
20378 * 当前用户是否在该消息中被提及
20379 * @type {Boolean}
20380 * @readonly
20381 * @since 4.0.0
20382 */
20383 }, {
20384 key: "mentioned",
20385 get: function get() {
20386 return this._mentioned;
20387 }
20388 }]);
20389 return Message;
20390 }();
20391
20392 /* eslint-disable no-param-reassign */
20393
20394 // documented in ../index.js
20395 var messageType = function messageType(type) {
20396 if (typeof type !== 'number') {
20397 throw new TypeError("".concat(type, " is not a Number"));
20398 }
20399 return function (target) {
20400 target.TYPE = type;
20401 target.validate = function (json) {
20402 return json._lctype === type;
20403 };
20404 target.prototype._getType = function () {
20405 return {
20406 _lctype: type
20407 };
20408 };
20409 };
20410 };
20411
20412 // documented in ../plugin-im.js
20413 var messageField = function messageField(fields) {
20414 if (typeof fields !== 'string') {
20415 if (!Array.isArray(fields)) {
20416 throw new TypeError("".concat(fields, " is not an Array"));
20417 } else if (fields.some(function (value) {
20418 return typeof value !== 'string';
20419 })) {
20420 throw new TypeError('fields contains non-string typed member');
20421 }
20422 }
20423 return function (target) {
20424 // IE10 Hack:
20425 // static properties in IE10 will not be inherited from super
20426 // search for parse method and assign it manually
20427 var originalCustomFields = isIE10 ? getStaticProperty(target, '_customFields') : target._customFields;
20428 originalCustomFields = Array.isArray(originalCustomFields) ? originalCustomFields : [];
20429 target._customFields = originalCustomFields.concat(fields);
20430 };
20431 };
20432
20433 // IE10 Hack:
20434 // static properties in IE10 will not be inherited from super
20435 // search for parse method and assign it manually
20436
20437 var IE10Compatible = function IE10Compatible(target) {
20438 if (isIE10) {
20439 target.parse = getStaticProperty(target, 'parse');
20440 }
20441 };
20442
20443 var _dec, _class$1;
20444 function ownKeys$4(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
20445 function _objectSpread$4(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys$4(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$4(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
20446
20447 // jsdoc-ignore-start
20448 var TypedMessage = (_dec = messageField(['_lctext', '_lcattrs']), _dec(_class$1 = /*#__PURE__*/function (_Message) {
20449 _inheritsLoose(TypedMessage, _Message);
20450 function TypedMessage() {
20451 return _Message.apply(this, arguments) || this;
20452 }
20453 var _proto = TypedMessage.prototype;
20454 /**
20455 * @param {String} text
20456 * @return {this} self
20457 */
20458 _proto.setText = function setText(text) {
20459 this._lctext = text;
20460 return this;
20461 }
20462
20463 /**
20464 * @return {String}
20465 */;
20466 _proto.getText = function getText() {
20467 return this._lctext;
20468 }
20469
20470 /**
20471 * @param {Object} attributes
20472 * @return {this} self
20473 */;
20474 _proto.setAttributes = function setAttributes(attributes) {
20475 this._lcattrs = attributes;
20476 return this;
20477 }
20478
20479 /**
20480 * @return {Object}
20481 */;
20482 _proto.getAttributes = function getAttributes() {
20483 return this._lcattrs;
20484 };
20485 _proto._getCustomFields = function _getCustomFields() {
20486 var _this = this;
20487 var fields = Array.isArray(this.constructor._customFields) ? this.constructor._customFields : [];
20488 return fields.reduce(function (result, field) {
20489 if (typeof field !== 'string') return result;
20490 result[field] = _this[field]; // eslint-disable-line no-param-reassign
20491 return result;
20492 }, {});
20493 }
20494
20495 /* eslint-disable class-methods-use-this */;
20496 _proto._getType = function _getType() {
20497 throw new Error('not implemented');
20498 }
20499 /* eslint-enable class-methods-use-this */;
20500 _proto.getPayload = function getPayload() {
20501 return compact(_objectSpread$4(_objectSpread$4({
20502 _lctext: this.getText(),
20503 _lcattrs: this.getAttributes()
20504 }, this._getCustomFields()), this._getType()));
20505 };
20506 _proto.toJSON = function toJSON() {
20507 var type = this.type,
20508 text = this.text,
20509 attributes = this.attributes,
20510 summary = this.summary;
20511 return _objectSpread$4(_objectSpread$4({}, _Message.prototype._toJSON.call(this)), {}, {
20512 type: type,
20513 text: text,
20514 attributes: attributes,
20515 summary: summary
20516 });
20517 };
20518 _proto.toFullJSON = function toFullJSON() {
20519 return _objectSpread$4(_objectSpread$4({}, _Message.prototype.toFullJSON.call(this)), {}, {
20520 data: this.getPayload()
20521 });
20522 }
20523
20524 /**
20525 * 解析处理消息内容
20526 * <pre>
20527 * 为给定的 message 设置 text 与 attributes 属性,返回该 message
20528 * 如果子类没有提供 message,new this()
20529 * @protected
20530 * @param {Object} json json 格式的消息内容
20531 * @param {TypedMessage} message 子类提供的 message
20532 * @return {TypedMessage}
20533 * @implements AVMessage.parse
20534 */;
20535 TypedMessage.parse = function parse(json) {
20536 var message = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : new this();
20537 message.content = json; // eslint-disable-line no-param-reassign
20538 var customFields = isIE10 ? getStaticProperty(message.constructor, '_customFields') : message.constructor._customFields;
20539 var fields = Array.isArray(customFields) ? customFields : [];
20540 fields = fields.reduce(function (result, field) {
20541 if (typeof field !== 'string') return result;
20542 result[field] = json[field]; // eslint-disable-line no-param-reassign
20543 return result;
20544 }, {});
20545 Object.assign(message, fields);
20546 return _Message.parse.call(this, json, message);
20547 };
20548 _createClass(TypedMessage, [{
20549 key: "type",
20550 get:
20551 /**
20552 * @type {Number}
20553 * @readonly
20554 */
20555 function get() {
20556 return this.constructor.TYPE;
20557 }
20558
20559 /** @type {String} */
20560 }, {
20561 key: "text",
20562 get: function get() {
20563 return this.getText();
20564 }
20565
20566 /** @type {Object} */,
20567 set: function set(text) {
20568 return this.setText(text);
20569 }
20570 }, {
20571 key: "attributes",
20572 get: function get() {
20573 return this.getAttributes();
20574 }
20575
20576 /**
20577 * 在客户端需要以文本形式展示该消息时显示的文案,
20578 * 如 <code>[红包] 新春快乐</code>。
20579 * 默认值为消息的 text。
20580 * @type {String}
20581 * @readonly
20582 */,
20583 set: function set(attributes) {
20584 return this.setAttributes(attributes);
20585 }
20586 }, {
20587 key: "summary",
20588 get: function get() {
20589 return this.text;
20590 }
20591 }]);
20592 return TypedMessage;
20593 }(Message)) || _class$1);
20594
20595 var _dec$1, _class$2;
20596
20597 // jsdoc-ignore-start
20598 var RecalledMessage = (_dec$1 = messageType(-127), _dec$1(_class$2 = IE10Compatible(_class$2 = /*#__PURE__*/function (_TypedMessage) {
20599 _inheritsLoose(RecalledMessage, _TypedMessage);
20600 function RecalledMessage() {
20601 return _TypedMessage.apply(this, arguments) || this;
20602 }
20603 _createClass(RecalledMessage, [{
20604 key: "summary",
20605 get:
20606 /**
20607 * 在客户端需要以文本形式展示该消息时显示的文案,值为 <code>[该消息已撤回]</code>
20608 * @type {String}
20609 * @readonly
20610 */
20611 // eslint-disable-next-line class-methods-use-this
20612 function get() {
20613 return '[该消息已撤回]';
20614 }
20615 }]);
20616 return RecalledMessage;
20617 }(TypedMessage)) || _class$2) || _class$2);
20618
20619 var _excluded$1 = ["id", "lastMessageAt", "lastMessage", "lastDeliveredAt", "lastReadAt", "unreadMessagesCount", "members", "mentioned"];
20620 function ownKeys$5(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
20621 function _objectSpread$5(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys$5(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$5(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
20622 var debug$7 = browser('LC:Conversation');
20623 var serializeMessage = function serializeMessage(message) {
20624 var content = message.getPayload();
20625 var msg;
20626 var binaryMsg;
20627 if (content instanceof ArrayBuffer) {
20628 binaryMsg = content;
20629 } else if (typeof content !== 'string') {
20630 msg = JSON.stringify(content);
20631 } else {
20632 msg = content;
20633 }
20634 return {
20635 msg: msg,
20636 binaryMsg: binaryMsg
20637 };
20638 };
20639 var _LogsCommand$QueryDir = LogsCommand.QueryDirection,
20640 NEW = _LogsCommand$QueryDir.NEW,
20641 OLD = _LogsCommand$QueryDir.OLD;
20642
20643 /**
20644 * 历史消息查询方向枚举
20645 * @enum {Number}
20646 * @since 4.0.0
20647 * @memberof module:leancloud-realtime
20648 */
20649 var MessageQueryDirection = {
20650 /** 从后向前 */
20651 NEW_TO_OLD: OLD,
20652 /** 从前向后 */
20653 OLD_TO_NEW: NEW
20654 };
20655 Object.freeze(MessageQueryDirection);
20656 var ConversationBase = /*#__PURE__*/function (_EventEmitter) {
20657 _inheritsLoose(ConversationBase, _EventEmitter);
20658 /**
20659 * @extends EventEmitter
20660 * @private
20661 * @abstract
20662 */
20663 function ConversationBase(_ref, client) {
20664 var _this;
20665 var id = _ref.id,
20666 lastMessageAt = _ref.lastMessageAt,
20667 lastMessage = _ref.lastMessage,
20668 lastDeliveredAt = _ref.lastDeliveredAt,
20669 lastReadAt = _ref.lastReadAt,
20670 _ref$unreadMessagesCo = _ref.unreadMessagesCount,
20671 unreadMessagesCount = _ref$unreadMessagesCo === void 0 ? 0 : _ref$unreadMessagesCo,
20672 _ref$members = _ref.members,
20673 members = _ref$members === void 0 ? [] : _ref$members,
20674 _ref$mentioned = _ref.mentioned,
20675 mentioned = _ref$mentioned === void 0 ? false : _ref$mentioned,
20676 properties = _objectWithoutProperties(_ref, _excluded$1);
20677 _this = _EventEmitter.call(this) || this;
20678 Object.assign(_assertThisInitialized(_this), _objectSpread$5({
20679 /**
20680 * 对话 id,对应 _Conversation 表中的 objectId
20681 * @memberof ConversationBase#
20682 * @type {String}
20683 */
20684 id: id,
20685 /**
20686 * 最后一条消息时间
20687 * @memberof ConversationBase#
20688 * @type {?Date}
20689 */
20690 lastMessageAt: lastMessageAt,
20691 /**
20692 * 最后一条消息
20693 * @memberof ConversationBase#
20694 * @type {?Message}
20695 */
20696 lastMessage: lastMessage,
20697 /**
20698 * 参与该对话的用户列表
20699 * @memberof ConversationBase#
20700 * @type {String[]}
20701 */
20702 members: members
20703 }, properties));
20704 _this.members = Array.from(new Set(_this.members));
20705 Object.assign(internal(_assertThisInitialized(_this)), {
20706 messagesWaitingForReceipt: {},
20707 lastDeliveredAt: lastDeliveredAt,
20708 lastReadAt: lastReadAt,
20709 unreadMessagesCount: unreadMessagesCount,
20710 mentioned: mentioned
20711 });
20712 _this._client = client;
20713 if (debug$7.enabled) {
20714 values_1(IMEvent).forEach(function (event) {
20715 return _this.on(event, function () {
20716 for (var _len = arguments.length, payload = new Array(_len), _key = 0; _key < _len; _key++) {
20717 payload[_key] = arguments[_key];
20718 }
20719 return _this._debug("".concat(event, " event emitted. %o"), payload);
20720 });
20721 });
20722 }
20723 // onConversationCreate hook
20724 applyDecorators(_this._client._plugins.onConversationCreate, _assertThisInitialized(_this));
20725 return _this;
20726 }
20727
20728 /**
20729 * 当前用户是否在该对话的未读消息中被提及
20730 * @type {Boolean}
20731 * @since 4.0.0
20732 */
20733 var _proto = ConversationBase.prototype;
20734 _proto._setUnreadMessagesMentioned = function _setUnreadMessagesMentioned(value) {
20735 internal(this).unreadMessagesMentioned = Boolean(value);
20736 };
20737 _proto._setLastDeliveredAt = function _setLastDeliveredAt(value) {
20738 var date = decodeDate(value);
20739 if (!(date < internal(this).lastDeliveredAt)) {
20740 internal(this).lastDeliveredAt = date;
20741 /**
20742 * 最后消息送达时间更新
20743 * @event ConversationBase#LAST_DELIVERED_AT_UPDATE
20744 * @since 3.4.0
20745 */
20746 this.emit(LAST_DELIVERED_AT_UPDATE);
20747 }
20748 }
20749
20750 /**
20751 * 最后消息被阅读时间,常用来实现发送消息的「已读」标记,可通过 {@link Conversation#fetchReceiptTimestamps} 获取或更新该属性
20752 * @type {?Date}
20753 * @since 3.4.0
20754 */;
20755 _proto._setLastReadAt = function _setLastReadAt(value) {
20756 var date = decodeDate(value);
20757 if (!(date < internal(this).lastReadAt)) {
20758 internal(this).lastReadAt = date;
20759 /**
20760 * 最后消息被阅读时间更新
20761 * @event ConversationBase#LAST_READ_AT_UPDATE
20762 * @since 3.4.0
20763 */
20764 this.emit(LAST_READ_AT_UPDATE);
20765 }
20766 }
20767
20768 /**
20769 * 返回 JSON 格式的对话,与 toJSON 不同的是,该对象包含了完整的信息,可以通过 {@link IMClient#parseConversation} 反序列化。
20770 * @return {Object} 返回值是一个 plain Object
20771 * @since 4.0.0
20772 */;
20773 _proto.toFullJSON = function toFullJSON() {
20774 var id = this.id,
20775 members = this.members,
20776 lastMessageAt = this.lastMessageAt,
20777 lastDeliveredAt = this.lastDeliveredAt,
20778 lastReadAt = this.lastReadAt,
20779 lastMessage = this.lastMessage,
20780 unreadMessagesCount = this.unreadMessagesCount;
20781 return {
20782 id: id,
20783 members: members,
20784 lastMessageAt: getTime(lastMessageAt),
20785 lastDeliveredAt: getTime(lastDeliveredAt),
20786 lastReadAt: getTime(lastReadAt),
20787 lastMessage: lastMessage ? lastMessage.toFullJSON() : undefined,
20788 unreadMessagesCount: unreadMessagesCount
20789 };
20790 }
20791
20792 /**
20793 * 返回 JSON 格式的对话
20794 * @return {Object} 返回值是一个 plain Object
20795 * @since 4.0.0
20796 */;
20797 _proto.toJSON = function toJSON() {
20798 var id = this.id,
20799 members = this.members,
20800 lastMessageAt = this.lastMessageAt,
20801 lastDeliveredAt = this.lastDeliveredAt,
20802 lastReadAt = this.lastReadAt,
20803 lastMessage = this.lastMessage,
20804 unreadMessagesCount = this.unreadMessagesCount,
20805 unreadMessagesMentioned = this.unreadMessagesMentioned;
20806 return {
20807 id: id,
20808 members: members,
20809 lastMessageAt: lastMessageAt,
20810 lastDeliveredAt: lastDeliveredAt,
20811 lastReadAt: lastReadAt,
20812 lastMessage: lastMessage ? lastMessage.toJSON() : undefined,
20813 unreadMessagesCount: unreadMessagesCount,
20814 unreadMessagesMentioned: unreadMessagesMentioned
20815 };
20816 };
20817 _proto._debug = function _debug() {
20818 for (var _len2 = arguments.length, params = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
20819 params[_key2] = arguments[_key2];
20820 }
20821 debug$7.apply(void 0, params.concat(["[".concat(this.id, "]")]));
20822 };
20823 _proto._send = function _send(command) {
20824 var _this$_client;
20825 /* eslint-disable no-param-reassign */
20826 if (command.cmd === null) {
20827 command.cmd = 'conv';
20828 }
20829 if (command.cmd === 'conv' && command.convMessage === null) {
20830 command.convMessage = new ConvCommand();
20831 }
20832 if (command.convMessage && command.convMessage.cid === null) {
20833 command.convMessage.cid = this.id;
20834 }
20835 /* eslint-enable no-param-reassign */
20836 for (var _len3 = arguments.length, args = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {
20837 args[_key3 - 1] = arguments[_key3];
20838 }
20839 return (_this$_client = this._client)._send.apply(_this$_client, [command].concat(args));
20840 }
20841
20842 /**
20843 * 发送消息
20844 * @param {Message} message 消息,Message 及其子类的实例
20845 * @param {Object} [options] since v3.3.0,发送选项
20846 * @param {Boolean} [options.transient] since v3.3.1,是否作为暂态消息发送
20847 * @param {Boolean} [options.receipt] 是否需要回执,仅在普通对话中有效
20848 * @param {Boolean} [options.will] since v3.4.0,是否指定该消息作为「掉线消息」发送,
20849 * 「掉线消息」会延迟到当前用户掉线后发送,常用来实现「下线通知」功能
20850 * @param {MessagePriority} [options.priority] 消息优先级,仅在暂态对话中有效,
20851 * see: {@link module:leancloud-realtime.MessagePriority MessagePriority}
20852 * @param {Object} [options.pushData] 消息对应的离线推送内容,如果消息接收方不在线,会推送指定的内容。其结构说明参见: {@link https://url.leanapp.cn/pushData 推送消息内容}
20853 * @return {Promise.<Message>} 发送的消息
20854 */;
20855 _proto.send =
20856 /*#__PURE__*/
20857 function () {
20858 var _send2 = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee(message, options) {
20859 var _message$constructor$, _transient, receipt, priority, pushData, will, _serializeMessage, msg, binaryMsg, command, resCommand, _resCommand$ackMessag, uid, t, code, reason, appCode;
20860 return regenerator.wrap(function _callee$(_context) {
20861 while (1) switch (_context.prev = _context.next) {
20862 case 0:
20863 this._debug(message, 'send');
20864 if (message instanceof Message) {
20865 _context.next = 3;
20866 break;
20867 }
20868 throw new TypeError("".concat(message, " is not a Message"));
20869 case 3:
20870 _message$constructor$ = _objectSpread$5(_objectSpread$5(_objectSpread$5({}, message.constructor.sendOptions), typeof message.constructor.getSendOptions === 'function' ? message.constructor.getSendOptions(message) : {}), options), _transient = _message$constructor$["transient"], receipt = _message$constructor$.receipt, priority = _message$constructor$.priority, pushData = _message$constructor$.pushData, will = _message$constructor$.will;
20871 if (receipt) {
20872 if (this["transient"]) {
20873 console.warn('receipt option is ignored as the conversation is transient.');
20874 } else if (_transient) {
20875 console.warn('receipt option is ignored as the message is sent transiently.');
20876 } else if (this.members.length > 2) {
20877 console.warn('receipt option is recommended to be used in one-on-one conversation.'); // eslint-disable-line max-len
20878 }
20879 }
20880
20881 if (priority && !this["transient"]) {
20882 console.warn('priority option is ignored as the conversation is not transient.');
20883 }
20884 Object.assign(message, {
20885 cid: this.id,
20886 from: this._client.id
20887 });
20888 message._setStatus(MessageStatus.SENDING);
20889 _serializeMessage = serializeMessage(message), msg = _serializeMessage.msg, binaryMsg = _serializeMessage.binaryMsg;
20890 command = new GenericCommand({
20891 cmd: 'direct',
20892 directMessage: new DirectCommand({
20893 msg: msg,
20894 binaryMsg: binaryMsg,
20895 cid: this.id,
20896 r: receipt,
20897 "transient": _transient,
20898 dt: message.id,
20899 pushData: JSON.stringify(pushData),
20900 will: will,
20901 mentionPids: message.mentionList,
20902 mentionAll: message.mentionedAll
20903 }),
20904 priority: priority
20905 });
20906 _context.prev = 10;
20907 _context.next = 13;
20908 return this._send(command);
20909 case 13:
20910 resCommand = _context.sent;
20911 _resCommand$ackMessag = resCommand.ackMessage, uid = _resCommand$ackMessag.uid, t = _resCommand$ackMessag.t, code = _resCommand$ackMessag.code, reason = _resCommand$ackMessag.reason, appCode = _resCommand$ackMessag.appCode;
20912 if (!(code !== null)) {
20913 _context.next = 17;
20914 break;
20915 }
20916 throw createError({
20917 code: code,
20918 reason: reason,
20919 appCode: appCode
20920 });
20921 case 17:
20922 Object.assign(message, {
20923 id: uid,
20924 timestamp: t
20925 });
20926 if (!_transient) {
20927 this.lastMessage = message;
20928 this.lastMessageAt = message.timestamp;
20929 }
20930 message._setStatus(MessageStatus.SENT);
20931 if (receipt) {
20932 internal(this).messagesWaitingForReceipt[message.id] = message;
20933 }
20934 return _context.abrupt("return", message);
20935 case 24:
20936 _context.prev = 24;
20937 _context.t0 = _context["catch"](10);
20938 message._setStatus(MessageStatus.FAILED);
20939 throw _context.t0;
20940 case 28:
20941 case "end":
20942 return _context.stop();
20943 }
20944 }, _callee, this, [[10, 24]]);
20945 }));
20946 function send(_x, _x2) {
20947 return _send2.apply(this, arguments);
20948 }
20949 return send;
20950 }();
20951 _proto._update = /*#__PURE__*/function () {
20952 var _update2 = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee2(message, newMessage, recall) {
20953 var msg, binaryMsg, content, id, cid, timestamp, from, _status;
20954 return regenerator.wrap(function _callee2$(_context2) {
20955 while (1) switch (_context2.prev = _context2.next) {
20956 case 0:
20957 this._debug('patch %O %O %O', message, newMessage, recall);
20958 if (!(message instanceof Message)) {
20959 _context2.next = 8;
20960 break;
20961 }
20962 if (!(message.from !== this._client.id)) {
20963 _context2.next = 4;
20964 break;
20965 }
20966 throw new Error('Updating message from others is not allowed');
20967 case 4:
20968 if (!(message.status !== MessageStatus.SENT && message.status !== MessageStatus.DELIVERED)) {
20969 _context2.next = 6;
20970 break;
20971 }
20972 throw new Error('Message is not sent');
20973 case 6:
20974 _context2.next = 10;
20975 break;
20976 case 8:
20977 if (message.id && message.timestamp) {
20978 _context2.next = 10;
20979 break;
20980 }
20981 throw new TypeError("".concat(message, " is not a Message"));
20982 case 10:
20983 if (!recall) {
20984 content = serializeMessage(newMessage);
20985 msg = content.msg;
20986 binaryMsg = content.binaryMsg;
20987 }
20988 _context2.next = 13;
20989 return this._send(new GenericCommand({
20990 cmd: CommandType.patch,
20991 op: OpType.modify,
20992 patchMessage: new PatchCommand({
20993 patches: [new PatchItem({
20994 cid: this.id,
20995 mid: message.id,
20996 timestamp: Number(message.timestamp),
20997 recall: recall,
20998 data: msg,
20999 binaryMsg: binaryMsg,
21000 mentionPids: newMessage.mentionList,
21001 mentionAll: newMessage.mentionedAll
21002 })],
21003 lastPatchTime: this._client._lastPatchTime
21004 })
21005 }));
21006 case 13:
21007 id = message.id, cid = message.cid, timestamp = message.timestamp, from = message.from, _status = message._status;
21008 Object.assign(newMessage, {
21009 id: id,
21010 cid: cid,
21011 timestamp: timestamp,
21012 from: from,
21013 _status: _status
21014 });
21015 if (this.lastMessage && this.lastMessage.id === newMessage.id) {
21016 this.lastMessage = newMessage;
21017 }
21018 return _context2.abrupt("return", newMessage);
21019 case 17:
21020 case "end":
21021 return _context2.stop();
21022 }
21023 }, _callee2, this);
21024 }));
21025 function _update(_x3, _x4, _x5) {
21026 return _update2.apply(this, arguments);
21027 }
21028 return _update;
21029 }()
21030 /**
21031 * 获取对话人数,或暂态对话的在线人数
21032 * @return {Promise.<Number>}
21033 */
21034 ;
21035 _proto.count =
21036 /*#__PURE__*/
21037 function () {
21038 var _count = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee3() {
21039 var resCommand;
21040 return regenerator.wrap(function _callee3$(_context3) {
21041 while (1) switch (_context3.prev = _context3.next) {
21042 case 0:
21043 this._debug('count');
21044 _context3.next = 3;
21045 return this._send(new GenericCommand({
21046 op: 'count'
21047 }));
21048 case 3:
21049 resCommand = _context3.sent;
21050 return _context3.abrupt("return", resCommand.convMessage.count);
21051 case 5:
21052 case "end":
21053 return _context3.stop();
21054 }
21055 }, _callee3, this);
21056 }));
21057 function count() {
21058 return _count.apply(this, arguments);
21059 }
21060 return count;
21061 }()
21062 /**
21063 * 应用增加成员的操作,产生副作用
21064 * @param {string[]} members
21065 * @abstract
21066 * @private
21067 */
21068 ;
21069 _proto._addMembers = function _addMembers() {}
21070
21071 /**
21072 * 应用减少成员的操作,产生副作用
21073 * @param {string[]} members
21074 * @abstract
21075 * @private
21076 */;
21077 _proto._removeMembers = function _removeMembers() {}
21078
21079 /**
21080 * 修改已发送的消息
21081 * @param {AVMessage} message 要修改的消息,该消息必须是由当前用户发送的。也可以提供一个包含消息 {id, timestamp} 的对象
21082 * @param {AVMessage} newMessage 新的消息
21083 * @return {Promise.<AVMessage>} 更新后的消息
21084 */;
21085 _proto.update =
21086 /*#__PURE__*/
21087 function () {
21088 var _update3 = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee4(message, newMessage) {
21089 return regenerator.wrap(function _callee4$(_context4) {
21090 while (1) switch (_context4.prev = _context4.next) {
21091 case 0:
21092 if (newMessage instanceof Message) {
21093 _context4.next = 2;
21094 break;
21095 }
21096 throw new TypeError("".concat(newMessage, " is not a Message"));
21097 case 2:
21098 return _context4.abrupt("return", this._update(message, newMessage, false));
21099 case 3:
21100 case "end":
21101 return _context4.stop();
21102 }
21103 }, _callee4, this);
21104 }));
21105 function update(_x6, _x7) {
21106 return _update3.apply(this, arguments);
21107 }
21108 return update;
21109 }()
21110 /**
21111 * 撤回已发送的消息
21112 * @param {AVMessage} message 要撤回的消息,该消息必须是由当前用户发送的。也可以提供一个包含消息 {id, timestamp} 的对象
21113 * @return {Promise.<RecalledMessage>} 一条已撤回的消息
21114 */
21115 ;
21116 _proto.recall =
21117 /*#__PURE__*/
21118 function () {
21119 var _recall = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee5(message) {
21120 return regenerator.wrap(function _callee5$(_context5) {
21121 while (1) switch (_context5.prev = _context5.next) {
21122 case 0:
21123 return _context5.abrupt("return", this._update(message, new RecalledMessage(), true));
21124 case 1:
21125 case "end":
21126 return _context5.stop();
21127 }
21128 }, _callee5, this);
21129 }));
21130 function recall(_x8) {
21131 return _recall.apply(this, arguments);
21132 }
21133 return recall;
21134 }()
21135 /**
21136 * 查询消息记录
21137 * 如果仅需实现消息向前记录翻页查询需求,建议使用 {@link Conversation#createMessagesIterator}。
21138 * 不论何种方向,获得的消息都是按照时间升序排列的。
21139 * startClosed 与 endClosed 用于指定查询区间的开闭。
21140 *
21141 * @param {Object} [options]
21142 * @param {Number} [options.limit] 限制查询结果的数量,目前服务端默认为 20
21143 * @param {Number} [options.type] 指定查询的富媒体消息类型,不指定则查询所有消息。
21144 * @param {MessageQueryDirection} [options.direction] 查询的方向。
21145 * 在不指定的情况下如果 startTime 大于 endTime,则为从新到旧查询,可以实现加载聊天记录等场景。
21146 * 如果 startTime 小于 endTime,则为从旧到新查询,可以实现弹幕等场景。
21147 * @param {Date} [options.startTime] 从该时间开始查询,不传则从当前时间开始查询
21148 * @param {String} [options.startMessageId] 从该消息之前开始查询,需要与 startTime 同时使用,为防止某时刻有重复消息
21149 * @param {Boolean}[options.startClosed] 指定查询范围是否包括开始的时间点,默认不包括
21150 * @param {Date} [options.endTime] 查询到该时间为止,不传则查询最早消息为止
21151 * @param {String} [options.endMessageId] 查询到该消息为止,需要与 endTime 同时使用,为防止某时刻有重复消息
21152 * @param {Boolean}[options.endClosed] 指定查询范围是否包括结束的时间点,默认不包括
21153 *
21154 * @param {Date} [options.beforeTime] DEPRECATED: 使用 startTime 代替。限制查询结果为小于该时间之前的消息,不传则为当前时间
21155 * @param {String} [options.beforeMessageId] DEPRECATED: 使用 startMessageId 代替。
21156 * 限制查询结果为该消息之前的消息,需要与 beforeTime 同时使用,为防止某时刻有重复消息
21157 * @param {Date} [options.afterTime] DEPRECATED: 使用 endTime 代替。限制查询结果为大于该时间之前的消息
21158 * @param {String} [options.afterMessageId] DEPRECATED: 使用 endMessageId 代替。
21159 * 限制查询结果为该消息之后的消息,需要与 afterTime 同时使用,为防止某时刻有重复消息
21160 * @return {Promise.<Message[]>} 消息列表
21161 */
21162 ;
21163 _proto.queryMessages =
21164 /*#__PURE__*/
21165 function () {
21166 var _queryMessages = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee7() {
21167 var _this2 = this;
21168 var options,
21169 beforeTime,
21170 beforeMessageId,
21171 afterTime,
21172 afterMessageId,
21173 limit,
21174 direction,
21175 type,
21176 startTime,
21177 startMessageId,
21178 startClosed,
21179 endTime,
21180 endMessageId,
21181 endClosed,
21182 conditions,
21183 resCommand,
21184 _args7 = arguments;
21185 return regenerator.wrap(function _callee7$(_context7) {
21186 while (1) switch (_context7.prev = _context7.next) {
21187 case 0:
21188 options = _args7.length > 0 && _args7[0] !== undefined ? _args7[0] : {};
21189 this._debug('query messages %O', options);
21190 beforeTime = options.beforeTime, beforeMessageId = options.beforeMessageId, afterTime = options.afterTime, afterMessageId = options.afterMessageId, limit = options.limit, direction = options.direction, type = options.type, startTime = options.startTime, startMessageId = options.startMessageId, startClosed = options.startClosed, endTime = options.endTime, endMessageId = options.endMessageId, endClosed = options.endClosed;
21191 if (!(beforeMessageId || beforeTime || afterMessageId || afterTime)) {
21192 _context7.next = 6;
21193 break;
21194 }
21195 console.warn('DEPRECATION: queryMessages options beforeTime, beforeMessageId, afterTime and afterMessageId are deprecated in favor of startTime, startMessageId, endTime and endMessageId.');
21196 return _context7.abrupt("return", this.queryMessages({
21197 startTime: beforeTime,
21198 startMessageId: beforeMessageId,
21199 endTime: afterTime,
21200 endMessageId: afterMessageId,
21201 limit: limit
21202 }));
21203 case 6:
21204 if (!(startMessageId && !startTime)) {
21205 _context7.next = 8;
21206 break;
21207 }
21208 throw new Error('query option startMessageId must be used with option startTime');
21209 case 8:
21210 if (!(endMessageId && !endTime)) {
21211 _context7.next = 10;
21212 break;
21213 }
21214 throw new Error('query option endMessageId must be used with option endTime');
21215 case 10:
21216 conditions = {
21217 t: startTime,
21218 mid: startMessageId,
21219 tIncluded: startClosed,
21220 tt: endTime,
21221 tmid: endMessageId,
21222 ttIncluded: endClosed,
21223 l: limit,
21224 lctype: type
21225 };
21226 if (conditions.t instanceof Date) {
21227 conditions.t = conditions.t.getTime();
21228 }
21229 if (conditions.tt instanceof Date) {
21230 conditions.tt = conditions.tt.getTime();
21231 }
21232 if (direction !== undefined) {
21233 conditions.direction = direction;
21234 } else if (conditions.tt > conditions.t) {
21235 conditions.direction = MessageQueryDirection.OLD_TO_NEW;
21236 }
21237 _context7.next = 16;
21238 return this._send(new GenericCommand({
21239 cmd: 'logs',
21240 logsMessage: new LogsCommand(Object.assign(conditions, {
21241 cid: this.id
21242 }))
21243 }));
21244 case 16:
21245 resCommand = _context7.sent;
21246 return _context7.abrupt("return", Promise.all(resCommand.logsMessage.logs.map( /*#__PURE__*/function () {
21247 var _ref3 = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee6(_ref2) {
21248 var msgId, timestamp, patchTimestamp, from, ackAt, readAt, data, mentionAll, mentionPids, bin, messageData, message, status;
21249 return regenerator.wrap(function _callee6$(_context6) {
21250 while (1) switch (_context6.prev = _context6.next) {
21251 case 0:
21252 msgId = _ref2.msgId, timestamp = _ref2.timestamp, patchTimestamp = _ref2.patchTimestamp, from = _ref2.from, ackAt = _ref2.ackAt, readAt = _ref2.readAt, data = _ref2.data, mentionAll = _ref2.mentionAll, mentionPids = _ref2.mentionPids, bin = _ref2.bin;
21253 messageData = {
21254 data: data,
21255 bin: bin,
21256 id: msgId,
21257 cid: _this2.id,
21258 timestamp: timestamp,
21259 from: from,
21260 deliveredAt: ackAt,
21261 updatedAt: patchTimestamp,
21262 mentionList: mentionPids,
21263 mentionedAll: mentionAll
21264 };
21265 _context6.next = 4;
21266 return _this2._client.parseMessage(messageData);
21267 case 4:
21268 message = _context6.sent;
21269 status = MessageStatus.SENT;
21270 if (_this2.members.length === 2) {
21271 if (ackAt) status = MessageStatus.DELIVERED;
21272 if (ackAt) _this2._setLastDeliveredAt(ackAt);
21273 if (readAt) _this2._setLastReadAt(readAt);
21274 }
21275 message._setStatus(status);
21276 return _context6.abrupt("return", message);
21277 case 9:
21278 case "end":
21279 return _context6.stop();
21280 }
21281 }, _callee6);
21282 }));
21283 return function (_x9) {
21284 return _ref3.apply(this, arguments);
21285 };
21286 }())));
21287 case 18:
21288 case "end":
21289 return _context7.stop();
21290 }
21291 }, _callee7, this);
21292 }));
21293 function queryMessages() {
21294 return _queryMessages.apply(this, arguments);
21295 }
21296 return queryMessages;
21297 }()
21298 /**
21299 * 获取消息翻页迭代器
21300 * @param {Object} [options]
21301 * @param {Date} [options.beforeTime] 限制起始查询结果为小于该时间之前的消息,不传则为当前时间
21302 * @param {String} [options.beforeMessageId] 限制起始查询结果为该消息之前的消息,需要与 beforeTime 同时使用,为防止某时刻有重复消息
21303 * @param {Number} [options.limit] 限制每页查询结果的数量,目前服务端默认为 20
21304 * @return {AsyncIterater.<Promise.<IteratorResult<Message[]>>>} [AsyncIterator]{@link https://github.com/tc39/proposal-async-iteration},调用其 next 方法返回获取下一页消息的 Promise
21305 * @example
21306 * var messageIterator = conversation.createMessagesIterator({ limit: 10 });
21307 * messageIterator.next().then(function(result) {
21308 * // result: {
21309 * // value: [message1, ..., message10],
21310 * // done: false,
21311 * // }
21312 * });
21313 * messageIterator.next().then(function(result) {
21314 * // result: {
21315 * // value: [message11, ..., message20],
21316 * // done: false,
21317 * // }
21318 * });
21319 * messageIterator.next().then(function(result) {
21320 * // No more messages
21321 * // result: { value: [], done: true }
21322 * });
21323 */
21324 ;
21325 _proto.createMessagesIterator = function createMessagesIterator() {
21326 var _this3 = this;
21327 var _ref4 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
21328 beforeTime = _ref4.beforeTime,
21329 beforeMessageId = _ref4.beforeMessageId,
21330 limit = _ref4.limit;
21331 var promise;
21332 return {
21333 next: function next() {
21334 if (promise === undefined) {
21335 // first call
21336 promise = _this3.queryMessages({
21337 limit: limit,
21338 startTime: beforeTime,
21339 startMessageId: beforeMessageId
21340 });
21341 } else {
21342 promise = promise.then(function (prevMessages) {
21343 if (prevMessages.length === 0 || prevMessages.length < limit) {
21344 // no more messages
21345 return [];
21346 }
21347 return _this3.queryMessages({
21348 startTime: prevMessages[0].timestamp,
21349 startMessageId: prevMessages[0].id,
21350 limit: limit
21351 });
21352 });
21353 }
21354 return promise.then(function (value) {
21355 return {
21356 value: Array.from(value),
21357 done: value.length === 0 || value.length < limit
21358 };
21359 });
21360 }
21361 };
21362 }
21363
21364 /**
21365 * 将该会话标记为已读
21366 * @return {Promise.<this>} self
21367 */;
21368 _proto.read =
21369 /*#__PURE__*/
21370 function () {
21371 var _read = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee8() {
21372 var client;
21373 return regenerator.wrap(function _callee8$(_context8) {
21374 while (1) switch (_context8.prev = _context8.next) {
21375 case 0:
21376 this.unreadMessagesCount = 0;
21377 this._setUnreadMessagesMentioned(false);
21378 // 跳过暂态会话
21379 if (!this["transient"]) {
21380 _context8.next = 4;
21381 break;
21382 }
21383 return _context8.abrupt("return", this);
21384 case 4:
21385 client = this._client;
21386 if (!internal(client).readConversationsBuffer) {
21387 internal(client).readConversationsBuffer = new Set();
21388 }
21389 internal(client).readConversationsBuffer.add(this);
21390 client._doSendRead();
21391 return _context8.abrupt("return", this);
21392 case 9:
21393 case "end":
21394 return _context8.stop();
21395 }
21396 }, _callee8, this);
21397 }));
21398 function read() {
21399 return _read.apply(this, arguments);
21400 }
21401 return read;
21402 }();
21403 _proto._handleReceipt = function _handleReceipt(_ref5) {
21404 var messageId = _ref5.messageId,
21405 timestamp = _ref5.timestamp,
21406 read = _ref5.read;
21407 if (read) {
21408 this._setLastReadAt(timestamp);
21409 } else {
21410 this._setLastDeliveredAt(timestamp);
21411 }
21412 var _internal = internal(this),
21413 messagesWaitingForReceipt = _internal.messagesWaitingForReceipt;
21414 var message = messagesWaitingForReceipt[messageId];
21415 if (!message) return;
21416 message._setStatus(MessageStatus.DELIVERED);
21417 message.deliveredAt = timestamp;
21418 delete messagesWaitingForReceipt[messageId];
21419 }
21420
21421 /**
21422 * 更新对话的最新回执时间戳(lastDeliveredAt、lastReadAt)
21423 * @since 3.4.0
21424 * @return {Promise.<this>} this
21425 */;
21426 _proto.fetchReceiptTimestamps =
21427 /*#__PURE__*/
21428 function () {
21429 var _fetchReceiptTimestamps = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee9() {
21430 var _yield$this$_send, _yield$this$_send$con, maxReadTimestamp, maxAckTimestamp;
21431 return regenerator.wrap(function _callee9$(_context9) {
21432 while (1) switch (_context9.prev = _context9.next) {
21433 case 0:
21434 if (!(this["transient"] || this.system)) {
21435 _context9.next = 2;
21436 break;
21437 }
21438 return _context9.abrupt("return", this);
21439 case 2:
21440 _context9.next = 4;
21441 return this._send(new GenericCommand({
21442 op: 'max_read'
21443 }));
21444 case 4:
21445 _yield$this$_send = _context9.sent;
21446 _yield$this$_send$con = _yield$this$_send.convMessage;
21447 maxReadTimestamp = _yield$this$_send$con.maxReadTimestamp;
21448 maxAckTimestamp = _yield$this$_send$con.maxAckTimestamp;
21449 this._setLastDeliveredAt(maxAckTimestamp);
21450 this._setLastReadAt(maxReadTimestamp);
21451 return _context9.abrupt("return", this);
21452 case 11:
21453 case "end":
21454 return _context9.stop();
21455 }
21456 }, _callee9, this);
21457 }));
21458 function fetchReceiptTimestamps() {
21459 return _fetchReceiptTimestamps.apply(this, arguments);
21460 }
21461 return fetchReceiptTimestamps;
21462 }();
21463 _proto._fetchAllReceiptTimestamps = function _fetchAllReceiptTimestamps() {
21464 // 暂态/系统会话不支持回执
21465 if (this["transient"] || this.system) return this;
21466 var convMessage = new ConvCommand({
21467 queryAllMembers: true
21468 });
21469 return this._send(new GenericCommand({
21470 op: 'max_read',
21471 convMessage: convMessage
21472 })).then(function (_ref6) {
21473 var maxReadTuples = _ref6.convMessage.maxReadTuples;
21474 return maxReadTuples.filter(function (maxReadTuple) {
21475 return maxReadTuple.maxAckTimestamp || maxReadTuple.maxReadTimestamp;
21476 }).map(function (_ref7) {
21477 var pid = _ref7.pid,
21478 maxAckTimestamp = _ref7.maxAckTimestamp,
21479 maxReadTimestamp = _ref7.maxReadTimestamp;
21480 return {
21481 pid: pid,
21482 lastDeliveredAt: decodeDate(maxAckTimestamp),
21483 lastReadAt: decodeDate(maxReadTimestamp)
21484 };
21485 });
21486 });
21487 };
21488 _createClass(ConversationBase, [{
21489 key: "unreadMessagesMentioned",
21490 get: function get() {
21491 return internal(this).unreadMessagesMentioned;
21492 }
21493 }, {
21494 key: "unreadMessagesCount",
21495 get:
21496 /**
21497 * 当前用户在该对话的未读消息数
21498 * @type {Number}
21499 */
21500 function get() {
21501 return internal(this).unreadMessagesCount;
21502 },
21503 set: function set(value) {
21504 if (value !== this.unreadMessagesCount) {
21505 internal(this).unreadMessagesCount = value;
21506 this._client.emit(UNREAD_MESSAGES_COUNT_UPDATE, [this]);
21507 }
21508 }
21509 }, {
21510 key: "lastMessageAt",
21511 get: function get() {
21512 return this._lastMessageAt;
21513 }
21514
21515 /**
21516 * 最后消息送达时间,常用来实现消息的「已送达」标记,可通过 {@link Conversation#fetchReceiptTimestamps} 获取或更新该属性
21517 * @type {?Date}
21518 * @since 3.4.0
21519 */,
21520 set: function set(value) {
21521 var time = decodeDate(value);
21522 if (time <= this._lastMessageAt) return;
21523 this._lastMessageAt = time;
21524 }
21525 }, {
21526 key: "lastDeliveredAt",
21527 get: function get() {
21528 if (this.members.length !== 2) return null;
21529 return internal(this).lastDeliveredAt;
21530 }
21531 }, {
21532 key: "lastReadAt",
21533 get: function get() {
21534 if (this.members.length !== 2) return null;
21535 return internal(this).lastReadAt;
21536 }
21537 }]);
21538 return ConversationBase;
21539 }(eventemitter3);
21540
21541 var debug$8 = browser('LC:SignatureFactoryRunner');
21542 function _validateSignature() {
21543 var signatureResult = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
21544 var signature = signatureResult.signature,
21545 timestamp = signatureResult.timestamp,
21546 nonce = signatureResult.nonce;
21547 if (typeof signature !== 'string' || typeof timestamp !== 'number' || typeof nonce !== 'string') {
21548 throw new Error('malformed signature');
21549 }
21550 return {
21551 signature: signature,
21552 timestamp: timestamp,
21553 nonce: nonce
21554 };
21555 }
21556 var runSignatureFactory = (function (signatureFactory, params) {
21557 return Promise.resolve().then(function () {
21558 debug$8('call signatureFactory with %O', params);
21559 return signatureFactory.apply(void 0, _toConsumableArray(params));
21560 }).then(tap(function (signatureResult) {
21561 return debug$8('sign result %O', signatureResult);
21562 }), function (error) {
21563 // eslint-disable-next-line no-param-reassign
21564 error.message = "sign error: ".concat(error.message);
21565 debug$8(error);
21566 throw error;
21567 }).then(_validateSignature);
21568 });
21569
21570 var _excluded$2 = ["pids"],
21571 _excluded2 = ["creator", "createdAt", "updatedAt", "transient", "system", "muted", "mutedMembers"];
21572 function ownKeys$6(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
21573 function _objectSpread$6(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys$6(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$6(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
21574
21575 /**
21576 * 部分失败异常
21577 * @typedef OperationFailureError
21578 * @type {Error}
21579 * @property {string} message 异常信息
21580 * @property {string[]} clientIds 因为该原因失败的 client id 列表
21581 * @property {number} [code] 错误码
21582 * @property {string} [detail] 详细信息
21583 */
21584
21585 /**
21586 * 部分成功的结果
21587 * @typedef PartiallySuccess
21588 * @type {Object}
21589 * @property {string[]} successfulClientIds 成功的 client id 列表
21590 * @property {OperationFailureError[]} failures 失败的异常列表
21591 */
21592
21593 /**
21594 * 分页查询结果
21595 * @typedef PagedResults
21596 * @type {Object}
21597 * @property {T[]} results 查询结果
21598 * @property {string} [next] 存在表示还有更多结果,在下次查询中带上可实现翻页。
21599 */
21600
21601 var createPartiallySuccess = function createPartiallySuccess(_ref) {
21602 var allowedPids = _ref.allowedPids,
21603 failedPids = _ref.failedPids;
21604 return {
21605 successfulClientIds: allowedPids,
21606 failures: failedPids.map(function (_ref2) {
21607 var pids = _ref2.pids,
21608 error = _objectWithoutProperties(_ref2, _excluded$2);
21609 return Object.assign(createError(error), {
21610 clientIds: pids
21611 });
21612 })
21613 };
21614 };
21615
21616 /**
21617 * @extends ConversationBase
21618 * @private
21619 * @abstract
21620 */
21621 var PersistentConversation = /*#__PURE__*/function (_ConversationBase) {
21622 _inheritsLoose(PersistentConversation, _ConversationBase);
21623 function PersistentConversation(data, _ref3, client) {
21624 var _this;
21625 var creator = _ref3.creator,
21626 createdAt = _ref3.createdAt,
21627 updatedAt = _ref3.updatedAt,
21628 _ref3$transient = _ref3["transient"],
21629 _transient = _ref3$transient === void 0 ? false : _ref3$transient,
21630 _ref3$system = _ref3.system,
21631 system = _ref3$system === void 0 ? false : _ref3$system,
21632 _ref3$muted = _ref3.muted,
21633 muted = _ref3$muted === void 0 ? false : _ref3$muted,
21634 _ref3$mutedMembers = _ref3.mutedMembers,
21635 mutedMembers = _ref3$mutedMembers === void 0 ? [] : _ref3$mutedMembers,
21636 attributes = _objectWithoutProperties(_ref3, _excluded2);
21637 _this = _ConversationBase.call(this, _objectSpread$6(_objectSpread$6({}, data), {}, {
21638 /**
21639 * 对话创建者
21640 * @memberof PersistentConversation#
21641 * @type {String}
21642 */
21643 creator: creator,
21644 /**
21645 * 对话创建时间
21646 * @memberof PersistentConversation#
21647 * @type {Date}
21648 */
21649 createdAt: createdAt,
21650 /**
21651 * 对话更新时间
21652 * @memberof PersistentConversation#
21653 * @type {Date}
21654 */
21655 updatedAt: updatedAt,
21656 /**
21657 * 对该对话设置了静音的用户列表
21658 * @memberof PersistentConversation#
21659 * @type {?String[]}
21660 */
21661 mutedMembers: mutedMembers,
21662 /**
21663 * 暂态对话标记
21664 * @memberof PersistentConversation#
21665 * @type {Boolean}
21666 */
21667 "transient": _transient,
21668 /**
21669 * 系统对话标记
21670 * @memberof PersistentConversation#
21671 * @type {Boolean}
21672 * @since 3.3.0
21673 */
21674 system: system,
21675 /**
21676 * 当前用户静音该对话标记
21677 * @memberof PersistentConversation#
21678 * @type {Boolean}
21679 */
21680 muted: muted,
21681 _attributes: attributes
21682 }), client) || this;
21683 _this._reset();
21684 return _this;
21685 }
21686 var _proto = PersistentConversation.prototype;
21687 /**
21688 * 获取对话的自定义属性
21689 * @since 3.2.0
21690 * @param {String} key key 属性的键名,'x' 对应 Conversation 表中的 x 列
21691 * @return {Any} 属性的值
21692 */
21693 _proto.get = function get(key) {
21694 return get_1(internal(this).currentAttributes, key);
21695 }
21696
21697 /**
21698 * 设置对话的自定义属性
21699 * @since 3.2.0
21700 * @param {String} key 属性的键名,'x' 对应 Conversation 表中的 x 列,支持使用 'x.y.z' 来修改对象的部分字段。
21701 * @param {Any} value 属性的值
21702 * @return {this} self
21703 * @example
21704 *
21705 * // 设置对话的 color 属性
21706 * conversation.set('color', {
21707 * text: '#000',
21708 * background: '#DDD',
21709 * });
21710 * // 设置对话的 color.text 属性
21711 * conversation.set('color.text', '#333');
21712 */;
21713 _proto.set = function set(key, value) {
21714 this._debug("set [".concat(key, "]: ").concat(value));
21715 var _internal = internal(this),
21716 pendingAttributes = _internal.pendingAttributes;
21717 var pendingKeys = Object.keys(pendingAttributes);
21718 // suppose pendingAttributes = { 'a.b': {} }
21719 // set 'a' or 'a.b': delete 'a.b'
21720 var re = new RegExp("^".concat(key));
21721 var childKeys = pendingKeys.filter(re.test.bind(re));
21722 childKeys.forEach(function (k) {
21723 delete pendingAttributes[k];
21724 });
21725 if (childKeys.length) {
21726 pendingAttributes[key] = value;
21727 } else {
21728 // set 'a.c': nothing to do
21729 // set 'a.b.c.d': assign c: { d: {} } to 'a.b'
21730 var parentKey = find_1(pendingKeys, function (k) {
21731 return key.indexOf(k) === 0;
21732 }); // 'a.b'
21733 if (parentKey) {
21734 setValue(pendingAttributes[parentKey], key.slice(parentKey.length + 1), value);
21735 } else {
21736 pendingAttributes[key] = value;
21737 }
21738 }
21739 this._buildCurrentAttributes();
21740 return this;
21741 };
21742 _proto._buildCurrentAttributes = function _buildCurrentAttributes() {
21743 var _internal2 = internal(this),
21744 pendingAttributes = _internal2.pendingAttributes;
21745 internal(this).currentAttributes = Object.keys(pendingAttributes).reduce(function (target, k) {
21746 return setValue(target, k, pendingAttributes[k]);
21747 }, cloneDeep_1(this._attributes));
21748 };
21749 _proto._updateServerAttributes = function _updateServerAttributes(attributes) {
21750 var _this2 = this;
21751 Object.keys(attributes).forEach(function (key) {
21752 return setValue(_this2._attributes, key, attributes[key]);
21753 });
21754 this._buildCurrentAttributes();
21755 };
21756 _proto._reset = function _reset() {
21757 Object.assign(internal(this), {
21758 pendingAttributes: {},
21759 currentAttributes: this._attributes
21760 });
21761 }
21762
21763 /**
21764 * 保存当前对话的属性至服务器
21765 * @return {Promise.<this>} self
21766 */;
21767 _proto.save =
21768 /*#__PURE__*/
21769 function () {
21770 var _save = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee() {
21771 var attr, convMessage, resCommand;
21772 return regenerator.wrap(function _callee$(_context) {
21773 while (1) switch (_context.prev = _context.next) {
21774 case 0:
21775 this._debug('save');
21776 attr = internal(this).pendingAttributes;
21777 if (!isEmpty_1(attr)) {
21778 _context.next = 5;
21779 break;
21780 }
21781 this._debug('nothing touched, resolve with self');
21782 return _context.abrupt("return", this);
21783 case 5:
21784 this._debug('attr: %O', attr);
21785 convMessage = new ConvCommand({
21786 attr: new JsonObjectMessage({
21787 data: JSON.stringify(encode(attr))
21788 })
21789 });
21790 _context.next = 9;
21791 return this._send(new GenericCommand({
21792 op: 'update',
21793 convMessage: convMessage
21794 }));
21795 case 9:
21796 resCommand = _context.sent;
21797 this.updatedAt = resCommand.convMessage.udate;
21798 this._attributes = internal(this).currentAttributes;
21799 internal(this).pendingAttributes = {};
21800 return _context.abrupt("return", this);
21801 case 14:
21802 case "end":
21803 return _context.stop();
21804 }
21805 }, _callee, this);
21806 }));
21807 function save() {
21808 return _save.apply(this, arguments);
21809 }
21810 return save;
21811 }()
21812 /**
21813 * 从服务器更新对话的属性
21814 * @return {Promise.<this>} self
21815 */
21816 ;
21817 _proto.fetch =
21818 /*#__PURE__*/
21819 function () {
21820 var _fetch = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee2() {
21821 var query;
21822 return regenerator.wrap(function _callee2$(_context2) {
21823 while (1) switch (_context2.prev = _context2.next) {
21824 case 0:
21825 query = this._client.getQuery().equalTo('objectId', this.id);
21826 _context2.next = 3;
21827 return query.find();
21828 case 3:
21829 return _context2.abrupt("return", this);
21830 case 4:
21831 case "end":
21832 return _context2.stop();
21833 }
21834 }, _callee2, this);
21835 }));
21836 function fetch() {
21837 return _fetch.apply(this, arguments);
21838 }
21839 return fetch;
21840 }()
21841 /**
21842 * 静音,客户端拒绝收到服务器端的离线推送通知
21843 * @return {Promise.<this>} self
21844 */
21845 ;
21846 _proto.mute =
21847 /*#__PURE__*/
21848 function () {
21849 var _mute = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee3() {
21850 return regenerator.wrap(function _callee3$(_context3) {
21851 while (1) switch (_context3.prev = _context3.next) {
21852 case 0:
21853 this._debug('mute');
21854 _context3.next = 3;
21855 return this._send(new GenericCommand({
21856 op: 'mute'
21857 }));
21858 case 3:
21859 if (!this["transient"]) {
21860 this.muted = true;
21861 this.mutedMembers = union(this.mutedMembers, [this._client.id]);
21862 }
21863 return _context3.abrupt("return", this);
21864 case 5:
21865 case "end":
21866 return _context3.stop();
21867 }
21868 }, _callee3, this);
21869 }));
21870 function mute() {
21871 return _mute.apply(this, arguments);
21872 }
21873 return mute;
21874 }()
21875 /**
21876 * 取消静音
21877 * @return {Promise.<this>} self
21878 */
21879 ;
21880 _proto.unmute =
21881 /*#__PURE__*/
21882 function () {
21883 var _unmute = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee4() {
21884 return regenerator.wrap(function _callee4$(_context4) {
21885 while (1) switch (_context4.prev = _context4.next) {
21886 case 0:
21887 this._debug('unmute');
21888 _context4.next = 3;
21889 return this._send(new GenericCommand({
21890 op: 'unmute'
21891 }));
21892 case 3:
21893 if (!this["transient"]) {
21894 this.muted = false;
21895 this.mutedMembers = difference(this.mutedMembers, [this._client.id]);
21896 }
21897 return _context4.abrupt("return", this);
21898 case 5:
21899 case "end":
21900 return _context4.stop();
21901 }
21902 }, _callee4, this);
21903 }));
21904 function unmute() {
21905 return _unmute.apply(this, arguments);
21906 }
21907 return unmute;
21908 }();
21909 _proto._appendConversationSignature = /*#__PURE__*/function () {
21910 var _appendConversationSignature2 = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee5(command, action, clientIds) {
21911 var params, signatureResult;
21912 return regenerator.wrap(function _callee5$(_context5) {
21913 while (1) switch (_context5.prev = _context5.next) {
21914 case 0:
21915 if (!this._client.options.conversationSignatureFactory) {
21916 _context5.next = 6;
21917 break;
21918 }
21919 params = [this.id, this._client.id, clientIds.sort(), action];
21920 _context5.next = 4;
21921 return runSignatureFactory(this._client.options.conversationSignatureFactory, params);
21922 case 4:
21923 signatureResult = _context5.sent;
21924 Object.assign(command.convMessage, keyRemap({
21925 signature: 's',
21926 timestamp: 't',
21927 nonce: 'n'
21928 }, signatureResult));
21929 case 6:
21930 case "end":
21931 return _context5.stop();
21932 }
21933 }, _callee5, this);
21934 }));
21935 function _appendConversationSignature(_x, _x2, _x3) {
21936 return _appendConversationSignature2.apply(this, arguments);
21937 }
21938 return _appendConversationSignature;
21939 }();
21940 _proto._appendBlacklistSignature = /*#__PURE__*/function () {
21941 var _appendBlacklistSignature2 = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee6(command, action, clientIds) {
21942 var params, signatureResult;
21943 return regenerator.wrap(function _callee6$(_context6) {
21944 while (1) switch (_context6.prev = _context6.next) {
21945 case 0:
21946 if (!this._client.options.blacklistSignatureFactory) {
21947 _context6.next = 6;
21948 break;
21949 }
21950 params = [this.id, this._client.id, clientIds.sort(), action];
21951 _context6.next = 4;
21952 return runSignatureFactory(this._client.options.blacklistSignatureFactory, params);
21953 case 4:
21954 signatureResult = _context6.sent;
21955 Object.assign(command.blacklistMessage, keyRemap({
21956 signature: 's',
21957 timestamp: 't',
21958 nonce: 'n'
21959 }, signatureResult));
21960 case 6:
21961 case "end":
21962 return _context6.stop();
21963 }
21964 }, _callee6, this);
21965 }));
21966 function _appendBlacklistSignature(_x4, _x5, _x6) {
21967 return _appendBlacklistSignature2.apply(this, arguments);
21968 }
21969 return _appendBlacklistSignature;
21970 }()
21971 /**
21972 * 增加成员
21973 * @param {String|String[]} clientIds 新增成员 client id
21974 * @return {Promise.<PartiallySuccess>} 部分成功结果,包含了成功的 id 列表、失败原因与对应的 id 列表
21975 */
21976 ;
21977 _proto.add =
21978 /*#__PURE__*/
21979 function () {
21980 var _add = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee7(clientIds) {
21981 var command, _yield$this$_send, convMessage, allowedPids;
21982 return regenerator.wrap(function _callee7$(_context7) {
21983 while (1) switch (_context7.prev = _context7.next) {
21984 case 0:
21985 this._debug('add', clientIds);
21986 if (typeof clientIds === 'string') {
21987 clientIds = [clientIds]; // eslint-disable-line no-param-reassign
21988 }
21989 command = new GenericCommand({
21990 op: 'add',
21991 convMessage: new ConvCommand({
21992 m: clientIds
21993 })
21994 });
21995 _context7.next = 5;
21996 return this._appendConversationSignature(command, 'invite', clientIds);
21997 case 5:
21998 _context7.next = 7;
21999 return this._send(command);
22000 case 7:
22001 _yield$this$_send = _context7.sent;
22002 convMessage = _yield$this$_send.convMessage;
22003 allowedPids = _yield$this$_send.convMessage.allowedPids;
22004 this._addMembers(allowedPids);
22005 return _context7.abrupt("return", createPartiallySuccess(convMessage));
22006 case 12:
22007 case "end":
22008 return _context7.stop();
22009 }
22010 }, _callee7, this);
22011 }));
22012 function add(_x7) {
22013 return _add.apply(this, arguments);
22014 }
22015 return add;
22016 }()
22017 /**
22018 * 剔除成员
22019 * @param {String|String[]} clientIds 成员 client id
22020 * @return {Promise.<PartiallySuccess>} 部分成功结果,包含了成功的 id 列表、失败原因与对应的 id 列表
22021 */
22022 ;
22023 _proto.remove =
22024 /*#__PURE__*/
22025 function () {
22026 var _remove = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee8(clientIds) {
22027 var command, _yield$this$_send2, convMessage, allowedPids;
22028 return regenerator.wrap(function _callee8$(_context8) {
22029 while (1) switch (_context8.prev = _context8.next) {
22030 case 0:
22031 this._debug('remove', clientIds);
22032 if (typeof clientIds === 'string') {
22033 clientIds = [clientIds]; // eslint-disable-line no-param-reassign
22034 }
22035 command = new GenericCommand({
22036 op: 'remove',
22037 convMessage: new ConvCommand({
22038 m: clientIds
22039 })
22040 });
22041 _context8.next = 5;
22042 return this._appendConversationSignature(command, 'kick', clientIds);
22043 case 5:
22044 _context8.next = 7;
22045 return this._send(command);
22046 case 7:
22047 _yield$this$_send2 = _context8.sent;
22048 convMessage = _yield$this$_send2.convMessage;
22049 allowedPids = _yield$this$_send2.convMessage.allowedPids;
22050 this._removeMembers(allowedPids);
22051 return _context8.abrupt("return", createPartiallySuccess(convMessage));
22052 case 12:
22053 case "end":
22054 return _context8.stop();
22055 }
22056 }, _callee8, this);
22057 }));
22058 function remove(_x8) {
22059 return _remove.apply(this, arguments);
22060 }
22061 return remove;
22062 }()
22063 /**
22064 * (当前用户)加入该对话
22065 * @return {Promise.<this>} self
22066 */
22067 ;
22068 _proto.join =
22069 /*#__PURE__*/
22070 function () {
22071 var _join = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee9() {
22072 var _this3 = this;
22073 return regenerator.wrap(function _callee9$(_context9) {
22074 while (1) switch (_context9.prev = _context9.next) {
22075 case 0:
22076 this._debug('join');
22077 return _context9.abrupt("return", this.add(this._client.id).then(function (_ref4) {
22078 var failures = _ref4.failures;
22079 if (failures[0]) throw failures[0];
22080 return _this3;
22081 }));
22082 case 2:
22083 case "end":
22084 return _context9.stop();
22085 }
22086 }, _callee9, this);
22087 }));
22088 function join() {
22089 return _join.apply(this, arguments);
22090 }
22091 return join;
22092 }()
22093 /**
22094 * (当前用户)退出该对话
22095 * @return {Promise.<this>} self
22096 */
22097 ;
22098 _proto.quit =
22099 /*#__PURE__*/
22100 function () {
22101 var _quit = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee10() {
22102 var _this4 = this;
22103 return regenerator.wrap(function _callee10$(_context10) {
22104 while (1) switch (_context10.prev = _context10.next) {
22105 case 0:
22106 this._debug('quit');
22107 return _context10.abrupt("return", this.remove(this._client.id).then(function (_ref5) {
22108 var failures = _ref5.failures;
22109 if (failures[0]) throw failures[0];
22110 return _this4;
22111 }));
22112 case 2:
22113 case "end":
22114 return _context10.stop();
22115 }
22116 }, _callee10, this);
22117 }));
22118 function quit() {
22119 return _quit.apply(this, arguments);
22120 }
22121 return quit;
22122 }()
22123 /**
22124 * 在该对话中禁言成员
22125 * @param {String|String[]} clientIds 成员 client id
22126 * @return {Promise.<PartiallySuccess>} 部分成功结果,包含了成功的 id 列表、失败原因与对应的 id 列表
22127 */
22128 ;
22129 _proto.muteMembers =
22130 /*#__PURE__*/
22131 function () {
22132 var _muteMembers = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee11(clientIds) {
22133 var command, _yield$this$_send3, convMessage;
22134 return regenerator.wrap(function _callee11$(_context11) {
22135 while (1) switch (_context11.prev = _context11.next) {
22136 case 0:
22137 this._debug('mute', clientIds);
22138 clientIds = ensureArray(clientIds); // eslint-disable-line no-param-reassign
22139 command = new GenericCommand({
22140 op: OpType.add_shutup,
22141 convMessage: new ConvCommand({
22142 m: clientIds
22143 })
22144 });
22145 _context11.next = 5;
22146 return this._send(command);
22147 case 5:
22148 _yield$this$_send3 = _context11.sent;
22149 convMessage = _yield$this$_send3.convMessage;
22150 return _context11.abrupt("return", createPartiallySuccess(convMessage));
22151 case 8:
22152 case "end":
22153 return _context11.stop();
22154 }
22155 }, _callee11, this);
22156 }));
22157 function muteMembers(_x9) {
22158 return _muteMembers.apply(this, arguments);
22159 }
22160 return muteMembers;
22161 }()
22162 /**
22163 * 在该对话中解除成员禁言
22164 * @param {String|String[]} clientIds 成员 client id
22165 * @return {Promise.<PartiallySuccess>} 部分成功结果,包含了成功的 id 列表、失败原因与对应的 id 列表
22166 */
22167 ;
22168 _proto.unmuteMembers =
22169 /*#__PURE__*/
22170 function () {
22171 var _unmuteMembers = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee12(clientIds) {
22172 var command, _yield$this$_send4, convMessage;
22173 return regenerator.wrap(function _callee12$(_context12) {
22174 while (1) switch (_context12.prev = _context12.next) {
22175 case 0:
22176 this._debug('unmute', clientIds);
22177 clientIds = ensureArray(clientIds); // eslint-disable-line no-param-reassign
22178 command = new GenericCommand({
22179 op: OpType.remove_shutup,
22180 convMessage: new ConvCommand({
22181 m: clientIds
22182 })
22183 });
22184 _context12.next = 5;
22185 return this._send(command);
22186 case 5:
22187 _yield$this$_send4 = _context12.sent;
22188 convMessage = _yield$this$_send4.convMessage;
22189 return _context12.abrupt("return", createPartiallySuccess(convMessage));
22190 case 8:
22191 case "end":
22192 return _context12.stop();
22193 }
22194 }, _callee12, this);
22195 }));
22196 function unmuteMembers(_x10) {
22197 return _unmuteMembers.apply(this, arguments);
22198 }
22199 return unmuteMembers;
22200 }()
22201 /**
22202 * 查询该对话禁言成员列表
22203 * @param {Object} [options]
22204 * @param {Number} [options.limit] 返回的成员数量,服务器默认值 10
22205 * @param {String} [options.next] 从指定 next 开始查询,与 limit 一起使用可以完成翻页。
22206 * @return {PagedResults.<string>} 查询结果。其中的 cureser 存在表示还有更多结果。
22207 */
22208 ;
22209 _proto.queryMutedMembers =
22210 /*#__PURE__*/
22211 function () {
22212 var _queryMutedMembers = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee13() {
22213 var _ref6,
22214 limit,
22215 next,
22216 command,
22217 _yield$this$_send5,
22218 _yield$this$_send5$co,
22219 m,
22220 newNext,
22221 _args13 = arguments;
22222 return regenerator.wrap(function _callee13$(_context13) {
22223 while (1) switch (_context13.prev = _context13.next) {
22224 case 0:
22225 _ref6 = _args13.length > 0 && _args13[0] !== undefined ? _args13[0] : {}, limit = _ref6.limit, next = _ref6.next;
22226 this._debug('query muted: limit %O, next: %O', limit, next);
22227 command = new GenericCommand({
22228 op: OpType.query_shutup,
22229 convMessage: new ConvCommand({
22230 limit: limit,
22231 next: next
22232 })
22233 });
22234 _context13.next = 5;
22235 return this._send(command);
22236 case 5:
22237 _yield$this$_send5 = _context13.sent;
22238 _yield$this$_send5$co = _yield$this$_send5.convMessage;
22239 m = _yield$this$_send5$co.m;
22240 newNext = _yield$this$_send5$co.next;
22241 return _context13.abrupt("return", {
22242 results: m,
22243 next: newNext
22244 });
22245 case 10:
22246 case "end":
22247 return _context13.stop();
22248 }
22249 }, _callee13, this);
22250 }));
22251 function queryMutedMembers() {
22252 return _queryMutedMembers.apply(this, arguments);
22253 }
22254 return queryMutedMembers;
22255 }()
22256 /**
22257 * 将用户加入该对话黑名单
22258 * @param {String|String[]} clientIds 成员 client id
22259 * @return {Promise.<PartiallySuccess>} 部分成功结果,包含了成功的 id 列表、失败原因与对应的 id 列表
22260 */
22261 ;
22262 _proto.blockMembers =
22263 /*#__PURE__*/
22264 function () {
22265 var _blockMembers = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee14(clientIds) {
22266 var command, _yield$this$_send6, blacklistMessage;
22267 return regenerator.wrap(function _callee14$(_context14) {
22268 while (1) switch (_context14.prev = _context14.next) {
22269 case 0:
22270 this._debug('block', clientIds);
22271 clientIds = ensureArray(clientIds); // eslint-disable-line no-param-reassign
22272 command = new GenericCommand({
22273 cmd: 'blacklist',
22274 op: OpType.block,
22275 blacklistMessage: new BlacklistCommand({
22276 srcCid: this.id,
22277 toPids: clientIds
22278 })
22279 });
22280 _context14.next = 5;
22281 return this._appendBlacklistSignature(command, 'conversation-block-clients', clientIds);
22282 case 5:
22283 _context14.next = 7;
22284 return this._send(command);
22285 case 7:
22286 _yield$this$_send6 = _context14.sent;
22287 blacklistMessage = _yield$this$_send6.blacklistMessage;
22288 return _context14.abrupt("return", createPartiallySuccess(blacklistMessage));
22289 case 10:
22290 case "end":
22291 return _context14.stop();
22292 }
22293 }, _callee14, this);
22294 }));
22295 function blockMembers(_x11) {
22296 return _blockMembers.apply(this, arguments);
22297 }
22298 return blockMembers;
22299 }()
22300 /**
22301 * 将用户移出该对话黑名单
22302 * @param {String|String[]} clientIds 成员 client id
22303 * @return {Promise.<PartiallySuccess>} 部分成功结果,包含了成功的 id 列表、失败原因与对应的 id 列表
22304 */
22305 ;
22306 _proto.unblockMembers =
22307 /*#__PURE__*/
22308 function () {
22309 var _unblockMembers = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee15(clientIds) {
22310 var command, _yield$this$_send7, blacklistMessage;
22311 return regenerator.wrap(function _callee15$(_context15) {
22312 while (1) switch (_context15.prev = _context15.next) {
22313 case 0:
22314 this._debug('unblock', clientIds);
22315 clientIds = ensureArray(clientIds); // eslint-disable-line no-param-reassign
22316 command = new GenericCommand({
22317 cmd: 'blacklist',
22318 op: OpType.unblock,
22319 blacklistMessage: new BlacklistCommand({
22320 srcCid: this.id,
22321 toPids: clientIds
22322 })
22323 });
22324 _context15.next = 5;
22325 return this._appendBlacklistSignature(command, 'conversation-unblock-clients', clientIds);
22326 case 5:
22327 _context15.next = 7;
22328 return this._send(command);
22329 case 7:
22330 _yield$this$_send7 = _context15.sent;
22331 blacklistMessage = _yield$this$_send7.blacklistMessage;
22332 return _context15.abrupt("return", createPartiallySuccess(blacklistMessage));
22333 case 10:
22334 case "end":
22335 return _context15.stop();
22336 }
22337 }, _callee15, this);
22338 }));
22339 function unblockMembers(_x12) {
22340 return _unblockMembers.apply(this, arguments);
22341 }
22342 return unblockMembers;
22343 }()
22344 /**
22345 * 查询该对话黑名单
22346 * @param {Object} [options]
22347 * @param {Number} [options.limit] 返回的成员数量,服务器默认值 10
22348 * @param {String} [options.next] 从指定 next 开始查询,与 limit 一起使用可以完成翻页
22349 * @return {PagedResults.<string>} 查询结果。其中的 cureser 存在表示还有更多结果。
22350 */
22351 ;
22352 _proto.queryBlockedMembers =
22353 /*#__PURE__*/
22354 function () {
22355 var _queryBlockedMembers = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee16() {
22356 var _ref7,
22357 limit,
22358 next,
22359 command,
22360 _yield$this$_send8,
22361 _yield$this$_send8$bl,
22362 blockedPids,
22363 newNext,
22364 _args16 = arguments;
22365 return regenerator.wrap(function _callee16$(_context16) {
22366 while (1) switch (_context16.prev = _context16.next) {
22367 case 0:
22368 _ref7 = _args16.length > 0 && _args16[0] !== undefined ? _args16[0] : {}, limit = _ref7.limit, next = _ref7.next;
22369 this._debug('query blocked: limit %O, next: %O', limit, next);
22370 command = new GenericCommand({
22371 cmd: 'blacklist',
22372 op: OpType.query,
22373 blacklistMessage: new BlacklistCommand({
22374 srcCid: this.id,
22375 limit: limit,
22376 next: next
22377 })
22378 });
22379 _context16.next = 5;
22380 return this._send(command);
22381 case 5:
22382 _yield$this$_send8 = _context16.sent;
22383 _yield$this$_send8$bl = _yield$this$_send8.blacklistMessage;
22384 blockedPids = _yield$this$_send8$bl.blockedPids;
22385 newNext = _yield$this$_send8$bl.next;
22386 return _context16.abrupt("return", {
22387 results: blockedPids,
22388 next: newNext
22389 });
22390 case 10:
22391 case "end":
22392 return _context16.stop();
22393 }
22394 }, _callee16, this);
22395 }));
22396 function queryBlockedMembers() {
22397 return _queryBlockedMembers.apply(this, arguments);
22398 }
22399 return queryBlockedMembers;
22400 }();
22401 _proto.toFullJSON = function toFullJSON() {
22402 var creator = this.creator,
22403 system = this.system,
22404 _transient2 = this["transient"],
22405 createdAt = this.createdAt,
22406 updatedAt = this.updatedAt,
22407 _attributes = this._attributes;
22408 return _objectSpread$6(_objectSpread$6({}, _ConversationBase.prototype.toFullJSON.call(this)), {}, {
22409 creator: creator,
22410 system: system,
22411 "transient": _transient2,
22412 createdAt: getTime(createdAt),
22413 updatedAt: getTime(updatedAt)
22414 }, _attributes);
22415 };
22416 _proto.toJSON = function toJSON() {
22417 var creator = this.creator,
22418 system = this.system,
22419 _transient3 = this["transient"],
22420 muted = this.muted,
22421 mutedMembers = this.mutedMembers,
22422 createdAt = this.createdAt,
22423 updatedAt = this.updatedAt,
22424 _attributes = this._attributes;
22425 return _objectSpread$6(_objectSpread$6({}, _ConversationBase.prototype.toJSON.call(this)), {}, {
22426 creator: creator,
22427 system: system,
22428 "transient": _transient3,
22429 muted: muted,
22430 mutedMembers: mutedMembers,
22431 createdAt: createdAt,
22432 updatedAt: updatedAt
22433 }, _attributes);
22434 };
22435 _createClass(PersistentConversation, [{
22436 key: "createdAt",
22437 get: function get() {
22438 return this._createdAt;
22439 },
22440 set: function set(value) {
22441 this._createdAt = decodeDate(value);
22442 }
22443 }, {
22444 key: "updatedAt",
22445 get: function get() {
22446 return this._updatedAt;
22447 }
22448
22449 /**
22450 * 对话名字,对应 _Conversation 表中的 name
22451 * @type {String}
22452 */,
22453 set: function set(value) {
22454 this._updatedAt = decodeDate(value);
22455 }
22456 }, {
22457 key: "name",
22458 get: function get() {
22459 return this.get('name');
22460 },
22461 set: function set(value) {
22462 this.set('name', value);
22463 }
22464 }]);
22465 return PersistentConversation;
22466 }(ConversationBase);
22467
22468 /**
22469 * 对话成员角色枚举
22470 * @enum {String}
22471 * @since 4.0.0
22472 * @memberof module:leancloud-realtime
22473 */
22474 var ConversationMemberRole = {
22475 /** 所有者 */
22476 OWNER: 'Owner',
22477 /** 管理员 */
22478 MANAGER: 'Manager',
22479 /** 成员 */
22480 MEMBER: 'Member'
22481 };
22482 Object.freeze(ConversationMemberRole);
22483 var ConversationMemberInfo = /*#__PURE__*/function () {
22484 /**
22485 * 对话成员属性,保存了成员与某个对话相关的属性,对应 _ConversationMemberInfo 表
22486 * @since 4.0.0
22487 */
22488 function ConversationMemberInfo(_ref) {
22489 var conversation = _ref.conversation,
22490 memberId = _ref.memberId,
22491 role = _ref.role;
22492 if (!conversation) throw new Error('conversation requried');
22493 if (!memberId) throw new Error('memberId requried');
22494 Object.assign(internal(this), {
22495 conversation: conversation,
22496 memberId: memberId,
22497 role: role
22498 });
22499 }
22500
22501 /**
22502 * 对话 Id
22503 * @type {String}
22504 * @readonly
22505 */
22506 var _proto = ConversationMemberInfo.prototype;
22507 _proto.toJSON = function toJSON() {
22508 var conversationId = this.conversationId,
22509 memberId = this.memberId,
22510 role = this.role,
22511 isOwner = this.isOwner;
22512 return {
22513 conversationId: conversationId,
22514 memberId: memberId,
22515 role: role,
22516 isOwner: isOwner
22517 };
22518 };
22519 _createClass(ConversationMemberInfo, [{
22520 key: "conversationId",
22521 get: function get() {
22522 return internal(this).conversation.id;
22523 }
22524
22525 /**
22526 * 成员 Id
22527 * @type {String}
22528 * @readonly
22529 */
22530 }, {
22531 key: "memberId",
22532 get: function get() {
22533 return internal(this).memberId;
22534 }
22535
22536 /**
22537 * 角色
22538 * @type {module:leancloud-realtime.ConversationMemberRole | String}
22539 * @readonly
22540 */
22541 }, {
22542 key: "role",
22543 get: function get() {
22544 if (this.isOwner) return ConversationMemberRole.OWNER;
22545 return internal(this).role;
22546 }
22547
22548 /**
22549 * 是否是管理员
22550 * @type {Boolean}
22551 * @readonly
22552 */
22553 }, {
22554 key: "isOwner",
22555 get: function get() {
22556 return this.memberId === internal(this).conversation.creator;
22557 }
22558 }]);
22559 return ConversationMemberInfo;
22560 }();
22561
22562 /**
22563 * 普通对话
22564 *
22565 * 无法直接实例化,请使用 {@link IMClient#createConversation} 创建新的普通对话。
22566 * @extends PersistentConversation
22567 * @public
22568 */
22569 var Conversation = /*#__PURE__*/function (_PersistentConversati) {
22570 _inheritsLoose(Conversation, _PersistentConversati);
22571 function Conversation() {
22572 return _PersistentConversati.apply(this, arguments) || this;
22573 }
22574 var _proto = Conversation.prototype;
22575 _proto._addMembers = function _addMembers(members) {
22576 var _this = this;
22577 _PersistentConversati.prototype._addMembers.call(this, members);
22578 this.members = union(this.members, members);
22579 var _internal = internal(this),
22580 memberInfoMap = _internal.memberInfoMap;
22581 if (!memberInfoMap) return;
22582 members.forEach(function (memberId) {
22583 memberInfoMap[memberId] = memberInfoMap[memberId] || new ConversationMemberInfo({
22584 conversation: _this,
22585 memberId: memberId,
22586 role: ConversationMemberRole.MEMBER
22587 });
22588 });
22589 };
22590 _proto._removeMembers = function _removeMembers(members) {
22591 _PersistentConversati.prototype._removeMembers.call(this, members);
22592 this.members = difference(this.members, members);
22593 var _internal2 = internal(this),
22594 memberInfoMap = _internal2.memberInfoMap;
22595 if (!memberInfoMap) return;
22596 members.forEach(function (memberId) {
22597 delete memberInfoMap[memberId];
22598 });
22599 };
22600 _proto._fetchAllMemberInfo = /*#__PURE__*/function () {
22601 var _fetchAllMemberInfo2 = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee() {
22602 var _this2 = this;
22603 var response, memberInfos, memberInfoMap;
22604 return regenerator.wrap(function _callee$(_context) {
22605 while (1) switch (_context.prev = _context.next) {
22606 case 0:
22607 _context.next = 2;
22608 return this._client._requestWithSessionToken({
22609 method: 'GET',
22610 path: '/classes/_ConversationMemberInfo',
22611 query: {
22612 where: {
22613 cid: this.id
22614 }
22615 }
22616 });
22617 case 2:
22618 response = _context.sent;
22619 memberInfos = response.results.map(function (info) {
22620 return new ConversationMemberInfo({
22621 conversation: _this2,
22622 memberId: info.clientId,
22623 role: info.role
22624 });
22625 });
22626 memberInfoMap = {};
22627 memberInfos.forEach(function (memberInfo) {
22628 memberInfoMap[memberInfo.memberId] = memberInfo;
22629 });
22630 this.members.forEach(function (memberId) {
22631 memberInfoMap[memberId] = memberInfoMap[memberId] || new ConversationMemberInfo({
22632 conversation: _this2,
22633 memberId: memberId,
22634 role: ConversationMemberRole.MEMBER
22635 });
22636 });
22637 internal(this).memberInfoMap = memberInfoMap;
22638 return _context.abrupt("return", memberInfoMap);
22639 case 9:
22640 case "end":
22641 return _context.stop();
22642 }
22643 }, _callee, this);
22644 }));
22645 function _fetchAllMemberInfo() {
22646 return _fetchAllMemberInfo2.apply(this, arguments);
22647 }
22648 return _fetchAllMemberInfo;
22649 }()
22650 /**
22651 * 获取所有成员的对话属性
22652 * @since 4.0.0
22653 * @return {Promise.<ConversationMemberInfo[]>} 所有成员的对话属性列表
22654 */
22655 ;
22656 _proto.getAllMemberInfo =
22657 /*#__PURE__*/
22658 function () {
22659 var _getAllMemberInfo = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee2() {
22660 var _ref,
22661 _ref$noCache,
22662 noCache,
22663 _internal3,
22664 memberInfoMap,
22665 _args2 = arguments;
22666 return regenerator.wrap(function _callee2$(_context2) {
22667 while (1) switch (_context2.prev = _context2.next) {
22668 case 0:
22669 _ref = _args2.length > 0 && _args2[0] !== undefined ? _args2[0] : {}, _ref$noCache = _ref.noCache, noCache = _ref$noCache === void 0 ? false : _ref$noCache;
22670 _internal3 = internal(this), memberInfoMap = _internal3.memberInfoMap;
22671 if (!(!memberInfoMap || noCache)) {
22672 _context2.next = 6;
22673 break;
22674 }
22675 _context2.next = 5;
22676 return this._fetchAllMemberInfo();
22677 case 5:
22678 memberInfoMap = _context2.sent;
22679 case 6:
22680 return _context2.abrupt("return", this.members.map(function (memberId) {
22681 return memberInfoMap[memberId];
22682 }));
22683 case 7:
22684 case "end":
22685 return _context2.stop();
22686 }
22687 }, _callee2, this);
22688 }));
22689 function getAllMemberInfo() {
22690 return _getAllMemberInfo.apply(this, arguments);
22691 }
22692 return getAllMemberInfo;
22693 }()
22694 /**
22695 * 获取指定成员的对话属性
22696 * @since 4.0.0
22697 * @param {String} memberId 成员 Id
22698 * @return {Promise.<ConversationMemberInfo>} 指定成员的对话属性
22699 */
22700 ;
22701 _proto.getMemberInfo =
22702 /*#__PURE__*/
22703 function () {
22704 var _getMemberInfo = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee3(memberId) {
22705 var _internal4, memberInfoMap;
22706 return regenerator.wrap(function _callee3$(_context3) {
22707 while (1) switch (_context3.prev = _context3.next) {
22708 case 0:
22709 if (!(this.members.indexOf(memberId) === -1)) {
22710 _context3.next = 2;
22711 break;
22712 }
22713 throw new Error("".concat(memberId, " is not the mumber of conversation[").concat(this.id, "]"));
22714 case 2:
22715 _internal4 = internal(this), memberInfoMap = _internal4.memberInfoMap;
22716 if (memberInfoMap && memberInfoMap[memberId]) {
22717 _context3.next = 6;
22718 break;
22719 }
22720 _context3.next = 6;
22721 return this.getAllMemberInfo();
22722 case 6:
22723 return _context3.abrupt("return", internal(this).memberInfoMap[memberId]);
22724 case 7:
22725 case "end":
22726 return _context3.stop();
22727 }
22728 }, _callee3, this);
22729 }));
22730 function getMemberInfo(_x) {
22731 return _getMemberInfo.apply(this, arguments);
22732 }
22733 return getMemberInfo;
22734 }()
22735 /**
22736 * 更新指定用户的角色
22737 * @since 4.0.0
22738 * @param {String} memberId 成员 Id
22739 * @param {module:leancloud-realtime.ConversationMemberRole | String} role 角色
22740 * @return {Promise.<this>} self
22741 */
22742 ;
22743 _proto.updateMemberRole =
22744 /*#__PURE__*/
22745 function () {
22746 var _updateMemberRole = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee4(memberId, role) {
22747 var _internal5, memberInfos;
22748 return regenerator.wrap(function _callee4$(_context4) {
22749 while (1) switch (_context4.prev = _context4.next) {
22750 case 0:
22751 this._debug('update member role');
22752 if (!(role === ConversationMemberRole.OWNER)) {
22753 _context4.next = 3;
22754 break;
22755 }
22756 throw createError({
22757 code: ErrorCode.OWNER_PROMOTION_NOT_ALLOWED
22758 });
22759 case 3:
22760 _context4.next = 5;
22761 return this._send(new GenericCommand({
22762 op: OpType.member_info_update,
22763 convMessage: new ConvCommand({
22764 targetClientId: memberId,
22765 info: new ConvMemberInfo({
22766 pid: memberId,
22767 role: role
22768 })
22769 })
22770 }));
22771 case 5:
22772 _internal5 = internal(this), memberInfos = _internal5.memberInfos;
22773 if (memberInfos && memberInfos[memberId]) {
22774 internal(memberInfos[memberId]).role = role;
22775 }
22776 return _context4.abrupt("return", this);
22777 case 8:
22778 case "end":
22779 return _context4.stop();
22780 }
22781 }, _callee4, this);
22782 }));
22783 function updateMemberRole(_x2, _x3) {
22784 return _updateMemberRole.apply(this, arguments);
22785 }
22786 return updateMemberRole;
22787 }();
22788 return Conversation;
22789 }(PersistentConversation);
22790
22791 /**
22792 * 聊天室。
22793 *
22794 * 无法直接实例化,请使用 {@link IMClient#createChatRoom} 创建新的聊天室。
22795 * @since 4.0.0
22796 * @extends PersistentConversation
22797 * @public
22798 */
22799 var ChatRoom = /*#__PURE__*/function (_PersistentConversati) {
22800 _inheritsLoose(ChatRoom, _PersistentConversati);
22801 function ChatRoom() {
22802 return _PersistentConversati.apply(this, arguments) || this;
22803 }
22804 return ChatRoom;
22805 }(PersistentConversation);
22806
22807 /**
22808 * 服务号。
22809 *
22810 * 服务号不支持在客户端创建。
22811 * @since 4.0.0
22812 * @extends PersistentConversation
22813 * @public
22814 */
22815 var ServiceConversation = /*#__PURE__*/function (_PersistentConversati) {
22816 _inheritsLoose(ServiceConversation, _PersistentConversati);
22817 function ServiceConversation() {
22818 return _PersistentConversati.apply(this, arguments) || this;
22819 }
22820 var _proto = ServiceConversation.prototype;
22821 /**
22822 * 订阅该服务号
22823 * @return {Promise.<this>} self
22824 */
22825 _proto.subscribe =
22826 /*#__PURE__*/
22827 function () {
22828 var _subscribe = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee() {
22829 return regenerator.wrap(function _callee$(_context) {
22830 while (1) switch (_context.prev = _context.next) {
22831 case 0:
22832 return _context.abrupt("return", this.join());
22833 case 1:
22834 case "end":
22835 return _context.stop();
22836 }
22837 }, _callee, this);
22838 }));
22839 function subscribe() {
22840 return _subscribe.apply(this, arguments);
22841 }
22842 return subscribe;
22843 }()
22844 /**
22845 * 退订该服务号
22846 * @return {Promise.<this>} self
22847 */
22848 ;
22849 _proto.unsubscribe =
22850 /*#__PURE__*/
22851 function () {
22852 var _unsubscribe = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee2() {
22853 return regenerator.wrap(function _callee2$(_context2) {
22854 while (1) switch (_context2.prev = _context2.next) {
22855 case 0:
22856 return _context2.abrupt("return", this.quit());
22857 case 1:
22858 case "end":
22859 return _context2.stop();
22860 }
22861 }, _callee2, this);
22862 }));
22863 function unsubscribe() {
22864 return _unsubscribe.apply(this, arguments);
22865 }
22866 return unsubscribe;
22867 }();
22868 return ServiceConversation;
22869 }(PersistentConversation);
22870
22871 function ownKeys$7(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
22872 function _objectSpread$7(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys$7(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$7(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
22873 var transformNotFoundError = function transformNotFoundError(error) {
22874 return error.code === ErrorCode.CONVERSATION_NOT_FOUND ? createError({
22875 code: ErrorCode.TEMPORARY_CONVERSATION_EXPIRED
22876 }) : error;
22877 };
22878
22879 /**
22880 * 临时对话
22881 * @since 4.0.0
22882 * @extends ConversationBase
22883 * @public
22884 */
22885 var TemporaryConversation = /*#__PURE__*/function (_ConversationBase) {
22886 _inheritsLoose(TemporaryConversation, _ConversationBase);
22887 /**
22888 * 无法直接实例化,请使用 {@link IMClient#createTemporaryConversation} 创建新的临时对话。
22889 */
22890 function TemporaryConversation(data, _ref, client) {
22891 var expiredAt = _ref.expiredAt;
22892 return _ConversationBase.call(this, _objectSpread$7(_objectSpread$7({}, data), {}, {
22893 expiredAt: expiredAt
22894 }), client) || this;
22895 }
22896
22897 /**
22898 * 对话失效时间
22899 * @type {Date}
22900 */
22901 var _proto = TemporaryConversation.prototype;
22902 _proto._send = /*#__PURE__*/function () {
22903 var _send2 = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee() {
22904 var _ConversationBase$pro,
22905 _len,
22906 args,
22907 _key,
22908 _args = arguments;
22909 return regenerator.wrap(function _callee$(_context) {
22910 while (1) switch (_context.prev = _context.next) {
22911 case 0:
22912 if (!this.expired) {
22913 _context.next = 2;
22914 break;
22915 }
22916 throw createError({
22917 code: ErrorCode.TEMPORARY_CONVERSATION_EXPIRED
22918 });
22919 case 2:
22920 _context.prev = 2;
22921 for (_len = _args.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
22922 args[_key] = _args[_key];
22923 }
22924 _context.next = 6;
22925 return (_ConversationBase$pro = _ConversationBase.prototype._send).call.apply(_ConversationBase$pro, [this].concat(args));
22926 case 6:
22927 return _context.abrupt("return", _context.sent);
22928 case 9:
22929 _context.prev = 9;
22930 _context.t0 = _context["catch"](2);
22931 throw transformNotFoundError(_context.t0);
22932 case 12:
22933 case "end":
22934 return _context.stop();
22935 }
22936 }, _callee, this, [[2, 9]]);
22937 }));
22938 function _send() {
22939 return _send2.apply(this, arguments);
22940 }
22941 return _send;
22942 }();
22943 _proto.send = /*#__PURE__*/function () {
22944 var _send3 = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee2() {
22945 var _ConversationBase$pro2,
22946 _len2,
22947 args,
22948 _key2,
22949 _args2 = arguments;
22950 return regenerator.wrap(function _callee2$(_context2) {
22951 while (1) switch (_context2.prev = _context2.next) {
22952 case 0:
22953 _context2.prev = 0;
22954 for (_len2 = _args2.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
22955 args[_key2] = _args2[_key2];
22956 }
22957 _context2.next = 4;
22958 return (_ConversationBase$pro2 = _ConversationBase.prototype.send).call.apply(_ConversationBase$pro2, [this].concat(args));
22959 case 4:
22960 return _context2.abrupt("return", _context2.sent);
22961 case 7:
22962 _context2.prev = 7;
22963 _context2.t0 = _context2["catch"](0);
22964 throw transformNotFoundError(_context2.t0);
22965 case 10:
22966 case "end":
22967 return _context2.stop();
22968 }
22969 }, _callee2, this, [[0, 7]]);
22970 }));
22971 function send() {
22972 return _send3.apply(this, arguments);
22973 }
22974 return send;
22975 }();
22976 _proto.toFullJSON = function toFullJSON() {
22977 var expiredAt = this.expiredAt;
22978 return _objectSpread$7(_objectSpread$7({}, _ConversationBase.prototype.toFullJSON.call(this)), {}, {
22979 expiredAt: getTime(expiredAt)
22980 });
22981 };
22982 _proto.toJSON = function toJSON() {
22983 var expiredAt = this.expiredAt,
22984 expired = this.expired;
22985 return _objectSpread$7(_objectSpread$7({}, _ConversationBase.prototype.toJSON.call(this)), {}, {
22986 expiredAt: expiredAt,
22987 expired: expired
22988 });
22989 };
22990 _createClass(TemporaryConversation, [{
22991 key: "expiredAt",
22992 get: function get() {
22993 return this._expiredAt;
22994 }
22995
22996 /**
22997 * 对话是否已失效
22998 * @type {Boolean}
22999 */,
23000 set: function set(value) {
23001 this._expiredAt = decodeDate(value);
23002 }
23003 }, {
23004 key: "expired",
23005 get: function get() {
23006 return this.expiredAt < new Date();
23007 }
23008 }]);
23009 return TemporaryConversation;
23010 }(ConversationBase);
23011
23012 var debug$9 = browser('LC:ConversationQuery');
23013 var ConversationQuery = /*#__PURE__*/function () {
23014 ConversationQuery._encode = function _encode(value) {
23015 if (value instanceof Date) {
23016 return {
23017 __type: 'Date',
23018 iso: value.toJSON()
23019 };
23020 }
23021 if (value instanceof RegExp) {
23022 return value.source;
23023 }
23024 return value;
23025 };
23026 ConversationQuery._quote = function _quote(s) {
23027 return "\\Q".concat(s.replace('\\E', '\\E\\\\E\\Q'), "\\E");
23028 };
23029 ConversationQuery._calculateFlag = function _calculateFlag(options) {
23030 return ['withLastMessagesRefreshed', 'compact'].reduce(
23031 // eslint-disable-next-line no-bitwise
23032 function (prev, key) {
23033 return (prev << 1) + Boolean(options[key]);
23034 }, 0);
23035 }
23036
23037 /**
23038 * 构造一个用 AND 连接所有查询的 ConversationQuery
23039 * @param {...ConversationQuery} queries
23040 * @return {ConversationQuery}
23041 */;
23042 ConversationQuery.and = function and() {
23043 for (var _len = arguments.length, queries = new Array(_len), _key = 0; _key < _len; _key++) {
23044 queries[_key] = arguments[_key];
23045 }
23046 if (queries.length < 2) {
23047 throw new Error('The queries must contain at least two elements');
23048 }
23049 if (!queries.every(function (q) {
23050 return q instanceof ConversationQuery;
23051 })) {
23052 throw new Error('The element of queries must be an instance of ConversationQuery');
23053 }
23054 var combined = new ConversationQuery(queries[0]._client);
23055 combined._where.$and = queries.map(function (q) {
23056 return q._where;
23057 });
23058 return combined;
23059 }
23060
23061 /**
23062 * 构造一个用 OR 连接所有查询的 ConversationQuery
23063 * @param {...ConversationQuery} queries
23064 * @return {ConversationQuery}
23065 */;
23066 ConversationQuery.or = function or() {
23067 var combined = ConversationQuery.and.apply(ConversationQuery, arguments);
23068 combined._where.$or = combined._where.$and;
23069 delete combined._where.$and;
23070 return combined;
23071 }
23072
23073 /**
23074 * Create a ConversationQuery
23075 * @param {IMClient} client
23076 */;
23077 function ConversationQuery(client) {
23078 this._client = client;
23079 this._where = {};
23080 this._extraOptions = {};
23081 }
23082 var _proto = ConversationQuery.prototype;
23083 _proto._addCondition = function _addCondition(key, condition, value) {
23084 // Check if we already have a condition
23085 if (!this._where[key]) {
23086 this._where[key] = {};
23087 }
23088 this._where[key][condition] = this.constructor._encode(value);
23089 return this;
23090 };
23091 _proto.toJSON = function toJSON() {
23092 var json = {
23093 where: this._where,
23094 flag: this.constructor._calculateFlag(this._extraOptions)
23095 };
23096 if (typeof this._skip !== 'undefined') json.skip = this._skip;
23097 if (typeof this._limit !== 'undefined') json.limit = this._limit;
23098 if (typeof this._order !== 'undefined') json.sort = this._order;
23099 debug$9(json);
23100 return json;
23101 }
23102
23103 /**
23104 * 增加查询条件,指定聊天室的组员包含某些成员即可返回
23105 * @param {string[]} peerIds - 成员 ID 列表
23106 * @return {ConversationQuery} self
23107 */;
23108 _proto.containsMembers = function containsMembers(peerIds) {
23109 return this.containsAll('m', peerIds);
23110 }
23111
23112 /**
23113 * 增加查询条件,指定聊天室的组员条件满足条件的才返回
23114 *
23115 * @param {string[]} - 成员 ID 列表
23116 * @param {Boolean} includeSelf - 是否包含自己
23117 * @return {ConversationQuery} self
23118 */;
23119 _proto.withMembers = function withMembers(peerIds, includeSelf) {
23120 var peerIdsSet = new Set(peerIds);
23121 if (includeSelf) {
23122 peerIdsSet.add(this._client.id);
23123 }
23124 this.sizeEqualTo('m', peerIdsSet.size);
23125 return this.containsMembers(Array.from(peerIdsSet));
23126 }
23127
23128 /**
23129 * 增加查询条件,当 conversation 的属性中对应的字段满足等于条件时即可返回
23130 *
23131 * @param {string} key
23132 * @param value
23133 * @return {ConversationQuery} self
23134 */;
23135 _proto.equalTo = function equalTo(key, value) {
23136 this._where[key] = this.constructor._encode(value);
23137 return this;
23138 }
23139
23140 /**
23141 * 增加查询条件,当 conversation 的属性中对应的字段满足小于条件时即可返回
23142 * @param {string} key
23143 * @param value
23144 * @return {ConversationQuery} self
23145 */;
23146 _proto.lessThan = function lessThan(key, value) {
23147 return this._addCondition(key, '$lt', value);
23148 }
23149
23150 /**
23151 * 增加查询条件,当 conversation 的属性中对应的字段满足小于等于条件时即可返回
23152 * @param {string} key
23153 * @param value
23154 * @return {ConversationQuery} self
23155 */;
23156 _proto.lessThanOrEqualTo = function lessThanOrEqualTo(key, value) {
23157 return this._addCondition(key, '$lte', value);
23158 }
23159
23160 /**
23161 * 增加查询条件,当 conversation 的属性中对应的字段满足大于条件时即可返回
23162 *
23163 * @param {string} key
23164 * @param value
23165 * @return {ConversationQuery} self
23166 */;
23167 _proto.greaterThan = function greaterThan(key, value) {
23168 return this._addCondition(key, '$gt', value);
23169 }
23170
23171 /**
23172 * 增加查询条件,当 conversation 的属性中对应的字段满足大于等于条件时即可返回
23173 *
23174 * @param {string} key
23175 * @param value
23176 * @return {ConversationQuery} self
23177 */;
23178 _proto.greaterThanOrEqualTo = function greaterThanOrEqualTo(key, value) {
23179 return this._addCondition(key, '$gte', value);
23180 }
23181
23182 /**
23183 * 增加查询条件,当 conversation 的属性中对应的字段满足不等于条件时即可返回
23184 *
23185 * @param {string} key
23186 * @param value
23187 * @return {ConversationQuery} self
23188 */;
23189 _proto.notEqualTo = function notEqualTo(key, value) {
23190 return this._addCondition(key, '$ne', value);
23191 }
23192
23193 /**
23194 * 增加查询条件,当 conversation 存在指定的字段时即可返回
23195 *
23196 * @since 3.5.0
23197 * @param {string} key
23198 * @return {ConversationQuery} self
23199 */;
23200 _proto.exists = function exists(key) {
23201 return this._addCondition(key, '$exists', true);
23202 }
23203
23204 /**
23205 * 增加查询条件,当 conversation 不存在指定的字段时即可返回
23206 *
23207 * @since 3.5.0
23208 * @param {string} key
23209 * @return {ConversationQuery} self
23210 */;
23211 _proto.doesNotExist = function doesNotExist(key) {
23212 return this._addCondition(key, '$exists', false);
23213 }
23214
23215 /**
23216 * 增加查询条件,当 conversation 的属性中对应的字段对应的值包含在指定值中时即可返回
23217 *
23218 * @param {string} key
23219 * @param values
23220 * @return {ConversationQuery} self
23221 */;
23222 _proto.containedIn = function containedIn(key, values) {
23223 return this._addCondition(key, '$in', values);
23224 }
23225
23226 /**
23227 * 增加查询条件,当 conversation 的属性中对应的字段对应的值不包含在指定值中时即可返回
23228 *
23229 * @param {string} key
23230 * @param values
23231 * @return {ConversationQuery} self
23232 */;
23233 _proto.notContainsIn = function notContainsIn(key, values) {
23234 return this._addCondition(key, '$nin', values);
23235 }
23236
23237 /**
23238 * 增加查询条件,当conversation的属性中对应的字段中的元素包含所有的值才可返回
23239 *
23240 * @param {string} key
23241 * @param values
23242 * @return {ConversationQuery} self
23243 */;
23244 _proto.containsAll = function containsAll(key, values) {
23245 return this._addCondition(key, '$all', values);
23246 }
23247
23248 /**
23249 * 增加查询条件,当 conversation 的属性中对应的字段对应的值包含此字符串即可返回
23250 *
23251 * @param {string} key
23252 * @param {string} subString
23253 * @return {ConversationQuery} self
23254 */;
23255 _proto.contains = function contains(key, subString) {
23256 return this._addCondition(key, '$regex', ConversationQuery._quote(subString));
23257 }
23258
23259 /**
23260 * 增加查询条件,当 conversation 的属性中对应的字段对应的值以此字符串起始即可返回
23261 *
23262 * @param {string} key
23263 * @param {string} prefix
23264 * @return {ConversationQuery} self
23265 */;
23266 _proto.startsWith = function startsWith(key, prefix) {
23267 return this._addCondition(key, '$regex', "^".concat(ConversationQuery._quote(prefix)));
23268 }
23269
23270 /**
23271 * 增加查询条件,当 conversation 的属性中对应的字段对应的值以此字符串结束即可返回
23272 *
23273 * @param {string} key
23274 * @param {string} suffix
23275 * @return {ConversationQuery} self
23276 */;
23277 _proto.endsWith = function endsWith(key, suffix) {
23278 return this._addCondition(key, '$regex', "".concat(ConversationQuery._quote(suffix), "$"));
23279 }
23280
23281 /**
23282 * 增加查询条件,当 conversation 的属性中对应的字段对应的值满足提供的正则表达式即可返回
23283 *
23284 * @param {string} key
23285 * @param {RegExp} regex
23286 * @return {ConversationQuery} self
23287 */;
23288 _proto.matches = function matches(key, regex) {
23289 this._addCondition(key, '$regex', regex);
23290 // Javascript regex options support mig as inline options but store them
23291 // as properties of the object. We support mi & should migrate them to
23292 // modifiers
23293 var _modifiers = '';
23294 if (regex.ignoreCase) {
23295 _modifiers += 'i';
23296 }
23297 if (regex.multiline) {
23298 _modifiers += 'm';
23299 }
23300 if (_modifiers && _modifiers.length) {
23301 this._addCondition(key, '$options', _modifiers);
23302 }
23303 return this;
23304 }
23305
23306 /**
23307 * 添加查询约束条件,查找 key 类型是数组,该数组的长度匹配提供的数值
23308 *
23309 * @param {string} key
23310 * @param {Number} length
23311 * @return {ConversationQuery} self
23312 */;
23313 _proto.sizeEqualTo = function sizeEqualTo(key, length) {
23314 return this._addCondition(key, '$size', length);
23315 }
23316
23317 /**
23318 * 设置返回集合的大小上限
23319 *
23320 * @param {Number} limit - 上限
23321 * @return {ConversationQuery} self
23322 */;
23323 _proto.limit = function limit(_limit) {
23324 this._limit = _limit;
23325 return this;
23326 }
23327
23328 /**
23329 * 设置返回集合的起始位置,一般用于分页
23330 *
23331 * @param {Number} skip - 起始位置跳过几个对象
23332 * @return {ConversationQuery} self
23333 */;
23334 _proto.skip = function skip(_skip) {
23335 this._skip = _skip;
23336 return this;
23337 }
23338
23339 /**
23340 * 设置返回集合按照指定key进行增序排列
23341 *
23342 * @param {string} key
23343 * @return {ConversationQuery} self
23344 */;
23345 _proto.ascending = function ascending(key) {
23346 this._order = key;
23347 return this;
23348 }
23349
23350 /**
23351 * 设置返回集合按照指定key进行增序排列,如果已设置其他排序,原排序的优先级较高
23352 *
23353 * @param {string} key
23354 * @return {ConversationQuery} self
23355 */;
23356 _proto.addAscending = function addAscending(key) {
23357 if (this._order) {
23358 this._order += ",".concat(key);
23359 } else {
23360 this._order = key;
23361 }
23362 return this;
23363 }
23364
23365 /**
23366 * 设置返回集合按照指定 key 进行降序排列
23367 *
23368 * @param {string} key
23369 * @return {ConversationQuery} self
23370 */;
23371 _proto.descending = function descending(key) {
23372 this._order = "-".concat(key);
23373 return this;
23374 }
23375
23376 /**
23377 * 设置返回集合按照指定 key 进行降序排列,如果已设置其他排序,原排序的优先级较高
23378 *
23379 * @param {string} key
23380 * @return {ConversationQuery} self
23381 */;
23382 _proto.addDescending = function addDescending(key) {
23383 if (this._order) {
23384 this._order += ",-".concat(key);
23385 } else {
23386 this._order = "-".concat(key);
23387 }
23388 return this;
23389 }
23390
23391 /**
23392 * 设置返回的 conversations 刷新最后一条消息
23393 * @param {Boolean} [enabled=true]
23394 * @return {ConversationQuery} self
23395 */;
23396 _proto.withLastMessagesRefreshed = function withLastMessagesRefreshed() {
23397 var enabled = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
23398 this._extraOptions.withLastMessagesRefreshed = enabled;
23399 return this;
23400 }
23401
23402 /**
23403 * 设置返回的 conversations 为精简模式,即不含成员列表
23404 * @param {Boolean} [enabled=true]
23405 * @return {ConversationQuery} self
23406 */;
23407 _proto.compact = function compact() {
23408 var enabled = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
23409 this._extraOptions.compact = enabled;
23410 return this;
23411 }
23412
23413 /**
23414 * 执行查询
23415 * @return {Promise.<ConversationBase[]>}
23416 */;
23417 _proto.find =
23418 /*#__PURE__*/
23419 function () {
23420 var _find = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee() {
23421 return regenerator.wrap(function _callee$(_context) {
23422 while (1) switch (_context.prev = _context.next) {
23423 case 0:
23424 return _context.abrupt("return", this._client._executeQuery(this));
23425 case 1:
23426 case "end":
23427 return _context.stop();
23428 }
23429 }, _callee, this);
23430 }));
23431 function find() {
23432 return _find.apply(this, arguments);
23433 }
23434 return find;
23435 }()
23436 /**
23437 * 返回符合条件的第一个结果
23438 * @return {Promise.<ConversationBase>}
23439 */
23440 ;
23441 _proto.first =
23442 /*#__PURE__*/
23443 function () {
23444 var _first = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee2() {
23445 return regenerator.wrap(function _callee2$(_context2) {
23446 while (1) switch (_context2.prev = _context2.next) {
23447 case 0:
23448 _context2.next = 2;
23449 return this.limit(1).find();
23450 case 2:
23451 return _context2.abrupt("return", _context2.sent[0]);
23452 case 3:
23453 case "end":
23454 return _context2.stop();
23455 }
23456 }, _callee2, this);
23457 }));
23458 function first() {
23459 return _first.apply(this, arguments);
23460 }
23461 return first;
23462 }();
23463 return ConversationQuery;
23464 }();
23465
23466 var debug$a = browser('LC:SessionManager');
23467 var SessionManager = /*#__PURE__*/function () {
23468 function SessionManager() {
23469 var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
23470 refresh = _ref.refresh,
23471 onBeforeGetSessionToken = _ref.onBeforeGetSessionToken;
23472 this.refresh = refresh;
23473 this._onBeforeGetSessionToken = onBeforeGetSessionToken;
23474 this.setSessionToken(null, 0);
23475 }
23476 var _proto = SessionManager.prototype;
23477 _proto.setSessionToken = function setSessionToken(token, ttl) {
23478 debug$a('set session token', token, ttl);
23479 var sessionToken = new Expirable(token, ttl * 1000);
23480 this._sessionToken = sessionToken;
23481 delete this._pendingSessionTokenPromise;
23482 return sessionToken;
23483 };
23484 _proto.setSessionTokenAsync = /*#__PURE__*/function () {
23485 var _setSessionTokenAsync = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee(promise) {
23486 var _this = this;
23487 var currentSessionToken;
23488 return regenerator.wrap(function _callee$(_context) {
23489 while (1) switch (_context.prev = _context.next) {
23490 case 0:
23491 currentSessionToken = this._sessionToken;
23492 this._pendingSessionTokenPromise = promise["catch"](function (error) {
23493 // revert, otherwise the following getSessionToken calls
23494 // will all be rejected
23495 _this._sessionToken = currentSessionToken;
23496 throw error;
23497 });
23498 _context.t0 = this.setSessionToken;
23499 _context.t1 = this;
23500 _context.t2 = _toConsumableArray;
23501 _context.next = 7;
23502 return this._pendingSessionTokenPromise;
23503 case 7:
23504 _context.t3 = _context.sent;
23505 _context.t4 = (0, _context.t2)(_context.t3);
23506 return _context.abrupt("return", _context.t0.apply.call(_context.t0, _context.t1, _context.t4));
23507 case 10:
23508 case "end":
23509 return _context.stop();
23510 }
23511 }, _callee, this);
23512 }));
23513 function setSessionTokenAsync(_x) {
23514 return _setSessionTokenAsync.apply(this, arguments);
23515 }
23516 return setSessionTokenAsync;
23517 }();
23518 _proto.getSessionToken = /*#__PURE__*/function () {
23519 var _getSessionToken = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee2() {
23520 var _ref2,
23521 _ref2$autoRefresh,
23522 autoRefresh,
23523 _ref3,
23524 value,
23525 originalValue,
23526 _yield$this$setSessio,
23527 newValue,
23528 _args2 = arguments;
23529 return regenerator.wrap(function _callee2$(_context2) {
23530 while (1) switch (_context2.prev = _context2.next) {
23531 case 0:
23532 _ref2 = _args2.length > 0 && _args2[0] !== undefined ? _args2[0] : {}, _ref2$autoRefresh = _ref2.autoRefresh, autoRefresh = _ref2$autoRefresh === void 0 ? true : _ref2$autoRefresh;
23533 debug$a('get session token');
23534 if (this._onBeforeGetSessionToken) {
23535 this._onBeforeGetSessionToken(this);
23536 }
23537 _context2.t0 = this._sessionToken;
23538 if (_context2.t0) {
23539 _context2.next = 8;
23540 break;
23541 }
23542 _context2.next = 7;
23543 return this._pendingSessionTokenPromise;
23544 case 7:
23545 _context2.t0 = _context2.sent;
23546 case 8:
23547 _ref3 = _context2.t0;
23548 value = _ref3.value;
23549 originalValue = _ref3.originalValue;
23550 if (!(value === Expirable.EXPIRED && autoRefresh && this.refresh)) {
23551 _context2.next = 19;
23552 break;
23553 }
23554 debug$a('refresh expired session token');
23555 _context2.next = 15;
23556 return this.setSessionTokenAsync(this.refresh(this, originalValue));
23557 case 15:
23558 _yield$this$setSessio = _context2.sent;
23559 newValue = _yield$this$setSessio.value;
23560 debug$a('session token', newValue);
23561 return _context2.abrupt("return", newValue);
23562 case 19:
23563 debug$a('session token', value);
23564 return _context2.abrupt("return", value);
23565 case 21:
23566 case "end":
23567 return _context2.stop();
23568 }
23569 }, _callee2, this);
23570 }));
23571 function getSessionToken() {
23572 return _getSessionToken.apply(this, arguments);
23573 }
23574 return getSessionToken;
23575 }();
23576 _proto.revoke = function revoke() {
23577 if (this._sessionToken) this._sessionToken.expiredAt = -1;
23578 };
23579 return SessionManager;
23580 }();
23581
23582 var _excluded$3 = ["cmd", "op", "serverTs", "notificationType"],
23583 _excluded2$1 = ["headers", "query"],
23584 _excluded3 = ["data", "bin"],
23585 _excluded4 = ["id", "lastMessageAt", "lastMessage", "lastDeliveredAt", "lastReadAt", "unreadMessagesCount", "members", "mentioned"],
23586 _excluded5 = ["members", "name", "transient", "unique", "_tempConv", "_tempConvTTL"],
23587 _excluded6 = ["ttl"];
23588 var _dec$2, _dec2, _class$3;
23589 function ownKeys$8(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
23590 function _objectSpread$8(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys$8(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$8(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
23591 var debug$b = browser('LC:IMClient');
23592 var INVITED$1 = INVITED,
23593 KICKED$1 = KICKED,
23594 MEMBERS_JOINED$1 = MEMBERS_JOINED,
23595 MEMBERS_LEFT$1 = MEMBERS_LEFT,
23596 MEMBER_INFO_UPDATED$1 = MEMBER_INFO_UPDATED,
23597 BLOCKED$1 = BLOCKED,
23598 UNBLOCKED$1 = UNBLOCKED,
23599 MEMBERS_BLOCKED$1 = MEMBERS_BLOCKED,
23600 MEMBERS_UNBLOCKED$1 = MEMBERS_UNBLOCKED,
23601 MUTED$1 = MUTED,
23602 UNMUTED$1 = UNMUTED,
23603 MEMBERS_MUTED$1 = MEMBERS_MUTED,
23604 MEMBERS_UNMUTED$1 = MEMBERS_UNMUTED,
23605 MESSAGE$2 = MESSAGE$1,
23606 UNREAD_MESSAGES_COUNT_UPDATE$1 = UNREAD_MESSAGES_COUNT_UPDATE,
23607 CLOSE$1 = CLOSE,
23608 CONFLICT$1 = CONFLICT,
23609 UNHANDLED_MESSAGE$1 = UNHANDLED_MESSAGE,
23610 CONVERSATION_INFO_UPDATED$1 = CONVERSATION_INFO_UPDATED,
23611 MESSAGE_RECALL$1 = MESSAGE_RECALL,
23612 MESSAGE_UPDATE$1 = MESSAGE_UPDATE,
23613 INFO_UPDATED$1 = INFO_UPDATED;
23614 var isTemporaryConversatrionId = function isTemporaryConversatrionId(id) {
23615 return /^_tmp:/.test(id);
23616 };
23617
23618 /**
23619 * 1 patch-msg
23620 * 1 temp-conv-msg
23621 * 0 auto-bind-deviceid-and-installation
23622 * 1 transient-msg-ack
23623 * 1 keep-notification
23624 * 1 partial-failed-msg
23625 * 0 group-chat-rcp
23626 * 1 omit-peer-id
23627 * @ignore
23628 */
23629 var configBitmap = 187;
23630 var IMClient = (_dec$2 = throttle(1000), _dec2 = throttle(1000), (_class$3 = /*#__PURE__*/function (_EventEmitter) {
23631 _inheritsLoose(IMClient, _EventEmitter);
23632 /**
23633 * 无法直接实例化,请使用 {@link Realtime#createIMClient} 创建新的 IMClient。
23634 *
23635 * @extends EventEmitter
23636 */
23637 function IMClient(id) {
23638 var _this;
23639 var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
23640 var props = arguments.length > 2 ? arguments[2] : undefined;
23641 if (!(id === undefined || typeof id === 'string')) {
23642 throw new TypeError("Client id [".concat(id, "] is not a String"));
23643 }
23644 _this = _EventEmitter.call(this) || this;
23645 Object.assign(_assertThisInitialized(_this), {
23646 /**
23647 * @var id {String} 客户端 id
23648 * @memberof IMClient#
23649 */
23650 id: id,
23651 options: options
23652 }, props);
23653 if (!_this._messageParser) {
23654 throw new Error('IMClient must be initialized with a MessageParser');
23655 }
23656 _this._conversationCache = new Cache("client:".concat(_this.id));
23657 _this._ackMessageBuffer = {};
23658 internal(_assertThisInitialized(_this)).lastPatchTime = Date.now();
23659 internal(_assertThisInitialized(_this)).lastNotificationTime = undefined;
23660 internal(_assertThisInitialized(_this))._eventemitter = new eventemitter3();
23661 if (debug$b.enabled) {
23662 values_1(IMEvent).forEach(function (event) {
23663 return _this.on(event, function () {
23664 for (var _len = arguments.length, payload = new Array(_len), _key = 0; _key < _len; _key++) {
23665 payload[_key] = arguments[_key];
23666 }
23667 return _this._debug("".concat(event, " event emitted. %o"), payload);
23668 });
23669 });
23670 }
23671 // onIMClientCreate hook
23672 applyDecorators(_this._plugins.onIMClientCreate, _assertThisInitialized(_this));
23673 return _this;
23674 }
23675 var _proto = IMClient.prototype;
23676 _proto._debug = function _debug() {
23677 for (var _len2 = arguments.length, params = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
23678 params[_key2] = arguments[_key2];
23679 }
23680 debug$b.apply(void 0, params.concat(["[".concat(this.id, "]")]));
23681 }
23682
23683 /**
23684 * @override
23685 * @private
23686 */;
23687 _proto._dispatchCommand =
23688 /*#__PURE__*/
23689 function () {
23690 var _dispatchCommand2 = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee(command) {
23691 return regenerator.wrap(function _callee$(_context) {
23692 while (1) switch (_context.prev = _context.next) {
23693 case 0:
23694 this._debug(trim(command), 'received');
23695 if (command.serverTs && command.notificationType === 1) {
23696 internal(this).lastNotificationTime = getTime(decodeDate(command.serverTs));
23697 }
23698 _context.t0 = command.cmd;
23699 _context.next = _context.t0 === CommandType.conv ? 5 : _context.t0 === CommandType.direct ? 6 : _context.t0 === CommandType.session ? 7 : _context.t0 === CommandType.unread ? 8 : _context.t0 === CommandType.rcp ? 9 : _context.t0 === CommandType.patch ? 10 : 11;
23700 break;
23701 case 5:
23702 return _context.abrupt("return", this._dispatchConvMessage(command));
23703 case 6:
23704 return _context.abrupt("return", this._dispatchDirectMessage(command));
23705 case 7:
23706 return _context.abrupt("return", this._dispatchSessionMessage(command));
23707 case 8:
23708 return _context.abrupt("return", this._dispatchUnreadMessage(command));
23709 case 9:
23710 return _context.abrupt("return", this._dispatchRcpMessage(command));
23711 case 10:
23712 return _context.abrupt("return", this._dispatchPatchMessage(command));
23713 case 11:
23714 return _context.abrupt("return", this.emit(UNHANDLED_MESSAGE$1, command));
23715 case 12:
23716 case "end":
23717 return _context.stop();
23718 }
23719 }, _callee, this);
23720 }));
23721 function _dispatchCommand(_x) {
23722 return _dispatchCommand2.apply(this, arguments);
23723 }
23724 return _dispatchCommand;
23725 }();
23726 _proto._dispatchSessionMessage = /*#__PURE__*/function () {
23727 var _dispatchSessionMessage2 = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee2(message) {
23728 var _message$sessionMessa, code, reason;
23729 return regenerator.wrap(function _callee2$(_context2) {
23730 while (1) switch (_context2.prev = _context2.next) {
23731 case 0:
23732 _message$sessionMessa = message.sessionMessage, code = _message$sessionMessa.code, reason = _message$sessionMessa.reason;
23733 _context2.t0 = message.op;
23734 _context2.next = _context2.t0 === OpType.closed ? 4 : 8;
23735 break;
23736 case 4:
23737 internal(this)._eventemitter.emit('close');
23738 if (!(code === ErrorCode.SESSION_CONFLICT)) {
23739 _context2.next = 7;
23740 break;
23741 }
23742 return _context2.abrupt("return", this.emit(CONFLICT$1, {
23743 reason: reason
23744 }));
23745 case 7:
23746 return _context2.abrupt("return", this.emit(CLOSE$1, {
23747 code: code,
23748 reason: reason
23749 }));
23750 case 8:
23751 this.emit(UNHANDLED_MESSAGE$1, message);
23752 throw new Error('Unrecognized session command');
23753 case 10:
23754 case "end":
23755 return _context2.stop();
23756 }
23757 }, _callee2, this);
23758 }));
23759 function _dispatchSessionMessage(_x2) {
23760 return _dispatchSessionMessage2.apply(this, arguments);
23761 }
23762 return _dispatchSessionMessage;
23763 }();
23764 _proto._dispatchUnreadMessage = function _dispatchUnreadMessage(_ref) {
23765 var _this2 = this;
23766 var _ref$unreadMessage = _ref.unreadMessage,
23767 convs = _ref$unreadMessage.convs,
23768 notifTime = _ref$unreadMessage.notifTime;
23769 internal(this).lastUnreadNotifTime = notifTime;
23770 // ensure all converstions are cached
23771 return this.getConversations(convs.map(function (conv) {
23772 return conv.cid;
23773 })).then(function () {
23774 return (
23775 // update conversations data
23776 Promise.all(convs.map(function (_ref2) {
23777 var cid = _ref2.cid,
23778 unread = _ref2.unread,
23779 mid = _ref2.mid,
23780 ts = _ref2.timestamp,
23781 from = _ref2.from,
23782 data = _ref2.data,
23783 binaryMsg = _ref2.binaryMsg,
23784 patchTimestamp = _ref2.patchTimestamp,
23785 mentioned = _ref2.mentioned;
23786 var conversation = _this2._conversationCache.get(cid);
23787 // deleted conversation
23788 if (!conversation) return null;
23789 var timestamp;
23790 if (ts) {
23791 timestamp = decodeDate(ts);
23792 conversation.lastMessageAt = timestamp; // eslint-disable-line no-param-reassign
23793 }
23794
23795 return (mid ? _this2._messageParser.parse(binaryMsg || data).then(function (message) {
23796 var messageProps = {
23797 id: mid,
23798 cid: cid,
23799 timestamp: timestamp,
23800 updatedAt: patchTimestamp,
23801 from: from
23802 };
23803 Object.assign(message, messageProps);
23804 conversation.lastMessage = message; // eslint-disable-line no-param-reassign
23805 }) : Promise.resolve()).then(function () {
23806 conversation._setUnreadMessagesMentioned(mentioned);
23807 var countNotUpdated = unread === internal(conversation).unreadMessagesCount;
23808 if (countNotUpdated) return null; // to be filtered
23809 // manipulate internal property directly to skip unreadmessagescountupdate event
23810 internal(conversation).unreadMessagesCount = unread;
23811 return conversation;
23812 });
23813 // filter conversations without unread count update
23814 })).then(function (conversations) {
23815 return conversations.filter(function (conversation) {
23816 return conversation;
23817 });
23818 })
23819 );
23820 }).then(function (conversations) {
23821 if (conversations.length) {
23822 /**
23823 * 未读消息数目更新
23824 * @event IMClient#UNREAD_MESSAGES_COUNT_UPDATE
23825 * @since 3.4.0
23826 * @param {Conversation[]} conversations 未读消息数目有更新的对话列表
23827 */
23828 _this2.emit(UNREAD_MESSAGES_COUNT_UPDATE$1, conversations);
23829 }
23830 });
23831 };
23832 _proto._dispatchRcpMessage = /*#__PURE__*/function () {
23833 var _dispatchRcpMessage2 = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee3(message) {
23834 var rcpMessage, read, conversationId, messageId, timestamp, conversation;
23835 return regenerator.wrap(function _callee3$(_context3) {
23836 while (1) switch (_context3.prev = _context3.next) {
23837 case 0:
23838 rcpMessage = message.rcpMessage, read = message.rcpMessage.read;
23839 conversationId = rcpMessage.cid;
23840 messageId = rcpMessage.id;
23841 timestamp = decodeDate(rcpMessage.t);
23842 conversation = this._conversationCache.get(conversationId); // conversation not cached means the client does not send the message
23843 // during this session
23844 if (conversation) {
23845 _context3.next = 7;
23846 break;
23847 }
23848 return _context3.abrupt("return");
23849 case 7:
23850 conversation._handleReceipt({
23851 messageId: messageId,
23852 timestamp: timestamp,
23853 read: read
23854 });
23855 case 8:
23856 case "end":
23857 return _context3.stop();
23858 }
23859 }, _callee3, this);
23860 }));
23861 function _dispatchRcpMessage(_x3) {
23862 return _dispatchRcpMessage2.apply(this, arguments);
23863 }
23864 return _dispatchRcpMessage;
23865 }();
23866 _proto._dispatchPatchMessage = function _dispatchPatchMessage(_ref3) {
23867 var _this3 = this;
23868 var patches = _ref3.patchMessage.patches;
23869 // ensure all converstions are cached
23870 return this.getConversations(patches.map(function (patch) {
23871 return patch.cid;
23872 })).then(function () {
23873 return Promise.all(patches.map(function (_ref4) {
23874 var cid = _ref4.cid,
23875 mid = _ref4.mid,
23876 timestamp = _ref4.timestamp,
23877 recall = _ref4.recall,
23878 data = _ref4.data,
23879 patchTimestamp = _ref4.patchTimestamp,
23880 from = _ref4.from,
23881 binaryMsg = _ref4.binaryMsg,
23882 mentionAll = _ref4.mentionAll,
23883 mentionPids = _ref4.mentionPids,
23884 patchCode = _ref4.patchCode,
23885 patchReason = _ref4.patchReason;
23886 var conversation = _this3._conversationCache.get(cid);
23887 // deleted conversation
23888 if (!conversation) return null;
23889 return _this3._messageParser.parse(binaryMsg || data).then(function (message) {
23890 var patchTime = getTime(decodeDate(patchTimestamp));
23891 var messageProps = {
23892 id: mid,
23893 cid: cid,
23894 timestamp: timestamp,
23895 updatedAt: patchTime,
23896 from: from,
23897 mentionList: mentionPids,
23898 mentionedAll: mentionAll
23899 };
23900 Object.assign(message, messageProps);
23901 message._setStatus(MessageStatus.SENT);
23902 message._updateMentioned(_this3.id);
23903 if (internal(_this3).lastPatchTime < patchTime) {
23904 internal(_this3).lastPatchTime = patchTime;
23905 }
23906 // update conversation lastMessage
23907 if (conversation.lastMessage && conversation.lastMessage.id === mid) {
23908 conversation.lastMessage = message; // eslint-disable-line no-param-reassign
23909 }
23910
23911 var reason;
23912 if (patchCode) {
23913 reason = {
23914 code: patchCode.toNumber(),
23915 detail: patchReason
23916 };
23917 }
23918 if (recall) {
23919 /**
23920 * 消息被撤回
23921 * @event IMClient#MESSAGE_RECALL
23922 * @param {AVMessage} message 被撤回的消息
23923 * @param {ConversationBase} conversation 消息所在的会话
23924 * @param {PatchReason} [reason] 撤回的原因,不存在代表是发送者主动撤回
23925 */
23926 _this3.emit(MESSAGE_RECALL$1, message, conversation, reason);
23927 /**
23928 * 消息被撤回
23929 * @event ConversationBase#MESSAGE_RECALL
23930 * @param {AVMessage} message 被撤回的消息
23931 * @param {PatchReason} [reason] 撤回的原因,不存在代表是发送者主动撤回
23932 */
23933 conversation.emit(MESSAGE_RECALL$1, message, reason);
23934 } else {
23935 /**
23936 * 消息被修改
23937 * @event IMClient#MESSAGE_UPDATE
23938 * @param {AVMessage} message 被修改的消息
23939 * @param {ConversationBase} conversation 消息所在的会话
23940 * @param {PatchReason} [reason] 修改的原因,不存在代表是发送者主动修改
23941 */
23942 _this3.emit(MESSAGE_UPDATE$1, message, conversation, reason);
23943 /**
23944 * 消息被修改
23945 * @event ConversationBase#MESSAGE_UPDATE
23946 * @param {AVMessage} message 被修改的消息
23947 * @param {PatchReason} [reason] 修改的原因,不存在代表是发送者主动修改
23948 */
23949 conversation.emit(MESSAGE_UPDATE$1, message, reason);
23950 }
23951 });
23952 }));
23953 });
23954 };
23955 _proto._dispatchConvMessage = /*#__PURE__*/function () {
23956 var _dispatchConvMessage2 = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee4(message) {
23957 var convMessage, _message$convMessage, initBy, m, info, attr, conversation, payload, _payload, _payload2, _payload3, _payload4, _payload5, _payload6, _payload7, _payload8, _payload9, _payload10, _payload11, pid, role, _internal, memberInfoMap, memberInfo, _payload12, attributes, _payload13;
23958 return regenerator.wrap(function _callee4$(_context4) {
23959 while (1) switch (_context4.prev = _context4.next) {
23960 case 0:
23961 convMessage = message.convMessage, _message$convMessage = message.convMessage, initBy = _message$convMessage.initBy, m = _message$convMessage.m, info = _message$convMessage.info, attr = _message$convMessage.attr;
23962 _context4.next = 3;
23963 return this.getConversation(convMessage.cid);
23964 case 3:
23965 conversation = _context4.sent;
23966 _context4.t0 = message.op;
23967 _context4.next = _context4.t0 === OpType.joined ? 7 : _context4.t0 === OpType.left ? 12 : _context4.t0 === OpType.members_joined ? 17 : _context4.t0 === OpType.members_left ? 22 : _context4.t0 === OpType.members_blocked ? 27 : _context4.t0 === OpType.members_unblocked ? 31 : _context4.t0 === OpType.blocked ? 35 : _context4.t0 === OpType.unblocked ? 39 : _context4.t0 === OpType.members_shutuped ? 43 : _context4.t0 === OpType.members_unshutuped ? 47 : _context4.t0 === OpType.shutuped ? 51 : _context4.t0 === OpType.unshutuped ? 55 : _context4.t0 === OpType.member_info_changed ? 59 : _context4.t0 === OpType.updated ? 71 : 77;
23968 break;
23969 case 7:
23970 conversation._addMembers([this.id]);
23971 payload = {
23972 invitedBy: initBy
23973 };
23974 /**
23975 * 当前用户被添加至某个对话
23976 * @event IMClient#INVITED
23977 * @param {Object} payload
23978 * @param {String} payload.invitedBy 邀请者 id
23979 * @param {ConversationBase} conversation
23980 */
23981 this.emit(INVITED$1, payload, conversation);
23982 /**
23983 * 当前用户被添加至当前对话
23984 * @event ConversationBase#INVITED
23985 * @param {Object} payload
23986 * @param {String} payload.invitedBy 该移除操作的发起者 id
23987 */
23988 conversation.emit(INVITED$1, payload);
23989 return _context4.abrupt("return");
23990 case 12:
23991 conversation._removeMembers([this.id]);
23992 _payload = {
23993 kickedBy: initBy
23994 };
23995 /**
23996 * 当前用户被从某个对话中移除
23997 * @event IMClient#KICKED
23998 * @param {Object} payload
23999 * @param {String} payload.kickedBy 该移除操作的发起者 id
24000 * @param {ConversationBase} conversation
24001 */
24002 this.emit(KICKED$1, _payload, conversation);
24003 /**
24004 * 当前用户被从当前对话中移除
24005 * @event ConversationBase#KICKED
24006 * @param {Object} payload
24007 * @param {String} payload.kickedBy 该移除操作的发起者 id
24008 */
24009 conversation.emit(KICKED$1, _payload);
24010 return _context4.abrupt("return");
24011 case 17:
24012 conversation._addMembers(m);
24013 _payload2 = {
24014 invitedBy: initBy,
24015 members: m
24016 };
24017 /**
24018 * 有用户被添加至某个对话
24019 * @event IMClient#MEMBERS_JOINED
24020 * @param {Object} payload
24021 * @param {String[]} payload.members 被添加的用户 id 列表
24022 * @param {String} payload.invitedBy 邀请者 id
24023 * @param {ConversationBase} conversation
24024 */
24025 this.emit(MEMBERS_JOINED$1, _payload2, conversation);
24026 /**
24027 * 有成员被添加至当前对话
24028 * @event ConversationBase#MEMBERS_JOINED
24029 * @param {Object} payload
24030 * @param {String[]} payload.members 被添加的成员 id 列表
24031 * @param {String} payload.invitedBy 邀请者 id
24032 */
24033 conversation.emit(MEMBERS_JOINED$1, _payload2);
24034 return _context4.abrupt("return");
24035 case 22:
24036 conversation._removeMembers(m);
24037 _payload3 = {
24038 kickedBy: initBy,
24039 members: m
24040 };
24041 /**
24042 * 有成员被从某个对话中移除
24043 * @event IMClient#MEMBERS_LEFT
24044 * @param {Object} payload
24045 * @param {String[]} payload.members 被移除的成员 id 列表
24046 * @param {String} payload.kickedBy 该移除操作的发起者 id
24047 * @param {ConversationBase} conversation
24048 */
24049 this.emit(MEMBERS_LEFT$1, _payload3, conversation);
24050 /**
24051 * 有成员被从当前对话中移除
24052 * @event ConversationBase#MEMBERS_LEFT
24053 * @param {Object} payload
24054 * @param {String[]} payload.members 被移除的成员 id 列表
24055 * @param {String} payload.kickedBy 该移除操作的发起者 id
24056 */
24057 conversation.emit(MEMBERS_LEFT$1, _payload3);
24058 return _context4.abrupt("return");
24059 case 27:
24060 _payload4 = {
24061 blockedBy: initBy,
24062 members: m
24063 };
24064 /**
24065 * 有成员被加入某个对话的黑名单
24066 * @event IMClient#MEMBERS_BLOCKED
24067 * @param {Object} payload
24068 * @param {String[]} payload.members 成员 id 列表
24069 * @param {String} payload.blockedBy 该操作的发起者 id
24070 * @param {ConversationBase} conversation
24071 */
24072 this.emit(MEMBERS_BLOCKED$1, _payload4, conversation);
24073 /**
24074 * 有成员被加入当前对话的黑名单
24075 * @event ConversationBase#MEMBERS_BLOCKED
24076 * @param {Object} payload
24077 * @param {String[]} payload.members 成员 id 列表
24078 * @param {String} payload.blockedBy 该操作的发起者 id
24079 */
24080 conversation.emit(MEMBERS_BLOCKED$1, _payload4);
24081 return _context4.abrupt("return");
24082 case 31:
24083 _payload5 = {
24084 unblockedBy: initBy,
24085 members: m
24086 };
24087 /**
24088 * 有成员被移出某个对话的黑名单
24089 * @event IMClient#MEMBERS_UNBLOCKED
24090 * @param {Object} payload
24091 * @param {String[]} payload.members 成员 id 列表
24092 * @param {String} payload.unblockedBy 该操作的发起者 id
24093 * @param {ConversationBase} conversation
24094 */
24095 this.emit(MEMBERS_UNBLOCKED$1, _payload5, conversation);
24096 /**
24097 * 有成员被移出当前对话的黑名单
24098 * @event ConversationBase#MEMBERS_UNBLOCKED
24099 * @param {Object} payload
24100 * @param {String[]} payload.members 成员 id 列表
24101 * @param {String} payload.unblockedBy 该操作的发起者 id
24102 */
24103 conversation.emit(MEMBERS_UNBLOCKED$1, _payload5);
24104 return _context4.abrupt("return");
24105 case 35:
24106 _payload6 = {
24107 blockedBy: initBy
24108 };
24109 /**
24110 * 当前用户被加入某个对话的黑名单
24111 * @event IMClient#BLOCKED
24112 * @param {Object} payload
24113 * @param {String} payload.blockedBy 该操作的发起者 id
24114 * @param {ConversationBase} conversation
24115 */
24116 this.emit(BLOCKED$1, _payload6, conversation);
24117 /**
24118 * 当前用户被加入当前对话的黑名单
24119 * @event ConversationBase#BLOCKED
24120 * @param {Object} payload
24121 * @param {String} payload.blockedBy 该操作的发起者 id
24122 */
24123 conversation.emit(BLOCKED$1, _payload6);
24124 return _context4.abrupt("return");
24125 case 39:
24126 _payload7 = {
24127 unblockedBy: initBy
24128 };
24129 /**
24130 * 当前用户被移出某个对话的黑名单
24131 * @event IMClient#UNBLOCKED
24132 * @param {Object} payload
24133 * @param {String} payload.unblockedBy 该操作的发起者 id
24134 * @param {ConversationBase} conversation
24135 */
24136 this.emit(UNBLOCKED$1, _payload7, conversation);
24137 /**
24138 * 当前用户被移出当前对话的黑名单
24139 * @event ConversationBase#UNBLOCKED
24140 * @param {Object} payload
24141 * @param {String} payload.unblockedBy 该操作的发起者 id
24142 */
24143 conversation.emit(UNBLOCKED$1, _payload7);
24144 return _context4.abrupt("return");
24145 case 43:
24146 _payload8 = {
24147 mutedBy: initBy,
24148 members: m
24149 };
24150 /**
24151 * 有成员在某个对话中被禁言
24152 * @event IMClient#MEMBERS_MUTED
24153 * @param {Object} payload
24154 * @param {String[]} payload.members 成员 id 列表
24155 * @param {String} payload.mutedBy 该操作的发起者 id
24156 * @param {ConversationBase} conversation
24157 */
24158 this.emit(MEMBERS_MUTED$1, _payload8, conversation);
24159 /**
24160 * 有成员在当前对话中被禁言
24161 * @event ConversationBase#MEMBERS_MUTED
24162 * @param {Object} payload
24163 * @param {String[]} payload.members 成员 id 列表
24164 * @param {String} payload.mutedBy 该操作的发起者 id
24165 */
24166 conversation.emit(MEMBERS_MUTED$1, _payload8);
24167 return _context4.abrupt("return");
24168 case 47:
24169 _payload9 = {
24170 unmutedBy: initBy,
24171 members: m
24172 };
24173 /**
24174 * 有成员在某个对话中被解除禁言
24175 * @event IMClient#MEMBERS_UNMUTED
24176 * @param {Object} payload
24177 * @param {String[]} payload.members 成员 id 列表
24178 * @param {String} payload.unmutedBy 该操作的发起者 id
24179 * @param {ConversationBase} conversation
24180 */
24181 this.emit(MEMBERS_UNMUTED$1, _payload9, conversation);
24182 /**
24183 * 有成员在当前对话中被解除禁言
24184 * @event ConversationBase#MEMBERS_UNMUTED
24185 * @param {Object} payload
24186 * @param {String[]} payload.members 成员 id 列表
24187 * @param {String} payload.unmutedBy 该操作的发起者 id
24188 */
24189 conversation.emit(MEMBERS_UNMUTED$1, _payload9);
24190 return _context4.abrupt("return");
24191 case 51:
24192 _payload10 = {
24193 mutedBy: initBy
24194 };
24195 /**
24196 * 有成员在某个对话中被禁言
24197 * @event IMClient#MUTED
24198 * @param {Object} payload
24199 * @param {String} payload.mutedBy 该操作的发起者 id
24200 * @param {ConversationBase} conversation
24201 */
24202 this.emit(MUTED$1, _payload10, conversation);
24203 /**
24204 * 有成员在当前对话中被禁言
24205 * @event ConversationBase#MUTED
24206 * @param {Object} payload
24207 * @param {String} payload.mutedBy 该操作的发起者 id
24208 */
24209 conversation.emit(MUTED$1, _payload10);
24210 return _context4.abrupt("return");
24211 case 55:
24212 _payload11 = {
24213 unmutedBy: initBy
24214 };
24215 /**
24216 * 有成员在某个对话中被解除禁言
24217 * @event IMClient#UNMUTED
24218 * @param {Object} payload
24219 * @param {String} payload.unmutedBy 该操作的发起者 id
24220 * @param {ConversationBase} conversation
24221 */
24222 this.emit(UNMUTED$1, _payload11, conversation);
24223 /**
24224 * 有成员在当前对话中被解除禁言
24225 * @event ConversationBase#UNMUTED
24226 * @param {Object} payload
24227 * @param {String} payload.unmutedBy 该操作的发起者 id
24228 */
24229 conversation.emit(UNMUTED$1, _payload11);
24230 return _context4.abrupt("return");
24231 case 59:
24232 pid = info.pid, role = info.role;
24233 _internal = internal(conversation), memberInfoMap = _internal.memberInfoMap; // 如果不存在缓存,且不是 role 的更新,则不通知
24234 if (!(!memberInfoMap && !role)) {
24235 _context4.next = 63;
24236 break;
24237 }
24238 return _context4.abrupt("return");
24239 case 63:
24240 _context4.next = 65;
24241 return conversation.getMemberInfo(pid);
24242 case 65:
24243 memberInfo = _context4.sent;
24244 internal(memberInfo).role = role;
24245 _payload12 = {
24246 member: pid,
24247 memberInfo: memberInfo,
24248 updatedBy: initBy
24249 };
24250 /**
24251 * 有成员的对话信息被更新
24252 * @event IMClient#MEMBER_INFO_UPDATED
24253 * @param {Object} payload
24254 * @param {String} payload.member 被更新对话信息的成员 id
24255 * @param {ConversationMumberInfo} payload.memberInfo 被更新的成员对话信息
24256 * @param {String} payload.updatedBy 该操作的发起者 id
24257 * @param {ConversationBase} conversation
24258 */
24259 this.emit(MEMBER_INFO_UPDATED$1, _payload12, conversation);
24260 /**
24261 * 有成员的对话信息被更新
24262 * @event ConversationBase#MEMBER_INFO_UPDATED
24263 * @param {Object} payload
24264 * @param {String} payload.member 被更新对话信息的成员 id
24265 * @param {ConversationMumberInfo} payload.memberInfo 被更新的成员对话信息
24266 * @param {String} payload.updatedBy 该操作的发起者 id
24267 */
24268 conversation.emit(MEMBER_INFO_UPDATED$1, _payload12);
24269 return _context4.abrupt("return");
24270 case 71:
24271 attributes = decode(JSON.parse(attr.data));
24272 conversation._updateServerAttributes(attributes);
24273 _payload13 = {
24274 attributes: attributes,
24275 updatedBy: initBy
24276 };
24277 /**
24278 * 该对话信息被更新
24279 * @event IMClient#CONVERSATION_INFO_UPDATED
24280 * @param {Object} payload
24281 * @param {Object} payload.attributes 被更新的属性
24282 * @param {String} payload.updatedBy 该操作的发起者 id
24283 * @param {ConversationBase} conversation
24284 */
24285 this.emit(CONVERSATION_INFO_UPDATED$1, _payload13, conversation);
24286 /**
24287 * 有对话信息被更新
24288 * @event ConversationBase#INFO_UPDATED
24289 * @param {Object} payload
24290 * @param {Object} payload.attributes 被更新的属性
24291 * @param {String} payload.updatedBy 该操作的发起者 id
24292 */
24293 conversation.emit(INFO_UPDATED$1, _payload13);
24294 return _context4.abrupt("return");
24295 case 77:
24296 this.emit(UNHANDLED_MESSAGE$1, message);
24297 throw new Error('Unrecognized conversation command');
24298 case 79:
24299 case "end":
24300 return _context4.stop();
24301 }
24302 }, _callee4, this);
24303 }));
24304 function _dispatchConvMessage(_x4) {
24305 return _dispatchConvMessage2.apply(this, arguments);
24306 }
24307 return _dispatchConvMessage;
24308 }();
24309 _proto._dispatchDirectMessage = function _dispatchDirectMessage(originalMessage) {
24310 var _this4 = this;
24311 var directMessage = originalMessage.directMessage,
24312 _originalMessage$dire = originalMessage.directMessage,
24313 id = _originalMessage$dire.id,
24314 cid = _originalMessage$dire.cid,
24315 fromPeerId = _originalMessage$dire.fromPeerId,
24316 timestamp = _originalMessage$dire.timestamp,
24317 _transient = _originalMessage$dire["transient"],
24318 patchTimestamp = _originalMessage$dire.patchTimestamp,
24319 mentionPids = _originalMessage$dire.mentionPids,
24320 mentionAll = _originalMessage$dire.mentionAll,
24321 binaryMsg = _originalMessage$dire.binaryMsg,
24322 msg = _originalMessage$dire.msg;
24323 var content = binaryMsg ? binaryMsg.toArrayBuffer() : msg;
24324 return Promise.all([this.getConversation(directMessage.cid), this._messageParser.parse(content)]).then(function (_ref5) {
24325 var _ref6 = _slicedToArray(_ref5, 2),
24326 conversation = _ref6[0],
24327 message = _ref6[1];
24328 // deleted conversation
24329 if (!conversation) return undefined;
24330 var messageProps = {
24331 id: id,
24332 cid: cid,
24333 timestamp: timestamp,
24334 updatedAt: patchTimestamp,
24335 from: fromPeerId,
24336 mentionList: mentionPids,
24337 mentionedAll: mentionAll
24338 };
24339 Object.assign(message, messageProps);
24340 message._updateMentioned(_this4.id);
24341 message._setStatus(MessageStatus.SENT);
24342 // filter outgoing message sent from another device
24343 if (message.from !== _this4.id) {
24344 if (!(_transient || conversation["transient"])) {
24345 _this4._sendAck(message);
24346 }
24347 }
24348 return _this4._dispatchParsedMessage(message, conversation);
24349 });
24350 };
24351 _proto._dispatchParsedMessage = function _dispatchParsedMessage(message, conversation) {
24352 var _this5 = this;
24353 // beforeMessageDispatch hook
24354 return applyDispatcher(this._plugins.beforeMessageDispatch, [message, conversation]).then(function (shouldDispatch) {
24355 if (shouldDispatch === false) return;
24356 conversation.lastMessage = message; // eslint-disable-line no-param-reassign
24357 conversation.lastMessageAt = message.timestamp; // eslint-disable-line no-param-reassign
24358 // filter outgoing message sent from another device
24359 if (message.from !== _this5.id) {
24360 conversation.unreadMessagesCount += 1; // eslint-disable-line no-param-reassign
24361 if (message.mentioned) conversation._setUnreadMessagesMentioned(true);
24362 }
24363 /**
24364 * 当前用户收到消息
24365 * @event IMClient#MESSAGE
24366 * @param {Message} message
24367 * @param {ConversationBase} conversation 收到消息的对话
24368 */
24369 _this5.emit(MESSAGE$2, message, conversation);
24370 /**
24371 * 当前对话收到消息
24372 * @event ConversationBase#MESSAGE
24373 * @param {Message} message
24374 */
24375 conversation.emit(MESSAGE$2, message);
24376 });
24377 };
24378 _proto._sendAck = function _sendAck(message) {
24379 this._debug('send ack for %O', message);
24380 var cid = message.cid;
24381 if (!cid) {
24382 throw new Error('missing cid');
24383 }
24384 if (!this._ackMessageBuffer[cid]) {
24385 this._ackMessageBuffer[cid] = [];
24386 }
24387 this._ackMessageBuffer[cid].push(message);
24388 return this._doSendAck();
24389 }
24390
24391 // jsdoc-ignore-start
24392 ;
24393 _proto.
24394 // jsdoc-ignore-end
24395 _doSendAck = function _doSendAck() {
24396 var _this6 = this;
24397 // if not connected, just skip everything
24398 if (!this._connection.is('connected')) return;
24399 this._debug('do send ack %O', this._ackMessageBuffer);
24400 Promise.all(Object.keys(this._ackMessageBuffer).map(function (cid) {
24401 var convAckMessages = _this6._ackMessageBuffer[cid];
24402 var timestamps = convAckMessages.map(function (message) {
24403 return message.timestamp;
24404 });
24405 var command = new GenericCommand({
24406 cmd: 'ack',
24407 ackMessage: new AckCommand({
24408 cid: cid,
24409 fromts: Math.min.apply(null, timestamps),
24410 tots: Math.max.apply(null, timestamps)
24411 })
24412 });
24413 delete _this6._ackMessageBuffer[cid];
24414 return _this6._send(command, false)["catch"](function (error) {
24415 _this6._debug('send ack failed: %O', error);
24416 _this6._ackMessageBuffer[cid] = convAckMessages;
24417 });
24418 }));
24419 };
24420 _proto._omitPeerId = function _omitPeerId(value) {
24421 internal(this).peerIdOmittable = value;
24422 };
24423 _proto._send = function _send(cmd) {
24424 var _this$_connection;
24425 var command = cmd;
24426 if (!internal(this).peerIdOmittable && this.id) {
24427 command.peerId = this.id;
24428 }
24429 for (var _len3 = arguments.length, args = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {
24430 args[_key3 - 1] = arguments[_key3];
24431 }
24432 return (_this$_connection = this._connection).send.apply(_this$_connection, [command].concat(args));
24433 };
24434 _proto._open = /*#__PURE__*/function () {
24435 var _open2 = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee5(appId, tag, deviceId) {
24436 var isReconnect,
24437 _internal2,
24438 lastUnreadNotifTime,
24439 lastPatchTime,
24440 lastNotificationTime,
24441 command,
24442 signatureResult,
24443 sessionToken,
24444 resCommand,
24445 _resCommand,
24446 peerId,
24447 sessionMessage,
24448 _resCommand$sessionMe,
24449 token,
24450 tokenTTL,
24451 code,
24452 serverTs,
24453 serverTime,
24454 _args5 = arguments;
24455 return regenerator.wrap(function _callee5$(_context5) {
24456 while (1) switch (_context5.prev = _context5.next) {
24457 case 0:
24458 isReconnect = _args5.length > 3 && _args5[3] !== undefined ? _args5[3] : false;
24459 this._debug('open session');
24460 _internal2 = internal(this), lastUnreadNotifTime = _internal2.lastUnreadNotifTime, lastPatchTime = _internal2.lastPatchTime, lastNotificationTime = _internal2.lastNotificationTime;
24461 command = new GenericCommand({
24462 cmd: 'session',
24463 op: 'open',
24464 appId: appId,
24465 peerId: this.id,
24466 sessionMessage: new SessionCommand({
24467 ua: "js/".concat(version),
24468 r: isReconnect,
24469 lastUnreadNotifTime: lastUnreadNotifTime,
24470 lastPatchTime: lastPatchTime,
24471 configBitmap: configBitmap
24472 })
24473 });
24474 if (isReconnect) {
24475 _context5.next = 13;
24476 break;
24477 }
24478 Object.assign(command.sessionMessage, trim({
24479 tag: tag,
24480 deviceId: deviceId
24481 }));
24482 if (!this.options.signatureFactory) {
24483 _context5.next = 11;
24484 break;
24485 }
24486 _context5.next = 9;
24487 return runSignatureFactory(this.options.signatureFactory, [this._identity]);
24488 case 9:
24489 signatureResult = _context5.sent;
24490 Object.assign(command.sessionMessage, keyRemap({
24491 signature: 's',
24492 timestamp: 't',
24493 nonce: 'n'
24494 }, signatureResult));
24495 case 11:
24496 _context5.next = 17;
24497 break;
24498 case 13:
24499 _context5.next = 15;
24500 return this._sessionManager.getSessionToken({
24501 autoRefresh: false
24502 });
24503 case 15:
24504 sessionToken = _context5.sent;
24505 if (sessionToken && sessionToken !== Expirable.EXPIRED) {
24506 Object.assign(command.sessionMessage, {
24507 st: sessionToken
24508 });
24509 }
24510 case 17:
24511 _context5.prev = 17;
24512 _context5.next = 20;
24513 return this._send(command);
24514 case 20:
24515 resCommand = _context5.sent;
24516 _context5.next = 32;
24517 break;
24518 case 23:
24519 _context5.prev = 23;
24520 _context5.t0 = _context5["catch"](17);
24521 if (!(_context5.t0.code === ErrorCode.SESSION_TOKEN_EXPIRED)) {
24522 _context5.next = 31;
24523 break;
24524 }
24525 if (this._sessionManager) {
24526 _context5.next = 28;
24527 break;
24528 }
24529 throw new Error('Unexpected session expiration');
24530 case 28:
24531 debug$b('Session token expired, reopening');
24532 this._sessionManager.revoke();
24533 return _context5.abrupt("return", this._open(appId, tag, deviceId, isReconnect));
24534 case 31:
24535 throw _context5.t0;
24536 case 32:
24537 _resCommand = resCommand, peerId = _resCommand.peerId, sessionMessage = _resCommand.sessionMessage, _resCommand$sessionMe = _resCommand.sessionMessage, token = _resCommand$sessionMe.st, tokenTTL = _resCommand$sessionMe.stTtl, code = _resCommand$sessionMe.code, serverTs = _resCommand.serverTs;
24538 if (!code) {
24539 _context5.next = 35;
24540 break;
24541 }
24542 throw createError(sessionMessage);
24543 case 35:
24544 if (peerId) {
24545 this.id = peerId;
24546 if (!this._identity) this._identity = peerId;
24547 if (token) {
24548 this._sessionManager = this._sessionManager || this._createSessionManager();
24549 this._sessionManager.setSessionToken(token, tokenTTL);
24550 }
24551 serverTime = getTime(decodeDate(serverTs));
24552 if (serverTs) {
24553 internal(this).lastPatchTime = serverTime;
24554 }
24555 if (lastNotificationTime) {
24556 // Do not await for it as this is failable
24557 this._syncNotifications(lastNotificationTime)["catch"](function (error) {
24558 return console.warn('Syncing notifications failed:', error);
24559 });
24560 } else {
24561 // Set timestamp to now for next reconnection
24562 internal(this).lastNotificationTime = serverTime;
24563 }
24564 } else {
24565 console.warn('Unexpected session opened without peerId.');
24566 }
24567 return _context5.abrupt("return", undefined);
24568 case 37:
24569 case "end":
24570 return _context5.stop();
24571 }
24572 }, _callee5, this, [[17, 23]]);
24573 }));
24574 function _open(_x5, _x6, _x7) {
24575 return _open2.apply(this, arguments);
24576 }
24577 return _open;
24578 }();
24579 _proto._syncNotifications = /*#__PURE__*/function () {
24580 var _syncNotifications2 = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee6(timestamp) {
24581 var _this7 = this;
24582 var _yield$this$_fetchNot, hasMore, notifications;
24583 return regenerator.wrap(function _callee6$(_context6) {
24584 while (1) switch (_context6.prev = _context6.next) {
24585 case 0:
24586 _context6.next = 2;
24587 return this._fetchNotifications(timestamp);
24588 case 2:
24589 _yield$this$_fetchNot = _context6.sent;
24590 hasMore = _yield$this$_fetchNot.hasMore;
24591 notifications = _yield$this$_fetchNot.notifications;
24592 notifications.forEach(function (notification) {
24593 var cmd = notification.cmd,
24594 op = notification.op,
24595 serverTs = notification.serverTs,
24596 notificationType = notification.notificationType,
24597 payload = _objectWithoutProperties(notification, _excluded$3);
24598 _this7._dispatchCommand(_defineProperty({
24599 cmd: CommandType[cmd],
24600 op: OpType[op],
24601 serverTs: serverTs,
24602 notificationType: notificationType
24603 }, "".concat(cmd, "Message"), payload));
24604 });
24605 if (!hasMore) {
24606 _context6.next = 8;
24607 break;
24608 }
24609 return _context6.abrupt("return", this._syncNotifications(internal(this).lastNotificationTime));
24610 case 8:
24611 return _context6.abrupt("return", undefined);
24612 case 9:
24613 case "end":
24614 return _context6.stop();
24615 }
24616 }, _callee6, this);
24617 }));
24618 function _syncNotifications(_x8) {
24619 return _syncNotifications2.apply(this, arguments);
24620 }
24621 return _syncNotifications;
24622 }();
24623 _proto._fetchNotifications = /*#__PURE__*/function () {
24624 var _fetchNotifications2 = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee7(timestamp) {
24625 return regenerator.wrap(function _callee7$(_context7) {
24626 while (1) switch (_context7.prev = _context7.next) {
24627 case 0:
24628 return _context7.abrupt("return", this._requestWithSessionToken({
24629 method: 'GET',
24630 path: '/rtm/notifications',
24631 query: {
24632 start_ts: timestamp,
24633 notification_type: 'permanent'
24634 }
24635 }));
24636 case 1:
24637 case "end":
24638 return _context7.stop();
24639 }
24640 }, _callee7, this);
24641 }));
24642 function _fetchNotifications(_x9) {
24643 return _fetchNotifications2.apply(this, arguments);
24644 }
24645 return _fetchNotifications;
24646 }();
24647 _proto._createSessionManager = function _createSessionManager() {
24648 var _this8 = this;
24649 debug$b('create SessionManager');
24650 return new SessionManager({
24651 onBeforeGetSessionToken: this._connection.checkConnectionAvailability.bind(this._connection),
24652 refresh: function refresh(manager, expiredSessionToken) {
24653 return manager.setSessionTokenAsync(Promise.resolve(new GenericCommand({
24654 cmd: 'session',
24655 op: 'refresh',
24656 sessionMessage: new SessionCommand({
24657 ua: "js/".concat(version),
24658 st: expiredSessionToken
24659 })
24660 })).then( /*#__PURE__*/function () {
24661 var _ref7 = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee8(command) {
24662 var signatureResult;
24663 return regenerator.wrap(function _callee8$(_context8) {
24664 while (1) switch (_context8.prev = _context8.next) {
24665 case 0:
24666 if (!_this8.options.signatureFactory) {
24667 _context8.next = 5;
24668 break;
24669 }
24670 _context8.next = 3;
24671 return runSignatureFactory(_this8.options.signatureFactory, [_this8._identity]);
24672 case 3:
24673 signatureResult = _context8.sent;
24674 Object.assign(command.sessionMessage, keyRemap({
24675 signature: 's',
24676 timestamp: 't',
24677 nonce: 'n'
24678 }, signatureResult));
24679 case 5:
24680 return _context8.abrupt("return", command);
24681 case 6:
24682 case "end":
24683 return _context8.stop();
24684 }
24685 }, _callee8);
24686 }));
24687 return function (_x10) {
24688 return _ref7.apply(this, arguments);
24689 };
24690 }()).then(_this8._send.bind(_this8)).then(function (_ref8) {
24691 var _ref8$sessionMessage = _ref8.sessionMessage,
24692 token = _ref8$sessionMessage.st,
24693 ttl = _ref8$sessionMessage.stTtl;
24694 return [token, ttl];
24695 }));
24696 }
24697 });
24698 };
24699 _proto._requestWithSessionToken = /*#__PURE__*/function () {
24700 var _requestWithSessionToken2 = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee9(_ref9) {
24701 var headers, query, params, sessionToken;
24702 return regenerator.wrap(function _callee9$(_context9) {
24703 while (1) switch (_context9.prev = _context9.next) {
24704 case 0:
24705 headers = _ref9.headers, query = _ref9.query, params = _objectWithoutProperties(_ref9, _excluded2$1);
24706 _context9.next = 3;
24707 return this._sessionManager.getSessionToken();
24708 case 3:
24709 sessionToken = _context9.sent;
24710 return _context9.abrupt("return", this._request(_objectSpread$8({
24711 headers: _objectSpread$8({
24712 'X-LC-IM-Session-Token': sessionToken
24713 }, headers),
24714 query: _objectSpread$8({
24715 client_id: this.id
24716 }, query)
24717 }, params)));
24718 case 5:
24719 case "end":
24720 return _context9.stop();
24721 }
24722 }, _callee9, this);
24723 }));
24724 function _requestWithSessionToken(_x11) {
24725 return _requestWithSessionToken2.apply(this, arguments);
24726 }
24727 return _requestWithSessionToken;
24728 }()
24729 /**
24730 * 关闭客户端
24731 * @return {Promise}
24732 */
24733 ;
24734 _proto.close =
24735 /*#__PURE__*/
24736 function () {
24737 var _close = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee10() {
24738 var _ee, command;
24739 return regenerator.wrap(function _callee10$(_context10) {
24740 while (1) switch (_context10.prev = _context10.next) {
24741 case 0:
24742 this._debug('close session');
24743 _ee = internal(this)._eventemitter;
24744 _ee.emit('beforeclose');
24745 if (!this._connection.is('connected')) {
24746 _context10.next = 7;
24747 break;
24748 }
24749 command = new GenericCommand({
24750 cmd: 'session',
24751 op: 'close'
24752 });
24753 _context10.next = 7;
24754 return this._send(command);
24755 case 7:
24756 _ee.emit('close');
24757 this.emit(CLOSE$1, {
24758 code: 0
24759 });
24760 case 9:
24761 case "end":
24762 return _context10.stop();
24763 }
24764 }, _callee10, this);
24765 }));
24766 function close() {
24767 return _close.apply(this, arguments);
24768 }
24769 return close;
24770 }()
24771 /**
24772 * 获取 client 列表中在线的 client,每次查询最多 20 个 clientId,超出部分会被忽略
24773 * @param {String[]} clientIds 要查询的 client ids
24774 * @return {Primse.<String[]>} 在线的 client ids
24775 */
24776 ;
24777 _proto.ping =
24778 /*#__PURE__*/
24779 function () {
24780 var _ping = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee11(clientIds) {
24781 var command, resCommand;
24782 return regenerator.wrap(function _callee11$(_context11) {
24783 while (1) switch (_context11.prev = _context11.next) {
24784 case 0:
24785 this._debug('ping');
24786 if (clientIds instanceof Array) {
24787 _context11.next = 3;
24788 break;
24789 }
24790 throw new TypeError("clientIds ".concat(clientIds, " is not an Array"));
24791 case 3:
24792 if (clientIds.length) {
24793 _context11.next = 5;
24794 break;
24795 }
24796 return _context11.abrupt("return", Promise.resolve([]));
24797 case 5:
24798 command = new GenericCommand({
24799 cmd: 'session',
24800 op: 'query',
24801 sessionMessage: new SessionCommand({
24802 sessionPeerIds: clientIds
24803 })
24804 });
24805 _context11.next = 8;
24806 return this._send(command);
24807 case 8:
24808 resCommand = _context11.sent;
24809 return _context11.abrupt("return", resCommand.sessionMessage.onlineSessionPeerIds);
24810 case 10:
24811 case "end":
24812 return _context11.stop();
24813 }
24814 }, _callee11, this);
24815 }));
24816 function ping(_x12) {
24817 return _ping.apply(this, arguments);
24818 }
24819 return ping;
24820 }()
24821 /**
24822 * 获取某个特定的对话
24823 * @param {String} id 对话 id,对应 _Conversation 表中的 objectId
24824 * @param {Boolean} [noCache=false] 强制不从缓存中获取
24825 * @return {Promise.<ConversationBase>} 如果 id 对应的对话不存在则返回 null
24826 */
24827 ;
24828 _proto.getConversation =
24829 /*#__PURE__*/
24830 function () {
24831 var _getConversation = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee12(id) {
24832 var noCache,
24833 cachedConversation,
24834 _args12 = arguments;
24835 return regenerator.wrap(function _callee12$(_context12) {
24836 while (1) switch (_context12.prev = _context12.next) {
24837 case 0:
24838 noCache = _args12.length > 1 && _args12[1] !== undefined ? _args12[1] : false;
24839 if (!(typeof id !== 'string')) {
24840 _context12.next = 3;
24841 break;
24842 }
24843 throw new TypeError("".concat(id, " is not a String"));
24844 case 3:
24845 if (noCache) {
24846 _context12.next = 7;
24847 break;
24848 }
24849 cachedConversation = this._conversationCache.get(id);
24850 if (!cachedConversation) {
24851 _context12.next = 7;
24852 break;
24853 }
24854 return _context12.abrupt("return", cachedConversation);
24855 case 7:
24856 if (!isTemporaryConversatrionId(id)) {
24857 _context12.next = 14;
24858 break;
24859 }
24860 _context12.next = 10;
24861 return this._getTemporaryConversations([id]);
24862 case 10:
24863 _context12.t0 = _context12.sent[0];
24864 if (_context12.t0) {
24865 _context12.next = 13;
24866 break;
24867 }
24868 _context12.t0 = null;
24869 case 13:
24870 return _context12.abrupt("return", _context12.t0);
24871 case 14:
24872 return _context12.abrupt("return", this.getQuery().equalTo('objectId', id).find().then(function (conversations) {
24873 return conversations[0] || null;
24874 }));
24875 case 15:
24876 case "end":
24877 return _context12.stop();
24878 }
24879 }, _callee12, this);
24880 }));
24881 function getConversation(_x13) {
24882 return _getConversation.apply(this, arguments);
24883 }
24884 return getConversation;
24885 }()
24886 /**
24887 * 通过 id 批量获取某个特定的对话
24888 * @since 3.4.0
24889 * @param {String[]} ids 对话 id 列表,对应 _Conversation 表中的 objectId
24890 * @param {Boolean} [noCache=false] 强制不从缓存中获取
24891 * @return {Promise.<ConversationBase[]>} 如果 id 对应的对话不存在则返回 null
24892 */
24893 ;
24894 _proto.getConversations =
24895 /*#__PURE__*/
24896 function () {
24897 var _getConversations = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee13(ids) {
24898 var _this9 = this;
24899 var noCache,
24900 remoteConversationIds,
24901 remoteTemporaryConversationIds,
24902 query,
24903 remoteTemporaryConversationsPromise,
24904 _args13 = arguments;
24905 return regenerator.wrap(function _callee13$(_context13) {
24906 while (1) switch (_context13.prev = _context13.next) {
24907 case 0:
24908 noCache = _args13.length > 1 && _args13[1] !== undefined ? _args13[1] : false;
24909 remoteConversationIds = noCache ? ids : ids.filter(function (id) {
24910 return _this9._conversationCache.get(id) === null;
24911 });
24912 if (!remoteConversationIds.length) {
24913 _context13.next = 9;
24914 break;
24915 }
24916 remoteTemporaryConversationIds = remove_1(remoteConversationIds, isTemporaryConversatrionId);
24917 query = [];
24918 if (remoteConversationIds.length) {
24919 query.push(this.getQuery().containedIn('objectId', remoteConversationIds).limit(999).find());
24920 }
24921 if (remoteTemporaryConversationIds.length) {
24922 remoteTemporaryConversationsPromise = remoteTemporaryConversationIds.map(this._getTemporaryConversations.bind(this));
24923 query.push.apply(query, _toConsumableArray(remoteTemporaryConversationsPromise));
24924 }
24925 _context13.next = 9;
24926 return Promise.all(query);
24927 case 9:
24928 return _context13.abrupt("return", ids.map(function (id) {
24929 return _this9._conversationCache.get(id);
24930 }));
24931 case 10:
24932 case "end":
24933 return _context13.stop();
24934 }
24935 }, _callee13, this);
24936 }));
24937 function getConversations(_x14) {
24938 return _getConversations.apply(this, arguments);
24939 }
24940 return getConversations;
24941 }();
24942 _proto._getTemporaryConversations = /*#__PURE__*/function () {
24943 var _getTemporaryConversations2 = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee14(ids) {
24944 var command, resCommand;
24945 return regenerator.wrap(function _callee14$(_context14) {
24946 while (1) switch (_context14.prev = _context14.next) {
24947 case 0:
24948 command = new GenericCommand({
24949 cmd: 'conv',
24950 op: 'query',
24951 convMessage: new ConvCommand({
24952 tempConvIds: ids
24953 })
24954 });
24955 _context14.next = 3;
24956 return this._send(command);
24957 case 3:
24958 resCommand = _context14.sent;
24959 return _context14.abrupt("return", this._handleQueryResults(resCommand));
24960 case 5:
24961 case "end":
24962 return _context14.stop();
24963 }
24964 }, _callee14, this);
24965 }));
24966 function _getTemporaryConversations(_x15) {
24967 return _getTemporaryConversations2.apply(this, arguments);
24968 }
24969 return _getTemporaryConversations;
24970 }()
24971 /**
24972 * 构造一个 ConversationQuery 来查询对话
24973 * @return {ConversationQuery.<PersistentConversation>}
24974 */
24975 ;
24976 _proto.getQuery = function getQuery() {
24977 return new ConversationQuery(this);
24978 }
24979
24980 /**
24981 * 构造一个 ConversationQuery 来查询聊天室
24982 * @return {ConversationQuery.<ChatRoom>}
24983 */;
24984 _proto.getChatRoomQuery = function getChatRoomQuery() {
24985 return this.getQuery().equalTo('tr', true);
24986 }
24987
24988 /**
24989 * 构造一个 ConversationQuery 来查询服务号
24990 * @return {ConversationQuery.<ServiceConversation>}
24991 */;
24992 _proto.getServiceConversationQuery = function getServiceConversationQuery() {
24993 return this.getQuery().equalTo('sys', true);
24994 };
24995 _proto._executeQuery = /*#__PURE__*/function () {
24996 var _executeQuery2 = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee15(query) {
24997 var queryJSON, command, resCommand;
24998 return regenerator.wrap(function _callee15$(_context15) {
24999 while (1) switch (_context15.prev = _context15.next) {
25000 case 0:
25001 queryJSON = query.toJSON();
25002 queryJSON.where = new JsonObjectMessage({
25003 data: JSON.stringify(encode(queryJSON.where))
25004 });
25005 command = new GenericCommand({
25006 cmd: 'conv',
25007 op: 'query',
25008 convMessage: new ConvCommand(queryJSON)
25009 });
25010 _context15.next = 5;
25011 return this._send(command);
25012 case 5:
25013 resCommand = _context15.sent;
25014 return _context15.abrupt("return", this._handleQueryResults(resCommand));
25015 case 7:
25016 case "end":
25017 return _context15.stop();
25018 }
25019 }, _callee15, this);
25020 }));
25021 function _executeQuery(_x16) {
25022 return _executeQuery2.apply(this, arguments);
25023 }
25024 return _executeQuery;
25025 }();
25026 _proto._handleQueryResults = /*#__PURE__*/function () {
25027 var _handleQueryResults2 = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee16(resCommand) {
25028 var conversations, commandString;
25029 return regenerator.wrap(function _callee16$(_context16) {
25030 while (1) switch (_context16.prev = _context16.next) {
25031 case 0:
25032 _context16.prev = 0;
25033 conversations = decode(JSON.parse(resCommand.convMessage.results.data));
25034 _context16.next = 8;
25035 break;
25036 case 4:
25037 _context16.prev = 4;
25038 _context16.t0 = _context16["catch"](0);
25039 commandString = JSON.stringify(trim(resCommand));
25040 throw new Error("Parse query result failed: ".concat(_context16.t0.message, ". Command: ").concat(commandString));
25041 case 8:
25042 _context16.next = 10;
25043 return Promise.all(conversations.map(this._parseConversationFromRawData.bind(this)));
25044 case 10:
25045 conversations = _context16.sent;
25046 return _context16.abrupt("return", conversations.map(this._upsertConversationToCache.bind(this)));
25047 case 12:
25048 case "end":
25049 return _context16.stop();
25050 }
25051 }, _callee16, this, [[0, 4]]);
25052 }));
25053 function _handleQueryResults(_x17) {
25054 return _handleQueryResults2.apply(this, arguments);
25055 }
25056 return _handleQueryResults;
25057 }();
25058 _proto._upsertConversationToCache = function _upsertConversationToCache(fetchedConversation) {
25059 var conversation = this._conversationCache.get(fetchedConversation.id);
25060 if (!conversation) {
25061 conversation = fetchedConversation;
25062 this._debug('no match, set cache');
25063 this._conversationCache.set(fetchedConversation.id, fetchedConversation);
25064 } else {
25065 this._debug('update cached conversation');
25066 ['creator', 'createdAt', 'updatedAt', 'lastMessageAt', 'lastMessage', 'mutedMembers', 'members', '_attributes', 'transient', 'muted'].forEach(function (key) {
25067 var value = fetchedConversation[key];
25068 if (value !== undefined) conversation[key] = value;
25069 });
25070 if (conversation._reset) conversation._reset();
25071 }
25072 return conversation;
25073 }
25074
25075 /**
25076 * 反序列化消息,与 {@link Message#toFullJSON} 相对。
25077 * @param {Object}
25078 * @return {AVMessage} 解析后的消息
25079 * @since 4.0.0
25080 */;
25081 _proto.parseMessage =
25082 /*#__PURE__*/
25083 function () {
25084 var _parseMessage = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee17(_ref10) {
25085 var data, _ref10$bin, bin, properties, content, message;
25086 return regenerator.wrap(function _callee17$(_context17) {
25087 while (1) switch (_context17.prev = _context17.next) {
25088 case 0:
25089 data = _ref10.data, _ref10$bin = _ref10.bin, bin = _ref10$bin === void 0 ? false : _ref10$bin, properties = _objectWithoutProperties(_ref10, _excluded3);
25090 content = bin ? base64Arraybuffer_2(data) : data;
25091 _context17.next = 4;
25092 return this._messageParser.parse(content);
25093 case 4:
25094 message = _context17.sent;
25095 Object.assign(message, properties);
25096 message._updateMentioned(this.id);
25097 return _context17.abrupt("return", message);
25098 case 8:
25099 case "end":
25100 return _context17.stop();
25101 }
25102 }, _callee17, this);
25103 }));
25104 function parseMessage(_x18) {
25105 return _parseMessage.apply(this, arguments);
25106 }
25107 return parseMessage;
25108 }()
25109 /**
25110 * 反序列化对话,与 {@link Conversation#toFullJSON} 相对。
25111 * @param {Object}
25112 * @return {ConversationBase} 解析后的对话
25113 * @since 4.0.0
25114 */
25115 ;
25116 _proto.parseConversation =
25117 /*#__PURE__*/
25118 function () {
25119 var _parseConversation = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee18(_ref11) {
25120 var id, lastMessageAt, lastMessage, lastDeliveredAt, lastReadAt, unreadMessagesCount, members, mentioned, properties, conversationData, _transient2, system, expiredAt;
25121 return regenerator.wrap(function _callee18$(_context18) {
25122 while (1) switch (_context18.prev = _context18.next) {
25123 case 0:
25124 id = _ref11.id, lastMessageAt = _ref11.lastMessageAt, lastMessage = _ref11.lastMessage, lastDeliveredAt = _ref11.lastDeliveredAt, lastReadAt = _ref11.lastReadAt, unreadMessagesCount = _ref11.unreadMessagesCount, members = _ref11.members, mentioned = _ref11.mentioned, properties = _objectWithoutProperties(_ref11, _excluded4);
25125 conversationData = {
25126 id: id,
25127 lastMessageAt: lastMessageAt,
25128 lastMessage: lastMessage,
25129 lastDeliveredAt: lastDeliveredAt,
25130 lastReadAt: lastReadAt,
25131 unreadMessagesCount: unreadMessagesCount,
25132 members: members,
25133 mentioned: mentioned
25134 };
25135 if (!lastMessage) {
25136 _context18.next = 7;
25137 break;
25138 }
25139 _context18.next = 5;
25140 return this.parseMessage(lastMessage);
25141 case 5:
25142 conversationData.lastMessage = _context18.sent;
25143 conversationData.lastMessage._setStatus(MessageStatus.SENT);
25144 case 7:
25145 _transient2 = properties["transient"], system = properties.system, expiredAt = properties.expiredAt;
25146 if (!_transient2) {
25147 _context18.next = 10;
25148 break;
25149 }
25150 return _context18.abrupt("return", new ChatRoom(conversationData, properties, this));
25151 case 10:
25152 if (!system) {
25153 _context18.next = 12;
25154 break;
25155 }
25156 return _context18.abrupt("return", new ServiceConversation(conversationData, properties, this));
25157 case 12:
25158 if (!(expiredAt || isTemporaryConversatrionId(id))) {
25159 _context18.next = 14;
25160 break;
25161 }
25162 return _context18.abrupt("return", new TemporaryConversation(conversationData, {
25163 expiredAt: expiredAt
25164 }, this));
25165 case 14:
25166 return _context18.abrupt("return", new Conversation(conversationData, properties, this));
25167 case 15:
25168 case "end":
25169 return _context18.stop();
25170 }
25171 }, _callee18, this);
25172 }));
25173 function parseConversation(_x19) {
25174 return _parseConversation.apply(this, arguments);
25175 }
25176 return parseConversation;
25177 }();
25178 _proto._parseConversationFromRawData = /*#__PURE__*/function () {
25179 var _parseConversationFromRawData2 = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee19(rawData) {
25180 var data, ttl;
25181 return regenerator.wrap(function _callee19$(_context19) {
25182 while (1) switch (_context19.prev = _context19.next) {
25183 case 0:
25184 data = keyRemap({
25185 objectId: 'id',
25186 lm: 'lastMessageAt',
25187 m: 'members',
25188 tr: 'transient',
25189 sys: 'system',
25190 c: 'creator',
25191 mu: 'mutedMembers'
25192 }, rawData);
25193 if (data.msg) {
25194 data.lastMessage = {
25195 data: data.msg,
25196 bin: data.bin,
25197 from: data.msg_from,
25198 id: data.msg_mid,
25199 timestamp: data.msg_timestamp,
25200 updatedAt: data.patch_timestamp
25201 };
25202 delete data.lastMessageFrom;
25203 delete data.lastMessageId;
25204 delete data.lastMessageTimestamp;
25205 delete data.lastMessagePatchTimestamp;
25206 }
25207 ttl = data.ttl;
25208 if (ttl) data.expiredAt = Date.now() + ttl * 1000;
25209 return _context19.abrupt("return", this.parseConversation(data));
25210 case 5:
25211 case "end":
25212 return _context19.stop();
25213 }
25214 }, _callee19, this);
25215 }));
25216 function _parseConversationFromRawData(_x20) {
25217 return _parseConversationFromRawData2.apply(this, arguments);
25218 }
25219 return _parseConversationFromRawData;
25220 }()
25221 /**
25222 * 创建一个对话
25223 * @param {Object} options 除了下列字段外的其他字段将被视为对话的自定义属性
25224 * @param {String[]} options.members 对话的初始成员列表,默认包含当前 client
25225 * @param {String} [options.name] 对话的名字
25226 * @param {Boolean} [options.unique=true] 唯一对话,当其为 true 时,如果当前已经有相同成员的对话存在则返回该对话,否则会创建新的对话
25227 * @return {Promise.<Conversation>}
25228 */
25229 ;
25230 _proto.createConversation =
25231 /*#__PURE__*/
25232 function () {
25233 var _createConversation = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee20() {
25234 var _ref12,
25235 m,
25236 name,
25237 _transient3,
25238 _ref12$unique,
25239 unique,
25240 tempConv,
25241 tempConvTTL,
25242 properties,
25243 members,
25244 attr,
25245 startCommandJson,
25246 command,
25247 params,
25248 signatureResult,
25249 _yield$this$_send,
25250 _yield$this$_send$con,
25251 cid,
25252 cdate,
25253 ttl,
25254 data,
25255 conversation,
25256 _args20 = arguments;
25257 return regenerator.wrap(function _callee20$(_context20) {
25258 while (1) switch (_context20.prev = _context20.next) {
25259 case 0:
25260 _ref12 = _args20.length > 0 && _args20[0] !== undefined ? _args20[0] : {}, m = _ref12.members, name = _ref12.name, _transient3 = _ref12["transient"], _ref12$unique = _ref12.unique, unique = _ref12$unique === void 0 ? true : _ref12$unique, tempConv = _ref12._tempConv, tempConvTTL = _ref12._tempConvTTL, properties = _objectWithoutProperties(_ref12, _excluded5);
25261 if (_transient3 || Array.isArray(m)) {
25262 _context20.next = 3;
25263 break;
25264 }
25265 throw new TypeError("conversation members ".concat(m, " is not an array"));
25266 case 3:
25267 members = new Set(m);
25268 members.add(this.id);
25269 members = Array.from(members).sort();
25270 attr = properties || {};
25271 if (!name) {
25272 _context20.next = 11;
25273 break;
25274 }
25275 if (!(typeof name !== 'string')) {
25276 _context20.next = 10;
25277 break;
25278 }
25279 throw new TypeError("conversation name ".concat(name, " is not a string"));
25280 case 10:
25281 attr.name = name;
25282 case 11:
25283 attr = new JsonObjectMessage({
25284 data: JSON.stringify(encode(attr))
25285 });
25286 startCommandJson = {
25287 m: members,
25288 attr: attr,
25289 "transient": _transient3,
25290 unique: unique,
25291 tempConv: tempConv,
25292 tempConvTTL: tempConvTTL
25293 };
25294 command = new GenericCommand({
25295 cmd: 'conv',
25296 op: 'start',
25297 convMessage: new ConvCommand(startCommandJson)
25298 });
25299 if (!this.options.conversationSignatureFactory) {
25300 _context20.next = 20;
25301 break;
25302 }
25303 params = [null, this._identity, members, 'create'];
25304 _context20.next = 18;
25305 return runSignatureFactory(this.options.conversationSignatureFactory, params);
25306 case 18:
25307 signatureResult = _context20.sent;
25308 Object.assign(command.convMessage, keyRemap({
25309 signature: 's',
25310 timestamp: 't',
25311 nonce: 'n'
25312 }, signatureResult));
25313 case 20:
25314 _context20.next = 22;
25315 return this._send(command);
25316 case 22:
25317 _yield$this$_send = _context20.sent;
25318 _yield$this$_send$con = _yield$this$_send.convMessage;
25319 cid = _yield$this$_send$con.cid;
25320 cdate = _yield$this$_send$con.cdate;
25321 ttl = _yield$this$_send$con.tempConvTTL;
25322 data = _objectSpread$8({
25323 name: name,
25324 "transient": _transient3,
25325 unique: unique,
25326 id: cid,
25327 createdAt: cdate,
25328 updatedAt: cdate,
25329 lastMessageAt: null,
25330 creator: this.id,
25331 members: _transient3 ? [] : members
25332 }, properties);
25333 if (ttl) data.expiredAt = Date.now() + ttl * 1000;
25334 _context20.next = 31;
25335 return this.parseConversation(data);
25336 case 31:
25337 conversation = _context20.sent;
25338 return _context20.abrupt("return", this._upsertConversationToCache(conversation));
25339 case 33:
25340 case "end":
25341 return _context20.stop();
25342 }
25343 }, _callee20, this);
25344 }));
25345 function createConversation() {
25346 return _createConversation.apply(this, arguments);
25347 }
25348 return createConversation;
25349 }()
25350 /**
25351 * 创建一个聊天室
25352 * @since 4.0.0
25353 * @param {Object} options 除了下列字段外的其他字段将被视为对话的自定义属性
25354 * @param {String} [options.name] 对话的名字
25355 * @return {Promise.<ChatRoom>}
25356 */
25357 ;
25358 _proto.createChatRoom =
25359 /*#__PURE__*/
25360 function () {
25361 var _createChatRoom = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee21(param) {
25362 return regenerator.wrap(function _callee21$(_context21) {
25363 while (1) switch (_context21.prev = _context21.next) {
25364 case 0:
25365 return _context21.abrupt("return", this.createConversation(_objectSpread$8(_objectSpread$8({}, param), {}, {
25366 "transient": true,
25367 members: null,
25368 unique: false,
25369 _tempConv: false
25370 })));
25371 case 1:
25372 case "end":
25373 return _context21.stop();
25374 }
25375 }, _callee21, this);
25376 }));
25377 function createChatRoom(_x21) {
25378 return _createChatRoom.apply(this, arguments);
25379 }
25380 return createChatRoom;
25381 }()
25382 /**
25383 * 创建一个临时对话
25384 * @since 4.0.0
25385 * @param {Object} options
25386 * @param {String[]} options.members 对话的初始成员列表,默认包含当前 client
25387 * @param {String} [options.ttl] 对话存在时间,单位为秒,最大值与默认值均为 86400(一天),过期后该对话不再可用。
25388 * @return {Promise.<TemporaryConversation>}
25389 */
25390 ;
25391 _proto.createTemporaryConversation =
25392 /*#__PURE__*/
25393 function () {
25394 var _createTemporaryConversation = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee22(_ref13) {
25395 var _tempConvTTL, param;
25396 return regenerator.wrap(function _callee22$(_context22) {
25397 while (1) switch (_context22.prev = _context22.next) {
25398 case 0:
25399 _tempConvTTL = _ref13.ttl, param = _objectWithoutProperties(_ref13, _excluded6);
25400 return _context22.abrupt("return", this.createConversation(_objectSpread$8(_objectSpread$8({}, param), {}, {
25401 _tempConv: true,
25402 _tempConvTTL: _tempConvTTL
25403 })));
25404 case 2:
25405 case "end":
25406 return _context22.stop();
25407 }
25408 }, _callee22, this);
25409 }));
25410 function createTemporaryConversation(_x22) {
25411 return _createTemporaryConversation.apply(this, arguments);
25412 }
25413 return createTemporaryConversation;
25414 }() // jsdoc-ignore-start
25415 ;
25416 _proto.
25417 // jsdoc-ignore-end
25418 _doSendRead = function _doSendRead() {
25419 var _this10 = this;
25420 // if not connected, just skip everything
25421 if (!this._connection.is('connected')) return;
25422 var buffer = internal(this).readConversationsBuffer;
25423 var conversations = Array.from(buffer);
25424 if (!conversations.length) return;
25425 var ids = conversations.map(function (conversation) {
25426 if (!(conversation instanceof ConversationBase)) {
25427 throw new TypeError("".concat(conversation, " is not a Conversation"));
25428 }
25429 return conversation.id;
25430 });
25431 this._debug("mark [".concat(ids, "] as read"));
25432 buffer.clear();
25433 this._sendReadCommand(conversations)["catch"](function (error) {
25434 _this10._debug('send read failed: %O', error);
25435 conversations.forEach(buffer.add.bind(buffer));
25436 });
25437 };
25438 _proto._sendReadCommand = function _sendReadCommand(conversations) {
25439 var _this11 = this;
25440 return this._send(new GenericCommand({
25441 cmd: 'read',
25442 readMessage: new ReadCommand({
25443 convs: conversations.map(function (conversation) {
25444 return new ReadTuple({
25445 cid: conversation.id,
25446 mid: conversation.lastMessage && conversation.lastMessage.from !== _this11.id ? conversation.lastMessage.id : undefined,
25447 timestamp: (conversation.lastMessageAt || new Date()).getTime()
25448 });
25449 })
25450 })
25451 }), false);
25452 };
25453 return IMClient;
25454 }(eventemitter3), (_applyDecoratedDescriptor(_class$3.prototype, "_doSendAck", [_dec$2], Object.getOwnPropertyDescriptor(_class$3.prototype, "_doSendAck"), _class$3.prototype), _applyDecoratedDescriptor(_class$3.prototype, "_doSendRead", [_dec2], Object.getOwnPropertyDescriptor(_class$3.prototype, "_doSendRead"), _class$3.prototype)), _class$3));
25455 /**
25456 * 修改、撤回消息的原因
25457 * @typedef PatchReason
25458 * @type {Object}
25459 * @property {number} code 负数为内置 code,正数为开发者在 hook 中自定义的 code。比如因为敏感词过滤被修改的 code 为 -4408。
25460 * @property {string} [detail] 具体的原因说明。
25461 */
25462
25463 var RECONNECT_ERROR = 'reconnecterror';
25464
25465 var CoreEvent = /*#__PURE__*/Object.freeze({
25466 __proto__: null,
25467 RECONNECT_ERROR: RECONNECT_ERROR,
25468 DISCONNECT: DISCONNECT,
25469 RECONNECT: RECONNECT,
25470 RETRY: RETRY,
25471 SCHEDULE: SCHEDULE,
25472 OFFLINE: OFFLINE,
25473 ONLINE: ONLINE
25474 });
25475
25476 var _class$4;
25477 function ownKeys$9(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
25478 function _objectSpread$9(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys$9(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$9(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
25479 // jsdoc-ignore-start
25480 var BinaryMessage = IE10Compatible(_class$4 = /*#__PURE__*/function (_Message) {
25481 _inheritsLoose(BinaryMessage, _Message);
25482 /**
25483 * 二进制消息
25484 * @extends Message
25485 * @param {ArrayBuffer} buffer
25486 * @since 4.0.0
25487 */
25488 function BinaryMessage(buffer) {
25489 if (!(buffer instanceof ArrayBuffer)) {
25490 throw new TypeError("".concat(buffer, " is not an ArrayBuffer"));
25491 }
25492 return _Message.call(this, buffer) || this;
25493 }
25494
25495 /**
25496 * @type ArrayBuffer
25497 */
25498 BinaryMessage.validate = function validate(target) {
25499 return target instanceof ArrayBuffer;
25500 };
25501 var _proto = BinaryMessage.prototype;
25502 _proto.toJSON = function toJSON() {
25503 return _objectSpread$9(_objectSpread$9({}, _Message.prototype._toJSON.call(this)), {}, {
25504 data: base64Arraybuffer_1(this.content)
25505 });
25506 };
25507 _proto.toFullJSON = function toFullJSON() {
25508 return _objectSpread$9(_objectSpread$9({}, _Message.prototype.toFullJSON.call(this)), {}, {
25509 bin: true,
25510 data: base64Arraybuffer_1(this.content)
25511 });
25512 };
25513 _createClass(BinaryMessage, [{
25514 key: "buffer",
25515 get: function get() {
25516 return this.content;
25517 },
25518 set: function set(buffer) {
25519 this.content = buffer;
25520 }
25521 }]);
25522 return BinaryMessage;
25523 }(Message)) || _class$4;
25524
25525 var _dec$3, _class$5;
25526
25527 // jsdoc-ignore-start
25528 var TextMessage = (_dec$3 = messageType(-1), _dec$3(_class$5 = IE10Compatible(_class$5 = /*#__PURE__*/function (_TypedMessage) {
25529 _inheritsLoose(TextMessage, _TypedMessage);
25530 /**
25531 * 文类类型消息
25532 * @extends TypedMessage
25533 * @param {String} [text='']
25534 * @throws {TypeError} text 不是 String 类型
25535 */
25536 function TextMessage() {
25537 var _this;
25538 var text = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
25539 if (typeof text !== 'string') {
25540 throw new TypeError("".concat(text, " is not a string"));
25541 }
25542 _this = _TypedMessage.call(this) || this;
25543 _this.setText(text);
25544 return _this;
25545 }
25546 return TextMessage;
25547 }(TypedMessage)) || _class$5) || _class$5);
25548 /**
25549 * @name TYPE
25550 * @memberof TextMessage
25551 * @type Number
25552 * @static
25553 * @const
25554 */
25555
25556 var _class$6;
25557 function ownKeys$a(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
25558 function _objectSpread$a(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys$a(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$a(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
25559 function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; }
25560 function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
25561 function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
25562 var debug$c = browser('LC:MessageParser');
25563 var tryParseJson = function tryParseJson(target, key, descriptor) {
25564 var fn = descriptor.value;
25565 // eslint-disable-next-line no-param-reassign
25566 descriptor.value = function wrapper(param) {
25567 var content;
25568 if (typeof param !== 'string') {
25569 content = param;
25570 } else {
25571 try {
25572 content = JSON.parse(param);
25573 } catch (error) {
25574 content = param;
25575 }
25576 }
25577 return fn.call(this, content);
25578 };
25579 };
25580 var applyPlugins = function applyPlugins(target, key, descriptor) {
25581 var fn = descriptor.value;
25582 // eslint-disable-next-line no-param-reassign
25583 descriptor.value = function wrapper(json) {
25584 var _this = this;
25585 return Promise.resolve(json).then(applyMiddlewares(this._plugins.beforeMessageParse)).then(function (decoratedJson) {
25586 return fn.call(_this, decoratedJson);
25587 }).then(applyMiddlewares(this._plugins.afterMessageParse));
25588 };
25589 };
25590 var MessageParser = (_class$6 = /*#__PURE__*/function () {
25591 /**
25592 * 消息解析器
25593 * @param {Object} plugins 插件,插件的 messageClasses 会自动被注册,在解析时 beforeMessageParse 与 afterMessageParse Middleware 会被应用。
25594 */
25595 function MessageParser() {
25596 var plugins = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
25597 this._plugins = plugins;
25598 this._messageClasses = [];
25599 this.register(plugins.messageClasses);
25600 }
25601
25602 /**
25603 * 注册消息类
25604 *
25605 * @param {Function | Function[]} messageClass 消息类,需要实现 {@link AVMessage} 接口,
25606 * 建议继承自 {@link TypedMessage},也可以传入一个消息类数组。
25607 * @throws {TypeError} 如果 messageClass 没有实现 {@link AVMessage} 接口则抛出异常
25608 */
25609 var _proto = MessageParser.prototype;
25610 _proto.register = function register(messageClasses) {
25611 var _this2 = this;
25612 ensureArray(messageClasses).map(function (klass) {
25613 return _this2._register(klass);
25614 });
25615 };
25616 _proto._register = function _register(messageClass) {
25617 if (messageClass && messageClass.parse && messageClass.prototype && messageClass.prototype.getPayload) {
25618 this._messageClasses.unshift(messageClass);
25619 } else {
25620 throw new TypeError('Invalid messageClass');
25621 }
25622 }
25623
25624 // jsdoc-ignore-start
25625 ;
25626 _proto.
25627 // jsdoc-ignore-end
25628 /**
25629 * 解析消息内容
25630 * @param {Object | string | any} target 消息内容,如果是字符串会尝试 parse 为 JSON。
25631 * @return {AVMessage} 解析后的消息
25632 * @throws {Error} 如果不匹配任何注册的消息则抛出异常
25633 */
25634 parse = function parse(content) {
25635 debug$c('parsing message: %O', content);
25636 // eslint-disable-next-line
25637 var _iterator = _createForOfIteratorHelper(this._messageClasses),
25638 _step;
25639 try {
25640 for (_iterator.s(); !(_step = _iterator.n()).done;) {
25641 var Klass = _step.value;
25642 var contentCopy = isPlainObject_1(content) ? _objectSpread$a({}, content) : content;
25643 var valid = void 0;
25644 var result = void 0;
25645 try {
25646 valid = Klass.validate(contentCopy);
25647 } catch (error) {
25648 // eslint-disable-line no-empty
25649 }
25650 if (valid) {
25651 try {
25652 result = Klass.parse(contentCopy);
25653 } catch (error) {
25654 console.warn('parsing a valid message content error', {
25655 error: error,
25656 Klass: Klass,
25657 content: contentCopy
25658 });
25659 }
25660 if (result !== undefined) {
25661 debug$c('parse result: %O', result);
25662 return result;
25663 }
25664 }
25665 }
25666 } catch (err) {
25667 _iterator.e(err);
25668 } finally {
25669 _iterator.f();
25670 }
25671 throw new Error('No Message Class matched');
25672 };
25673 return MessageParser;
25674 }(), (_applyDecoratedDescriptor(_class$6.prototype, "parse", [tryParseJson, applyPlugins], Object.getOwnPropertyDescriptor(_class$6.prototype, "parse"), _class$6.prototype)), _class$6);
25675
25676 var _excluded$4 = ["tag", "isReconnect"];
25677 function ownKeys$b(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
25678 function _objectSpread$b(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys$b(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$b(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
25679 var debug$d = browser('LC:IMPlugin');
25680
25681 /**
25682 * 消息优先级枚举
25683 * @enum {Number}
25684 * @since 3.3.0
25685 */
25686 var MessagePriority = {
25687 /** 高 */
25688 HIGH: 1,
25689 /** 普通 */
25690 NORMAL: 2,
25691 /** 低 */
25692 LOW: 3
25693 };
25694 Object.freeze(MessagePriority);
25695
25696 /**
25697 * 为 Conversation 定义一个新属性
25698 * @param {String} prop 属性名
25699 * @param {Object} [descriptor] 属性的描述符,参见 {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyDescriptor#Description getOwnPropertyDescriptor#Description - MDN},默认为该属性名对应的 Conversation 自定义属性的 getter/setter
25700 * @returns void
25701 * @example
25702 *
25703 * conversation.get('type');
25704 * conversation.set('type', 1);
25705 *
25706 * // equals to
25707 * defineConversationProperty('type');
25708 * conversation.type;
25709 * conversation.type = 1;
25710 */
25711 var defineConversationProperty = function defineConversationProperty(prop) {
25712 var descriptor = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {
25713 get: function get() {
25714 return this.get(prop);
25715 },
25716 set: function set(value) {
25717 this.set(prop, value);
25718 }
25719 };
25720 Object.defineProperty(Conversation.prototype, prop, descriptor);
25721 };
25722 var onRealtimeCreate = function onRealtimeCreate(realtime) {
25723 /* eslint-disable no-param-reassign */
25724 var deviceId = v4_1();
25725 realtime._IMClients = {};
25726 realtime._IMClientsCreationCount = 0;
25727 var messageParser = new MessageParser(realtime._plugins);
25728 realtime._messageParser = messageParser;
25729 var signAVUser = /*#__PURE__*/function () {
25730 var _ref = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee(user) {
25731 return regenerator.wrap(function _callee$(_context) {
25732 while (1) switch (_context.prev = _context.next) {
25733 case 0:
25734 return _context.abrupt("return", realtime._request({
25735 method: 'POST',
25736 path: '/rtm/sign',
25737 data: {
25738 session_token: user.getSessionToken()
25739 }
25740 }));
25741 case 1:
25742 case "end":
25743 return _context.stop();
25744 }
25745 }, _callee);
25746 }));
25747 return function signAVUser(_x) {
25748 return _ref.apply(this, arguments);
25749 };
25750 }();
25751
25752 /**
25753 * 注册消息类
25754 *
25755 * 在接收消息、查询消息时,会按照消息类注册顺序的逆序依次尝试解析消息内容
25756 *
25757 * @memberof Realtime
25758 * @instance
25759 * @param {Function | Function[]} messageClass 消息类,需要实现 {@link AVMessage} 接口,
25760 * 建议继承自 {@link TypedMessage}
25761 * @throws {TypeError} 如果 messageClass 没有实现 {@link AVMessage} 接口则抛出异常
25762 */
25763 var register = messageParser.register.bind(messageParser);
25764 /**
25765 * 创建一个即时通讯客户端,多次创建相同 id 的客户端会返回同一个实例
25766 * @memberof Realtime
25767 * @instance
25768 * @param {String|AV.User} [identity] 客户端 identity,如果不指定该参数,服务端会随机生成一个字符串作为 identity,
25769 * 如果传入一个已登录的 AV.User,则会使用该用户的 id 作为客户端 identity 登录。
25770 * @param {Object} [options]
25771 * @param {Function} [options.signatureFactory] open session 时的签名方法 // TODO need details
25772 * @param {Function} [options.conversationSignatureFactory] 对话创建、增减成员操作时的签名方法
25773 * @param {Function} [options.blacklistSignatureFactory] 黑名单操作时的签名方法
25774 * @param {String} [options.tag] 客户端类型标记,以支持单点登录功能
25775 * @param {String} [options.isReconnect=false] 单点登录时标记该次登录是不是应用启动时自动重新登录
25776 * @return {Promise.<IMClient>}
25777 */
25778 var createIMClient = /*#__PURE__*/function () {
25779 var _ref2 = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee2(identity) {
25780 var _realtime$_open$then;
25781 var _ref3,
25782 tag,
25783 isReconnect,
25784 clientOptions,
25785 lagecyTag,
25786 id,
25787 buildinOptions,
25788 sessionToken,
25789 _tag,
25790 promise,
25791 _args2 = arguments;
25792 return regenerator.wrap(function _callee2$(_context2) {
25793 while (1) switch (_context2.prev = _context2.next) {
25794 case 0:
25795 _ref3 = _args2.length > 1 && _args2[1] !== undefined ? _args2[1] : {}, tag = _ref3.tag, isReconnect = _ref3.isReconnect, clientOptions = _objectWithoutProperties(_ref3, _excluded$4);
25796 lagecyTag = _args2.length > 2 ? _args2[2] : undefined;
25797 buildinOptions = {};
25798 if (!identity) {
25799 _context2.next = 19;
25800 break;
25801 }
25802 if (!(typeof identity === 'string')) {
25803 _context2.next = 8;
25804 break;
25805 }
25806 id = identity;
25807 _context2.next = 17;
25808 break;
25809 case 8:
25810 if (!(identity.id && identity.getSessionToken)) {
25811 _context2.next = 16;
25812 break;
25813 }
25814 id = identity.id;
25815 sessionToken = identity.getSessionToken();
25816 if (sessionToken) {
25817 _context2.next = 13;
25818 break;
25819 }
25820 throw new Error('User must be authenticated');
25821 case 13:
25822 buildinOptions.signatureFactory = signAVUser;
25823 _context2.next = 17;
25824 break;
25825 case 16:
25826 throw new TypeError('Identity must be a String or an AV.User');
25827 case 17:
25828 if (!(realtime._IMClients[id] !== undefined)) {
25829 _context2.next = 19;
25830 break;
25831 }
25832 return _context2.abrupt("return", realtime._IMClients[id]);
25833 case 19:
25834 if (lagecyTag) {
25835 console.warn('DEPRECATION createIMClient tag param: Use options.tag instead.');
25836 }
25837 _tag = tag || lagecyTag;
25838 promise = (_realtime$_open$then = realtime._open().then(function (connection) {
25839 var client = new IMClient(id, _objectSpread$b(_objectSpread$b({}, buildinOptions), clientOptions), {
25840 _connection: connection,
25841 _request: realtime._request.bind(realtime),
25842 _messageParser: messageParser,
25843 _plugins: realtime._plugins,
25844 _identity: identity
25845 });
25846 connection.on(RECONNECT, function () {
25847 return client._open(realtime._options.appId, _tag, deviceId, true)
25848 /**
25849 * 客户端连接恢复正常,该事件通常在 {@link Realtime#event:RECONNECT} 之后发生
25850 * @event IMClient#RECONNECT
25851 * @see Realtime#event:RECONNECT
25852 * @since 3.2.0
25853 */
25854 /**
25855 * 客户端重新登录发生错误(网络连接已恢复,但重新登录错误)
25856 * @event IMClient#RECONNECT_ERROR
25857 * @since 3.2.0
25858 */.then(function () {
25859 return client.emit(RECONNECT);
25860 }, function (error) {
25861 return client.emit(RECONNECT_ERROR, error);
25862 });
25863 });
25864 internal(client)._eventemitter.on('beforeclose', function () {
25865 delete realtime._IMClients[client.id];
25866 if (realtime._firstIMClient === client) {
25867 delete realtime._firstIMClient;
25868 }
25869 }, realtime);
25870 internal(client)._eventemitter.on('close', function () {
25871 realtime._deregister(client);
25872 }, realtime);
25873 return client._open(realtime._options.appId, _tag, deviceId, isReconnect).then(function () {
25874 realtime._IMClients[client.id] = client;
25875 realtime._IMClientsCreationCount += 1;
25876 if (realtime._IMClientsCreationCount === 1) {
25877 client._omitPeerId(true);
25878 realtime._firstIMClient = client;
25879 } else if (realtime._IMClientsCreationCount > 1 && realtime._firstIMClient) {
25880 realtime._firstIMClient._omitPeerId(false);
25881 }
25882 realtime._register(client);
25883 return client;
25884 })["catch"](function (error) {
25885 delete realtime._IMClients[client.id];
25886 throw error;
25887 });
25888 })).then.apply(_realtime$_open$then, _toConsumableArray(finalize(function () {
25889 realtime._deregisterPending(promise);
25890 })))["catch"](function (error) {
25891 delete realtime._IMClients[id];
25892 throw error;
25893 });
25894 if (identity) {
25895 realtime._IMClients[id] = promise;
25896 }
25897 realtime._registerPending(promise);
25898 return _context2.abrupt("return", promise);
25899 case 25:
25900 case "end":
25901 return _context2.stop();
25902 }
25903 }, _callee2);
25904 }));
25905 return function createIMClient(_x2) {
25906 return _ref2.apply(this, arguments);
25907 };
25908 }();
25909 Object.assign(realtime, {
25910 register: register,
25911 createIMClient: createIMClient
25912 });
25913 /* eslint-enable no-param-reassign */
25914 };
25915
25916 var beforeCommandDispatch = function beforeCommandDispatch(command, realtime) {
25917 var isIMCommand = command.service === null || command.service === 2;
25918 if (!isIMCommand) return true;
25919 var targetClient = command.peerId ? realtime._IMClients[command.peerId] : realtime._firstIMClient;
25920 if (targetClient) {
25921 Promise.resolve(targetClient).then(function (client) {
25922 return client._dispatchCommand(command);
25923 })["catch"](debug$d);
25924 } else {
25925 debug$d('[WARN] Unexpected message received without any live client match: %O', trim(command));
25926 }
25927 return false;
25928 };
25929 var IMPlugin = {
25930 name: 'leancloud-realtime-plugin-im',
25931 onRealtimeCreate: onRealtimeCreate,
25932 beforeCommandDispatch: beforeCommandDispatch,
25933 messageClasses: [Message, BinaryMessage, RecalledMessage, TextMessage]
25934 };
25935
25936 function ownKeys$c(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
25937 function _objectSpread$c(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys$c(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$c(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
25938 Realtime.defineConversationProperty = defineConversationProperty;
25939 Realtime.__preRegisteredPlugins = [IMPlugin];
25940 var Event = _objectSpread$c(_objectSpread$c({}, CoreEvent), IMEvent);
25941
25942 /** core + plugins + platform adapters */
25943 setAdapters({
25944 WebSocket: lib_1,
25945 request: lib_4
25946 });
25947
25948 exports.BinaryMessage = BinaryMessage;
25949 exports.ChatRoom = ChatRoom;
25950 exports.Conversation = Conversation;
25951 exports.ConversationMemberRole = ConversationMemberRole;
25952 exports.ConversationQuery = ConversationQuery;
25953 exports.ErrorCode = ErrorCode;
25954 exports.Event = Event;
25955 exports.EventEmitter = eventemitter3;
25956 exports.IE10Compatible = IE10Compatible;
25957 exports.IMPlugin = IMPlugin;
25958 exports.Message = Message;
25959 exports.MessageParser = MessageParser;
25960 exports.MessagePriority = MessagePriority;
25961 exports.MessageQueryDirection = MessageQueryDirection;
25962 exports.MessageStatus = MessageStatus;
25963 exports.Promise = polyfilledPromise;
25964 exports.Protocals = message;
25965 exports.Protocols = message;
25966 exports.Realtime = Realtime;
25967 exports.RecalledMessage = RecalledMessage;
25968 exports.ServiceConversation = ServiceConversation;
25969 exports.TemporaryConversation = TemporaryConversation;
25970 exports.TextMessage = TextMessage;
25971 exports.TypedMessage = TypedMessage;
25972 exports.debug = debug$2;
25973 exports.defineConversationProperty = defineConversationProperty;
25974 exports.getAdapter = getAdapter;
25975 exports.messageField = messageField;
25976 exports.messageType = messageType;
25977 exports.setAdapters = setAdapters;
25978
25979 Object.defineProperty(exports, '__esModule', { value: true });
25980
25981})));
25982//# sourceMappingURL=im-weapp.js.map