UNPKG

949 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 componentEmitter = createCommonjsModule(function (module) {
55 /**
56 * Expose `Emitter`.
57 */
58
59 {
60 module.exports = Emitter;
61 }
62
63 /**
64 * Initialize a new `Emitter`.
65 *
66 * @api public
67 */
68
69 function Emitter(obj) {
70 if (obj) return mixin(obj);
71 }
72
73 /**
74 * Mixin the emitter properties.
75 *
76 * @param {Object} obj
77 * @return {Object}
78 * @api private
79 */
80
81 function mixin(obj) {
82 for (var key in Emitter.prototype) {
83 obj[key] = Emitter.prototype[key];
84 }
85 return obj;
86 }
87
88 /**
89 * Listen on the given `event` with `fn`.
90 *
91 * @param {String} event
92 * @param {Function} fn
93 * @return {Emitter}
94 * @api public
95 */
96
97 Emitter.prototype.on = Emitter.prototype.addEventListener = function (event, fn) {
98 this._callbacks = this._callbacks || {};
99 (this._callbacks['$' + event] = this._callbacks['$' + event] || []).push(fn);
100 return this;
101 };
102
103 /**
104 * Adds an `event` listener that will be invoked a single
105 * time then automatically removed.
106 *
107 * @param {String} event
108 * @param {Function} fn
109 * @return {Emitter}
110 * @api public
111 */
112
113 Emitter.prototype.once = function (event, fn) {
114 function on() {
115 this.off(event, on);
116 fn.apply(this, arguments);
117 }
118 on.fn = fn;
119 this.on(event, on);
120 return this;
121 };
122
123 /**
124 * Remove the given callback for `event` or all
125 * registered callbacks.
126 *
127 * @param {String} event
128 * @param {Function} fn
129 * @return {Emitter}
130 * @api public
131 */
132
133 Emitter.prototype.off = Emitter.prototype.removeListener = Emitter.prototype.removeAllListeners = Emitter.prototype.removeEventListener = function (event, fn) {
134 this._callbacks = this._callbacks || {};
135
136 // all
137 if (0 == arguments.length) {
138 this._callbacks = {};
139 return this;
140 }
141
142 // specific event
143 var callbacks = this._callbacks['$' + event];
144 if (!callbacks) return this;
145
146 // remove all handlers
147 if (1 == arguments.length) {
148 delete this._callbacks['$' + event];
149 return this;
150 }
151
152 // remove specific handler
153 var cb;
154 for (var i = 0; i < callbacks.length; i++) {
155 cb = callbacks[i];
156 if (cb === fn || cb.fn === fn) {
157 callbacks.splice(i, 1);
158 break;
159 }
160 }
161
162 // Remove event specific arrays for event types that no
163 // one is subscribed for to avoid memory leak.
164 if (callbacks.length === 0) {
165 delete this._callbacks['$' + event];
166 }
167 return this;
168 };
169
170 /**
171 * Emit `event` with the given args.
172 *
173 * @param {String} event
174 * @param {Mixed} ...
175 * @return {Emitter}
176 */
177
178 Emitter.prototype.emit = function (event) {
179 this._callbacks = this._callbacks || {};
180 var args = new Array(arguments.length - 1),
181 callbacks = this._callbacks['$' + event];
182 for (var i = 1; i < arguments.length; i++) {
183 args[i - 1] = arguments[i];
184 }
185 if (callbacks) {
186 callbacks = callbacks.slice(0);
187 for (var i = 0, len = callbacks.length; i < len; ++i) {
188 callbacks[i].apply(this, args);
189 }
190 }
191 return this;
192 };
193
194 /**
195 * Return array of callbacks for `event`.
196 *
197 * @param {String} event
198 * @return {Array}
199 * @api public
200 */
201
202 Emitter.prototype.listeners = function (event) {
203 this._callbacks = this._callbacks || {};
204 return this._callbacks['$' + event] || [];
205 };
206
207 /**
208 * Check if this emitter has `event` handlers.
209 *
210 * @param {String} event
211 * @return {Boolean}
212 * @api public
213 */
214
215 Emitter.prototype.hasListeners = function (event) {
216 return !!this.listeners(event).length;
217 };
218 });
219
220 var fastSafeStringify = stringify;
221 stringify.default = stringify;
222 stringify.stable = deterministicStringify;
223 stringify.stableStringify = deterministicStringify;
224
225 var arr = [];
226 var replacerStack = [];
227
228 // Regular stringify
229 function stringify (obj, replacer, spacer) {
230 decirc(obj, '', [], undefined);
231 var res;
232 if (replacerStack.length === 0) {
233 res = JSON.stringify(obj, replacer, spacer);
234 } else {
235 res = JSON.stringify(obj, replaceGetterValues(replacer), spacer);
236 }
237 while (arr.length !== 0) {
238 var part = arr.pop();
239 if (part.length === 4) {
240 Object.defineProperty(part[0], part[1], part[3]);
241 } else {
242 part[0][part[1]] = part[2];
243 }
244 }
245 return res
246 }
247 function decirc (val, k, stack, parent) {
248 var i;
249 if (typeof val === 'object' && val !== null) {
250 for (i = 0; i < stack.length; i++) {
251 if (stack[i] === val) {
252 var propertyDescriptor = Object.getOwnPropertyDescriptor(parent, k);
253 if (propertyDescriptor.get !== undefined) {
254 if (propertyDescriptor.configurable) {
255 Object.defineProperty(parent, k, { value: '[Circular]' });
256 arr.push([parent, k, val, propertyDescriptor]);
257 } else {
258 replacerStack.push([val, k]);
259 }
260 } else {
261 parent[k] = '[Circular]';
262 arr.push([parent, k, val]);
263 }
264 return
265 }
266 }
267 stack.push(val);
268 // Optimize for Arrays. Big arrays could kill the performance otherwise!
269 if (Array.isArray(val)) {
270 for (i = 0; i < val.length; i++) {
271 decirc(val[i], i, stack, val);
272 }
273 } else {
274 var keys = Object.keys(val);
275 for (i = 0; i < keys.length; i++) {
276 var key = keys[i];
277 decirc(val[key], key, stack, val);
278 }
279 }
280 stack.pop();
281 }
282 }
283
284 // Stable-stringify
285 function compareFunction (a, b) {
286 if (a < b) {
287 return -1
288 }
289 if (a > b) {
290 return 1
291 }
292 return 0
293 }
294
295 function deterministicStringify (obj, replacer, spacer) {
296 var tmp = deterministicDecirc(obj, '', [], undefined) || obj;
297 var res;
298 if (replacerStack.length === 0) {
299 res = JSON.stringify(tmp, replacer, spacer);
300 } else {
301 res = JSON.stringify(tmp, replaceGetterValues(replacer), spacer);
302 }
303 while (arr.length !== 0) {
304 var part = arr.pop();
305 if (part.length === 4) {
306 Object.defineProperty(part[0], part[1], part[3]);
307 } else {
308 part[0][part[1]] = part[2];
309 }
310 }
311 return res
312 }
313
314 function deterministicDecirc (val, k, stack, parent) {
315 var i;
316 if (typeof val === 'object' && val !== null) {
317 for (i = 0; i < stack.length; i++) {
318 if (stack[i] === val) {
319 var propertyDescriptor = Object.getOwnPropertyDescriptor(parent, k);
320 if (propertyDescriptor.get !== undefined) {
321 if (propertyDescriptor.configurable) {
322 Object.defineProperty(parent, k, { value: '[Circular]' });
323 arr.push([parent, k, val, propertyDescriptor]);
324 } else {
325 replacerStack.push([val, k]);
326 }
327 } else {
328 parent[k] = '[Circular]';
329 arr.push([parent, k, val]);
330 }
331 return
332 }
333 }
334 if (typeof val.toJSON === 'function') {
335 return
336 }
337 stack.push(val);
338 // Optimize for Arrays. Big arrays could kill the performance otherwise!
339 if (Array.isArray(val)) {
340 for (i = 0; i < val.length; i++) {
341 deterministicDecirc(val[i], i, stack, val);
342 }
343 } else {
344 // Create a temporary object in the required way
345 var tmp = {};
346 var keys = Object.keys(val).sort(compareFunction);
347 for (i = 0; i < keys.length; i++) {
348 var key = keys[i];
349 deterministicDecirc(val[key], key, stack, val);
350 tmp[key] = val[key];
351 }
352 if (parent !== undefined) {
353 arr.push([parent, k, val]);
354 parent[k] = tmp;
355 } else {
356 return tmp
357 }
358 }
359 stack.pop();
360 }
361 }
362
363 // wraps replacer function to handle values we couldn't replace
364 // and mark them as [Circular]
365 function replaceGetterValues (replacer) {
366 replacer = replacer !== undefined ? replacer : function (k, v) { return v };
367 return function (key, val) {
368 if (replacerStack.length > 0) {
369 for (var i = 0; i < replacerStack.length; i++) {
370 var part = replacerStack[i];
371 if (part[1] === key && part[0] === val) {
372 val = '[Circular]';
373 replacerStack.splice(i, 1);
374 break
375 }
376 }
377 }
378 return replacer.call(this, key, val)
379 }
380 }
381
382 function _typeof$1(obj) {
383 if (typeof Symbol === "function" && _typeof(Symbol.iterator) === "symbol") {
384 _typeof$1 = function _typeof$1(obj) {
385 return _typeof(obj);
386 };
387 } else {
388 _typeof$1 = function _typeof$1(obj) {
389 return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : _typeof(obj);
390 };
391 }
392 return _typeof$1(obj);
393 }
394
395 /**
396 * Check if `obj` is an object.
397 *
398 * @param {Object} obj
399 * @return {Boolean}
400 * @api private
401 */
402 function isObject(obj) {
403 return obj !== null && _typeof$1(obj) === 'object';
404 }
405 var isObject_1 = isObject;
406
407 function _typeof$2(obj) {
408 if (typeof Symbol === "function" && _typeof(Symbol.iterator) === "symbol") {
409 _typeof$2 = function _typeof$1(obj) {
410 return _typeof(obj);
411 };
412 } else {
413 _typeof$2 = function _typeof$1(obj) {
414 return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : _typeof(obj);
415 };
416 }
417 return _typeof$2(obj);
418 }
419
420 /**
421 * Module of mixed-in functions shared between node and client code
422 */
423
424 /**
425 * Expose `RequestBase`.
426 */
427
428 var requestBase = RequestBase;
429 /**
430 * Initialize a new `RequestBase`.
431 *
432 * @api public
433 */
434
435 function RequestBase(obj) {
436 if (obj) return mixin(obj);
437 }
438 /**
439 * Mixin the prototype properties.
440 *
441 * @param {Object} obj
442 * @return {Object}
443 * @api private
444 */
445
446 function mixin(obj) {
447 for (var key in RequestBase.prototype) {
448 if (Object.prototype.hasOwnProperty.call(RequestBase.prototype, key)) obj[key] = RequestBase.prototype[key];
449 }
450 return obj;
451 }
452 /**
453 * Clear previous timeout.
454 *
455 * @return {Request} for chaining
456 * @api public
457 */
458
459 RequestBase.prototype.clearTimeout = function () {
460 clearTimeout(this._timer);
461 clearTimeout(this._responseTimeoutTimer);
462 clearTimeout(this._uploadTimeoutTimer);
463 delete this._timer;
464 delete this._responseTimeoutTimer;
465 delete this._uploadTimeoutTimer;
466 return this;
467 };
468 /**
469 * Override default response body parser
470 *
471 * This function will be called to convert incoming data into request.body
472 *
473 * @param {Function}
474 * @api public
475 */
476
477 RequestBase.prototype.parse = function (fn) {
478 this._parser = fn;
479 return this;
480 };
481 /**
482 * Set format of binary response body.
483 * In browser valid formats are 'blob' and 'arraybuffer',
484 * which return Blob and ArrayBuffer, respectively.
485 *
486 * In Node all values result in Buffer.
487 *
488 * Examples:
489 *
490 * req.get('/')
491 * .responseType('blob')
492 * .end(callback);
493 *
494 * @param {String} val
495 * @return {Request} for chaining
496 * @api public
497 */
498
499 RequestBase.prototype.responseType = function (val) {
500 this._responseType = val;
501 return this;
502 };
503 /**
504 * Override default request body serializer
505 *
506 * This function will be called to convert data set via .send or .attach into payload to send
507 *
508 * @param {Function}
509 * @api public
510 */
511
512 RequestBase.prototype.serialize = function (fn) {
513 this._serializer = fn;
514 return this;
515 };
516 /**
517 * Set timeouts.
518 *
519 * - response timeout is time between sending request and receiving the first byte of the response. Includes DNS and connection time.
520 * - deadline is the time from start of the request to receiving response body in full. If the deadline is too short large files may not load at all on slow connections.
521 * - upload is the time since last bit of data was sent or received. This timeout works only if deadline timeout is off
522 *
523 * Value of 0 or false means no timeout.
524 *
525 * @param {Number|Object} ms or {response, deadline}
526 * @return {Request} for chaining
527 * @api public
528 */
529
530 RequestBase.prototype.timeout = function (options) {
531 if (!options || _typeof$2(options) !== 'object') {
532 this._timeout = options;
533 this._responseTimeout = 0;
534 this._uploadTimeout = 0;
535 return this;
536 }
537 for (var option in options) {
538 if (Object.prototype.hasOwnProperty.call(options, option)) {
539 switch (option) {
540 case 'deadline':
541 this._timeout = options.deadline;
542 break;
543 case 'response':
544 this._responseTimeout = options.response;
545 break;
546 case 'upload':
547 this._uploadTimeout = options.upload;
548 break;
549 default:
550 console.warn('Unknown timeout option', option);
551 }
552 }
553 }
554 return this;
555 };
556 /**
557 * Set number of retry attempts on error.
558 *
559 * Failed requests will be retried 'count' times if timeout or err.code >= 500.
560 *
561 * @param {Number} count
562 * @param {Function} [fn]
563 * @return {Request} for chaining
564 * @api public
565 */
566
567 RequestBase.prototype.retry = function (count, fn) {
568 // Default to 1 if no count passed or true
569 if (arguments.length === 0 || count === true) count = 1;
570 if (count <= 0) count = 0;
571 this._maxRetries = count;
572 this._retries = 0;
573 this._retryCallback = fn;
574 return this;
575 };
576 var ERROR_CODES = ['ECONNRESET', 'ETIMEDOUT', 'EADDRINFO', 'ESOCKETTIMEDOUT'];
577 /**
578 * Determine if a request should be retried.
579 * (Borrowed from segmentio/superagent-retry)
580 *
581 * @param {Error} err an error
582 * @param {Response} [res] response
583 * @returns {Boolean} if segment should be retried
584 */
585
586 RequestBase.prototype._shouldRetry = function (err, res) {
587 if (!this._maxRetries || this._retries++ >= this._maxRetries) {
588 return false;
589 }
590 if (this._retryCallback) {
591 try {
592 var override = this._retryCallback(err, res);
593 if (override === true) return true;
594 if (override === false) return false; // undefined falls back to defaults
595 } catch (err_) {
596 console.error(err_);
597 }
598 }
599 if (res && res.status && res.status >= 500 && res.status !== 501) return true;
600 if (err) {
601 if (err.code && ERROR_CODES.includes(err.code)) return true; // Superagent timeout
602
603 if (err.timeout && err.code === 'ECONNABORTED') return true;
604 if (err.crossDomain) return true;
605 }
606 return false;
607 };
608 /**
609 * Retry request
610 *
611 * @return {Request} for chaining
612 * @api private
613 */
614
615 RequestBase.prototype._retry = function () {
616 this.clearTimeout(); // node
617
618 if (this.req) {
619 this.req = null;
620 this.req = this.request();
621 }
622 this._aborted = false;
623 this.timedout = false;
624 this.timedoutError = null;
625 return this._end();
626 };
627 /**
628 * Promise support
629 *
630 * @param {Function} resolve
631 * @param {Function} [reject]
632 * @return {Request}
633 */
634
635 RequestBase.prototype.then = function (resolve, reject) {
636 var _this = this;
637 if (!this._fullfilledPromise) {
638 var self = this;
639 if (this._endCalled) {
640 console.warn('Warning: superagent request was sent twice, because both .end() and .then() were called. Never call .end() if you use promises');
641 }
642 this._fullfilledPromise = new Promise(function (resolve, reject) {
643 self.on('abort', function () {
644 if (_this.timedout && _this.timedoutError) {
645 reject(_this.timedoutError);
646 return;
647 }
648 var err = new Error('Aborted');
649 err.code = 'ABORTED';
650 err.status = _this.status;
651 err.method = _this.method;
652 err.url = _this.url;
653 reject(err);
654 });
655 self.end(function (err, res) {
656 if (err) reject(err);else resolve(res);
657 });
658 });
659 }
660 return this._fullfilledPromise.then(resolve, reject);
661 };
662 RequestBase.prototype["catch"] = function (cb) {
663 return this.then(undefined, cb);
664 };
665 /**
666 * Allow for extension
667 */
668
669 RequestBase.prototype.use = function (fn) {
670 fn(this);
671 return this;
672 };
673 RequestBase.prototype.ok = function (cb) {
674 if (typeof cb !== 'function') throw new Error('Callback required');
675 this._okCallback = cb;
676 return this;
677 };
678 RequestBase.prototype._isResponseOK = function (res) {
679 if (!res) {
680 return false;
681 }
682 if (this._okCallback) {
683 return this._okCallback(res);
684 }
685 return res.status >= 200 && res.status < 300;
686 };
687 /**
688 * Get request header `field`.
689 * Case-insensitive.
690 *
691 * @param {String} field
692 * @return {String}
693 * @api public
694 */
695
696 RequestBase.prototype.get = function (field) {
697 return this._header[field.toLowerCase()];
698 };
699 /**
700 * Get case-insensitive header `field` value.
701 * This is a deprecated internal API. Use `.get(field)` instead.
702 *
703 * (getHeader is no longer used internally by the superagent code base)
704 *
705 * @param {String} field
706 * @return {String}
707 * @api private
708 * @deprecated
709 */
710
711 RequestBase.prototype.getHeader = RequestBase.prototype.get;
712 /**
713 * Set header `field` to `val`, or multiple fields with one object.
714 * Case-insensitive.
715 *
716 * Examples:
717 *
718 * req.get('/')
719 * .set('Accept', 'application/json')
720 * .set('X-API-Key', 'foobar')
721 * .end(callback);
722 *
723 * req.get('/')
724 * .set({ Accept: 'application/json', 'X-API-Key': 'foobar' })
725 * .end(callback);
726 *
727 * @param {String|Object} field
728 * @param {String} val
729 * @return {Request} for chaining
730 * @api public
731 */
732
733 RequestBase.prototype.set = function (field, val) {
734 if (isObject_1(field)) {
735 for (var key in field) {
736 if (Object.prototype.hasOwnProperty.call(field, key)) this.set(key, field[key]);
737 }
738 return this;
739 }
740 this._header[field.toLowerCase()] = val;
741 this.header[field] = val;
742 return this;
743 };
744 /**
745 * Remove header `field`.
746 * Case-insensitive.
747 *
748 * Example:
749 *
750 * req.get('/')
751 * .unset('User-Agent')
752 * .end(callback);
753 *
754 * @param {String} field field name
755 */
756
757 RequestBase.prototype.unset = function (field) {
758 delete this._header[field.toLowerCase()];
759 delete this.header[field];
760 return this;
761 };
762 /**
763 * Write the field `name` and `val`, or multiple fields with one object
764 * for "multipart/form-data" request bodies.
765 *
766 * ``` js
767 * request.post('/upload')
768 * .field('foo', 'bar')
769 * .end(callback);
770 *
771 * request.post('/upload')
772 * .field({ foo: 'bar', baz: 'qux' })
773 * .end(callback);
774 * ```
775 *
776 * @param {String|Object} name name of field
777 * @param {String|Blob|File|Buffer|fs.ReadStream} val value of field
778 * @return {Request} for chaining
779 * @api public
780 */
781
782 RequestBase.prototype.field = function (name, val) {
783 // name should be either a string or an object.
784 if (name === null || undefined === name) {
785 throw new Error('.field(name, val) name can not be empty');
786 }
787 if (this._data) {
788 throw new Error(".field() can't be used if .send() is used. Please use only .send() or only .field() & .attach()");
789 }
790 if (isObject_1(name)) {
791 for (var key in name) {
792 if (Object.prototype.hasOwnProperty.call(name, key)) this.field(key, name[key]);
793 }
794 return this;
795 }
796 if (Array.isArray(val)) {
797 for (var i in val) {
798 if (Object.prototype.hasOwnProperty.call(val, i)) this.field(name, val[i]);
799 }
800 return this;
801 } // val should be defined now
802
803 if (val === null || undefined === val) {
804 throw new Error('.field(name, val) val can not be empty');
805 }
806 if (typeof val === 'boolean') {
807 val = String(val);
808 }
809 this._getFormData().append(name, val);
810 return this;
811 };
812 /**
813 * Abort the request, and clear potential timeout.
814 *
815 * @return {Request} request
816 * @api public
817 */
818
819 RequestBase.prototype.abort = function () {
820 if (this._aborted) {
821 return this;
822 }
823 this._aborted = true;
824 if (this.xhr) this.xhr.abort(); // browser
825
826 if (this.req) this.req.abort(); // node
827
828 this.clearTimeout();
829 this.emit('abort');
830 return this;
831 };
832 RequestBase.prototype._auth = function (user, pass, options, base64Encoder) {
833 switch (options.type) {
834 case 'basic':
835 this.set('Authorization', "Basic ".concat(base64Encoder("".concat(user, ":").concat(pass))));
836 break;
837 case 'auto':
838 this.username = user;
839 this.password = pass;
840 break;
841 case 'bearer':
842 // usage would be .auth(accessToken, { type: 'bearer' })
843 this.set('Authorization', "Bearer ".concat(user));
844 break;
845 }
846 return this;
847 };
848 /**
849 * Enable transmission of cookies with x-domain requests.
850 *
851 * Note that for this to work the origin must not be
852 * using "Access-Control-Allow-Origin" with a wildcard,
853 * and also must set "Access-Control-Allow-Credentials"
854 * to "true".
855 *
856 * @api public
857 */
858
859 RequestBase.prototype.withCredentials = function (on) {
860 // This is browser-only functionality. Node side is no-op.
861 if (on === undefined) on = true;
862 this._withCredentials = on;
863 return this;
864 };
865 /**
866 * Set the max redirects to `n`. Does nothing in browser XHR implementation.
867 *
868 * @param {Number} n
869 * @return {Request} for chaining
870 * @api public
871 */
872
873 RequestBase.prototype.redirects = function (n) {
874 this._maxRedirects = n;
875 return this;
876 };
877 /**
878 * Maximum size of buffered response body, in bytes. Counts uncompressed size.
879 * Default 200MB.
880 *
881 * @param {Number} n number of bytes
882 * @return {Request} for chaining
883 */
884
885 RequestBase.prototype.maxResponseSize = function (n) {
886 if (typeof n !== 'number') {
887 throw new TypeError('Invalid argument');
888 }
889 this._maxResponseSize = n;
890 return this;
891 };
892 /**
893 * Convert to a plain javascript object (not JSON string) of scalar properties.
894 * Note as this method is designed to return a useful non-this value,
895 * it cannot be chained.
896 *
897 * @return {Object} describing method, url, and data of this request
898 * @api public
899 */
900
901 RequestBase.prototype.toJSON = function () {
902 return {
903 method: this.method,
904 url: this.url,
905 data: this._data,
906 headers: this._header
907 };
908 };
909 /**
910 * Send `data` as the request body, defaulting the `.type()` to "json" when
911 * an object is given.
912 *
913 * Examples:
914 *
915 * // manual json
916 * request.post('/user')
917 * .type('json')
918 * .send('{"name":"tj"}')
919 * .end(callback)
920 *
921 * // auto json
922 * request.post('/user')
923 * .send({ name: 'tj' })
924 * .end(callback)
925 *
926 * // manual x-www-form-urlencoded
927 * request.post('/user')
928 * .type('form')
929 * .send('name=tj')
930 * .end(callback)
931 *
932 * // auto x-www-form-urlencoded
933 * request.post('/user')
934 * .type('form')
935 * .send({ name: 'tj' })
936 * .end(callback)
937 *
938 * // defaults to x-www-form-urlencoded
939 * request.post('/user')
940 * .send('name=tobi')
941 * .send('species=ferret')
942 * .end(callback)
943 *
944 * @param {String|Object} data
945 * @return {Request} for chaining
946 * @api public
947 */
948 // eslint-disable-next-line complexity
949
950 RequestBase.prototype.send = function (data) {
951 var isObj = isObject_1(data);
952 var type = this._header['content-type'];
953 if (this._formData) {
954 throw new Error(".send() can't be used if .attach() or .field() is used. Please use only .send() or only .field() & .attach()");
955 }
956 if (isObj && !this._data) {
957 if (Array.isArray(data)) {
958 this._data = [];
959 } else if (!this._isHost(data)) {
960 this._data = {};
961 }
962 } else if (data && this._data && this._isHost(this._data)) {
963 throw new Error("Can't merge these send calls");
964 } // merge
965
966 if (isObj && isObject_1(this._data)) {
967 for (var key in data) {
968 if (Object.prototype.hasOwnProperty.call(data, key)) this._data[key] = data[key];
969 }
970 } else if (typeof data === 'string') {
971 // default to x-www-form-urlencoded
972 if (!type) this.type('form');
973 type = this._header['content-type'];
974 if (type === 'application/x-www-form-urlencoded') {
975 this._data = this._data ? "".concat(this._data, "&").concat(data) : data;
976 } else {
977 this._data = (this._data || '') + data;
978 }
979 } else {
980 this._data = data;
981 }
982 if (!isObj || this._isHost(data)) {
983 return this;
984 } // default to json
985
986 if (!type) this.type('json');
987 return this;
988 };
989 /**
990 * Sort `querystring` by the sort function
991 *
992 *
993 * Examples:
994 *
995 * // default order
996 * request.get('/user')
997 * .query('name=Nick')
998 * .query('search=Manny')
999 * .sortQuery()
1000 * .end(callback)
1001 *
1002 * // customized sort function
1003 * request.get('/user')
1004 * .query('name=Nick')
1005 * .query('search=Manny')
1006 * .sortQuery(function(a, b){
1007 * return a.length - b.length;
1008 * })
1009 * .end(callback)
1010 *
1011 *
1012 * @param {Function} sort
1013 * @return {Request} for chaining
1014 * @api public
1015 */
1016
1017 RequestBase.prototype.sortQuery = function (sort) {
1018 // _sort default to true but otherwise can be a function or boolean
1019 this._sort = typeof sort === 'undefined' ? true : sort;
1020 return this;
1021 };
1022 /**
1023 * Compose querystring to append to req.url
1024 *
1025 * @api private
1026 */
1027
1028 RequestBase.prototype._finalizeQueryString = function () {
1029 var query = this._query.join('&');
1030 if (query) {
1031 this.url += (this.url.includes('?') ? '&' : '?') + query;
1032 }
1033 this._query.length = 0; // Makes the call idempotent
1034
1035 if (this._sort) {
1036 var index = this.url.indexOf('?');
1037 if (index >= 0) {
1038 var queryArr = this.url.slice(index + 1).split('&');
1039 if (typeof this._sort === 'function') {
1040 queryArr.sort(this._sort);
1041 } else {
1042 queryArr.sort();
1043 }
1044 this.url = this.url.slice(0, index) + '?' + queryArr.join('&');
1045 }
1046 }
1047 }; // For backwards compat only
1048
1049 RequestBase.prototype._appendQueryString = function () {
1050 console.warn('Unsupported');
1051 };
1052 /**
1053 * Invoke callback with timeout error.
1054 *
1055 * @api private
1056 */
1057
1058 RequestBase.prototype._timeoutError = function (reason, timeout, errno) {
1059 if (this._aborted) {
1060 return;
1061 }
1062 var err = new Error("".concat(reason + timeout, "ms exceeded"));
1063 err.timeout = timeout;
1064 err.code = 'ECONNABORTED';
1065 err.errno = errno;
1066 this.timedout = true;
1067 this.timedoutError = err;
1068 this.abort();
1069 this.callback(err);
1070 };
1071 RequestBase.prototype._setTimeouts = function () {
1072 var self = this; // deadline
1073
1074 if (this._timeout && !this._timer) {
1075 this._timer = setTimeout(function () {
1076 self._timeoutError('Timeout of ', self._timeout, 'ETIME');
1077 }, this._timeout);
1078 } // response timeout
1079
1080 if (this._responseTimeout && !this._responseTimeoutTimer) {
1081 this._responseTimeoutTimer = setTimeout(function () {
1082 self._timeoutError('Response timeout of ', self._responseTimeout, 'ETIMEDOUT');
1083 }, this._responseTimeout);
1084 }
1085 };
1086
1087 /**
1088 * Return the mime type for the given `str`.
1089 *
1090 * @param {String} str
1091 * @return {String}
1092 * @api private
1093 */
1094 var type = function type(str) {
1095 return str.split(/ *; */).shift();
1096 };
1097 /**
1098 * Return header field parameters.
1099 *
1100 * @param {String} str
1101 * @return {Object}
1102 * @api private
1103 */
1104
1105 var params = function params(str) {
1106 return str.split(/ *; */).reduce(function (obj, str) {
1107 var parts = str.split(/ *= */);
1108 var key = parts.shift();
1109 var val = parts.shift();
1110 if (key && val) obj[key] = val;
1111 return obj;
1112 }, {});
1113 };
1114 /**
1115 * Parse Link header fields.
1116 *
1117 * @param {String} str
1118 * @return {Object}
1119 * @api private
1120 */
1121
1122 var parseLinks = function parseLinks(str) {
1123 return str.split(/ *, */).reduce(function (obj, str) {
1124 var parts = str.split(/ *; */);
1125 var url = parts[0].slice(1, -1);
1126 var rel = parts[1].split(/ *= */)[1].slice(1, -1);
1127 obj[rel] = url;
1128 return obj;
1129 }, {});
1130 };
1131 /**
1132 * Strip content related fields from `header`.
1133 *
1134 * @param {Object} header
1135 * @return {Object} header
1136 * @api private
1137 */
1138
1139 var cleanHeader = function cleanHeader(header, changesOrigin) {
1140 delete header['content-type'];
1141 delete header['content-length'];
1142 delete header['transfer-encoding'];
1143 delete header.host; // secuirty
1144
1145 if (changesOrigin) {
1146 delete header.authorization;
1147 delete header.cookie;
1148 }
1149 return header;
1150 };
1151 var utils = {
1152 type: type,
1153 params: params,
1154 parseLinks: parseLinks,
1155 cleanHeader: cleanHeader
1156 };
1157
1158 /**
1159 * Module dependencies.
1160 */
1161
1162 /**
1163 * Expose `ResponseBase`.
1164 */
1165
1166 var responseBase = ResponseBase;
1167 /**
1168 * Initialize a new `ResponseBase`.
1169 *
1170 * @api public
1171 */
1172
1173 function ResponseBase(obj) {
1174 if (obj) return mixin$1(obj);
1175 }
1176 /**
1177 * Mixin the prototype properties.
1178 *
1179 * @param {Object} obj
1180 * @return {Object}
1181 * @api private
1182 */
1183
1184 function mixin$1(obj) {
1185 for (var key in ResponseBase.prototype) {
1186 if (Object.prototype.hasOwnProperty.call(ResponseBase.prototype, key)) obj[key] = ResponseBase.prototype[key];
1187 }
1188 return obj;
1189 }
1190 /**
1191 * Get case-insensitive `field` value.
1192 *
1193 * @param {String} field
1194 * @return {String}
1195 * @api public
1196 */
1197
1198 ResponseBase.prototype.get = function (field) {
1199 return this.header[field.toLowerCase()];
1200 };
1201 /**
1202 * Set header related properties:
1203 *
1204 * - `.type` the content type without params
1205 *
1206 * A response of "Content-Type: text/plain; charset=utf-8"
1207 * will provide you with a `.type` of "text/plain".
1208 *
1209 * @param {Object} header
1210 * @api private
1211 */
1212
1213 ResponseBase.prototype._setHeaderProperties = function (header) {
1214 // TODO: moar!
1215 // TODO: make this a util
1216 // content-type
1217 var ct = header['content-type'] || '';
1218 this.type = utils.type(ct); // params
1219
1220 var params = utils.params(ct);
1221 for (var key in params) {
1222 if (Object.prototype.hasOwnProperty.call(params, key)) this[key] = params[key];
1223 }
1224 this.links = {}; // links
1225
1226 try {
1227 if (header.link) {
1228 this.links = utils.parseLinks(header.link);
1229 }
1230 } catch (_unused) {// ignore
1231 }
1232 };
1233 /**
1234 * Set flags such as `.ok` based on `status`.
1235 *
1236 * For example a 2xx response will give you a `.ok` of __true__
1237 * whereas 5xx will be __false__ and `.error` will be __true__. The
1238 * `.clientError` and `.serverError` are also available to be more
1239 * specific, and `.statusType` is the class of error ranging from 1..5
1240 * sometimes useful for mapping respond colors etc.
1241 *
1242 * "sugar" properties are also defined for common cases. Currently providing:
1243 *
1244 * - .noContent
1245 * - .badRequest
1246 * - .unauthorized
1247 * - .notAcceptable
1248 * - .notFound
1249 *
1250 * @param {Number} status
1251 * @api private
1252 */
1253
1254 ResponseBase.prototype._setStatusProperties = function (status) {
1255 var type = status / 100 | 0; // status / class
1256
1257 this.statusCode = status;
1258 this.status = this.statusCode;
1259 this.statusType = type; // basics
1260
1261 this.info = type === 1;
1262 this.ok = type === 2;
1263 this.redirect = type === 3;
1264 this.clientError = type === 4;
1265 this.serverError = type === 5;
1266 this.error = type === 4 || type === 5 ? this.toError() : false; // sugar
1267
1268 this.created = status === 201;
1269 this.accepted = status === 202;
1270 this.noContent = status === 204;
1271 this.badRequest = status === 400;
1272 this.unauthorized = status === 401;
1273 this.notAcceptable = status === 406;
1274 this.forbidden = status === 403;
1275 this.notFound = status === 404;
1276 this.unprocessableEntity = status === 422;
1277 };
1278
1279 function _toConsumableArray(arr) {
1280 return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread();
1281 }
1282 function _nonIterableSpread() {
1283 throw new TypeError("Invalid attempt to spread non-iterable instance");
1284 }
1285 function _iterableToArray(iter) {
1286 if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter);
1287 }
1288 function _arrayWithoutHoles(arr) {
1289 if (Array.isArray(arr)) {
1290 for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) {
1291 arr2[i] = arr[i];
1292 }
1293 return arr2;
1294 }
1295 }
1296 function Agent() {
1297 this._defaults = [];
1298 }
1299 ['use', 'on', 'once', 'set', 'query', 'type', 'accept', 'auth', 'withCredentials', 'sortQuery', 'retry', 'ok', 'redirects', 'timeout', 'buffer', 'serialize', 'parse', 'ca', 'key', 'pfx', 'cert', 'disableTLSCerts'].forEach(function (fn) {
1300 // Default setting for all requests from this agent
1301 Agent.prototype[fn] = function () {
1302 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
1303 args[_key] = arguments[_key];
1304 }
1305 this._defaults.push({
1306 fn: fn,
1307 args: args
1308 });
1309 return this;
1310 };
1311 });
1312 Agent.prototype._setDefaults = function (req) {
1313 this._defaults.forEach(function (def) {
1314 req[def.fn].apply(req, _toConsumableArray(def.args));
1315 });
1316 };
1317 var agentBase = Agent;
1318
1319 var client = createCommonjsModule(function (module, exports) {
1320
1321 function _typeof$1(obj) {
1322 if (typeof Symbol === "function" && _typeof(Symbol.iterator) === "symbol") {
1323 _typeof$1 = function _typeof$1(obj) {
1324 return _typeof(obj);
1325 };
1326 } else {
1327 _typeof$1 = function _typeof$1(obj) {
1328 return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : _typeof(obj);
1329 };
1330 }
1331 return _typeof$1(obj);
1332 }
1333
1334 /**
1335 * Root reference for iframes.
1336 */
1337 var root;
1338 if (typeof window !== 'undefined') {
1339 // Browser window
1340 root = window;
1341 } else if (typeof self === 'undefined') {
1342 // Other environments
1343 console.warn('Using browser-only version of superagent in non-browser environment');
1344 root = void 0;
1345 } else {
1346 // Web Worker
1347 root = self;
1348 }
1349
1350 /**
1351 * Noop.
1352 */
1353
1354 function noop() {}
1355 /**
1356 * Expose `request`.
1357 */
1358
1359 module.exports = function (method, url) {
1360 // callback
1361 if (typeof url === 'function') {
1362 return new exports.Request('GET', method).end(url);
1363 } // url first
1364
1365 if (arguments.length === 1) {
1366 return new exports.Request('GET', method);
1367 }
1368 return new exports.Request(method, url);
1369 };
1370 exports = module.exports;
1371 var request = exports;
1372 exports.Request = Request;
1373 /**
1374 * Determine XHR.
1375 */
1376
1377 request.getXHR = function () {
1378 if (root.XMLHttpRequest && (!root.location || root.location.protocol !== 'file:' || !root.ActiveXObject)) {
1379 return new XMLHttpRequest();
1380 }
1381 try {
1382 return new ActiveXObject('Microsoft.XMLHTTP');
1383 } catch (_unused) {}
1384 try {
1385 return new ActiveXObject('Msxml2.XMLHTTP.6.0');
1386 } catch (_unused2) {}
1387 try {
1388 return new ActiveXObject('Msxml2.XMLHTTP.3.0');
1389 } catch (_unused3) {}
1390 try {
1391 return new ActiveXObject('Msxml2.XMLHTTP');
1392 } catch (_unused4) {}
1393 throw new Error('Browser-only version of superagent could not find XHR');
1394 };
1395 /**
1396 * Removes leading and trailing whitespace, added to support IE.
1397 *
1398 * @param {String} s
1399 * @return {String}
1400 * @api private
1401 */
1402
1403 var trim = ''.trim ? function (s) {
1404 return s.trim();
1405 } : function (s) {
1406 return s.replace(/(^\s*|\s*$)/g, '');
1407 };
1408 /**
1409 * Serialize the given `obj`.
1410 *
1411 * @param {Object} obj
1412 * @return {String}
1413 * @api private
1414 */
1415
1416 function serialize(obj) {
1417 if (!isObject_1(obj)) return obj;
1418 var pairs = [];
1419 for (var key in obj) {
1420 if (Object.prototype.hasOwnProperty.call(obj, key)) pushEncodedKeyValuePair(pairs, key, obj[key]);
1421 }
1422 return pairs.join('&');
1423 }
1424 /**
1425 * Helps 'serialize' with serializing arrays.
1426 * Mutates the pairs array.
1427 *
1428 * @param {Array} pairs
1429 * @param {String} key
1430 * @param {Mixed} val
1431 */
1432
1433 function pushEncodedKeyValuePair(pairs, key, val) {
1434 if (val === undefined) return;
1435 if (val === null) {
1436 pairs.push(encodeURI(key));
1437 return;
1438 }
1439 if (Array.isArray(val)) {
1440 val.forEach(function (v) {
1441 pushEncodedKeyValuePair(pairs, key, v);
1442 });
1443 } else if (isObject_1(val)) {
1444 for (var subkey in val) {
1445 if (Object.prototype.hasOwnProperty.call(val, subkey)) pushEncodedKeyValuePair(pairs, "".concat(key, "[").concat(subkey, "]"), val[subkey]);
1446 }
1447 } else {
1448 pairs.push(encodeURI(key) + '=' + encodeURIComponent(val));
1449 }
1450 }
1451 /**
1452 * Expose serialization method.
1453 */
1454
1455 request.serializeObject = serialize;
1456 /**
1457 * Parse the given x-www-form-urlencoded `str`.
1458 *
1459 * @param {String} str
1460 * @return {Object}
1461 * @api private
1462 */
1463
1464 function parseString(str) {
1465 var obj = {};
1466 var pairs = str.split('&');
1467 var pair;
1468 var pos;
1469 for (var i = 0, len = pairs.length; i < len; ++i) {
1470 pair = pairs[i];
1471 pos = pair.indexOf('=');
1472 if (pos === -1) {
1473 obj[decodeURIComponent(pair)] = '';
1474 } else {
1475 obj[decodeURIComponent(pair.slice(0, pos))] = decodeURIComponent(pair.slice(pos + 1));
1476 }
1477 }
1478 return obj;
1479 }
1480 /**
1481 * Expose parser.
1482 */
1483
1484 request.parseString = parseString;
1485 /**
1486 * Default MIME type map.
1487 *
1488 * superagent.types.xml = 'application/xml';
1489 *
1490 */
1491
1492 request.types = {
1493 html: 'text/html',
1494 json: 'application/json',
1495 xml: 'text/xml',
1496 urlencoded: 'application/x-www-form-urlencoded',
1497 form: 'application/x-www-form-urlencoded',
1498 'form-data': 'application/x-www-form-urlencoded'
1499 };
1500 /**
1501 * Default serialization map.
1502 *
1503 * superagent.serialize['application/xml'] = function(obj){
1504 * return 'generated xml here';
1505 * };
1506 *
1507 */
1508
1509 request.serialize = {
1510 'application/x-www-form-urlencoded': serialize,
1511 'application/json': fastSafeStringify
1512 };
1513 /**
1514 * Default parsers.
1515 *
1516 * superagent.parse['application/xml'] = function(str){
1517 * return { object parsed from str };
1518 * };
1519 *
1520 */
1521
1522 request.parse = {
1523 'application/x-www-form-urlencoded': parseString,
1524 'application/json': JSON.parse
1525 };
1526 /**
1527 * Parse the given header `str` into
1528 * an object containing the mapped fields.
1529 *
1530 * @param {String} str
1531 * @return {Object}
1532 * @api private
1533 */
1534
1535 function parseHeader(str) {
1536 var lines = str.split(/\r?\n/);
1537 var fields = {};
1538 var index;
1539 var line;
1540 var field;
1541 var val;
1542 for (var i = 0, len = lines.length; i < len; ++i) {
1543 line = lines[i];
1544 index = line.indexOf(':');
1545 if (index === -1) {
1546 // could be empty line, just skip it
1547 continue;
1548 }
1549 field = line.slice(0, index).toLowerCase();
1550 val = trim(line.slice(index + 1));
1551 fields[field] = val;
1552 }
1553 return fields;
1554 }
1555 /**
1556 * Check if `mime` is json or has +json structured syntax suffix.
1557 *
1558 * @param {String} mime
1559 * @return {Boolean}
1560 * @api private
1561 */
1562
1563 function isJSON(mime) {
1564 // should match /json or +json
1565 // but not /json-seq
1566 return /[/+]json($|[^-\w])/.test(mime);
1567 }
1568 /**
1569 * Initialize a new `Response` with the given `xhr`.
1570 *
1571 * - set flags (.ok, .error, etc)
1572 * - parse header
1573 *
1574 * Examples:
1575 *
1576 * Aliasing `superagent` as `request` is nice:
1577 *
1578 * request = superagent;
1579 *
1580 * We can use the promise-like API, or pass callbacks:
1581 *
1582 * request.get('/').end(function(res){});
1583 * request.get('/', function(res){});
1584 *
1585 * Sending data can be chained:
1586 *
1587 * request
1588 * .post('/user')
1589 * .send({ name: 'tj' })
1590 * .end(function(res){});
1591 *
1592 * Or passed to `.send()`:
1593 *
1594 * request
1595 * .post('/user')
1596 * .send({ name: 'tj' }, function(res){});
1597 *
1598 * Or passed to `.post()`:
1599 *
1600 * request
1601 * .post('/user', { name: 'tj' })
1602 * .end(function(res){});
1603 *
1604 * Or further reduced to a single call for simple cases:
1605 *
1606 * request
1607 * .post('/user', { name: 'tj' }, function(res){});
1608 *
1609 * @param {XMLHTTPRequest} xhr
1610 * @param {Object} options
1611 * @api private
1612 */
1613
1614 function Response(req) {
1615 this.req = req;
1616 this.xhr = this.req.xhr; // responseText is accessible only if responseType is '' or 'text' and on older browsers
1617
1618 this.text = this.req.method !== 'HEAD' && (this.xhr.responseType === '' || this.xhr.responseType === 'text') || typeof this.xhr.responseType === 'undefined' ? this.xhr.responseText : null;
1619 this.statusText = this.req.xhr.statusText;
1620 var status = this.xhr.status; // handle IE9 bug: http://stackoverflow.com/questions/10046972/msie-returns-status-code-of-1223-for-ajax-request
1621
1622 if (status === 1223) {
1623 status = 204;
1624 }
1625 this._setStatusProperties(status);
1626 this.headers = parseHeader(this.xhr.getAllResponseHeaders());
1627 this.header = this.headers; // getAllResponseHeaders sometimes falsely returns "" for CORS requests, but
1628 // getResponseHeader still works. so we get content-type even if getting
1629 // other headers fails.
1630
1631 this.header['content-type'] = this.xhr.getResponseHeader('content-type');
1632 this._setHeaderProperties(this.header);
1633 if (this.text === null && req._responseType) {
1634 this.body = this.xhr.response;
1635 } else {
1636 this.body = this.req.method === 'HEAD' ? null : this._parseBody(this.text ? this.text : this.xhr.response);
1637 }
1638 } // eslint-disable-next-line new-cap
1639
1640 responseBase(Response.prototype);
1641 /**
1642 * Parse the given body `str`.
1643 *
1644 * Used for auto-parsing of bodies. Parsers
1645 * are defined on the `superagent.parse` object.
1646 *
1647 * @param {String} str
1648 * @return {Mixed}
1649 * @api private
1650 */
1651
1652 Response.prototype._parseBody = function (str) {
1653 var parse = request.parse[this.type];
1654 if (this.req._parser) {
1655 return this.req._parser(this, str);
1656 }
1657 if (!parse && isJSON(this.type)) {
1658 parse = request.parse['application/json'];
1659 }
1660 return parse && str && (str.length > 0 || str instanceof Object) ? parse(str) : null;
1661 };
1662 /**
1663 * Return an `Error` representative of this response.
1664 *
1665 * @return {Error}
1666 * @api public
1667 */
1668
1669 Response.prototype.toError = function () {
1670 var req = this.req;
1671 var method = req.method;
1672 var url = req.url;
1673 var msg = "cannot ".concat(method, " ").concat(url, " (").concat(this.status, ")");
1674 var err = new Error(msg);
1675 err.status = this.status;
1676 err.method = method;
1677 err.url = url;
1678 return err;
1679 };
1680 /**
1681 * Expose `Response`.
1682 */
1683
1684 request.Response = Response;
1685 /**
1686 * Initialize a new `Request` with the given `method` and `url`.
1687 *
1688 * @param {String} method
1689 * @param {String} url
1690 * @api public
1691 */
1692
1693 function Request(method, url) {
1694 var self = this;
1695 this._query = this._query || [];
1696 this.method = method;
1697 this.url = url;
1698 this.header = {}; // preserves header name case
1699
1700 this._header = {}; // coerces header names to lowercase
1701
1702 this.on('end', function () {
1703 var err = null;
1704 var res = null;
1705 try {
1706 res = new Response(self);
1707 } catch (err_) {
1708 err = new Error('Parser is unable to parse the response');
1709 err.parse = true;
1710 err.original = err_; // issue #675: return the raw response if the response parsing fails
1711
1712 if (self.xhr) {
1713 // ie9 doesn't have 'response' property
1714 err.rawResponse = typeof self.xhr.responseType === 'undefined' ? self.xhr.responseText : self.xhr.response; // issue #876: return the http status code if the response parsing fails
1715
1716 err.status = self.xhr.status ? self.xhr.status : null;
1717 err.statusCode = err.status; // backwards-compat only
1718 } else {
1719 err.rawResponse = null;
1720 err.status = null;
1721 }
1722 return self.callback(err);
1723 }
1724 self.emit('response', res);
1725 var new_err;
1726 try {
1727 if (!self._isResponseOK(res)) {
1728 new_err = new Error(res.statusText || res.text || 'Unsuccessful HTTP response');
1729 }
1730 } catch (err_) {
1731 new_err = err_; // ok() callback can throw
1732 } // #1000 don't catch errors from the callback to avoid double calling it
1733
1734 if (new_err) {
1735 new_err.original = err;
1736 new_err.response = res;
1737 new_err.status = res.status;
1738 self.callback(new_err, res);
1739 } else {
1740 self.callback(null, res);
1741 }
1742 });
1743 }
1744 /**
1745 * Mixin `Emitter` and `RequestBase`.
1746 */
1747 // eslint-disable-next-line new-cap
1748
1749 componentEmitter(Request.prototype); // eslint-disable-next-line new-cap
1750
1751 requestBase(Request.prototype);
1752 /**
1753 * Set Content-Type to `type`, mapping values from `request.types`.
1754 *
1755 * Examples:
1756 *
1757 * superagent.types.xml = 'application/xml';
1758 *
1759 * request.post('/')
1760 * .type('xml')
1761 * .send(xmlstring)
1762 * .end(callback);
1763 *
1764 * request.post('/')
1765 * .type('application/xml')
1766 * .send(xmlstring)
1767 * .end(callback);
1768 *
1769 * @param {String} type
1770 * @return {Request} for chaining
1771 * @api public
1772 */
1773
1774 Request.prototype.type = function (type) {
1775 this.set('Content-Type', request.types[type] || type);
1776 return this;
1777 };
1778 /**
1779 * Set Accept to `type`, mapping values from `request.types`.
1780 *
1781 * Examples:
1782 *
1783 * superagent.types.json = 'application/json';
1784 *
1785 * request.get('/agent')
1786 * .accept('json')
1787 * .end(callback);
1788 *
1789 * request.get('/agent')
1790 * .accept('application/json')
1791 * .end(callback);
1792 *
1793 * @param {String} accept
1794 * @return {Request} for chaining
1795 * @api public
1796 */
1797
1798 Request.prototype.accept = function (type) {
1799 this.set('Accept', request.types[type] || type);
1800 return this;
1801 };
1802 /**
1803 * Set Authorization field value with `user` and `pass`.
1804 *
1805 * @param {String} user
1806 * @param {String} [pass] optional in case of using 'bearer' as type
1807 * @param {Object} options with 'type' property 'auto', 'basic' or 'bearer' (default 'basic')
1808 * @return {Request} for chaining
1809 * @api public
1810 */
1811
1812 Request.prototype.auth = function (user, pass, options) {
1813 if (arguments.length === 1) pass = '';
1814 if (_typeof$1(pass) === 'object' && pass !== null) {
1815 // pass is optional and can be replaced with options
1816 options = pass;
1817 pass = '';
1818 }
1819 if (!options) {
1820 options = {
1821 type: typeof btoa === 'function' ? 'basic' : 'auto'
1822 };
1823 }
1824 var encoder = function encoder(string) {
1825 if (typeof btoa === 'function') {
1826 return btoa(string);
1827 }
1828 throw new Error('Cannot use basic auth, btoa is not a function');
1829 };
1830 return this._auth(user, pass, options, encoder);
1831 };
1832 /**
1833 * Add query-string `val`.
1834 *
1835 * Examples:
1836 *
1837 * request.get('/shoes')
1838 * .query('size=10')
1839 * .query({ color: 'blue' })
1840 *
1841 * @param {Object|String} val
1842 * @return {Request} for chaining
1843 * @api public
1844 */
1845
1846 Request.prototype.query = function (val) {
1847 if (typeof val !== 'string') val = serialize(val);
1848 if (val) this._query.push(val);
1849 return this;
1850 };
1851 /**
1852 * Queue the given `file` as an attachment to the specified `field`,
1853 * with optional `options` (or filename).
1854 *
1855 * ``` js
1856 * request.post('/upload')
1857 * .attach('content', new Blob(['<a id="a"><b id="b">hey!</b></a>'], { type: "text/html"}))
1858 * .end(callback);
1859 * ```
1860 *
1861 * @param {String} field
1862 * @param {Blob|File} file
1863 * @param {String|Object} options
1864 * @return {Request} for chaining
1865 * @api public
1866 */
1867
1868 Request.prototype.attach = function (field, file, options) {
1869 if (file) {
1870 if (this._data) {
1871 throw new Error("superagent can't mix .send() and .attach()");
1872 }
1873 this._getFormData().append(field, file, options || file.name);
1874 }
1875 return this;
1876 };
1877 Request.prototype._getFormData = function () {
1878 if (!this._formData) {
1879 this._formData = new root.FormData();
1880 }
1881 return this._formData;
1882 };
1883 /**
1884 * Invoke the callback with `err` and `res`
1885 * and handle arity check.
1886 *
1887 * @param {Error} err
1888 * @param {Response} res
1889 * @api private
1890 */
1891
1892 Request.prototype.callback = function (err, res) {
1893 if (this._shouldRetry(err, res)) {
1894 return this._retry();
1895 }
1896 var fn = this._callback;
1897 this.clearTimeout();
1898 if (err) {
1899 if (this._maxRetries) err.retries = this._retries - 1;
1900 this.emit('error', err);
1901 }
1902 fn(err, res);
1903 };
1904 /**
1905 * Invoke callback with x-domain error.
1906 *
1907 * @api private
1908 */
1909
1910 Request.prototype.crossDomainError = function () {
1911 var err = new Error('Request has been terminated\nPossible causes: the network is offline, Origin is not allowed by Access-Control-Allow-Origin, the page is being unloaded, etc.');
1912 err.crossDomain = true;
1913 err.status = this.status;
1914 err.method = this.method;
1915 err.url = this.url;
1916 this.callback(err);
1917 }; // This only warns, because the request is still likely to work
1918
1919 Request.prototype.agent = function () {
1920 console.warn('This is not supported in browser version of superagent');
1921 return this;
1922 };
1923 Request.prototype.ca = Request.prototype.agent;
1924 Request.prototype.buffer = Request.prototype.ca; // This throws, because it can't send/receive data as expected
1925
1926 Request.prototype.write = function () {
1927 throw new Error('Streaming is not supported in browser version of superagent');
1928 };
1929 Request.prototype.pipe = Request.prototype.write;
1930 /**
1931 * Check if `obj` is a host object,
1932 * we don't want to serialize these :)
1933 *
1934 * @param {Object} obj host object
1935 * @return {Boolean} is a host object
1936 * @api private
1937 */
1938
1939 Request.prototype._isHost = function (obj) {
1940 // Native objects stringify to [object File], [object Blob], [object FormData], etc.
1941 return obj && _typeof$1(obj) === 'object' && !Array.isArray(obj) && Object.prototype.toString.call(obj) !== '[object Object]';
1942 };
1943 /**
1944 * Initiate request, invoking callback `fn(res)`
1945 * with an instanceof `Response`.
1946 *
1947 * @param {Function} fn
1948 * @return {Request} for chaining
1949 * @api public
1950 */
1951
1952 Request.prototype.end = function (fn) {
1953 if (this._endCalled) {
1954 console.warn('Warning: .end() was called twice. This is not supported in superagent');
1955 }
1956 this._endCalled = true; // store callback
1957
1958 this._callback = fn || noop; // querystring
1959
1960 this._finalizeQueryString();
1961 this._end();
1962 };
1963 Request.prototype._setUploadTimeout = function () {
1964 var self = this; // upload timeout it's wokrs only if deadline timeout is off
1965
1966 if (this._uploadTimeout && !this._uploadTimeoutTimer) {
1967 this._uploadTimeoutTimer = setTimeout(function () {
1968 self._timeoutError('Upload timeout of ', self._uploadTimeout, 'ETIMEDOUT');
1969 }, this._uploadTimeout);
1970 }
1971 }; // eslint-disable-next-line complexity
1972
1973 Request.prototype._end = function () {
1974 if (this._aborted) return this.callback(new Error('The request has been aborted even before .end() was called'));
1975 var self = this;
1976 this.xhr = request.getXHR();
1977 var xhr = this.xhr;
1978 var data = this._formData || this._data;
1979 this._setTimeouts(); // state change
1980
1981 xhr.onreadystatechange = function () {
1982 var readyState = xhr.readyState;
1983 if (readyState >= 2 && self._responseTimeoutTimer) {
1984 clearTimeout(self._responseTimeoutTimer);
1985 }
1986 if (readyState !== 4) {
1987 return;
1988 } // In IE9, reads to any property (e.g. status) off of an aborted XHR will
1989 // result in the error "Could not complete the operation due to error c00c023f"
1990
1991 var status;
1992 try {
1993 status = xhr.status;
1994 } catch (_unused5) {
1995 status = 0;
1996 }
1997 if (!status) {
1998 if (self.timedout || self._aborted) return;
1999 return self.crossDomainError();
2000 }
2001 self.emit('end');
2002 }; // progress
2003
2004 var handleProgress = function handleProgress(direction, e) {
2005 if (e.total > 0) {
2006 e.percent = e.loaded / e.total * 100;
2007 if (e.percent === 100) {
2008 clearTimeout(self._uploadTimeoutTimer);
2009 }
2010 }
2011 e.direction = direction;
2012 self.emit('progress', e);
2013 };
2014 if (this.hasListeners('progress')) {
2015 try {
2016 xhr.addEventListener('progress', handleProgress.bind(null, 'download'));
2017 if (xhr.upload) {
2018 xhr.upload.addEventListener('progress', handleProgress.bind(null, 'upload'));
2019 }
2020 } catch (_unused6) {// Accessing xhr.upload fails in IE from a web worker, so just pretend it doesn't exist.
2021 // Reported here:
2022 // https://connect.microsoft.com/IE/feedback/details/837245/xmlhttprequest-upload-throws-invalid-argument-when-used-from-web-worker-context
2023 }
2024 }
2025 if (xhr.upload) {
2026 this._setUploadTimeout();
2027 } // initiate request
2028
2029 try {
2030 if (this.username && this.password) {
2031 xhr.open(this.method, this.url, true, this.username, this.password);
2032 } else {
2033 xhr.open(this.method, this.url, true);
2034 }
2035 } catch (err) {
2036 // see #1149
2037 return this.callback(err);
2038 } // CORS
2039
2040 if (this._withCredentials) xhr.withCredentials = true; // body
2041
2042 if (!this._formData && this.method !== 'GET' && this.method !== 'HEAD' && typeof data !== 'string' && !this._isHost(data)) {
2043 // serialize stuff
2044 var contentType = this._header['content-type'];
2045 var _serialize = this._serializer || request.serialize[contentType ? contentType.split(';')[0] : ''];
2046 if (!_serialize && isJSON(contentType)) {
2047 _serialize = request.serialize['application/json'];
2048 }
2049 if (_serialize) data = _serialize(data);
2050 } // set header fields
2051
2052 for (var field in this.header) {
2053 if (this.header[field] === null) continue;
2054 if (Object.prototype.hasOwnProperty.call(this.header, field)) xhr.setRequestHeader(field, this.header[field]);
2055 }
2056 if (this._responseType) {
2057 xhr.responseType = this._responseType;
2058 } // send stuff
2059
2060 this.emit('request', this); // IE11 xhr.send(undefined) sends 'undefined' string as POST payload (instead of nothing)
2061 // We need null here if data is undefined
2062
2063 xhr.send(typeof data === 'undefined' ? null : data);
2064 };
2065 request.agent = function () {
2066 return new agentBase();
2067 };
2068 ['GET', 'POST', 'OPTIONS', 'PATCH', 'PUT', 'DELETE'].forEach(function (method) {
2069 agentBase.prototype[method.toLowerCase()] = function (url, fn) {
2070 var req = new request.Request(method, url);
2071 this._setDefaults(req);
2072 if (fn) {
2073 req.end(fn);
2074 }
2075 return req;
2076 };
2077 });
2078 agentBase.prototype.del = agentBase.prototype["delete"];
2079 /**
2080 * GET `url` with optional callback `fn(res)`.
2081 *
2082 * @param {String} url
2083 * @param {Mixed|Function} [data] or fn
2084 * @param {Function} [fn]
2085 * @return {Request}
2086 * @api public
2087 */
2088
2089 request.get = function (url, data, fn) {
2090 var req = request('GET', url);
2091 if (typeof data === 'function') {
2092 fn = data;
2093 data = null;
2094 }
2095 if (data) req.query(data);
2096 if (fn) req.end(fn);
2097 return req;
2098 };
2099 /**
2100 * HEAD `url` with optional callback `fn(res)`.
2101 *
2102 * @param {String} url
2103 * @param {Mixed|Function} [data] or fn
2104 * @param {Function} [fn]
2105 * @return {Request}
2106 * @api public
2107 */
2108
2109 request.head = function (url, data, fn) {
2110 var req = request('HEAD', url);
2111 if (typeof data === 'function') {
2112 fn = data;
2113 data = null;
2114 }
2115 if (data) req.query(data);
2116 if (fn) req.end(fn);
2117 return req;
2118 };
2119 /**
2120 * OPTIONS query to `url` with optional callback `fn(res)`.
2121 *
2122 * @param {String} url
2123 * @param {Mixed|Function} [data] or fn
2124 * @param {Function} [fn]
2125 * @return {Request}
2126 * @api public
2127 */
2128
2129 request.options = function (url, data, fn) {
2130 var req = request('OPTIONS', url);
2131 if (typeof data === 'function') {
2132 fn = data;
2133 data = null;
2134 }
2135 if (data) req.send(data);
2136 if (fn) req.end(fn);
2137 return req;
2138 };
2139 /**
2140 * DELETE `url` with optional `data` and callback `fn(res)`.
2141 *
2142 * @param {String} url
2143 * @param {Mixed} [data]
2144 * @param {Function} [fn]
2145 * @return {Request}
2146 * @api public
2147 */
2148
2149 function del(url, data, fn) {
2150 var req = request('DELETE', url);
2151 if (typeof data === 'function') {
2152 fn = data;
2153 data = null;
2154 }
2155 if (data) req.send(data);
2156 if (fn) req.end(fn);
2157 return req;
2158 }
2159 request.del = del;
2160 request["delete"] = del;
2161 /**
2162 * PATCH `url` with optional `data` and callback `fn(res)`.
2163 *
2164 * @param {String} url
2165 * @param {Mixed} [data]
2166 * @param {Function} [fn]
2167 * @return {Request}
2168 * @api public
2169 */
2170
2171 request.patch = function (url, data, fn) {
2172 var req = request('PATCH', url);
2173 if (typeof data === 'function') {
2174 fn = data;
2175 data = null;
2176 }
2177 if (data) req.send(data);
2178 if (fn) req.end(fn);
2179 return req;
2180 };
2181 /**
2182 * POST `url` with optional `data` and callback `fn(res)`.
2183 *
2184 * @param {String} url
2185 * @param {Mixed} [data]
2186 * @param {Function} [fn]
2187 * @return {Request}
2188 * @api public
2189 */
2190
2191 request.post = function (url, data, fn) {
2192 var req = request('POST', url);
2193 if (typeof data === 'function') {
2194 fn = data;
2195 data = null;
2196 }
2197 if (data) req.send(data);
2198 if (fn) req.end(fn);
2199 return req;
2200 };
2201 /**
2202 * PUT `url` with optional `data` and callback `fn(res)`.
2203 *
2204 * @param {String} url
2205 * @param {Mixed|Function} [data] or fn
2206 * @param {Function} [fn]
2207 * @return {Request}
2208 * @api public
2209 */
2210
2211 request.put = function (url, data, fn) {
2212 var req = request('PUT', url);
2213 if (typeof data === 'function') {
2214 fn = data;
2215 data = null;
2216 }
2217 if (data) req.send(data);
2218 if (fn) req.end(fn);
2219 return req;
2220 };
2221 });
2222 var client_1 = client.Request;
2223
2224 var lib = createCommonjsModule(function (module, exports) {
2225 Object.defineProperty(exports, "__esModule", { value: true });
2226
2227 exports.request = function (url, options) {
2228 if (options === void 0) { options = {}; }
2229 var _a = options.method, method = _a === void 0 ? "GET" : _a, data = options.data, headers = options.headers, onprogress = options.onprogress;
2230 var req = client(method, url);
2231 if (headers) {
2232 req.set(headers);
2233 }
2234 if (onprogress) {
2235 req.on("progress", onprogress);
2236 }
2237 return req
2238 .send(data)
2239 .catch(function (error) {
2240 if (error.response) {
2241 return error.response;
2242 }
2243 throw error;
2244 })
2245 .then(function (_a) {
2246 var status = _a.status, ok = _a.ok, header = _a.header, body = _a.body;
2247 return ({
2248 status: status,
2249 ok: ok,
2250 headers: header,
2251 data: body
2252 });
2253 });
2254 };
2255 exports.upload = function (url, file, options) {
2256 if (options === void 0) { options = {}; }
2257 var data = options.data, headers = options.headers, onprogress = options.onprogress;
2258 var req = client("POST", url).attach(file.field, file.data, file.name);
2259 if (data) {
2260 req.field(data);
2261 }
2262 if (headers) {
2263 req.set(headers);
2264 }
2265 if (onprogress) {
2266 req.on("progress", onprogress);
2267 }
2268 return req
2269 .catch(function (error) {
2270 if (error.response) {
2271 return error.response;
2272 }
2273 throw error;
2274 })
2275 .then(function (_a) {
2276 var status = _a.status, ok = _a.ok, header = _a.header, body = _a.body;
2277 return ({
2278 status: status,
2279 ok: ok,
2280 headers: header,
2281 data: body
2282 });
2283 });
2284 };
2285
2286 });
2287
2288 unwrapExports(lib);
2289 var lib_1 = lib.request;
2290 var lib_2 = lib.upload;
2291
2292 var lib$1 = createCommonjsModule(function (module, exports) {
2293
2294 Object.defineProperty(exports, "__esModule", {
2295 value: true
2296 });
2297 exports.request = lib.request;
2298 exports.upload = lib.upload;
2299 exports.storage = window.localStorage;
2300 exports.WebSocket = window.WebSocket;
2301 exports.platformInfo = {
2302 name: "Browser"
2303 };
2304 });
2305 unwrapExports(lib$1);
2306 var lib_1$1 = lib$1.request;
2307 var lib_2$1 = lib$1.upload;
2308 var lib_3 = lib$1.storage;
2309 var lib_4 = lib$1.WebSocket;
2310 var lib_5 = lib$1.platformInfo;
2311
2312 var toPrimitive = createCommonjsModule(function (module) {
2313 var _typeof = _typeof_1["default"];
2314 function _toPrimitive(input, hint) {
2315 if (_typeof(input) !== "object" || input === null) return input;
2316 var prim = input[Symbol.toPrimitive];
2317 if (prim !== undefined) {
2318 var res = prim.call(input, hint || "default");
2319 if (_typeof(res) !== "object") return res;
2320 throw new TypeError("@@toPrimitive must return a primitive value.");
2321 }
2322 return (hint === "string" ? String : Number)(input);
2323 }
2324 module.exports = _toPrimitive, module.exports.__esModule = true, module.exports["default"] = module.exports;
2325 });
2326
2327 unwrapExports(toPrimitive);
2328
2329 var toPropertyKey = createCommonjsModule(function (module) {
2330 var _typeof = _typeof_1["default"];
2331
2332 function _toPropertyKey(arg) {
2333 var key = toPrimitive(arg, "string");
2334 return _typeof(key) === "symbol" ? key : String(key);
2335 }
2336 module.exports = _toPropertyKey, module.exports.__esModule = true, module.exports["default"] = module.exports;
2337 });
2338
2339 unwrapExports(toPropertyKey);
2340
2341 var defineProperty = createCommonjsModule(function (module) {
2342 function _defineProperty(obj, key, value) {
2343 key = toPropertyKey(key);
2344 if (key in obj) {
2345 Object.defineProperty(obj, key, {
2346 value: value,
2347 enumerable: true,
2348 configurable: true,
2349 writable: true
2350 });
2351 } else {
2352 obj[key] = value;
2353 }
2354 return obj;
2355 }
2356 module.exports = _defineProperty, module.exports.__esModule = true, module.exports["default"] = module.exports;
2357 });
2358
2359 var _defineProperty = unwrapExports(defineProperty);
2360
2361 var long_1 = createCommonjsModule(function (module) {
2362 /*
2363 Copyright 2013 Daniel Wirtz <dcode@dcode.io>
2364 Copyright 2009 The Closure Library Authors. All Rights Reserved.
2365
2366 Licensed under the Apache License, Version 2.0 (the "License");
2367 you may not use this file except in compliance with the License.
2368 You may obtain a copy of the License at
2369
2370 http://www.apache.org/licenses/LICENSE-2.0
2371
2372 Unless required by applicable law or agreed to in writing, software
2373 distributed under the License is distributed on an "AS-IS" BASIS,
2374 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2375 See the License for the specific language governing permissions and
2376 limitations under the License.
2377 */
2378
2379 /**
2380 * @license long.js (c) 2013 Daniel Wirtz <dcode@dcode.io>
2381 * Released under the Apache License, Version 2.0
2382 * see: https://github.com/dcodeIO/long.js for details
2383 */
2384 (function(global, factory) {
2385
2386 /* AMD */ if (typeof commonjsRequire === 'function' && 'object' === "object" && module && module["exports"])
2387 module["exports"] = factory();
2388 /* Global */ else
2389 (global["dcodeIO"] = global["dcodeIO"] || {})["Long"] = factory();
2390
2391 })(commonjsGlobal, function() {
2392
2393 /**
2394 * Constructs a 64 bit two's-complement integer, given its low and high 32 bit values as *signed* integers.
2395 * See the from* functions below for more convenient ways of constructing Longs.
2396 * @exports Long
2397 * @class A Long class for representing a 64 bit two's-complement integer value.
2398 * @param {number} low The low (signed) 32 bits of the long
2399 * @param {number} high The high (signed) 32 bits of the long
2400 * @param {boolean=} unsigned Whether unsigned or not, defaults to `false` for signed
2401 * @constructor
2402 */
2403 function Long(low, high, unsigned) {
2404
2405 /**
2406 * The low 32 bits as a signed value.
2407 * @type {number}
2408 */
2409 this.low = low | 0;
2410
2411 /**
2412 * The high 32 bits as a signed value.
2413 * @type {number}
2414 */
2415 this.high = high | 0;
2416
2417 /**
2418 * Whether unsigned or not.
2419 * @type {boolean}
2420 */
2421 this.unsigned = !!unsigned;
2422 }
2423
2424 // The internal representation of a long is the two given signed, 32-bit values.
2425 // We use 32-bit pieces because these are the size of integers on which
2426 // Javascript performs bit-operations. For operations like addition and
2427 // multiplication, we split each number into 16 bit pieces, which can easily be
2428 // multiplied within Javascript's floating-point representation without overflow
2429 // or change in sign.
2430 //
2431 // In the algorithms below, we frequently reduce the negative case to the
2432 // positive case by negating the input(s) and then post-processing the result.
2433 // Note that we must ALWAYS check specially whether those values are MIN_VALUE
2434 // (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as
2435 // a positive number, it overflows back into a negative). Not handling this
2436 // case would often result in infinite recursion.
2437 //
2438 // Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the from*
2439 // methods on which they depend.
2440
2441 /**
2442 * An indicator used to reliably determine if an object is a Long or not.
2443 * @type {boolean}
2444 * @const
2445 * @private
2446 */
2447 Long.prototype.__isLong__;
2448
2449 Object.defineProperty(Long.prototype, "__isLong__", {
2450 value: true,
2451 enumerable: false,
2452 configurable: false
2453 });
2454
2455 /**
2456 * @function
2457 * @param {*} obj Object
2458 * @returns {boolean}
2459 * @inner
2460 */
2461 function isLong(obj) {
2462 return (obj && obj["__isLong__"]) === true;
2463 }
2464
2465 /**
2466 * Tests if the specified object is a Long.
2467 * @function
2468 * @param {*} obj Object
2469 * @returns {boolean}
2470 */
2471 Long.isLong = isLong;
2472
2473 /**
2474 * A cache of the Long representations of small integer values.
2475 * @type {!Object}
2476 * @inner
2477 */
2478 var INT_CACHE = {};
2479
2480 /**
2481 * A cache of the Long representations of small unsigned integer values.
2482 * @type {!Object}
2483 * @inner
2484 */
2485 var UINT_CACHE = {};
2486
2487 /**
2488 * @param {number} value
2489 * @param {boolean=} unsigned
2490 * @returns {!Long}
2491 * @inner
2492 */
2493 function fromInt(value, unsigned) {
2494 var obj, cachedObj, cache;
2495 if (unsigned) {
2496 value >>>= 0;
2497 if (cache = (0 <= value && value < 256)) {
2498 cachedObj = UINT_CACHE[value];
2499 if (cachedObj)
2500 return cachedObj;
2501 }
2502 obj = fromBits(value, (value | 0) < 0 ? -1 : 0, true);
2503 if (cache)
2504 UINT_CACHE[value] = obj;
2505 return obj;
2506 } else {
2507 value |= 0;
2508 if (cache = (-128 <= value && value < 128)) {
2509 cachedObj = INT_CACHE[value];
2510 if (cachedObj)
2511 return cachedObj;
2512 }
2513 obj = fromBits(value, value < 0 ? -1 : 0, false);
2514 if (cache)
2515 INT_CACHE[value] = obj;
2516 return obj;
2517 }
2518 }
2519
2520 /**
2521 * Returns a Long representing the given 32 bit integer value.
2522 * @function
2523 * @param {number} value The 32 bit integer in question
2524 * @param {boolean=} unsigned Whether unsigned or not, defaults to `false` for signed
2525 * @returns {!Long} The corresponding Long value
2526 */
2527 Long.fromInt = fromInt;
2528
2529 /**
2530 * @param {number} value
2531 * @param {boolean=} unsigned
2532 * @returns {!Long}
2533 * @inner
2534 */
2535 function fromNumber(value, unsigned) {
2536 if (isNaN(value) || !isFinite(value))
2537 return unsigned ? UZERO : ZERO;
2538 if (unsigned) {
2539 if (value < 0)
2540 return UZERO;
2541 if (value >= TWO_PWR_64_DBL)
2542 return MAX_UNSIGNED_VALUE;
2543 } else {
2544 if (value <= -TWO_PWR_63_DBL)
2545 return MIN_VALUE;
2546 if (value + 1 >= TWO_PWR_63_DBL)
2547 return MAX_VALUE;
2548 }
2549 if (value < 0)
2550 return fromNumber(-value, unsigned).neg();
2551 return fromBits((value % TWO_PWR_32_DBL) | 0, (value / TWO_PWR_32_DBL) | 0, unsigned);
2552 }
2553
2554 /**
2555 * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned.
2556 * @function
2557 * @param {number} value The number in question
2558 * @param {boolean=} unsigned Whether unsigned or not, defaults to `false` for signed
2559 * @returns {!Long} The corresponding Long value
2560 */
2561 Long.fromNumber = fromNumber;
2562
2563 /**
2564 * @param {number} lowBits
2565 * @param {number} highBits
2566 * @param {boolean=} unsigned
2567 * @returns {!Long}
2568 * @inner
2569 */
2570 function fromBits(lowBits, highBits, unsigned) {
2571 return new Long(lowBits, highBits, unsigned);
2572 }
2573
2574 /**
2575 * Returns a Long representing the 64 bit integer that comes by concatenating the given low and high bits. Each is
2576 * assumed to use 32 bits.
2577 * @function
2578 * @param {number} lowBits The low 32 bits
2579 * @param {number} highBits The high 32 bits
2580 * @param {boolean=} unsigned Whether unsigned or not, defaults to `false` for signed
2581 * @returns {!Long} The corresponding Long value
2582 */
2583 Long.fromBits = fromBits;
2584
2585 /**
2586 * @function
2587 * @param {number} base
2588 * @param {number} exponent
2589 * @returns {number}
2590 * @inner
2591 */
2592 var pow_dbl = Math.pow; // Used 4 times (4*8 to 15+4)
2593
2594 /**
2595 * @param {string} str
2596 * @param {(boolean|number)=} unsigned
2597 * @param {number=} radix
2598 * @returns {!Long}
2599 * @inner
2600 */
2601 function fromString(str, unsigned, radix) {
2602 if (str.length === 0)
2603 throw Error('empty string');
2604 if (str === "NaN" || str === "Infinity" || str === "+Infinity" || str === "-Infinity")
2605 return ZERO;
2606 if (typeof unsigned === 'number') {
2607 // For goog.math.long compatibility
2608 radix = unsigned,
2609 unsigned = false;
2610 } else {
2611 unsigned = !! unsigned;
2612 }
2613 radix = radix || 10;
2614 if (radix < 2 || 36 < radix)
2615 throw RangeError('radix');
2616
2617 var p;
2618 if ((p = str.indexOf('-')) > 0)
2619 throw Error('interior hyphen');
2620 else if (p === 0) {
2621 return fromString(str.substring(1), unsigned, radix).neg();
2622 }
2623
2624 // Do several (8) digits each time through the loop, so as to
2625 // minimize the calls to the very expensive emulated div.
2626 var radixToPower = fromNumber(pow_dbl(radix, 8));
2627
2628 var result = ZERO;
2629 for (var i = 0; i < str.length; i += 8) {
2630 var size = Math.min(8, str.length - i),
2631 value = parseInt(str.substring(i, i + size), radix);
2632 if (size < 8) {
2633 var power = fromNumber(pow_dbl(radix, size));
2634 result = result.mul(power).add(fromNumber(value));
2635 } else {
2636 result = result.mul(radixToPower);
2637 result = result.add(fromNumber(value));
2638 }
2639 }
2640 result.unsigned = unsigned;
2641 return result;
2642 }
2643
2644 /**
2645 * Returns a Long representation of the given string, written using the specified radix.
2646 * @function
2647 * @param {string} str The textual representation of the Long
2648 * @param {(boolean|number)=} unsigned Whether unsigned or not, defaults to `false` for signed
2649 * @param {number=} radix The radix in which the text is written (2-36), defaults to 10
2650 * @returns {!Long} The corresponding Long value
2651 */
2652 Long.fromString = fromString;
2653
2654 /**
2655 * @function
2656 * @param {!Long|number|string|!{low: number, high: number, unsigned: boolean}} val
2657 * @returns {!Long}
2658 * @inner
2659 */
2660 function fromValue(val) {
2661 if (val /* is compatible */ instanceof Long)
2662 return val;
2663 if (typeof val === 'number')
2664 return fromNumber(val);
2665 if (typeof val === 'string')
2666 return fromString(val);
2667 // Throws for non-objects, converts non-instanceof Long:
2668 return fromBits(val.low, val.high, val.unsigned);
2669 }
2670
2671 /**
2672 * Converts the specified value to a Long.
2673 * @function
2674 * @param {!Long|number|string|!{low: number, high: number, unsigned: boolean}} val Value
2675 * @returns {!Long}
2676 */
2677 Long.fromValue = fromValue;
2678
2679 // NOTE: the compiler should inline these constant values below and then remove these variables, so there should be
2680 // no runtime penalty for these.
2681
2682 /**
2683 * @type {number}
2684 * @const
2685 * @inner
2686 */
2687 var TWO_PWR_16_DBL = 1 << 16;
2688
2689 /**
2690 * @type {number}
2691 * @const
2692 * @inner
2693 */
2694 var TWO_PWR_24_DBL = 1 << 24;
2695
2696 /**
2697 * @type {number}
2698 * @const
2699 * @inner
2700 */
2701 var TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL;
2702
2703 /**
2704 * @type {number}
2705 * @const
2706 * @inner
2707 */
2708 var TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL;
2709
2710 /**
2711 * @type {number}
2712 * @const
2713 * @inner
2714 */
2715 var TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2;
2716
2717 /**
2718 * @type {!Long}
2719 * @const
2720 * @inner
2721 */
2722 var TWO_PWR_24 = fromInt(TWO_PWR_24_DBL);
2723
2724 /**
2725 * @type {!Long}
2726 * @inner
2727 */
2728 var ZERO = fromInt(0);
2729
2730 /**
2731 * Signed zero.
2732 * @type {!Long}
2733 */
2734 Long.ZERO = ZERO;
2735
2736 /**
2737 * @type {!Long}
2738 * @inner
2739 */
2740 var UZERO = fromInt(0, true);
2741
2742 /**
2743 * Unsigned zero.
2744 * @type {!Long}
2745 */
2746 Long.UZERO = UZERO;
2747
2748 /**
2749 * @type {!Long}
2750 * @inner
2751 */
2752 var ONE = fromInt(1);
2753
2754 /**
2755 * Signed one.
2756 * @type {!Long}
2757 */
2758 Long.ONE = ONE;
2759
2760 /**
2761 * @type {!Long}
2762 * @inner
2763 */
2764 var UONE = fromInt(1, true);
2765
2766 /**
2767 * Unsigned one.
2768 * @type {!Long}
2769 */
2770 Long.UONE = UONE;
2771
2772 /**
2773 * @type {!Long}
2774 * @inner
2775 */
2776 var NEG_ONE = fromInt(-1);
2777
2778 /**
2779 * Signed negative one.
2780 * @type {!Long}
2781 */
2782 Long.NEG_ONE = NEG_ONE;
2783
2784 /**
2785 * @type {!Long}
2786 * @inner
2787 */
2788 var MAX_VALUE = fromBits(0xFFFFFFFF|0, 0x7FFFFFFF|0, false);
2789
2790 /**
2791 * Maximum signed value.
2792 * @type {!Long}
2793 */
2794 Long.MAX_VALUE = MAX_VALUE;
2795
2796 /**
2797 * @type {!Long}
2798 * @inner
2799 */
2800 var MAX_UNSIGNED_VALUE = fromBits(0xFFFFFFFF|0, 0xFFFFFFFF|0, true);
2801
2802 /**
2803 * Maximum unsigned value.
2804 * @type {!Long}
2805 */
2806 Long.MAX_UNSIGNED_VALUE = MAX_UNSIGNED_VALUE;
2807
2808 /**
2809 * @type {!Long}
2810 * @inner
2811 */
2812 var MIN_VALUE = fromBits(0, 0x80000000|0, false);
2813
2814 /**
2815 * Minimum signed value.
2816 * @type {!Long}
2817 */
2818 Long.MIN_VALUE = MIN_VALUE;
2819
2820 /**
2821 * @alias Long.prototype
2822 * @inner
2823 */
2824 var LongPrototype = Long.prototype;
2825
2826 /**
2827 * Converts the Long to a 32 bit integer, assuming it is a 32 bit integer.
2828 * @returns {number}
2829 */
2830 LongPrototype.toInt = function toInt() {
2831 return this.unsigned ? this.low >>> 0 : this.low;
2832 };
2833
2834 /**
2835 * Converts the Long to a the nearest floating-point representation of this value (double, 53 bit mantissa).
2836 * @returns {number}
2837 */
2838 LongPrototype.toNumber = function toNumber() {
2839 if (this.unsigned)
2840 return ((this.high >>> 0) * TWO_PWR_32_DBL) + (this.low >>> 0);
2841 return this.high * TWO_PWR_32_DBL + (this.low >>> 0);
2842 };
2843
2844 /**
2845 * Converts the Long to a string written in the specified radix.
2846 * @param {number=} radix Radix (2-36), defaults to 10
2847 * @returns {string}
2848 * @override
2849 * @throws {RangeError} If `radix` is out of range
2850 */
2851 LongPrototype.toString = function toString(radix) {
2852 radix = radix || 10;
2853 if (radix < 2 || 36 < radix)
2854 throw RangeError('radix');
2855 if (this.isZero())
2856 return '0';
2857 if (this.isNegative()) { // Unsigned Longs are never negative
2858 if (this.eq(MIN_VALUE)) {
2859 // We need to change the Long value before it can be negated, so we remove
2860 // the bottom-most digit in this base and then recurse to do the rest.
2861 var radixLong = fromNumber(radix),
2862 div = this.div(radixLong),
2863 rem1 = div.mul(radixLong).sub(this);
2864 return div.toString(radix) + rem1.toInt().toString(radix);
2865 } else
2866 return '-' + this.neg().toString(radix);
2867 }
2868
2869 // Do several (6) digits each time through the loop, so as to
2870 // minimize the calls to the very expensive emulated div.
2871 var radixToPower = fromNumber(pow_dbl(radix, 6), this.unsigned),
2872 rem = this;
2873 var result = '';
2874 while (true) {
2875 var remDiv = rem.div(radixToPower),
2876 intval = rem.sub(remDiv.mul(radixToPower)).toInt() >>> 0,
2877 digits = intval.toString(radix);
2878 rem = remDiv;
2879 if (rem.isZero())
2880 return digits + result;
2881 else {
2882 while (digits.length < 6)
2883 digits = '0' + digits;
2884 result = '' + digits + result;
2885 }
2886 }
2887 };
2888
2889 /**
2890 * Gets the high 32 bits as a signed integer.
2891 * @returns {number} Signed high bits
2892 */
2893 LongPrototype.getHighBits = function getHighBits() {
2894 return this.high;
2895 };
2896
2897 /**
2898 * Gets the high 32 bits as an unsigned integer.
2899 * @returns {number} Unsigned high bits
2900 */
2901 LongPrototype.getHighBitsUnsigned = function getHighBitsUnsigned() {
2902 return this.high >>> 0;
2903 };
2904
2905 /**
2906 * Gets the low 32 bits as a signed integer.
2907 * @returns {number} Signed low bits
2908 */
2909 LongPrototype.getLowBits = function getLowBits() {
2910 return this.low;
2911 };
2912
2913 /**
2914 * Gets the low 32 bits as an unsigned integer.
2915 * @returns {number} Unsigned low bits
2916 */
2917 LongPrototype.getLowBitsUnsigned = function getLowBitsUnsigned() {
2918 return this.low >>> 0;
2919 };
2920
2921 /**
2922 * Gets the number of bits needed to represent the absolute value of this Long.
2923 * @returns {number}
2924 */
2925 LongPrototype.getNumBitsAbs = function getNumBitsAbs() {
2926 if (this.isNegative()) // Unsigned Longs are never negative
2927 return this.eq(MIN_VALUE) ? 64 : this.neg().getNumBitsAbs();
2928 var val = this.high != 0 ? this.high : this.low;
2929 for (var bit = 31; bit > 0; bit--)
2930 if ((val & (1 << bit)) != 0)
2931 break;
2932 return this.high != 0 ? bit + 33 : bit + 1;
2933 };
2934
2935 /**
2936 * Tests if this Long's value equals zero.
2937 * @returns {boolean}
2938 */
2939 LongPrototype.isZero = function isZero() {
2940 return this.high === 0 && this.low === 0;
2941 };
2942
2943 /**
2944 * Tests if this Long's value is negative.
2945 * @returns {boolean}
2946 */
2947 LongPrototype.isNegative = function isNegative() {
2948 return !this.unsigned && this.high < 0;
2949 };
2950
2951 /**
2952 * Tests if this Long's value is positive.
2953 * @returns {boolean}
2954 */
2955 LongPrototype.isPositive = function isPositive() {
2956 return this.unsigned || this.high >= 0;
2957 };
2958
2959 /**
2960 * Tests if this Long's value is odd.
2961 * @returns {boolean}
2962 */
2963 LongPrototype.isOdd = function isOdd() {
2964 return (this.low & 1) === 1;
2965 };
2966
2967 /**
2968 * Tests if this Long's value is even.
2969 * @returns {boolean}
2970 */
2971 LongPrototype.isEven = function isEven() {
2972 return (this.low & 1) === 0;
2973 };
2974
2975 /**
2976 * Tests if this Long's value equals the specified's.
2977 * @param {!Long|number|string} other Other value
2978 * @returns {boolean}
2979 */
2980 LongPrototype.equals = function equals(other) {
2981 if (!isLong(other))
2982 other = fromValue(other);
2983 if (this.unsigned !== other.unsigned && (this.high >>> 31) === 1 && (other.high >>> 31) === 1)
2984 return false;
2985 return this.high === other.high && this.low === other.low;
2986 };
2987
2988 /**
2989 * Tests if this Long's value equals the specified's. This is an alias of {@link Long#equals}.
2990 * @function
2991 * @param {!Long|number|string} other Other value
2992 * @returns {boolean}
2993 */
2994 LongPrototype.eq = LongPrototype.equals;
2995
2996 /**
2997 * Tests if this Long's value differs from the specified's.
2998 * @param {!Long|number|string} other Other value
2999 * @returns {boolean}
3000 */
3001 LongPrototype.notEquals = function notEquals(other) {
3002 return !this.eq(/* validates */ other);
3003 };
3004
3005 /**
3006 * Tests if this Long's value differs from the specified's. This is an alias of {@link Long#notEquals}.
3007 * @function
3008 * @param {!Long|number|string} other Other value
3009 * @returns {boolean}
3010 */
3011 LongPrototype.neq = LongPrototype.notEquals;
3012
3013 /**
3014 * Tests if this Long's value is less than the specified's.
3015 * @param {!Long|number|string} other Other value
3016 * @returns {boolean}
3017 */
3018 LongPrototype.lessThan = function lessThan(other) {
3019 return this.comp(/* validates */ other) < 0;
3020 };
3021
3022 /**
3023 * Tests if this Long's value is less than the specified's. This is an alias of {@link Long#lessThan}.
3024 * @function
3025 * @param {!Long|number|string} other Other value
3026 * @returns {boolean}
3027 */
3028 LongPrototype.lt = LongPrototype.lessThan;
3029
3030 /**
3031 * Tests if this Long's value is less than or equal the specified's.
3032 * @param {!Long|number|string} other Other value
3033 * @returns {boolean}
3034 */
3035 LongPrototype.lessThanOrEqual = function lessThanOrEqual(other) {
3036 return this.comp(/* validates */ other) <= 0;
3037 };
3038
3039 /**
3040 * Tests if this Long's value is less than or equal the specified's. This is an alias of {@link Long#lessThanOrEqual}.
3041 * @function
3042 * @param {!Long|number|string} other Other value
3043 * @returns {boolean}
3044 */
3045 LongPrototype.lte = LongPrototype.lessThanOrEqual;
3046
3047 /**
3048 * Tests if this Long's value is greater than the specified's.
3049 * @param {!Long|number|string} other Other value
3050 * @returns {boolean}
3051 */
3052 LongPrototype.greaterThan = function greaterThan(other) {
3053 return this.comp(/* validates */ other) > 0;
3054 };
3055
3056 /**
3057 * Tests if this Long's value is greater than the specified's. This is an alias of {@link Long#greaterThan}.
3058 * @function
3059 * @param {!Long|number|string} other Other value
3060 * @returns {boolean}
3061 */
3062 LongPrototype.gt = LongPrototype.greaterThan;
3063
3064 /**
3065 * Tests if this Long's value is greater than or equal the specified's.
3066 * @param {!Long|number|string} other Other value
3067 * @returns {boolean}
3068 */
3069 LongPrototype.greaterThanOrEqual = function greaterThanOrEqual(other) {
3070 return this.comp(/* validates */ other) >= 0;
3071 };
3072
3073 /**
3074 * Tests if this Long's value is greater than or equal the specified's. This is an alias of {@link Long#greaterThanOrEqual}.
3075 * @function
3076 * @param {!Long|number|string} other Other value
3077 * @returns {boolean}
3078 */
3079 LongPrototype.gte = LongPrototype.greaterThanOrEqual;
3080
3081 /**
3082 * Compares this Long's value with the specified's.
3083 * @param {!Long|number|string} other Other value
3084 * @returns {number} 0 if they are the same, 1 if the this is greater and -1
3085 * if the given one is greater
3086 */
3087 LongPrototype.compare = function compare(other) {
3088 if (!isLong(other))
3089 other = fromValue(other);
3090 if (this.eq(other))
3091 return 0;
3092 var thisNeg = this.isNegative(),
3093 otherNeg = other.isNegative();
3094 if (thisNeg && !otherNeg)
3095 return -1;
3096 if (!thisNeg && otherNeg)
3097 return 1;
3098 // At this point the sign bits are the same
3099 if (!this.unsigned)
3100 return this.sub(other).isNegative() ? -1 : 1;
3101 // Both are positive if at least one is unsigned
3102 return (other.high >>> 0) > (this.high >>> 0) || (other.high === this.high && (other.low >>> 0) > (this.low >>> 0)) ? -1 : 1;
3103 };
3104
3105 /**
3106 * Compares this Long's value with the specified's. This is an alias of {@link Long#compare}.
3107 * @function
3108 * @param {!Long|number|string} other Other value
3109 * @returns {number} 0 if they are the same, 1 if the this is greater and -1
3110 * if the given one is greater
3111 */
3112 LongPrototype.comp = LongPrototype.compare;
3113
3114 /**
3115 * Negates this Long's value.
3116 * @returns {!Long} Negated Long
3117 */
3118 LongPrototype.negate = function negate() {
3119 if (!this.unsigned && this.eq(MIN_VALUE))
3120 return MIN_VALUE;
3121 return this.not().add(ONE);
3122 };
3123
3124 /**
3125 * Negates this Long's value. This is an alias of {@link Long#negate}.
3126 * @function
3127 * @returns {!Long} Negated Long
3128 */
3129 LongPrototype.neg = LongPrototype.negate;
3130
3131 /**
3132 * Returns the sum of this and the specified Long.
3133 * @param {!Long|number|string} addend Addend
3134 * @returns {!Long} Sum
3135 */
3136 LongPrototype.add = function add(addend) {
3137 if (!isLong(addend))
3138 addend = fromValue(addend);
3139
3140 // Divide each number into 4 chunks of 16 bits, and then sum the chunks.
3141
3142 var a48 = this.high >>> 16;
3143 var a32 = this.high & 0xFFFF;
3144 var a16 = this.low >>> 16;
3145 var a00 = this.low & 0xFFFF;
3146
3147 var b48 = addend.high >>> 16;
3148 var b32 = addend.high & 0xFFFF;
3149 var b16 = addend.low >>> 16;
3150 var b00 = addend.low & 0xFFFF;
3151
3152 var c48 = 0, c32 = 0, c16 = 0, c00 = 0;
3153 c00 += a00 + b00;
3154 c16 += c00 >>> 16;
3155 c00 &= 0xFFFF;
3156 c16 += a16 + b16;
3157 c32 += c16 >>> 16;
3158 c16 &= 0xFFFF;
3159 c32 += a32 + b32;
3160 c48 += c32 >>> 16;
3161 c32 &= 0xFFFF;
3162 c48 += a48 + b48;
3163 c48 &= 0xFFFF;
3164 return fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned);
3165 };
3166
3167 /**
3168 * Returns the difference of this and the specified Long.
3169 * @param {!Long|number|string} subtrahend Subtrahend
3170 * @returns {!Long} Difference
3171 */
3172 LongPrototype.subtract = function subtract(subtrahend) {
3173 if (!isLong(subtrahend))
3174 subtrahend = fromValue(subtrahend);
3175 return this.add(subtrahend.neg());
3176 };
3177
3178 /**
3179 * Returns the difference of this and the specified Long. This is an alias of {@link Long#subtract}.
3180 * @function
3181 * @param {!Long|number|string} subtrahend Subtrahend
3182 * @returns {!Long} Difference
3183 */
3184 LongPrototype.sub = LongPrototype.subtract;
3185
3186 /**
3187 * Returns the product of this and the specified Long.
3188 * @param {!Long|number|string} multiplier Multiplier
3189 * @returns {!Long} Product
3190 */
3191 LongPrototype.multiply = function multiply(multiplier) {
3192 if (this.isZero())
3193 return ZERO;
3194 if (!isLong(multiplier))
3195 multiplier = fromValue(multiplier);
3196 if (multiplier.isZero())
3197 return ZERO;
3198 if (this.eq(MIN_VALUE))
3199 return multiplier.isOdd() ? MIN_VALUE : ZERO;
3200 if (multiplier.eq(MIN_VALUE))
3201 return this.isOdd() ? MIN_VALUE : ZERO;
3202
3203 if (this.isNegative()) {
3204 if (multiplier.isNegative())
3205 return this.neg().mul(multiplier.neg());
3206 else
3207 return this.neg().mul(multiplier).neg();
3208 } else if (multiplier.isNegative())
3209 return this.mul(multiplier.neg()).neg();
3210
3211 // If both longs are small, use float multiplication
3212 if (this.lt(TWO_PWR_24) && multiplier.lt(TWO_PWR_24))
3213 return fromNumber(this.toNumber() * multiplier.toNumber(), this.unsigned);
3214
3215 // Divide each long into 4 chunks of 16 bits, and then add up 4x4 products.
3216 // We can skip products that would overflow.
3217
3218 var a48 = this.high >>> 16;
3219 var a32 = this.high & 0xFFFF;
3220 var a16 = this.low >>> 16;
3221 var a00 = this.low & 0xFFFF;
3222
3223 var b48 = multiplier.high >>> 16;
3224 var b32 = multiplier.high & 0xFFFF;
3225 var b16 = multiplier.low >>> 16;
3226 var b00 = multiplier.low & 0xFFFF;
3227
3228 var c48 = 0, c32 = 0, c16 = 0, c00 = 0;
3229 c00 += a00 * b00;
3230 c16 += c00 >>> 16;
3231 c00 &= 0xFFFF;
3232 c16 += a16 * b00;
3233 c32 += c16 >>> 16;
3234 c16 &= 0xFFFF;
3235 c16 += a00 * b16;
3236 c32 += c16 >>> 16;
3237 c16 &= 0xFFFF;
3238 c32 += a32 * b00;
3239 c48 += c32 >>> 16;
3240 c32 &= 0xFFFF;
3241 c32 += a16 * b16;
3242 c48 += c32 >>> 16;
3243 c32 &= 0xFFFF;
3244 c32 += a00 * b32;
3245 c48 += c32 >>> 16;
3246 c32 &= 0xFFFF;
3247 c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48;
3248 c48 &= 0xFFFF;
3249 return fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned);
3250 };
3251
3252 /**
3253 * Returns the product of this and the specified Long. This is an alias of {@link Long#multiply}.
3254 * @function
3255 * @param {!Long|number|string} multiplier Multiplier
3256 * @returns {!Long} Product
3257 */
3258 LongPrototype.mul = LongPrototype.multiply;
3259
3260 /**
3261 * Returns this Long divided by the specified. The result is signed if this Long is signed or
3262 * unsigned if this Long is unsigned.
3263 * @param {!Long|number|string} divisor Divisor
3264 * @returns {!Long} Quotient
3265 */
3266 LongPrototype.divide = function divide(divisor) {
3267 if (!isLong(divisor))
3268 divisor = fromValue(divisor);
3269 if (divisor.isZero())
3270 throw Error('division by zero');
3271 if (this.isZero())
3272 return this.unsigned ? UZERO : ZERO;
3273 var approx, rem, res;
3274 if (!this.unsigned) {
3275 // This section is only relevant for signed longs and is derived from the
3276 // closure library as a whole.
3277 if (this.eq(MIN_VALUE)) {
3278 if (divisor.eq(ONE) || divisor.eq(NEG_ONE))
3279 return MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE
3280 else if (divisor.eq(MIN_VALUE))
3281 return ONE;
3282 else {
3283 // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|.
3284 var halfThis = this.shr(1);
3285 approx = halfThis.div(divisor).shl(1);
3286 if (approx.eq(ZERO)) {
3287 return divisor.isNegative() ? ONE : NEG_ONE;
3288 } else {
3289 rem = this.sub(divisor.mul(approx));
3290 res = approx.add(rem.div(divisor));
3291 return res;
3292 }
3293 }
3294 } else if (divisor.eq(MIN_VALUE))
3295 return this.unsigned ? UZERO : ZERO;
3296 if (this.isNegative()) {
3297 if (divisor.isNegative())
3298 return this.neg().div(divisor.neg());
3299 return this.neg().div(divisor).neg();
3300 } else if (divisor.isNegative())
3301 return this.div(divisor.neg()).neg();
3302 res = ZERO;
3303 } else {
3304 // The algorithm below has not been made for unsigned longs. It's therefore
3305 // required to take special care of the MSB prior to running it.
3306 if (!divisor.unsigned)
3307 divisor = divisor.toUnsigned();
3308 if (divisor.gt(this))
3309 return UZERO;
3310 if (divisor.gt(this.shru(1))) // 15 >>> 1 = 7 ; with divisor = 8 ; true
3311 return UONE;
3312 res = UZERO;
3313 }
3314
3315 // Repeat the following until the remainder is less than other: find a
3316 // floating-point that approximates remainder / other *from below*, add this
3317 // into the result, and subtract it from the remainder. It is critical that
3318 // the approximate value is less than or equal to the real value so that the
3319 // remainder never becomes negative.
3320 rem = this;
3321 while (rem.gte(divisor)) {
3322 // Approximate the result of division. This may be a little greater or
3323 // smaller than the actual value.
3324 approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber()));
3325
3326 // We will tweak the approximate result by changing it in the 48-th digit or
3327 // the smallest non-fractional digit, whichever is larger.
3328 var log2 = Math.ceil(Math.log(approx) / Math.LN2),
3329 delta = (log2 <= 48) ? 1 : pow_dbl(2, log2 - 48),
3330
3331 // Decrease the approximation until it is smaller than the remainder. Note
3332 // that if it is too large, the product overflows and is negative.
3333 approxRes = fromNumber(approx),
3334 approxRem = approxRes.mul(divisor);
3335 while (approxRem.isNegative() || approxRem.gt(rem)) {
3336 approx -= delta;
3337 approxRes = fromNumber(approx, this.unsigned);
3338 approxRem = approxRes.mul(divisor);
3339 }
3340
3341 // We know the answer can't be zero... and actually, zero would cause
3342 // infinite recursion since we would make no progress.
3343 if (approxRes.isZero())
3344 approxRes = ONE;
3345
3346 res = res.add(approxRes);
3347 rem = rem.sub(approxRem);
3348 }
3349 return res;
3350 };
3351
3352 /**
3353 * Returns this Long divided by the specified. This is an alias of {@link Long#divide}.
3354 * @function
3355 * @param {!Long|number|string} divisor Divisor
3356 * @returns {!Long} Quotient
3357 */
3358 LongPrototype.div = LongPrototype.divide;
3359
3360 /**
3361 * Returns this Long modulo the specified.
3362 * @param {!Long|number|string} divisor Divisor
3363 * @returns {!Long} Remainder
3364 */
3365 LongPrototype.modulo = function modulo(divisor) {
3366 if (!isLong(divisor))
3367 divisor = fromValue(divisor);
3368 return this.sub(this.div(divisor).mul(divisor));
3369 };
3370
3371 /**
3372 * Returns this Long modulo the specified. This is an alias of {@link Long#modulo}.
3373 * @function
3374 * @param {!Long|number|string} divisor Divisor
3375 * @returns {!Long} Remainder
3376 */
3377 LongPrototype.mod = LongPrototype.modulo;
3378
3379 /**
3380 * Returns the bitwise NOT of this Long.
3381 * @returns {!Long}
3382 */
3383 LongPrototype.not = function not() {
3384 return fromBits(~this.low, ~this.high, this.unsigned);
3385 };
3386
3387 /**
3388 * Returns the bitwise AND of this Long and the specified.
3389 * @param {!Long|number|string} other Other Long
3390 * @returns {!Long}
3391 */
3392 LongPrototype.and = function and(other) {
3393 if (!isLong(other))
3394 other = fromValue(other);
3395 return fromBits(this.low & other.low, this.high & other.high, this.unsigned);
3396 };
3397
3398 /**
3399 * Returns the bitwise OR of this Long and the specified.
3400 * @param {!Long|number|string} other Other Long
3401 * @returns {!Long}
3402 */
3403 LongPrototype.or = function or(other) {
3404 if (!isLong(other))
3405 other = fromValue(other);
3406 return fromBits(this.low | other.low, this.high | other.high, this.unsigned);
3407 };
3408
3409 /**
3410 * Returns the bitwise XOR of this Long and the given one.
3411 * @param {!Long|number|string} other Other Long
3412 * @returns {!Long}
3413 */
3414 LongPrototype.xor = function xor(other) {
3415 if (!isLong(other))
3416 other = fromValue(other);
3417 return fromBits(this.low ^ other.low, this.high ^ other.high, this.unsigned);
3418 };
3419
3420 /**
3421 * Returns this Long with bits shifted to the left by the given amount.
3422 * @param {number|!Long} numBits Number of bits
3423 * @returns {!Long} Shifted Long
3424 */
3425 LongPrototype.shiftLeft = function shiftLeft(numBits) {
3426 if (isLong(numBits))
3427 numBits = numBits.toInt();
3428 if ((numBits &= 63) === 0)
3429 return this;
3430 else if (numBits < 32)
3431 return fromBits(this.low << numBits, (this.high << numBits) | (this.low >>> (32 - numBits)), this.unsigned);
3432 else
3433 return fromBits(0, this.low << (numBits - 32), this.unsigned);
3434 };
3435
3436 /**
3437 * Returns this Long with bits shifted to the left by the given amount. This is an alias of {@link Long#shiftLeft}.
3438 * @function
3439 * @param {number|!Long} numBits Number of bits
3440 * @returns {!Long} Shifted Long
3441 */
3442 LongPrototype.shl = LongPrototype.shiftLeft;
3443
3444 /**
3445 * Returns this Long with bits arithmetically shifted to the right by the given amount.
3446 * @param {number|!Long} numBits Number of bits
3447 * @returns {!Long} Shifted Long
3448 */
3449 LongPrototype.shiftRight = function shiftRight(numBits) {
3450 if (isLong(numBits))
3451 numBits = numBits.toInt();
3452 if ((numBits &= 63) === 0)
3453 return this;
3454 else if (numBits < 32)
3455 return fromBits((this.low >>> numBits) | (this.high << (32 - numBits)), this.high >> numBits, this.unsigned);
3456 else
3457 return fromBits(this.high >> (numBits - 32), this.high >= 0 ? 0 : -1, this.unsigned);
3458 };
3459
3460 /**
3461 * Returns this Long with bits arithmetically shifted to the right by the given amount. This is an alias of {@link Long#shiftRight}.
3462 * @function
3463 * @param {number|!Long} numBits Number of bits
3464 * @returns {!Long} Shifted Long
3465 */
3466 LongPrototype.shr = LongPrototype.shiftRight;
3467
3468 /**
3469 * Returns this Long with bits logically shifted to the right by the given amount.
3470 * @param {number|!Long} numBits Number of bits
3471 * @returns {!Long} Shifted Long
3472 */
3473 LongPrototype.shiftRightUnsigned = function shiftRightUnsigned(numBits) {
3474 if (isLong(numBits))
3475 numBits = numBits.toInt();
3476 numBits &= 63;
3477 if (numBits === 0)
3478 return this;
3479 else {
3480 var high = this.high;
3481 if (numBits < 32) {
3482 var low = this.low;
3483 return fromBits((low >>> numBits) | (high << (32 - numBits)), high >>> numBits, this.unsigned);
3484 } else if (numBits === 32)
3485 return fromBits(high, 0, this.unsigned);
3486 else
3487 return fromBits(high >>> (numBits - 32), 0, this.unsigned);
3488 }
3489 };
3490
3491 /**
3492 * Returns this Long with bits logically shifted to the right by the given amount. This is an alias of {@link Long#shiftRightUnsigned}.
3493 * @function
3494 * @param {number|!Long} numBits Number of bits
3495 * @returns {!Long} Shifted Long
3496 */
3497 LongPrototype.shru = LongPrototype.shiftRightUnsigned;
3498
3499 /**
3500 * Converts this Long to signed.
3501 * @returns {!Long} Signed long
3502 */
3503 LongPrototype.toSigned = function toSigned() {
3504 if (!this.unsigned)
3505 return this;
3506 return fromBits(this.low, this.high, false);
3507 };
3508
3509 /**
3510 * Converts this Long to unsigned.
3511 * @returns {!Long} Unsigned long
3512 */
3513 LongPrototype.toUnsigned = function toUnsigned() {
3514 if (this.unsigned)
3515 return this;
3516 return fromBits(this.low, this.high, true);
3517 };
3518
3519 /**
3520 * Converts this Long to its byte representation.
3521 * @param {boolean=} le Whether little or big endian, defaults to big endian
3522 * @returns {!Array.<number>} Byte representation
3523 */
3524 LongPrototype.toBytes = function(le) {
3525 return le ? this.toBytesLE() : this.toBytesBE();
3526 };
3527
3528 /**
3529 * Converts this Long to its little endian byte representation.
3530 * @returns {!Array.<number>} Little endian byte representation
3531 */
3532 LongPrototype.toBytesLE = function() {
3533 var hi = this.high,
3534 lo = this.low;
3535 return [
3536 lo & 0xff,
3537 (lo >>> 8) & 0xff,
3538 (lo >>> 16) & 0xff,
3539 (lo >>> 24) & 0xff,
3540 hi & 0xff,
3541 (hi >>> 8) & 0xff,
3542 (hi >>> 16) & 0xff,
3543 (hi >>> 24) & 0xff
3544 ];
3545 };
3546
3547 /**
3548 * Converts this Long to its big endian byte representation.
3549 * @returns {!Array.<number>} Big endian byte representation
3550 */
3551 LongPrototype.toBytesBE = function() {
3552 var hi = this.high,
3553 lo = this.low;
3554 return [
3555 (hi >>> 24) & 0xff,
3556 (hi >>> 16) & 0xff,
3557 (hi >>> 8) & 0xff,
3558 hi & 0xff,
3559 (lo >>> 24) & 0xff,
3560 (lo >>> 16) & 0xff,
3561 (lo >>> 8) & 0xff,
3562 lo & 0xff
3563 ];
3564 };
3565
3566 return Long;
3567 });
3568 });
3569
3570 var bytebuffer = createCommonjsModule(function (module) {
3571 /*
3572 Copyright 2013-2014 Daniel Wirtz <dcode@dcode.io>
3573
3574 Licensed under the Apache License, Version 2.0 (the "License");
3575 you may not use this file except in compliance with the License.
3576 You may obtain a copy of the License at
3577
3578 http://www.apache.org/licenses/LICENSE-2.0
3579
3580 Unless required by applicable law or agreed to in writing, software
3581 distributed under the License is distributed on an "AS IS" BASIS,
3582 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
3583 See the License for the specific language governing permissions and
3584 limitations under the License.
3585 */
3586
3587 /**
3588 * @license bytebuffer.js (c) 2015 Daniel Wirtz <dcode@dcode.io>
3589 * Backing buffer: ArrayBuffer, Accessor: Uint8Array
3590 * Released under the Apache License, Version 2.0
3591 * see: https://github.com/dcodeIO/bytebuffer.js for details
3592 */
3593 (function(global, factory) {
3594
3595 /* AMD */ if (typeof commonjsRequire === 'function' && 'object' === "object" && module && module["exports"])
3596 module['exports'] = (function() {
3597 var Long; try { Long = long_1; } catch (e) {}
3598 return factory(Long);
3599 })();
3600 /* Global */ else
3601 (global["dcodeIO"] = global["dcodeIO"] || {})["ByteBuffer"] = factory(global["dcodeIO"]["Long"]);
3602
3603 })(commonjsGlobal, function(Long) {
3604
3605 /**
3606 * Constructs a new ByteBuffer.
3607 * @class The swiss army knife for binary data in JavaScript.
3608 * @exports ByteBuffer
3609 * @constructor
3610 * @param {number=} capacity Initial capacity. Defaults to {@link ByteBuffer.DEFAULT_CAPACITY}.
3611 * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
3612 * {@link ByteBuffer.DEFAULT_ENDIAN}.
3613 * @param {boolean=} noAssert Whether to skip assertions of offsets and values. Defaults to
3614 * {@link ByteBuffer.DEFAULT_NOASSERT}.
3615 * @expose
3616 */
3617 var ByteBuffer = function(capacity, littleEndian, noAssert) {
3618 if (typeof capacity === 'undefined')
3619 capacity = ByteBuffer.DEFAULT_CAPACITY;
3620 if (typeof littleEndian === 'undefined')
3621 littleEndian = ByteBuffer.DEFAULT_ENDIAN;
3622 if (typeof noAssert === 'undefined')
3623 noAssert = ByteBuffer.DEFAULT_NOASSERT;
3624 if (!noAssert) {
3625 capacity = capacity | 0;
3626 if (capacity < 0)
3627 throw RangeError("Illegal capacity");
3628 littleEndian = !!littleEndian;
3629 noAssert = !!noAssert;
3630 }
3631
3632 /**
3633 * Backing ArrayBuffer.
3634 * @type {!ArrayBuffer}
3635 * @expose
3636 */
3637 this.buffer = capacity === 0 ? EMPTY_BUFFER : new ArrayBuffer(capacity);
3638
3639 /**
3640 * Uint8Array utilized to manipulate the backing buffer. Becomes `null` if the backing buffer has a capacity of `0`.
3641 * @type {?Uint8Array}
3642 * @expose
3643 */
3644 this.view = capacity === 0 ? null : new Uint8Array(this.buffer);
3645
3646 /**
3647 * Absolute read/write offset.
3648 * @type {number}
3649 * @expose
3650 * @see ByteBuffer#flip
3651 * @see ByteBuffer#clear
3652 */
3653 this.offset = 0;
3654
3655 /**
3656 * Marked offset.
3657 * @type {number}
3658 * @expose
3659 * @see ByteBuffer#mark
3660 * @see ByteBuffer#reset
3661 */
3662 this.markedOffset = -1;
3663
3664 /**
3665 * Absolute limit of the contained data. Set to the backing buffer's capacity upon allocation.
3666 * @type {number}
3667 * @expose
3668 * @see ByteBuffer#flip
3669 * @see ByteBuffer#clear
3670 */
3671 this.limit = capacity;
3672
3673 /**
3674 * Whether to use little endian byte order, defaults to `false` for big endian.
3675 * @type {boolean}
3676 * @expose
3677 */
3678 this.littleEndian = littleEndian;
3679
3680 /**
3681 * Whether to skip assertions of offsets and values, defaults to `false`.
3682 * @type {boolean}
3683 * @expose
3684 */
3685 this.noAssert = noAssert;
3686 };
3687
3688 /**
3689 * ByteBuffer version.
3690 * @type {string}
3691 * @const
3692 * @expose
3693 */
3694 ByteBuffer.VERSION = "5.0.1";
3695
3696 /**
3697 * Little endian constant that can be used instead of its boolean value. Evaluates to `true`.
3698 * @type {boolean}
3699 * @const
3700 * @expose
3701 */
3702 ByteBuffer.LITTLE_ENDIAN = true;
3703
3704 /**
3705 * Big endian constant that can be used instead of its boolean value. Evaluates to `false`.
3706 * @type {boolean}
3707 * @const
3708 * @expose
3709 */
3710 ByteBuffer.BIG_ENDIAN = false;
3711
3712 /**
3713 * Default initial capacity of `16`.
3714 * @type {number}
3715 * @expose
3716 */
3717 ByteBuffer.DEFAULT_CAPACITY = 16;
3718
3719 /**
3720 * Default endianess of `false` for big endian.
3721 * @type {boolean}
3722 * @expose
3723 */
3724 ByteBuffer.DEFAULT_ENDIAN = ByteBuffer.BIG_ENDIAN;
3725
3726 /**
3727 * Default no assertions flag of `false`.
3728 * @type {boolean}
3729 * @expose
3730 */
3731 ByteBuffer.DEFAULT_NOASSERT = false;
3732
3733 /**
3734 * A `Long` class for representing a 64-bit two's-complement integer value. May be `null` if Long.js has not been loaded
3735 * and int64 support is not available.
3736 * @type {?Long}
3737 * @const
3738 * @see https://github.com/dcodeIO/long.js
3739 * @expose
3740 */
3741 ByteBuffer.Long = Long || null;
3742
3743 /**
3744 * @alias ByteBuffer.prototype
3745 * @inner
3746 */
3747 var ByteBufferPrototype = ByteBuffer.prototype;
3748
3749 /**
3750 * An indicator used to reliably determine if an object is a ByteBuffer or not.
3751 * @type {boolean}
3752 * @const
3753 * @expose
3754 * @private
3755 */
3756 ByteBufferPrototype.__isByteBuffer__;
3757
3758 Object.defineProperty(ByteBufferPrototype, "__isByteBuffer__", {
3759 value: true,
3760 enumerable: false,
3761 configurable: false
3762 });
3763
3764 // helpers
3765
3766 /**
3767 * @type {!ArrayBuffer}
3768 * @inner
3769 */
3770 var EMPTY_BUFFER = new ArrayBuffer(0);
3771
3772 /**
3773 * String.fromCharCode reference for compile-time renaming.
3774 * @type {function(...number):string}
3775 * @inner
3776 */
3777 var stringFromCharCode = String.fromCharCode;
3778
3779 /**
3780 * Creates a source function for a string.
3781 * @param {string} s String to read from
3782 * @returns {function():number|null} Source function returning the next char code respectively `null` if there are
3783 * no more characters left.
3784 * @throws {TypeError} If the argument is invalid
3785 * @inner
3786 */
3787 function stringSource(s) {
3788 var i=0; return function() {
3789 return i < s.length ? s.charCodeAt(i++) : null;
3790 };
3791 }
3792
3793 /**
3794 * Creates a destination function for a string.
3795 * @returns {function(number=):undefined|string} Destination function successively called with the next char code.
3796 * Returns the final string when called without arguments.
3797 * @inner
3798 */
3799 function stringDestination() {
3800 var cs = [], ps = []; return function() {
3801 if (arguments.length === 0)
3802 return ps.join('')+stringFromCharCode.apply(String, cs);
3803 if (cs.length + arguments.length > 1024)
3804 ps.push(stringFromCharCode.apply(String, cs)),
3805 cs.length = 0;
3806 Array.prototype.push.apply(cs, arguments);
3807 };
3808 }
3809
3810 /**
3811 * Gets the accessor type.
3812 * @returns {Function} `Buffer` under node.js, `Uint8Array` respectively `DataView` in the browser (classes)
3813 * @expose
3814 */
3815 ByteBuffer.accessor = function() {
3816 return Uint8Array;
3817 };
3818 /**
3819 * Allocates a new ByteBuffer backed by a buffer of the specified capacity.
3820 * @param {number=} capacity Initial capacity. Defaults to {@link ByteBuffer.DEFAULT_CAPACITY}.
3821 * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
3822 * {@link ByteBuffer.DEFAULT_ENDIAN}.
3823 * @param {boolean=} noAssert Whether to skip assertions of offsets and values. Defaults to
3824 * {@link ByteBuffer.DEFAULT_NOASSERT}.
3825 * @returns {!ByteBuffer}
3826 * @expose
3827 */
3828 ByteBuffer.allocate = function(capacity, littleEndian, noAssert) {
3829 return new ByteBuffer(capacity, littleEndian, noAssert);
3830 };
3831
3832 /**
3833 * Concatenates multiple ByteBuffers into one.
3834 * @param {!Array.<!ByteBuffer|!ArrayBuffer|!Uint8Array|string>} buffers Buffers to concatenate
3835 * @param {(string|boolean)=} encoding String encoding if `buffers` contains a string ("base64", "hex", "binary",
3836 * defaults to "utf8")
3837 * @param {boolean=} littleEndian Whether to use little or big endian byte order for the resulting ByteBuffer. Defaults
3838 * to {@link ByteBuffer.DEFAULT_ENDIAN}.
3839 * @param {boolean=} noAssert Whether to skip assertions of offsets and values for the resulting ByteBuffer. Defaults to
3840 * {@link ByteBuffer.DEFAULT_NOASSERT}.
3841 * @returns {!ByteBuffer} Concatenated ByteBuffer
3842 * @expose
3843 */
3844 ByteBuffer.concat = function(buffers, encoding, littleEndian, noAssert) {
3845 if (typeof encoding === 'boolean' || typeof encoding !== 'string') {
3846 noAssert = littleEndian;
3847 littleEndian = encoding;
3848 encoding = undefined;
3849 }
3850 var capacity = 0;
3851 for (var i=0, k=buffers.length, length; i<k; ++i) {
3852 if (!ByteBuffer.isByteBuffer(buffers[i]))
3853 buffers[i] = ByteBuffer.wrap(buffers[i], encoding);
3854 length = buffers[i].limit - buffers[i].offset;
3855 if (length > 0) capacity += length;
3856 }
3857 if (capacity === 0)
3858 return new ByteBuffer(0, littleEndian, noAssert);
3859 var bb = new ByteBuffer(capacity, littleEndian, noAssert),
3860 bi;
3861 i=0; while (i<k) {
3862 bi = buffers[i++];
3863 length = bi.limit - bi.offset;
3864 if (length <= 0) continue;
3865 bb.view.set(bi.view.subarray(bi.offset, bi.limit), bb.offset);
3866 bb.offset += length;
3867 }
3868 bb.limit = bb.offset;
3869 bb.offset = 0;
3870 return bb;
3871 };
3872
3873 /**
3874 * Tests if the specified type is a ByteBuffer.
3875 * @param {*} bb ByteBuffer to test
3876 * @returns {boolean} `true` if it is a ByteBuffer, otherwise `false`
3877 * @expose
3878 */
3879 ByteBuffer.isByteBuffer = function(bb) {
3880 return (bb && bb["__isByteBuffer__"]) === true;
3881 };
3882 /**
3883 * Gets the backing buffer type.
3884 * @returns {Function} `Buffer` under node.js, `ArrayBuffer` in the browser (classes)
3885 * @expose
3886 */
3887 ByteBuffer.type = function() {
3888 return ArrayBuffer;
3889 };
3890 /**
3891 * Wraps a buffer or a string. Sets the allocated ByteBuffer's {@link ByteBuffer#offset} to `0` and its
3892 * {@link ByteBuffer#limit} to the length of the wrapped data.
3893 * @param {!ByteBuffer|!ArrayBuffer|!Uint8Array|string|!Array.<number>} buffer Anything that can be wrapped
3894 * @param {(string|boolean)=} encoding String encoding if `buffer` is a string ("base64", "hex", "binary", defaults to
3895 * "utf8")
3896 * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
3897 * {@link ByteBuffer.DEFAULT_ENDIAN}.
3898 * @param {boolean=} noAssert Whether to skip assertions of offsets and values. Defaults to
3899 * {@link ByteBuffer.DEFAULT_NOASSERT}.
3900 * @returns {!ByteBuffer} A ByteBuffer wrapping `buffer`
3901 * @expose
3902 */
3903 ByteBuffer.wrap = function(buffer, encoding, littleEndian, noAssert) {
3904 if (typeof encoding !== 'string') {
3905 noAssert = littleEndian;
3906 littleEndian = encoding;
3907 encoding = undefined;
3908 }
3909 if (typeof buffer === 'string') {
3910 if (typeof encoding === 'undefined')
3911 encoding = "utf8";
3912 switch (encoding) {
3913 case "base64":
3914 return ByteBuffer.fromBase64(buffer, littleEndian);
3915 case "hex":
3916 return ByteBuffer.fromHex(buffer, littleEndian);
3917 case "binary":
3918 return ByteBuffer.fromBinary(buffer, littleEndian);
3919 case "utf8":
3920 return ByteBuffer.fromUTF8(buffer, littleEndian);
3921 case "debug":
3922 return ByteBuffer.fromDebug(buffer, littleEndian);
3923 default:
3924 throw Error("Unsupported encoding: "+encoding);
3925 }
3926 }
3927 if (buffer === null || typeof buffer !== 'object')
3928 throw TypeError("Illegal buffer");
3929 var bb;
3930 if (ByteBuffer.isByteBuffer(buffer)) {
3931 bb = ByteBufferPrototype.clone.call(buffer);
3932 bb.markedOffset = -1;
3933 return bb;
3934 }
3935 if (buffer instanceof Uint8Array) { // Extract ArrayBuffer from Uint8Array
3936 bb = new ByteBuffer(0, littleEndian, noAssert);
3937 if (buffer.length > 0) { // Avoid references to more than one EMPTY_BUFFER
3938 bb.buffer = buffer.buffer;
3939 bb.offset = buffer.byteOffset;
3940 bb.limit = buffer.byteOffset + buffer.byteLength;
3941 bb.view = new Uint8Array(buffer.buffer);
3942 }
3943 } else if (buffer instanceof ArrayBuffer) { // Reuse ArrayBuffer
3944 bb = new ByteBuffer(0, littleEndian, noAssert);
3945 if (buffer.byteLength > 0) {
3946 bb.buffer = buffer;
3947 bb.offset = 0;
3948 bb.limit = buffer.byteLength;
3949 bb.view = buffer.byteLength > 0 ? new Uint8Array(buffer) : null;
3950 }
3951 } else if (Object.prototype.toString.call(buffer) === "[object Array]") { // Create from octets
3952 bb = new ByteBuffer(buffer.length, littleEndian, noAssert);
3953 bb.limit = buffer.length;
3954 for (var i=0; i<buffer.length; ++i)
3955 bb.view[i] = buffer[i];
3956 } else
3957 throw TypeError("Illegal buffer"); // Otherwise fail
3958 return bb;
3959 };
3960
3961 /**
3962 * Writes the array as a bitset.
3963 * @param {Array<boolean>} value Array of booleans to write
3964 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `length` if omitted.
3965 * @returns {!ByteBuffer}
3966 * @expose
3967 */
3968 ByteBufferPrototype.writeBitSet = function(value, offset) {
3969 var relative = typeof offset === 'undefined';
3970 if (relative) offset = this.offset;
3971 if (!this.noAssert) {
3972 if (!(value instanceof Array))
3973 throw TypeError("Illegal BitSet: Not an array");
3974 if (typeof offset !== 'number' || offset % 1 !== 0)
3975 throw TypeError("Illegal offset: "+offset+" (not an integer)");
3976 offset >>>= 0;
3977 if (offset < 0 || offset + 0 > this.buffer.byteLength)
3978 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
3979 }
3980
3981 var start = offset,
3982 bits = value.length,
3983 bytes = (bits >> 3),
3984 bit = 0,
3985 k;
3986
3987 offset += this.writeVarint32(bits,offset);
3988
3989 while(bytes--) {
3990 k = (!!value[bit++] & 1) |
3991 ((!!value[bit++] & 1) << 1) |
3992 ((!!value[bit++] & 1) << 2) |
3993 ((!!value[bit++] & 1) << 3) |
3994 ((!!value[bit++] & 1) << 4) |
3995 ((!!value[bit++] & 1) << 5) |
3996 ((!!value[bit++] & 1) << 6) |
3997 ((!!value[bit++] & 1) << 7);
3998 this.writeByte(k,offset++);
3999 }
4000
4001 if(bit < bits) {
4002 var m = 0; k = 0;
4003 while(bit < bits) k = k | ((!!value[bit++] & 1) << (m++));
4004 this.writeByte(k,offset++);
4005 }
4006
4007 if (relative) {
4008 this.offset = offset;
4009 return this;
4010 }
4011 return offset - start;
4012 };
4013
4014 /**
4015 * Reads a BitSet as an array of booleans.
4016 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `length` if omitted.
4017 * @returns {Array<boolean>
4018 * @expose
4019 */
4020 ByteBufferPrototype.readBitSet = function(offset) {
4021 var relative = typeof offset === 'undefined';
4022 if (relative) offset = this.offset;
4023
4024 var ret = this.readVarint32(offset),
4025 bits = ret.value,
4026 bytes = (bits >> 3),
4027 bit = 0,
4028 value = [],
4029 k;
4030
4031 offset += ret.length;
4032
4033 while(bytes--) {
4034 k = this.readByte(offset++);
4035 value[bit++] = !!(k & 0x01);
4036 value[bit++] = !!(k & 0x02);
4037 value[bit++] = !!(k & 0x04);
4038 value[bit++] = !!(k & 0x08);
4039 value[bit++] = !!(k & 0x10);
4040 value[bit++] = !!(k & 0x20);
4041 value[bit++] = !!(k & 0x40);
4042 value[bit++] = !!(k & 0x80);
4043 }
4044
4045 if(bit < bits) {
4046 var m = 0;
4047 k = this.readByte(offset++);
4048 while(bit < bits) value[bit++] = !!((k >> (m++)) & 1);
4049 }
4050
4051 if (relative) {
4052 this.offset = offset;
4053 }
4054 return value;
4055 };
4056 /**
4057 * Reads the specified number of bytes.
4058 * @param {number} length Number of bytes to read
4059 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `length` if omitted.
4060 * @returns {!ByteBuffer}
4061 * @expose
4062 */
4063 ByteBufferPrototype.readBytes = function(length, offset) {
4064 var relative = typeof offset === 'undefined';
4065 if (relative) offset = this.offset;
4066 if (!this.noAssert) {
4067 if (typeof offset !== 'number' || offset % 1 !== 0)
4068 throw TypeError("Illegal offset: "+offset+" (not an integer)");
4069 offset >>>= 0;
4070 if (offset < 0 || offset + length > this.buffer.byteLength)
4071 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+length+") <= "+this.buffer.byteLength);
4072 }
4073 var slice = this.slice(offset, offset + length);
4074 if (relative) this.offset += length;
4075 return slice;
4076 };
4077
4078 /**
4079 * Writes a payload of bytes. This is an alias of {@link ByteBuffer#append}.
4080 * @function
4081 * @param {!ByteBuffer|!ArrayBuffer|!Uint8Array|string} source Data to write. If `source` is a ByteBuffer, its offsets
4082 * will be modified according to the performed read operation.
4083 * @param {(string|number)=} encoding Encoding if `data` is a string ("base64", "hex", "binary", defaults to "utf8")
4084 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
4085 * written if omitted.
4086 * @returns {!ByteBuffer} this
4087 * @expose
4088 */
4089 ByteBufferPrototype.writeBytes = ByteBufferPrototype.append;
4090
4091 // types/ints/int8
4092
4093 /**
4094 * Writes an 8bit signed integer.
4095 * @param {number} value Value to write
4096 * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `1` if omitted.
4097 * @returns {!ByteBuffer} this
4098 * @expose
4099 */
4100 ByteBufferPrototype.writeInt8 = function(value, offset) {
4101 var relative = typeof offset === 'undefined';
4102 if (relative) offset = this.offset;
4103 if (!this.noAssert) {
4104 if (typeof value !== 'number' || value % 1 !== 0)
4105 throw TypeError("Illegal value: "+value+" (not an integer)");
4106 value |= 0;
4107 if (typeof offset !== 'number' || offset % 1 !== 0)
4108 throw TypeError("Illegal offset: "+offset+" (not an integer)");
4109 offset >>>= 0;
4110 if (offset < 0 || offset + 0 > this.buffer.byteLength)
4111 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
4112 }
4113 offset += 1;
4114 var capacity0 = this.buffer.byteLength;
4115 if (offset > capacity0)
4116 this.resize((capacity0 *= 2) > offset ? capacity0 : offset);
4117 offset -= 1;
4118 this.view[offset] = value;
4119 if (relative) this.offset += 1;
4120 return this;
4121 };
4122
4123 /**
4124 * Writes an 8bit signed integer. This is an alias of {@link ByteBuffer#writeInt8}.
4125 * @function
4126 * @param {number} value Value to write
4127 * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `1` if omitted.
4128 * @returns {!ByteBuffer} this
4129 * @expose
4130 */
4131 ByteBufferPrototype.writeByte = ByteBufferPrototype.writeInt8;
4132
4133 /**
4134 * Reads an 8bit signed integer.
4135 * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `1` if omitted.
4136 * @returns {number} Value read
4137 * @expose
4138 */
4139 ByteBufferPrototype.readInt8 = function(offset) {
4140 var relative = typeof offset === 'undefined';
4141 if (relative) offset = this.offset;
4142 if (!this.noAssert) {
4143 if (typeof offset !== 'number' || offset % 1 !== 0)
4144 throw TypeError("Illegal offset: "+offset+" (not an integer)");
4145 offset >>>= 0;
4146 if (offset < 0 || offset + 1 > this.buffer.byteLength)
4147 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+1+") <= "+this.buffer.byteLength);
4148 }
4149 var value = this.view[offset];
4150 if ((value & 0x80) === 0x80) value = -(0xFF - value + 1); // Cast to signed
4151 if (relative) this.offset += 1;
4152 return value;
4153 };
4154
4155 /**
4156 * Reads an 8bit signed integer. This is an alias of {@link ByteBuffer#readInt8}.
4157 * @function
4158 * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `1` if omitted.
4159 * @returns {number} Value read
4160 * @expose
4161 */
4162 ByteBufferPrototype.readByte = ByteBufferPrototype.readInt8;
4163
4164 /**
4165 * Writes an 8bit unsigned integer.
4166 * @param {number} value Value to write
4167 * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `1` if omitted.
4168 * @returns {!ByteBuffer} this
4169 * @expose
4170 */
4171 ByteBufferPrototype.writeUint8 = function(value, offset) {
4172 var relative = typeof offset === 'undefined';
4173 if (relative) offset = this.offset;
4174 if (!this.noAssert) {
4175 if (typeof value !== 'number' || value % 1 !== 0)
4176 throw TypeError("Illegal value: "+value+" (not an integer)");
4177 value >>>= 0;
4178 if (typeof offset !== 'number' || offset % 1 !== 0)
4179 throw TypeError("Illegal offset: "+offset+" (not an integer)");
4180 offset >>>= 0;
4181 if (offset < 0 || offset + 0 > this.buffer.byteLength)
4182 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
4183 }
4184 offset += 1;
4185 var capacity1 = this.buffer.byteLength;
4186 if (offset > capacity1)
4187 this.resize((capacity1 *= 2) > offset ? capacity1 : offset);
4188 offset -= 1;
4189 this.view[offset] = value;
4190 if (relative) this.offset += 1;
4191 return this;
4192 };
4193
4194 /**
4195 * Writes an 8bit unsigned integer. This is an alias of {@link ByteBuffer#writeUint8}.
4196 * @function
4197 * @param {number} value Value to write
4198 * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `1` if omitted.
4199 * @returns {!ByteBuffer} this
4200 * @expose
4201 */
4202 ByteBufferPrototype.writeUInt8 = ByteBufferPrototype.writeUint8;
4203
4204 /**
4205 * Reads an 8bit unsigned integer.
4206 * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `1` if omitted.
4207 * @returns {number} Value read
4208 * @expose
4209 */
4210 ByteBufferPrototype.readUint8 = function(offset) {
4211 var relative = typeof offset === 'undefined';
4212 if (relative) offset = this.offset;
4213 if (!this.noAssert) {
4214 if (typeof offset !== 'number' || offset % 1 !== 0)
4215 throw TypeError("Illegal offset: "+offset+" (not an integer)");
4216 offset >>>= 0;
4217 if (offset < 0 || offset + 1 > this.buffer.byteLength)
4218 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+1+") <= "+this.buffer.byteLength);
4219 }
4220 var value = this.view[offset];
4221 if (relative) this.offset += 1;
4222 return value;
4223 };
4224
4225 /**
4226 * Reads an 8bit unsigned integer. This is an alias of {@link ByteBuffer#readUint8}.
4227 * @function
4228 * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `1` if omitted.
4229 * @returns {number} Value read
4230 * @expose
4231 */
4232 ByteBufferPrototype.readUInt8 = ByteBufferPrototype.readUint8;
4233
4234 // types/ints/int16
4235
4236 /**
4237 * Writes a 16bit signed integer.
4238 * @param {number} value Value to write
4239 * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `2` if omitted.
4240 * @throws {TypeError} If `offset` or `value` is not a valid number
4241 * @throws {RangeError} If `offset` is out of bounds
4242 * @expose
4243 */
4244 ByteBufferPrototype.writeInt16 = function(value, offset) {
4245 var relative = typeof offset === 'undefined';
4246 if (relative) offset = this.offset;
4247 if (!this.noAssert) {
4248 if (typeof value !== 'number' || value % 1 !== 0)
4249 throw TypeError("Illegal value: "+value+" (not an integer)");
4250 value |= 0;
4251 if (typeof offset !== 'number' || offset % 1 !== 0)
4252 throw TypeError("Illegal offset: "+offset+" (not an integer)");
4253 offset >>>= 0;
4254 if (offset < 0 || offset + 0 > this.buffer.byteLength)
4255 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
4256 }
4257 offset += 2;
4258 var capacity2 = this.buffer.byteLength;
4259 if (offset > capacity2)
4260 this.resize((capacity2 *= 2) > offset ? capacity2 : offset);
4261 offset -= 2;
4262 if (this.littleEndian) {
4263 this.view[offset+1] = (value & 0xFF00) >>> 8;
4264 this.view[offset ] = value & 0x00FF;
4265 } else {
4266 this.view[offset] = (value & 0xFF00) >>> 8;
4267 this.view[offset+1] = value & 0x00FF;
4268 }
4269 if (relative) this.offset += 2;
4270 return this;
4271 };
4272
4273 /**
4274 * Writes a 16bit signed integer. This is an alias of {@link ByteBuffer#writeInt16}.
4275 * @function
4276 * @param {number} value Value to write
4277 * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `2` if omitted.
4278 * @throws {TypeError} If `offset` or `value` is not a valid number
4279 * @throws {RangeError} If `offset` is out of bounds
4280 * @expose
4281 */
4282 ByteBufferPrototype.writeShort = ByteBufferPrototype.writeInt16;
4283
4284 /**
4285 * Reads a 16bit signed integer.
4286 * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `2` if omitted.
4287 * @returns {number} Value read
4288 * @throws {TypeError} If `offset` is not a valid number
4289 * @throws {RangeError} If `offset` is out of bounds
4290 * @expose
4291 */
4292 ByteBufferPrototype.readInt16 = function(offset) {
4293 var relative = typeof offset === 'undefined';
4294 if (relative) offset = this.offset;
4295 if (!this.noAssert) {
4296 if (typeof offset !== 'number' || offset % 1 !== 0)
4297 throw TypeError("Illegal offset: "+offset+" (not an integer)");
4298 offset >>>= 0;
4299 if (offset < 0 || offset + 2 > this.buffer.byteLength)
4300 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+2+") <= "+this.buffer.byteLength);
4301 }
4302 var value = 0;
4303 if (this.littleEndian) {
4304 value = this.view[offset ];
4305 value |= this.view[offset+1] << 8;
4306 } else {
4307 value = this.view[offset ] << 8;
4308 value |= this.view[offset+1];
4309 }
4310 if ((value & 0x8000) === 0x8000) value = -(0xFFFF - value + 1); // Cast to signed
4311 if (relative) this.offset += 2;
4312 return value;
4313 };
4314
4315 /**
4316 * Reads a 16bit signed integer. This is an alias of {@link ByteBuffer#readInt16}.
4317 * @function
4318 * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `2` if omitted.
4319 * @returns {number} Value read
4320 * @throws {TypeError} If `offset` is not a valid number
4321 * @throws {RangeError} If `offset` is out of bounds
4322 * @expose
4323 */
4324 ByteBufferPrototype.readShort = ByteBufferPrototype.readInt16;
4325
4326 /**
4327 * Writes a 16bit unsigned integer.
4328 * @param {number} value Value to write
4329 * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `2` if omitted.
4330 * @throws {TypeError} If `offset` or `value` is not a valid number
4331 * @throws {RangeError} If `offset` is out of bounds
4332 * @expose
4333 */
4334 ByteBufferPrototype.writeUint16 = function(value, offset) {
4335 var relative = typeof offset === 'undefined';
4336 if (relative) offset = this.offset;
4337 if (!this.noAssert) {
4338 if (typeof value !== 'number' || value % 1 !== 0)
4339 throw TypeError("Illegal value: "+value+" (not an integer)");
4340 value >>>= 0;
4341 if (typeof offset !== 'number' || offset % 1 !== 0)
4342 throw TypeError("Illegal offset: "+offset+" (not an integer)");
4343 offset >>>= 0;
4344 if (offset < 0 || offset + 0 > this.buffer.byteLength)
4345 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
4346 }
4347 offset += 2;
4348 var capacity3 = this.buffer.byteLength;
4349 if (offset > capacity3)
4350 this.resize((capacity3 *= 2) > offset ? capacity3 : offset);
4351 offset -= 2;
4352 if (this.littleEndian) {
4353 this.view[offset+1] = (value & 0xFF00) >>> 8;
4354 this.view[offset ] = value & 0x00FF;
4355 } else {
4356 this.view[offset] = (value & 0xFF00) >>> 8;
4357 this.view[offset+1] = value & 0x00FF;
4358 }
4359 if (relative) this.offset += 2;
4360 return this;
4361 };
4362
4363 /**
4364 * Writes a 16bit unsigned integer. This is an alias of {@link ByteBuffer#writeUint16}.
4365 * @function
4366 * @param {number} value Value to write
4367 * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `2` if omitted.
4368 * @throws {TypeError} If `offset` or `value` is not a valid number
4369 * @throws {RangeError} If `offset` is out of bounds
4370 * @expose
4371 */
4372 ByteBufferPrototype.writeUInt16 = ByteBufferPrototype.writeUint16;
4373
4374 /**
4375 * Reads a 16bit unsigned integer.
4376 * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `2` if omitted.
4377 * @returns {number} Value read
4378 * @throws {TypeError} If `offset` is not a valid number
4379 * @throws {RangeError} If `offset` is out of bounds
4380 * @expose
4381 */
4382 ByteBufferPrototype.readUint16 = function(offset) {
4383 var relative = typeof offset === 'undefined';
4384 if (relative) offset = this.offset;
4385 if (!this.noAssert) {
4386 if (typeof offset !== 'number' || offset % 1 !== 0)
4387 throw TypeError("Illegal offset: "+offset+" (not an integer)");
4388 offset >>>= 0;
4389 if (offset < 0 || offset + 2 > this.buffer.byteLength)
4390 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+2+") <= "+this.buffer.byteLength);
4391 }
4392 var value = 0;
4393 if (this.littleEndian) {
4394 value = this.view[offset ];
4395 value |= this.view[offset+1] << 8;
4396 } else {
4397 value = this.view[offset ] << 8;
4398 value |= this.view[offset+1];
4399 }
4400 if (relative) this.offset += 2;
4401 return value;
4402 };
4403
4404 /**
4405 * Reads a 16bit unsigned integer. This is an alias of {@link ByteBuffer#readUint16}.
4406 * @function
4407 * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `2` if omitted.
4408 * @returns {number} Value read
4409 * @throws {TypeError} If `offset` is not a valid number
4410 * @throws {RangeError} If `offset` is out of bounds
4411 * @expose
4412 */
4413 ByteBufferPrototype.readUInt16 = ByteBufferPrototype.readUint16;
4414
4415 // types/ints/int32
4416
4417 /**
4418 * Writes a 32bit signed integer.
4419 * @param {number} value Value to write
4420 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
4421 * @expose
4422 */
4423 ByteBufferPrototype.writeInt32 = function(value, offset) {
4424 var relative = typeof offset === 'undefined';
4425 if (relative) offset = this.offset;
4426 if (!this.noAssert) {
4427 if (typeof value !== 'number' || value % 1 !== 0)
4428 throw TypeError("Illegal value: "+value+" (not an integer)");
4429 value |= 0;
4430 if (typeof offset !== 'number' || offset % 1 !== 0)
4431 throw TypeError("Illegal offset: "+offset+" (not an integer)");
4432 offset >>>= 0;
4433 if (offset < 0 || offset + 0 > this.buffer.byteLength)
4434 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
4435 }
4436 offset += 4;
4437 var capacity4 = this.buffer.byteLength;
4438 if (offset > capacity4)
4439 this.resize((capacity4 *= 2) > offset ? capacity4 : offset);
4440 offset -= 4;
4441 if (this.littleEndian) {
4442 this.view[offset+3] = (value >>> 24) & 0xFF;
4443 this.view[offset+2] = (value >>> 16) & 0xFF;
4444 this.view[offset+1] = (value >>> 8) & 0xFF;
4445 this.view[offset ] = value & 0xFF;
4446 } else {
4447 this.view[offset ] = (value >>> 24) & 0xFF;
4448 this.view[offset+1] = (value >>> 16) & 0xFF;
4449 this.view[offset+2] = (value >>> 8) & 0xFF;
4450 this.view[offset+3] = value & 0xFF;
4451 }
4452 if (relative) this.offset += 4;
4453 return this;
4454 };
4455
4456 /**
4457 * Writes a 32bit signed integer. This is an alias of {@link ByteBuffer#writeInt32}.
4458 * @param {number} value Value to write
4459 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
4460 * @expose
4461 */
4462 ByteBufferPrototype.writeInt = ByteBufferPrototype.writeInt32;
4463
4464 /**
4465 * Reads a 32bit signed integer.
4466 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
4467 * @returns {number} Value read
4468 * @expose
4469 */
4470 ByteBufferPrototype.readInt32 = function(offset) {
4471 var relative = typeof offset === 'undefined';
4472 if (relative) offset = this.offset;
4473 if (!this.noAssert) {
4474 if (typeof offset !== 'number' || offset % 1 !== 0)
4475 throw TypeError("Illegal offset: "+offset+" (not an integer)");
4476 offset >>>= 0;
4477 if (offset < 0 || offset + 4 > this.buffer.byteLength)
4478 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+4+") <= "+this.buffer.byteLength);
4479 }
4480 var value = 0;
4481 if (this.littleEndian) {
4482 value = this.view[offset+2] << 16;
4483 value |= this.view[offset+1] << 8;
4484 value |= this.view[offset ];
4485 value += this.view[offset+3] << 24 >>> 0;
4486 } else {
4487 value = this.view[offset+1] << 16;
4488 value |= this.view[offset+2] << 8;
4489 value |= this.view[offset+3];
4490 value += this.view[offset ] << 24 >>> 0;
4491 }
4492 value |= 0; // Cast to signed
4493 if (relative) this.offset += 4;
4494 return value;
4495 };
4496
4497 /**
4498 * Reads a 32bit signed integer. This is an alias of {@link ByteBuffer#readInt32}.
4499 * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `4` if omitted.
4500 * @returns {number} Value read
4501 * @expose
4502 */
4503 ByteBufferPrototype.readInt = ByteBufferPrototype.readInt32;
4504
4505 /**
4506 * Writes a 32bit unsigned integer.
4507 * @param {number} value Value to write
4508 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
4509 * @expose
4510 */
4511 ByteBufferPrototype.writeUint32 = function(value, offset) {
4512 var relative = typeof offset === 'undefined';
4513 if (relative) offset = this.offset;
4514 if (!this.noAssert) {
4515 if (typeof value !== 'number' || value % 1 !== 0)
4516 throw TypeError("Illegal value: "+value+" (not an integer)");
4517 value >>>= 0;
4518 if (typeof offset !== 'number' || offset % 1 !== 0)
4519 throw TypeError("Illegal offset: "+offset+" (not an integer)");
4520 offset >>>= 0;
4521 if (offset < 0 || offset + 0 > this.buffer.byteLength)
4522 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
4523 }
4524 offset += 4;
4525 var capacity5 = this.buffer.byteLength;
4526 if (offset > capacity5)
4527 this.resize((capacity5 *= 2) > offset ? capacity5 : offset);
4528 offset -= 4;
4529 if (this.littleEndian) {
4530 this.view[offset+3] = (value >>> 24) & 0xFF;
4531 this.view[offset+2] = (value >>> 16) & 0xFF;
4532 this.view[offset+1] = (value >>> 8) & 0xFF;
4533 this.view[offset ] = value & 0xFF;
4534 } else {
4535 this.view[offset ] = (value >>> 24) & 0xFF;
4536 this.view[offset+1] = (value >>> 16) & 0xFF;
4537 this.view[offset+2] = (value >>> 8) & 0xFF;
4538 this.view[offset+3] = value & 0xFF;
4539 }
4540 if (relative) this.offset += 4;
4541 return this;
4542 };
4543
4544 /**
4545 * Writes a 32bit unsigned integer. This is an alias of {@link ByteBuffer#writeUint32}.
4546 * @function
4547 * @param {number} value Value to write
4548 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
4549 * @expose
4550 */
4551 ByteBufferPrototype.writeUInt32 = ByteBufferPrototype.writeUint32;
4552
4553 /**
4554 * Reads a 32bit unsigned integer.
4555 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
4556 * @returns {number} Value read
4557 * @expose
4558 */
4559 ByteBufferPrototype.readUint32 = function(offset) {
4560 var relative = typeof offset === 'undefined';
4561 if (relative) offset = this.offset;
4562 if (!this.noAssert) {
4563 if (typeof offset !== 'number' || offset % 1 !== 0)
4564 throw TypeError("Illegal offset: "+offset+" (not an integer)");
4565 offset >>>= 0;
4566 if (offset < 0 || offset + 4 > this.buffer.byteLength)
4567 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+4+") <= "+this.buffer.byteLength);
4568 }
4569 var value = 0;
4570 if (this.littleEndian) {
4571 value = this.view[offset+2] << 16;
4572 value |= this.view[offset+1] << 8;
4573 value |= this.view[offset ];
4574 value += this.view[offset+3] << 24 >>> 0;
4575 } else {
4576 value = this.view[offset+1] << 16;
4577 value |= this.view[offset+2] << 8;
4578 value |= this.view[offset+3];
4579 value += this.view[offset ] << 24 >>> 0;
4580 }
4581 if (relative) this.offset += 4;
4582 return value;
4583 };
4584
4585 /**
4586 * Reads a 32bit unsigned integer. This is an alias of {@link ByteBuffer#readUint32}.
4587 * @function
4588 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
4589 * @returns {number} Value read
4590 * @expose
4591 */
4592 ByteBufferPrototype.readUInt32 = ByteBufferPrototype.readUint32;
4593
4594 // types/ints/int64
4595
4596 if (Long) {
4597
4598 /**
4599 * Writes a 64bit signed integer.
4600 * @param {number|!Long} value Value to write
4601 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
4602 * @returns {!ByteBuffer} this
4603 * @expose
4604 */
4605 ByteBufferPrototype.writeInt64 = function(value, offset) {
4606 var relative = typeof offset === 'undefined';
4607 if (relative) offset = this.offset;
4608 if (!this.noAssert) {
4609 if (typeof value === 'number')
4610 value = Long.fromNumber(value);
4611 else if (typeof value === 'string')
4612 value = Long.fromString(value);
4613 else if (!(value && value instanceof Long))
4614 throw TypeError("Illegal value: "+value+" (not an integer or Long)");
4615 if (typeof offset !== 'number' || offset % 1 !== 0)
4616 throw TypeError("Illegal offset: "+offset+" (not an integer)");
4617 offset >>>= 0;
4618 if (offset < 0 || offset + 0 > this.buffer.byteLength)
4619 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
4620 }
4621 if (typeof value === 'number')
4622 value = Long.fromNumber(value);
4623 else if (typeof value === 'string')
4624 value = Long.fromString(value);
4625 offset += 8;
4626 var capacity6 = this.buffer.byteLength;
4627 if (offset > capacity6)
4628 this.resize((capacity6 *= 2) > offset ? capacity6 : offset);
4629 offset -= 8;
4630 var lo = value.low,
4631 hi = value.high;
4632 if (this.littleEndian) {
4633 this.view[offset+3] = (lo >>> 24) & 0xFF;
4634 this.view[offset+2] = (lo >>> 16) & 0xFF;
4635 this.view[offset+1] = (lo >>> 8) & 0xFF;
4636 this.view[offset ] = lo & 0xFF;
4637 offset += 4;
4638 this.view[offset+3] = (hi >>> 24) & 0xFF;
4639 this.view[offset+2] = (hi >>> 16) & 0xFF;
4640 this.view[offset+1] = (hi >>> 8) & 0xFF;
4641 this.view[offset ] = hi & 0xFF;
4642 } else {
4643 this.view[offset ] = (hi >>> 24) & 0xFF;
4644 this.view[offset+1] = (hi >>> 16) & 0xFF;
4645 this.view[offset+2] = (hi >>> 8) & 0xFF;
4646 this.view[offset+3] = hi & 0xFF;
4647 offset += 4;
4648 this.view[offset ] = (lo >>> 24) & 0xFF;
4649 this.view[offset+1] = (lo >>> 16) & 0xFF;
4650 this.view[offset+2] = (lo >>> 8) & 0xFF;
4651 this.view[offset+3] = lo & 0xFF;
4652 }
4653 if (relative) this.offset += 8;
4654 return this;
4655 };
4656
4657 /**
4658 * Writes a 64bit signed integer. This is an alias of {@link ByteBuffer#writeInt64}.
4659 * @param {number|!Long} value Value to write
4660 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
4661 * @returns {!ByteBuffer} this
4662 * @expose
4663 */
4664 ByteBufferPrototype.writeLong = ByteBufferPrototype.writeInt64;
4665
4666 /**
4667 * Reads a 64bit signed integer.
4668 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
4669 * @returns {!Long}
4670 * @expose
4671 */
4672 ByteBufferPrototype.readInt64 = function(offset) {
4673 var relative = typeof offset === 'undefined';
4674 if (relative) offset = this.offset;
4675 if (!this.noAssert) {
4676 if (typeof offset !== 'number' || offset % 1 !== 0)
4677 throw TypeError("Illegal offset: "+offset+" (not an integer)");
4678 offset >>>= 0;
4679 if (offset < 0 || offset + 8 > this.buffer.byteLength)
4680 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+8+") <= "+this.buffer.byteLength);
4681 }
4682 var lo = 0,
4683 hi = 0;
4684 if (this.littleEndian) {
4685 lo = this.view[offset+2] << 16;
4686 lo |= this.view[offset+1] << 8;
4687 lo |= this.view[offset ];
4688 lo += this.view[offset+3] << 24 >>> 0;
4689 offset += 4;
4690 hi = this.view[offset+2] << 16;
4691 hi |= this.view[offset+1] << 8;
4692 hi |= this.view[offset ];
4693 hi += this.view[offset+3] << 24 >>> 0;
4694 } else {
4695 hi = this.view[offset+1] << 16;
4696 hi |= this.view[offset+2] << 8;
4697 hi |= this.view[offset+3];
4698 hi += this.view[offset ] << 24 >>> 0;
4699 offset += 4;
4700 lo = this.view[offset+1] << 16;
4701 lo |= this.view[offset+2] << 8;
4702 lo |= this.view[offset+3];
4703 lo += this.view[offset ] << 24 >>> 0;
4704 }
4705 var value = new Long(lo, hi, false);
4706 if (relative) this.offset += 8;
4707 return value;
4708 };
4709
4710 /**
4711 * Reads a 64bit signed integer. This is an alias of {@link ByteBuffer#readInt64}.
4712 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
4713 * @returns {!Long}
4714 * @expose
4715 */
4716 ByteBufferPrototype.readLong = ByteBufferPrototype.readInt64;
4717
4718 /**
4719 * Writes a 64bit unsigned integer.
4720 * @param {number|!Long} value Value to write
4721 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
4722 * @returns {!ByteBuffer} this
4723 * @expose
4724 */
4725 ByteBufferPrototype.writeUint64 = function(value, offset) {
4726 var relative = typeof offset === 'undefined';
4727 if (relative) offset = this.offset;
4728 if (!this.noAssert) {
4729 if (typeof value === 'number')
4730 value = Long.fromNumber(value);
4731 else if (typeof value === 'string')
4732 value = Long.fromString(value);
4733 else if (!(value && value instanceof Long))
4734 throw TypeError("Illegal value: "+value+" (not an integer or Long)");
4735 if (typeof offset !== 'number' || offset % 1 !== 0)
4736 throw TypeError("Illegal offset: "+offset+" (not an integer)");
4737 offset >>>= 0;
4738 if (offset < 0 || offset + 0 > this.buffer.byteLength)
4739 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
4740 }
4741 if (typeof value === 'number')
4742 value = Long.fromNumber(value);
4743 else if (typeof value === 'string')
4744 value = Long.fromString(value);
4745 offset += 8;
4746 var capacity7 = this.buffer.byteLength;
4747 if (offset > capacity7)
4748 this.resize((capacity7 *= 2) > offset ? capacity7 : offset);
4749 offset -= 8;
4750 var lo = value.low,
4751 hi = value.high;
4752 if (this.littleEndian) {
4753 this.view[offset+3] = (lo >>> 24) & 0xFF;
4754 this.view[offset+2] = (lo >>> 16) & 0xFF;
4755 this.view[offset+1] = (lo >>> 8) & 0xFF;
4756 this.view[offset ] = lo & 0xFF;
4757 offset += 4;
4758 this.view[offset+3] = (hi >>> 24) & 0xFF;
4759 this.view[offset+2] = (hi >>> 16) & 0xFF;
4760 this.view[offset+1] = (hi >>> 8) & 0xFF;
4761 this.view[offset ] = hi & 0xFF;
4762 } else {
4763 this.view[offset ] = (hi >>> 24) & 0xFF;
4764 this.view[offset+1] = (hi >>> 16) & 0xFF;
4765 this.view[offset+2] = (hi >>> 8) & 0xFF;
4766 this.view[offset+3] = hi & 0xFF;
4767 offset += 4;
4768 this.view[offset ] = (lo >>> 24) & 0xFF;
4769 this.view[offset+1] = (lo >>> 16) & 0xFF;
4770 this.view[offset+2] = (lo >>> 8) & 0xFF;
4771 this.view[offset+3] = lo & 0xFF;
4772 }
4773 if (relative) this.offset += 8;
4774 return this;
4775 };
4776
4777 /**
4778 * Writes a 64bit unsigned integer. This is an alias of {@link ByteBuffer#writeUint64}.
4779 * @function
4780 * @param {number|!Long} value Value to write
4781 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
4782 * @returns {!ByteBuffer} this
4783 * @expose
4784 */
4785 ByteBufferPrototype.writeUInt64 = ByteBufferPrototype.writeUint64;
4786
4787 /**
4788 * Reads a 64bit unsigned integer.
4789 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
4790 * @returns {!Long}
4791 * @expose
4792 */
4793 ByteBufferPrototype.readUint64 = function(offset) {
4794 var relative = typeof offset === 'undefined';
4795 if (relative) offset = this.offset;
4796 if (!this.noAssert) {
4797 if (typeof offset !== 'number' || offset % 1 !== 0)
4798 throw TypeError("Illegal offset: "+offset+" (not an integer)");
4799 offset >>>= 0;
4800 if (offset < 0 || offset + 8 > this.buffer.byteLength)
4801 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+8+") <= "+this.buffer.byteLength);
4802 }
4803 var lo = 0,
4804 hi = 0;
4805 if (this.littleEndian) {
4806 lo = this.view[offset+2] << 16;
4807 lo |= this.view[offset+1] << 8;
4808 lo |= this.view[offset ];
4809 lo += this.view[offset+3] << 24 >>> 0;
4810 offset += 4;
4811 hi = this.view[offset+2] << 16;
4812 hi |= this.view[offset+1] << 8;
4813 hi |= this.view[offset ];
4814 hi += this.view[offset+3] << 24 >>> 0;
4815 } else {
4816 hi = this.view[offset+1] << 16;
4817 hi |= this.view[offset+2] << 8;
4818 hi |= this.view[offset+3];
4819 hi += this.view[offset ] << 24 >>> 0;
4820 offset += 4;
4821 lo = this.view[offset+1] << 16;
4822 lo |= this.view[offset+2] << 8;
4823 lo |= this.view[offset+3];
4824 lo += this.view[offset ] << 24 >>> 0;
4825 }
4826 var value = new Long(lo, hi, true);
4827 if (relative) this.offset += 8;
4828 return value;
4829 };
4830
4831 /**
4832 * Reads a 64bit unsigned integer. This is an alias of {@link ByteBuffer#readUint64}.
4833 * @function
4834 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
4835 * @returns {!Long}
4836 * @expose
4837 */
4838 ByteBufferPrototype.readUInt64 = ByteBufferPrototype.readUint64;
4839
4840 } // Long
4841
4842
4843 // types/floats/float32
4844
4845 /*
4846 ieee754 - https://github.com/feross/ieee754
4847
4848 The MIT License (MIT)
4849
4850 Copyright (c) Feross Aboukhadijeh
4851
4852 Permission is hereby granted, free of charge, to any person obtaining a copy
4853 of this software and associated documentation files (the "Software"), to deal
4854 in the Software without restriction, including without limitation the rights
4855 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
4856 copies of the Software, and to permit persons to whom the Software is
4857 furnished to do so, subject to the following conditions:
4858
4859 The above copyright notice and this permission notice shall be included in
4860 all copies or substantial portions of the Software.
4861
4862 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
4863 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
4864 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
4865 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
4866 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
4867 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
4868 THE SOFTWARE.
4869 */
4870
4871 /**
4872 * Reads an IEEE754 float from a byte array.
4873 * @param {!Array} buffer
4874 * @param {number} offset
4875 * @param {boolean} isLE
4876 * @param {number} mLen
4877 * @param {number} nBytes
4878 * @returns {number}
4879 * @inner
4880 */
4881 function ieee754_read(buffer, offset, isLE, mLen, nBytes) {
4882 var e, m,
4883 eLen = nBytes * 8 - mLen - 1,
4884 eMax = (1 << eLen) - 1,
4885 eBias = eMax >> 1,
4886 nBits = -7,
4887 i = isLE ? (nBytes - 1) : 0,
4888 d = isLE ? -1 : 1,
4889 s = buffer[offset + i];
4890
4891 i += d;
4892
4893 e = s & ((1 << (-nBits)) - 1);
4894 s >>= (-nBits);
4895 nBits += eLen;
4896 for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
4897
4898 m = e & ((1 << (-nBits)) - 1);
4899 e >>= (-nBits);
4900 nBits += mLen;
4901 for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
4902
4903 if (e === 0) {
4904 e = 1 - eBias;
4905 } else if (e === eMax) {
4906 return m ? NaN : ((s ? -1 : 1) * Infinity);
4907 } else {
4908 m = m + Math.pow(2, mLen);
4909 e = e - eBias;
4910 }
4911 return (s ? -1 : 1) * m * Math.pow(2, e - mLen);
4912 }
4913
4914 /**
4915 * Writes an IEEE754 float to a byte array.
4916 * @param {!Array} buffer
4917 * @param {number} value
4918 * @param {number} offset
4919 * @param {boolean} isLE
4920 * @param {number} mLen
4921 * @param {number} nBytes
4922 * @inner
4923 */
4924 function ieee754_write(buffer, value, offset, isLE, mLen, nBytes) {
4925 var e, m, c,
4926 eLen = nBytes * 8 - mLen - 1,
4927 eMax = (1 << eLen) - 1,
4928 eBias = eMax >> 1,
4929 rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0),
4930 i = isLE ? 0 : (nBytes - 1),
4931 d = isLE ? 1 : -1,
4932 s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0;
4933
4934 value = Math.abs(value);
4935
4936 if (isNaN(value) || value === Infinity) {
4937 m = isNaN(value) ? 1 : 0;
4938 e = eMax;
4939 } else {
4940 e = Math.floor(Math.log(value) / Math.LN2);
4941 if (value * (c = Math.pow(2, -e)) < 1) {
4942 e--;
4943 c *= 2;
4944 }
4945 if (e + eBias >= 1) {
4946 value += rt / c;
4947 } else {
4948 value += rt * Math.pow(2, 1 - eBias);
4949 }
4950 if (value * c >= 2) {
4951 e++;
4952 c /= 2;
4953 }
4954
4955 if (e + eBias >= eMax) {
4956 m = 0;
4957 e = eMax;
4958 } else if (e + eBias >= 1) {
4959 m = (value * c - 1) * Math.pow(2, mLen);
4960 e = e + eBias;
4961 } else {
4962 m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
4963 e = 0;
4964 }
4965 }
4966
4967 for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
4968
4969 e = (e << mLen) | m;
4970 eLen += mLen;
4971 for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
4972
4973 buffer[offset + i - d] |= s * 128;
4974 }
4975
4976 /**
4977 * Writes a 32bit float.
4978 * @param {number} value Value to write
4979 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
4980 * @returns {!ByteBuffer} this
4981 * @expose
4982 */
4983 ByteBufferPrototype.writeFloat32 = function(value, offset) {
4984 var relative = typeof offset === 'undefined';
4985 if (relative) offset = this.offset;
4986 if (!this.noAssert) {
4987 if (typeof value !== 'number')
4988 throw TypeError("Illegal value: "+value+" (not a number)");
4989 if (typeof offset !== 'number' || offset % 1 !== 0)
4990 throw TypeError("Illegal offset: "+offset+" (not an integer)");
4991 offset >>>= 0;
4992 if (offset < 0 || offset + 0 > this.buffer.byteLength)
4993 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
4994 }
4995 offset += 4;
4996 var capacity8 = this.buffer.byteLength;
4997 if (offset > capacity8)
4998 this.resize((capacity8 *= 2) > offset ? capacity8 : offset);
4999 offset -= 4;
5000 ieee754_write(this.view, value, offset, this.littleEndian, 23, 4);
5001 if (relative) this.offset += 4;
5002 return this;
5003 };
5004
5005 /**
5006 * Writes a 32bit float. This is an alias of {@link ByteBuffer#writeFloat32}.
5007 * @function
5008 * @param {number} value Value to write
5009 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
5010 * @returns {!ByteBuffer} this
5011 * @expose
5012 */
5013 ByteBufferPrototype.writeFloat = ByteBufferPrototype.writeFloat32;
5014
5015 /**
5016 * Reads a 32bit float.
5017 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
5018 * @returns {number}
5019 * @expose
5020 */
5021 ByteBufferPrototype.readFloat32 = function(offset) {
5022 var relative = typeof offset === 'undefined';
5023 if (relative) offset = this.offset;
5024 if (!this.noAssert) {
5025 if (typeof offset !== 'number' || offset % 1 !== 0)
5026 throw TypeError("Illegal offset: "+offset+" (not an integer)");
5027 offset >>>= 0;
5028 if (offset < 0 || offset + 4 > this.buffer.byteLength)
5029 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+4+") <= "+this.buffer.byteLength);
5030 }
5031 var value = ieee754_read(this.view, offset, this.littleEndian, 23, 4);
5032 if (relative) this.offset += 4;
5033 return value;
5034 };
5035
5036 /**
5037 * Reads a 32bit float. This is an alias of {@link ByteBuffer#readFloat32}.
5038 * @function
5039 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
5040 * @returns {number}
5041 * @expose
5042 */
5043 ByteBufferPrototype.readFloat = ByteBufferPrototype.readFloat32;
5044
5045 // types/floats/float64
5046
5047 /**
5048 * Writes a 64bit float.
5049 * @param {number} value Value to write
5050 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
5051 * @returns {!ByteBuffer} this
5052 * @expose
5053 */
5054 ByteBufferPrototype.writeFloat64 = function(value, offset) {
5055 var relative = typeof offset === 'undefined';
5056 if (relative) offset = this.offset;
5057 if (!this.noAssert) {
5058 if (typeof value !== 'number')
5059 throw TypeError("Illegal value: "+value+" (not a number)");
5060 if (typeof offset !== 'number' || offset % 1 !== 0)
5061 throw TypeError("Illegal offset: "+offset+" (not an integer)");
5062 offset >>>= 0;
5063 if (offset < 0 || offset + 0 > this.buffer.byteLength)
5064 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
5065 }
5066 offset += 8;
5067 var capacity9 = this.buffer.byteLength;
5068 if (offset > capacity9)
5069 this.resize((capacity9 *= 2) > offset ? capacity9 : offset);
5070 offset -= 8;
5071 ieee754_write(this.view, value, offset, this.littleEndian, 52, 8);
5072 if (relative) this.offset += 8;
5073 return this;
5074 };
5075
5076 /**
5077 * Writes a 64bit float. This is an alias of {@link ByteBuffer#writeFloat64}.
5078 * @function
5079 * @param {number} value Value to write
5080 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
5081 * @returns {!ByteBuffer} this
5082 * @expose
5083 */
5084 ByteBufferPrototype.writeDouble = ByteBufferPrototype.writeFloat64;
5085
5086 /**
5087 * Reads a 64bit float.
5088 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
5089 * @returns {number}
5090 * @expose
5091 */
5092 ByteBufferPrototype.readFloat64 = function(offset) {
5093 var relative = typeof offset === 'undefined';
5094 if (relative) offset = this.offset;
5095 if (!this.noAssert) {
5096 if (typeof offset !== 'number' || offset % 1 !== 0)
5097 throw TypeError("Illegal offset: "+offset+" (not an integer)");
5098 offset >>>= 0;
5099 if (offset < 0 || offset + 8 > this.buffer.byteLength)
5100 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+8+") <= "+this.buffer.byteLength);
5101 }
5102 var value = ieee754_read(this.view, offset, this.littleEndian, 52, 8);
5103 if (relative) this.offset += 8;
5104 return value;
5105 };
5106
5107 /**
5108 * Reads a 64bit float. This is an alias of {@link ByteBuffer#readFloat64}.
5109 * @function
5110 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
5111 * @returns {number}
5112 * @expose
5113 */
5114 ByteBufferPrototype.readDouble = ByteBufferPrototype.readFloat64;
5115
5116
5117 // types/varints/varint32
5118
5119 /**
5120 * Maximum number of bytes required to store a 32bit base 128 variable-length integer.
5121 * @type {number}
5122 * @const
5123 * @expose
5124 */
5125 ByteBuffer.MAX_VARINT32_BYTES = 5;
5126
5127 /**
5128 * Calculates the actual number of bytes required to store a 32bit base 128 variable-length integer.
5129 * @param {number} value Value to encode
5130 * @returns {number} Number of bytes required. Capped to {@link ByteBuffer.MAX_VARINT32_BYTES}
5131 * @expose
5132 */
5133 ByteBuffer.calculateVarint32 = function(value) {
5134 // ref: src/google/protobuf/io/coded_stream.cc
5135 value = value >>> 0;
5136 if (value < 1 << 7 ) return 1;
5137 else if (value < 1 << 14) return 2;
5138 else if (value < 1 << 21) return 3;
5139 else if (value < 1 << 28) return 4;
5140 else return 5;
5141 };
5142
5143 /**
5144 * Zigzag encodes a signed 32bit integer so that it can be effectively used with varint encoding.
5145 * @param {number} n Signed 32bit integer
5146 * @returns {number} Unsigned zigzag encoded 32bit integer
5147 * @expose
5148 */
5149 ByteBuffer.zigZagEncode32 = function(n) {
5150 return (((n |= 0) << 1) ^ (n >> 31)) >>> 0; // ref: src/google/protobuf/wire_format_lite.h
5151 };
5152
5153 /**
5154 * Decodes a zigzag encoded signed 32bit integer.
5155 * @param {number} n Unsigned zigzag encoded 32bit integer
5156 * @returns {number} Signed 32bit integer
5157 * @expose
5158 */
5159 ByteBuffer.zigZagDecode32 = function(n) {
5160 return ((n >>> 1) ^ -(n & 1)) | 0; // // ref: src/google/protobuf/wire_format_lite.h
5161 };
5162
5163 /**
5164 * Writes a 32bit base 128 variable-length integer.
5165 * @param {number} value Value to write
5166 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
5167 * written if omitted.
5168 * @returns {!ByteBuffer|number} this if `offset` is omitted, else the actual number of bytes written
5169 * @expose
5170 */
5171 ByteBufferPrototype.writeVarint32 = function(value, offset) {
5172 var relative = typeof offset === 'undefined';
5173 if (relative) offset = this.offset;
5174 if (!this.noAssert) {
5175 if (typeof value !== 'number' || value % 1 !== 0)
5176 throw TypeError("Illegal value: "+value+" (not an integer)");
5177 value |= 0;
5178 if (typeof offset !== 'number' || offset % 1 !== 0)
5179 throw TypeError("Illegal offset: "+offset+" (not an integer)");
5180 offset >>>= 0;
5181 if (offset < 0 || offset + 0 > this.buffer.byteLength)
5182 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
5183 }
5184 var size = ByteBuffer.calculateVarint32(value),
5185 b;
5186 offset += size;
5187 var capacity10 = this.buffer.byteLength;
5188 if (offset > capacity10)
5189 this.resize((capacity10 *= 2) > offset ? capacity10 : offset);
5190 offset -= size;
5191 value >>>= 0;
5192 while (value >= 0x80) {
5193 b = (value & 0x7f) | 0x80;
5194 this.view[offset++] = b;
5195 value >>>= 7;
5196 }
5197 this.view[offset++] = value;
5198 if (relative) {
5199 this.offset = offset;
5200 return this;
5201 }
5202 return size;
5203 };
5204
5205 /**
5206 * Writes a zig-zag encoded (signed) 32bit base 128 variable-length integer.
5207 * @param {number} value Value to write
5208 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
5209 * written if omitted.
5210 * @returns {!ByteBuffer|number} this if `offset` is omitted, else the actual number of bytes written
5211 * @expose
5212 */
5213 ByteBufferPrototype.writeVarint32ZigZag = function(value, offset) {
5214 return this.writeVarint32(ByteBuffer.zigZagEncode32(value), offset);
5215 };
5216
5217 /**
5218 * Reads a 32bit base 128 variable-length integer.
5219 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
5220 * written if omitted.
5221 * @returns {number|!{value: number, length: number}} The value read if offset is omitted, else the value read
5222 * and the actual number of bytes read.
5223 * @throws {Error} If it's not a valid varint. Has a property `truncated = true` if there is not enough data available
5224 * to fully decode the varint.
5225 * @expose
5226 */
5227 ByteBufferPrototype.readVarint32 = function(offset) {
5228 var relative = typeof offset === 'undefined';
5229 if (relative) offset = this.offset;
5230 if (!this.noAssert) {
5231 if (typeof offset !== 'number' || offset % 1 !== 0)
5232 throw TypeError("Illegal offset: "+offset+" (not an integer)");
5233 offset >>>= 0;
5234 if (offset < 0 || offset + 1 > this.buffer.byteLength)
5235 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+1+") <= "+this.buffer.byteLength);
5236 }
5237 var c = 0,
5238 value = 0 >>> 0,
5239 b;
5240 do {
5241 if (!this.noAssert && offset > this.limit) {
5242 var err = Error("Truncated");
5243 err['truncated'] = true;
5244 throw err;
5245 }
5246 b = this.view[offset++];
5247 if (c < 5)
5248 value |= (b & 0x7f) << (7*c);
5249 ++c;
5250 } while ((b & 0x80) !== 0);
5251 value |= 0;
5252 if (relative) {
5253 this.offset = offset;
5254 return value;
5255 }
5256 return {
5257 "value": value,
5258 "length": c
5259 };
5260 };
5261
5262 /**
5263 * Reads a zig-zag encoded (signed) 32bit base 128 variable-length integer.
5264 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
5265 * written if omitted.
5266 * @returns {number|!{value: number, length: number}} The value read if offset is omitted, else the value read
5267 * and the actual number of bytes read.
5268 * @throws {Error} If it's not a valid varint
5269 * @expose
5270 */
5271 ByteBufferPrototype.readVarint32ZigZag = function(offset) {
5272 var val = this.readVarint32(offset);
5273 if (typeof val === 'object')
5274 val["value"] = ByteBuffer.zigZagDecode32(val["value"]);
5275 else
5276 val = ByteBuffer.zigZagDecode32(val);
5277 return val;
5278 };
5279
5280 // types/varints/varint64
5281
5282 if (Long) {
5283
5284 /**
5285 * Maximum number of bytes required to store a 64bit base 128 variable-length integer.
5286 * @type {number}
5287 * @const
5288 * @expose
5289 */
5290 ByteBuffer.MAX_VARINT64_BYTES = 10;
5291
5292 /**
5293 * Calculates the actual number of bytes required to store a 64bit base 128 variable-length integer.
5294 * @param {number|!Long} value Value to encode
5295 * @returns {number} Number of bytes required. Capped to {@link ByteBuffer.MAX_VARINT64_BYTES}
5296 * @expose
5297 */
5298 ByteBuffer.calculateVarint64 = function(value) {
5299 if (typeof value === 'number')
5300 value = Long.fromNumber(value);
5301 else if (typeof value === 'string')
5302 value = Long.fromString(value);
5303 // ref: src/google/protobuf/io/coded_stream.cc
5304 var part0 = value.toInt() >>> 0,
5305 part1 = value.shiftRightUnsigned(28).toInt() >>> 0,
5306 part2 = value.shiftRightUnsigned(56).toInt() >>> 0;
5307 if (part2 == 0) {
5308 if (part1 == 0) {
5309 if (part0 < 1 << 14)
5310 return part0 < 1 << 7 ? 1 : 2;
5311 else
5312 return part0 < 1 << 21 ? 3 : 4;
5313 } else {
5314 if (part1 < 1 << 14)
5315 return part1 < 1 << 7 ? 5 : 6;
5316 else
5317 return part1 < 1 << 21 ? 7 : 8;
5318 }
5319 } else
5320 return part2 < 1 << 7 ? 9 : 10;
5321 };
5322
5323 /**
5324 * Zigzag encodes a signed 64bit integer so that it can be effectively used with varint encoding.
5325 * @param {number|!Long} value Signed long
5326 * @returns {!Long} Unsigned zigzag encoded long
5327 * @expose
5328 */
5329 ByteBuffer.zigZagEncode64 = function(value) {
5330 if (typeof value === 'number')
5331 value = Long.fromNumber(value, false);
5332 else if (typeof value === 'string')
5333 value = Long.fromString(value, false);
5334 else if (value.unsigned !== false) value = value.toSigned();
5335 // ref: src/google/protobuf/wire_format_lite.h
5336 return value.shiftLeft(1).xor(value.shiftRight(63)).toUnsigned();
5337 };
5338
5339 /**
5340 * Decodes a zigzag encoded signed 64bit integer.
5341 * @param {!Long|number} value Unsigned zigzag encoded long or JavaScript number
5342 * @returns {!Long} Signed long
5343 * @expose
5344 */
5345 ByteBuffer.zigZagDecode64 = function(value) {
5346 if (typeof value === 'number')
5347 value = Long.fromNumber(value, false);
5348 else if (typeof value === 'string')
5349 value = Long.fromString(value, false);
5350 else if (value.unsigned !== false) value = value.toSigned();
5351 // ref: src/google/protobuf/wire_format_lite.h
5352 return value.shiftRightUnsigned(1).xor(value.and(Long.ONE).toSigned().negate()).toSigned();
5353 };
5354
5355 /**
5356 * Writes a 64bit base 128 variable-length integer.
5357 * @param {number|Long} value Value to write
5358 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
5359 * written if omitted.
5360 * @returns {!ByteBuffer|number} `this` if offset is omitted, else the actual number of bytes written.
5361 * @expose
5362 */
5363 ByteBufferPrototype.writeVarint64 = function(value, offset) {
5364 var relative = typeof offset === 'undefined';
5365 if (relative) offset = this.offset;
5366 if (!this.noAssert) {
5367 if (typeof value === 'number')
5368 value = Long.fromNumber(value);
5369 else if (typeof value === 'string')
5370 value = Long.fromString(value);
5371 else if (!(value && value instanceof Long))
5372 throw TypeError("Illegal value: "+value+" (not an integer or Long)");
5373 if (typeof offset !== 'number' || offset % 1 !== 0)
5374 throw TypeError("Illegal offset: "+offset+" (not an integer)");
5375 offset >>>= 0;
5376 if (offset < 0 || offset + 0 > this.buffer.byteLength)
5377 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
5378 }
5379 if (typeof value === 'number')
5380 value = Long.fromNumber(value, false);
5381 else if (typeof value === 'string')
5382 value = Long.fromString(value, false);
5383 else if (value.unsigned !== false) value = value.toSigned();
5384 var size = ByteBuffer.calculateVarint64(value),
5385 part0 = value.toInt() >>> 0,
5386 part1 = value.shiftRightUnsigned(28).toInt() >>> 0,
5387 part2 = value.shiftRightUnsigned(56).toInt() >>> 0;
5388 offset += size;
5389 var capacity11 = this.buffer.byteLength;
5390 if (offset > capacity11)
5391 this.resize((capacity11 *= 2) > offset ? capacity11 : offset);
5392 offset -= size;
5393 switch (size) {
5394 case 10: this.view[offset+9] = (part2 >>> 7) & 0x01;
5395 case 9 : this.view[offset+8] = size !== 9 ? (part2 ) | 0x80 : (part2 ) & 0x7F;
5396 case 8 : this.view[offset+7] = size !== 8 ? (part1 >>> 21) | 0x80 : (part1 >>> 21) & 0x7F;
5397 case 7 : this.view[offset+6] = size !== 7 ? (part1 >>> 14) | 0x80 : (part1 >>> 14) & 0x7F;
5398 case 6 : this.view[offset+5] = size !== 6 ? (part1 >>> 7) | 0x80 : (part1 >>> 7) & 0x7F;
5399 case 5 : this.view[offset+4] = size !== 5 ? (part1 ) | 0x80 : (part1 ) & 0x7F;
5400 case 4 : this.view[offset+3] = size !== 4 ? (part0 >>> 21) | 0x80 : (part0 >>> 21) & 0x7F;
5401 case 3 : this.view[offset+2] = size !== 3 ? (part0 >>> 14) | 0x80 : (part0 >>> 14) & 0x7F;
5402 case 2 : this.view[offset+1] = size !== 2 ? (part0 >>> 7) | 0x80 : (part0 >>> 7) & 0x7F;
5403 case 1 : this.view[offset ] = size !== 1 ? (part0 ) | 0x80 : (part0 ) & 0x7F;
5404 }
5405 if (relative) {
5406 this.offset += size;
5407 return this;
5408 } else {
5409 return size;
5410 }
5411 };
5412
5413 /**
5414 * Writes a zig-zag encoded 64bit base 128 variable-length integer.
5415 * @param {number|Long} value Value to write
5416 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
5417 * written if omitted.
5418 * @returns {!ByteBuffer|number} `this` if offset is omitted, else the actual number of bytes written.
5419 * @expose
5420 */
5421 ByteBufferPrototype.writeVarint64ZigZag = function(value, offset) {
5422 return this.writeVarint64(ByteBuffer.zigZagEncode64(value), offset);
5423 };
5424
5425 /**
5426 * Reads a 64bit base 128 variable-length integer. Requires Long.js.
5427 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
5428 * read if omitted.
5429 * @returns {!Long|!{value: Long, length: number}} The value read if offset is omitted, else the value read and
5430 * the actual number of bytes read.
5431 * @throws {Error} If it's not a valid varint
5432 * @expose
5433 */
5434 ByteBufferPrototype.readVarint64 = function(offset) {
5435 var relative = typeof offset === 'undefined';
5436 if (relative) offset = this.offset;
5437 if (!this.noAssert) {
5438 if (typeof offset !== 'number' || offset % 1 !== 0)
5439 throw TypeError("Illegal offset: "+offset+" (not an integer)");
5440 offset >>>= 0;
5441 if (offset < 0 || offset + 1 > this.buffer.byteLength)
5442 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+1+") <= "+this.buffer.byteLength);
5443 }
5444 // ref: src/google/protobuf/io/coded_stream.cc
5445 var start = offset,
5446 part0 = 0,
5447 part1 = 0,
5448 part2 = 0,
5449 b = 0;
5450 b = this.view[offset++]; part0 = (b & 0x7F) ; if ( b & 0x80 ) {
5451 b = this.view[offset++]; part0 |= (b & 0x7F) << 7; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
5452 b = this.view[offset++]; part0 |= (b & 0x7F) << 14; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
5453 b = this.view[offset++]; part0 |= (b & 0x7F) << 21; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
5454 b = this.view[offset++]; part1 = (b & 0x7F) ; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
5455 b = this.view[offset++]; part1 |= (b & 0x7F) << 7; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
5456 b = this.view[offset++]; part1 |= (b & 0x7F) << 14; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
5457 b = this.view[offset++]; part1 |= (b & 0x7F) << 21; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
5458 b = this.view[offset++]; part2 = (b & 0x7F) ; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
5459 b = this.view[offset++]; part2 |= (b & 0x7F) << 7; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
5460 throw Error("Buffer overrun"); }}}}}}}}}}
5461 var value = Long.fromBits(part0 | (part1 << 28), (part1 >>> 4) | (part2) << 24, false);
5462 if (relative) {
5463 this.offset = offset;
5464 return value;
5465 } else {
5466 return {
5467 'value': value,
5468 'length': offset-start
5469 };
5470 }
5471 };
5472
5473 /**
5474 * Reads a zig-zag encoded 64bit base 128 variable-length integer. Requires Long.js.
5475 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
5476 * read if omitted.
5477 * @returns {!Long|!{value: Long, length: number}} The value read if offset is omitted, else the value read and
5478 * the actual number of bytes read.
5479 * @throws {Error} If it's not a valid varint
5480 * @expose
5481 */
5482 ByteBufferPrototype.readVarint64ZigZag = function(offset) {
5483 var val = this.readVarint64(offset);
5484 if (val && val['value'] instanceof Long)
5485 val["value"] = ByteBuffer.zigZagDecode64(val["value"]);
5486 else
5487 val = ByteBuffer.zigZagDecode64(val);
5488 return val;
5489 };
5490
5491 } // Long
5492
5493
5494 // types/strings/cstring
5495
5496 /**
5497 * Writes a NULL-terminated UTF8 encoded string. For this to work the specified string must not contain any NULL
5498 * characters itself.
5499 * @param {string} str String to write
5500 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
5501 * contained in `str` + 1 if omitted.
5502 * @returns {!ByteBuffer|number} this if offset is omitted, else the actual number of bytes written
5503 * @expose
5504 */
5505 ByteBufferPrototype.writeCString = function(str, offset) {
5506 var relative = typeof offset === 'undefined';
5507 if (relative) offset = this.offset;
5508 var i,
5509 k = str.length;
5510 if (!this.noAssert) {
5511 if (typeof str !== 'string')
5512 throw TypeError("Illegal str: Not a string");
5513 for (i=0; i<k; ++i) {
5514 if (str.charCodeAt(i) === 0)
5515 throw RangeError("Illegal str: Contains NULL-characters");
5516 }
5517 if (typeof offset !== 'number' || offset % 1 !== 0)
5518 throw TypeError("Illegal offset: "+offset+" (not an integer)");
5519 offset >>>= 0;
5520 if (offset < 0 || offset + 0 > this.buffer.byteLength)
5521 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
5522 }
5523 // UTF8 strings do not contain zero bytes in between except for the zero character, so:
5524 k = utfx.calculateUTF16asUTF8(stringSource(str))[1];
5525 offset += k+1;
5526 var capacity12 = this.buffer.byteLength;
5527 if (offset > capacity12)
5528 this.resize((capacity12 *= 2) > offset ? capacity12 : offset);
5529 offset -= k+1;
5530 utfx.encodeUTF16toUTF8(stringSource(str), function(b) {
5531 this.view[offset++] = b;
5532 }.bind(this));
5533 this.view[offset++] = 0;
5534 if (relative) {
5535 this.offset = offset;
5536 return this;
5537 }
5538 return k;
5539 };
5540
5541 /**
5542 * Reads a NULL-terminated UTF8 encoded string. For this to work the string read must not contain any NULL characters
5543 * itself.
5544 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
5545 * read if omitted.
5546 * @returns {string|!{string: string, length: number}} The string read if offset is omitted, else the string
5547 * read and the actual number of bytes read.
5548 * @expose
5549 */
5550 ByteBufferPrototype.readCString = function(offset) {
5551 var relative = typeof offset === 'undefined';
5552 if (relative) offset = this.offset;
5553 if (!this.noAssert) {
5554 if (typeof offset !== 'number' || offset % 1 !== 0)
5555 throw TypeError("Illegal offset: "+offset+" (not an integer)");
5556 offset >>>= 0;
5557 if (offset < 0 || offset + 1 > this.buffer.byteLength)
5558 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+1+") <= "+this.buffer.byteLength);
5559 }
5560 var start = offset;
5561 // UTF8 strings do not contain zero bytes in between except for the zero character itself, so:
5562 var sd, b = -1;
5563 utfx.decodeUTF8toUTF16(function() {
5564 if (b === 0) return null;
5565 if (offset >= this.limit)
5566 throw RangeError("Illegal range: Truncated data, "+offset+" < "+this.limit);
5567 b = this.view[offset++];
5568 return b === 0 ? null : b;
5569 }.bind(this), sd = stringDestination(), true);
5570 if (relative) {
5571 this.offset = offset;
5572 return sd();
5573 } else {
5574 return {
5575 "string": sd(),
5576 "length": offset - start
5577 };
5578 }
5579 };
5580
5581 // types/strings/istring
5582
5583 /**
5584 * Writes a length as uint32 prefixed UTF8 encoded string.
5585 * @param {string} str String to write
5586 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
5587 * written if omitted.
5588 * @returns {!ByteBuffer|number} `this` if `offset` is omitted, else the actual number of bytes written
5589 * @expose
5590 * @see ByteBuffer#writeVarint32
5591 */
5592 ByteBufferPrototype.writeIString = function(str, offset) {
5593 var relative = typeof offset === 'undefined';
5594 if (relative) offset = this.offset;
5595 if (!this.noAssert) {
5596 if (typeof str !== 'string')
5597 throw TypeError("Illegal str: Not a string");
5598 if (typeof offset !== 'number' || offset % 1 !== 0)
5599 throw TypeError("Illegal offset: "+offset+" (not an integer)");
5600 offset >>>= 0;
5601 if (offset < 0 || offset + 0 > this.buffer.byteLength)
5602 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
5603 }
5604 var start = offset,
5605 k;
5606 k = utfx.calculateUTF16asUTF8(stringSource(str), this.noAssert)[1];
5607 offset += 4+k;
5608 var capacity13 = this.buffer.byteLength;
5609 if (offset > capacity13)
5610 this.resize((capacity13 *= 2) > offset ? capacity13 : offset);
5611 offset -= 4+k;
5612 if (this.littleEndian) {
5613 this.view[offset+3] = (k >>> 24) & 0xFF;
5614 this.view[offset+2] = (k >>> 16) & 0xFF;
5615 this.view[offset+1] = (k >>> 8) & 0xFF;
5616 this.view[offset ] = k & 0xFF;
5617 } else {
5618 this.view[offset ] = (k >>> 24) & 0xFF;
5619 this.view[offset+1] = (k >>> 16) & 0xFF;
5620 this.view[offset+2] = (k >>> 8) & 0xFF;
5621 this.view[offset+3] = k & 0xFF;
5622 }
5623 offset += 4;
5624 utfx.encodeUTF16toUTF8(stringSource(str), function(b) {
5625 this.view[offset++] = b;
5626 }.bind(this));
5627 if (offset !== start + 4 + k)
5628 throw RangeError("Illegal range: Truncated data, "+offset+" == "+(offset+4+k));
5629 if (relative) {
5630 this.offset = offset;
5631 return this;
5632 }
5633 return offset - start;
5634 };
5635
5636 /**
5637 * Reads a length as uint32 prefixed UTF8 encoded string.
5638 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
5639 * read if omitted.
5640 * @returns {string|!{string: string, length: number}} The string read if offset is omitted, else the string
5641 * read and the actual number of bytes read.
5642 * @expose
5643 * @see ByteBuffer#readVarint32
5644 */
5645 ByteBufferPrototype.readIString = function(offset) {
5646 var relative = typeof offset === 'undefined';
5647 if (relative) offset = this.offset;
5648 if (!this.noAssert) {
5649 if (typeof offset !== 'number' || offset % 1 !== 0)
5650 throw TypeError("Illegal offset: "+offset+" (not an integer)");
5651 offset >>>= 0;
5652 if (offset < 0 || offset + 4 > this.buffer.byteLength)
5653 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+4+") <= "+this.buffer.byteLength);
5654 }
5655 var start = offset;
5656 var len = this.readUint32(offset);
5657 var str = this.readUTF8String(len, ByteBuffer.METRICS_BYTES, offset += 4);
5658 offset += str['length'];
5659 if (relative) {
5660 this.offset = offset;
5661 return str['string'];
5662 } else {
5663 return {
5664 'string': str['string'],
5665 'length': offset - start
5666 };
5667 }
5668 };
5669
5670 // types/strings/utf8string
5671
5672 /**
5673 * Metrics representing number of UTF8 characters. Evaluates to `c`.
5674 * @type {string}
5675 * @const
5676 * @expose
5677 */
5678 ByteBuffer.METRICS_CHARS = 'c';
5679
5680 /**
5681 * Metrics representing number of bytes. Evaluates to `b`.
5682 * @type {string}
5683 * @const
5684 * @expose
5685 */
5686 ByteBuffer.METRICS_BYTES = 'b';
5687
5688 /**
5689 * Writes an UTF8 encoded string.
5690 * @param {string} str String to write
5691 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} if omitted.
5692 * @returns {!ByteBuffer|number} this if offset is omitted, else the actual number of bytes written.
5693 * @expose
5694 */
5695 ByteBufferPrototype.writeUTF8String = function(str, offset) {
5696 var relative = typeof offset === 'undefined';
5697 if (relative) offset = this.offset;
5698 if (!this.noAssert) {
5699 if (typeof offset !== 'number' || offset % 1 !== 0)
5700 throw TypeError("Illegal offset: "+offset+" (not an integer)");
5701 offset >>>= 0;
5702 if (offset < 0 || offset + 0 > this.buffer.byteLength)
5703 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
5704 }
5705 var k;
5706 var start = offset;
5707 k = utfx.calculateUTF16asUTF8(stringSource(str))[1];
5708 offset += k;
5709 var capacity14 = this.buffer.byteLength;
5710 if (offset > capacity14)
5711 this.resize((capacity14 *= 2) > offset ? capacity14 : offset);
5712 offset -= k;
5713 utfx.encodeUTF16toUTF8(stringSource(str), function(b) {
5714 this.view[offset++] = b;
5715 }.bind(this));
5716 if (relative) {
5717 this.offset = offset;
5718 return this;
5719 }
5720 return offset - start;
5721 };
5722
5723 /**
5724 * Writes an UTF8 encoded string. This is an alias of {@link ByteBuffer#writeUTF8String}.
5725 * @function
5726 * @param {string} str String to write
5727 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} if omitted.
5728 * @returns {!ByteBuffer|number} this if offset is omitted, else the actual number of bytes written.
5729 * @expose
5730 */
5731 ByteBufferPrototype.writeString = ByteBufferPrototype.writeUTF8String;
5732
5733 /**
5734 * Calculates the number of UTF8 characters of a string. JavaScript itself uses UTF-16, so that a string's
5735 * `length` property does not reflect its actual UTF8 size if it contains code points larger than 0xFFFF.
5736 * @param {string} str String to calculate
5737 * @returns {number} Number of UTF8 characters
5738 * @expose
5739 */
5740 ByteBuffer.calculateUTF8Chars = function(str) {
5741 return utfx.calculateUTF16asUTF8(stringSource(str))[0];
5742 };
5743
5744 /**
5745 * Calculates the number of UTF8 bytes of a string.
5746 * @param {string} str String to calculate
5747 * @returns {number} Number of UTF8 bytes
5748 * @expose
5749 */
5750 ByteBuffer.calculateUTF8Bytes = function(str) {
5751 return utfx.calculateUTF16asUTF8(stringSource(str))[1];
5752 };
5753
5754 /**
5755 * Calculates the number of UTF8 bytes of a string. This is an alias of {@link ByteBuffer.calculateUTF8Bytes}.
5756 * @function
5757 * @param {string} str String to calculate
5758 * @returns {number} Number of UTF8 bytes
5759 * @expose
5760 */
5761 ByteBuffer.calculateString = ByteBuffer.calculateUTF8Bytes;
5762
5763 /**
5764 * Reads an UTF8 encoded string.
5765 * @param {number} length Number of characters or bytes to read.
5766 * @param {string=} metrics Metrics specifying what `length` is meant to count. Defaults to
5767 * {@link ByteBuffer.METRICS_CHARS}.
5768 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
5769 * read if omitted.
5770 * @returns {string|!{string: string, length: number}} The string read if offset is omitted, else the string
5771 * read and the actual number of bytes read.
5772 * @expose
5773 */
5774 ByteBufferPrototype.readUTF8String = function(length, metrics, offset) {
5775 if (typeof metrics === 'number') {
5776 offset = metrics;
5777 metrics = undefined;
5778 }
5779 var relative = typeof offset === 'undefined';
5780 if (relative) offset = this.offset;
5781 if (typeof metrics === 'undefined') metrics = ByteBuffer.METRICS_CHARS;
5782 if (!this.noAssert) {
5783 if (typeof length !== 'number' || length % 1 !== 0)
5784 throw TypeError("Illegal length: "+length+" (not an integer)");
5785 length |= 0;
5786 if (typeof offset !== 'number' || offset % 1 !== 0)
5787 throw TypeError("Illegal offset: "+offset+" (not an integer)");
5788 offset >>>= 0;
5789 if (offset < 0 || offset + 0 > this.buffer.byteLength)
5790 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
5791 }
5792 var i = 0,
5793 start = offset,
5794 sd;
5795 if (metrics === ByteBuffer.METRICS_CHARS) { // The same for node and the browser
5796 sd = stringDestination();
5797 utfx.decodeUTF8(function() {
5798 return i < length && offset < this.limit ? this.view[offset++] : null;
5799 }.bind(this), function(cp) {
5800 ++i; utfx.UTF8toUTF16(cp, sd);
5801 });
5802 if (i !== length)
5803 throw RangeError("Illegal range: Truncated data, "+i+" == "+length);
5804 if (relative) {
5805 this.offset = offset;
5806 return sd();
5807 } else {
5808 return {
5809 "string": sd(),
5810 "length": offset - start
5811 };
5812 }
5813 } else if (metrics === ByteBuffer.METRICS_BYTES) {
5814 if (!this.noAssert) {
5815 if (typeof offset !== 'number' || offset % 1 !== 0)
5816 throw TypeError("Illegal offset: "+offset+" (not an integer)");
5817 offset >>>= 0;
5818 if (offset < 0 || offset + length > this.buffer.byteLength)
5819 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+length+") <= "+this.buffer.byteLength);
5820 }
5821 var k = offset + length;
5822 utfx.decodeUTF8toUTF16(function() {
5823 return offset < k ? this.view[offset++] : null;
5824 }.bind(this), sd = stringDestination(), this.noAssert);
5825 if (offset !== k)
5826 throw RangeError("Illegal range: Truncated data, "+offset+" == "+k);
5827 if (relative) {
5828 this.offset = offset;
5829 return sd();
5830 } else {
5831 return {
5832 'string': sd(),
5833 'length': offset - start
5834 };
5835 }
5836 } else
5837 throw TypeError("Unsupported metrics: "+metrics);
5838 };
5839
5840 /**
5841 * Reads an UTF8 encoded string. This is an alias of {@link ByteBuffer#readUTF8String}.
5842 * @function
5843 * @param {number} length Number of characters or bytes to read
5844 * @param {number=} metrics Metrics specifying what `n` is meant to count. Defaults to
5845 * {@link ByteBuffer.METRICS_CHARS}.
5846 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
5847 * read if omitted.
5848 * @returns {string|!{string: string, length: number}} The string read if offset is omitted, else the string
5849 * read and the actual number of bytes read.
5850 * @expose
5851 */
5852 ByteBufferPrototype.readString = ByteBufferPrototype.readUTF8String;
5853
5854 // types/strings/vstring
5855
5856 /**
5857 * Writes a length as varint32 prefixed UTF8 encoded string.
5858 * @param {string} str String to write
5859 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
5860 * written if omitted.
5861 * @returns {!ByteBuffer|number} `this` if `offset` is omitted, else the actual number of bytes written
5862 * @expose
5863 * @see ByteBuffer#writeVarint32
5864 */
5865 ByteBufferPrototype.writeVString = function(str, offset) {
5866 var relative = typeof offset === 'undefined';
5867 if (relative) offset = this.offset;
5868 if (!this.noAssert) {
5869 if (typeof str !== 'string')
5870 throw TypeError("Illegal str: Not a string");
5871 if (typeof offset !== 'number' || offset % 1 !== 0)
5872 throw TypeError("Illegal offset: "+offset+" (not an integer)");
5873 offset >>>= 0;
5874 if (offset < 0 || offset + 0 > this.buffer.byteLength)
5875 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
5876 }
5877 var start = offset,
5878 k, l;
5879 k = utfx.calculateUTF16asUTF8(stringSource(str), this.noAssert)[1];
5880 l = ByteBuffer.calculateVarint32(k);
5881 offset += l+k;
5882 var capacity15 = this.buffer.byteLength;
5883 if (offset > capacity15)
5884 this.resize((capacity15 *= 2) > offset ? capacity15 : offset);
5885 offset -= l+k;
5886 offset += this.writeVarint32(k, offset);
5887 utfx.encodeUTF16toUTF8(stringSource(str), function(b) {
5888 this.view[offset++] = b;
5889 }.bind(this));
5890 if (offset !== start+k+l)
5891 throw RangeError("Illegal range: Truncated data, "+offset+" == "+(offset+k+l));
5892 if (relative) {
5893 this.offset = offset;
5894 return this;
5895 }
5896 return offset - start;
5897 };
5898
5899 /**
5900 * Reads a length as varint32 prefixed UTF8 encoded string.
5901 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
5902 * read if omitted.
5903 * @returns {string|!{string: string, length: number}} The string read if offset is omitted, else the string
5904 * read and the actual number of bytes read.
5905 * @expose
5906 * @see ByteBuffer#readVarint32
5907 */
5908 ByteBufferPrototype.readVString = function(offset) {
5909 var relative = typeof offset === 'undefined';
5910 if (relative) offset = this.offset;
5911 if (!this.noAssert) {
5912 if (typeof offset !== 'number' || offset % 1 !== 0)
5913 throw TypeError("Illegal offset: "+offset+" (not an integer)");
5914 offset >>>= 0;
5915 if (offset < 0 || offset + 1 > this.buffer.byteLength)
5916 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+1+") <= "+this.buffer.byteLength);
5917 }
5918 var start = offset;
5919 var len = this.readVarint32(offset);
5920 var str = this.readUTF8String(len['value'], ByteBuffer.METRICS_BYTES, offset += len['length']);
5921 offset += str['length'];
5922 if (relative) {
5923 this.offset = offset;
5924 return str['string'];
5925 } else {
5926 return {
5927 'string': str['string'],
5928 'length': offset - start
5929 };
5930 }
5931 };
5932
5933
5934 /**
5935 * Appends some data to this ByteBuffer. This will overwrite any contents behind the specified offset up to the appended
5936 * data's length.
5937 * @param {!ByteBuffer|!ArrayBuffer|!Uint8Array|string} source Data to append. If `source` is a ByteBuffer, its offsets
5938 * will be modified according to the performed read operation.
5939 * @param {(string|number)=} encoding Encoding if `data` is a string ("base64", "hex", "binary", defaults to "utf8")
5940 * @param {number=} offset Offset to append at. Will use and increase {@link ByteBuffer#offset} by the number of bytes
5941 * written if omitted.
5942 * @returns {!ByteBuffer} this
5943 * @expose
5944 * @example A relative `<01 02>03.append(<04 05>)` will result in `<01 02 04 05>, 04 05|`
5945 * @example An absolute `<01 02>03.append(04 05>, 1)` will result in `<01 04>05, 04 05|`
5946 */
5947 ByteBufferPrototype.append = function(source, encoding, offset) {
5948 if (typeof encoding === 'number' || typeof encoding !== 'string') {
5949 offset = encoding;
5950 encoding = undefined;
5951 }
5952 var relative = typeof offset === 'undefined';
5953 if (relative) offset = this.offset;
5954 if (!this.noAssert) {
5955 if (typeof offset !== 'number' || offset % 1 !== 0)
5956 throw TypeError("Illegal offset: "+offset+" (not an integer)");
5957 offset >>>= 0;
5958 if (offset < 0 || offset + 0 > this.buffer.byteLength)
5959 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
5960 }
5961 if (!(source instanceof ByteBuffer))
5962 source = ByteBuffer.wrap(source, encoding);
5963 var length = source.limit - source.offset;
5964 if (length <= 0) return this; // Nothing to append
5965 offset += length;
5966 var capacity16 = this.buffer.byteLength;
5967 if (offset > capacity16)
5968 this.resize((capacity16 *= 2) > offset ? capacity16 : offset);
5969 offset -= length;
5970 this.view.set(source.view.subarray(source.offset, source.limit), offset);
5971 source.offset += length;
5972 if (relative) this.offset += length;
5973 return this;
5974 };
5975
5976 /**
5977 * Appends this ByteBuffer's contents to another ByteBuffer. This will overwrite any contents at and after the
5978 specified offset up to the length of this ByteBuffer's data.
5979 * @param {!ByteBuffer} target Target ByteBuffer
5980 * @param {number=} offset Offset to append to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
5981 * read if omitted.
5982 * @returns {!ByteBuffer} this
5983 * @expose
5984 * @see ByteBuffer#append
5985 */
5986 ByteBufferPrototype.appendTo = function(target, offset) {
5987 target.append(this, offset);
5988 return this;
5989 };
5990
5991 /**
5992 * Enables or disables assertions of argument types and offsets. Assertions are enabled by default but you can opt to
5993 * disable them if your code already makes sure that everything is valid.
5994 * @param {boolean} assert `true` to enable assertions, otherwise `false`
5995 * @returns {!ByteBuffer} this
5996 * @expose
5997 */
5998 ByteBufferPrototype.assert = function(assert) {
5999 this.noAssert = !assert;
6000 return this;
6001 };
6002
6003 /**
6004 * Gets the capacity of this ByteBuffer's backing buffer.
6005 * @returns {number} Capacity of the backing buffer
6006 * @expose
6007 */
6008 ByteBufferPrototype.capacity = function() {
6009 return this.buffer.byteLength;
6010 };
6011 /**
6012 * Clears this ByteBuffer's offsets by setting {@link ByteBuffer#offset} to `0` and {@link ByteBuffer#limit} to the
6013 * backing buffer's capacity. Discards {@link ByteBuffer#markedOffset}.
6014 * @returns {!ByteBuffer} this
6015 * @expose
6016 */
6017 ByteBufferPrototype.clear = function() {
6018 this.offset = 0;
6019 this.limit = this.buffer.byteLength;
6020 this.markedOffset = -1;
6021 return this;
6022 };
6023
6024 /**
6025 * Creates a cloned instance of this ByteBuffer, preset with this ByteBuffer's values for {@link ByteBuffer#offset},
6026 * {@link ByteBuffer#markedOffset} and {@link ByteBuffer#limit}.
6027 * @param {boolean=} copy Whether to copy the backing buffer or to return another view on the same, defaults to `false`
6028 * @returns {!ByteBuffer} Cloned instance
6029 * @expose
6030 */
6031 ByteBufferPrototype.clone = function(copy) {
6032 var bb = new ByteBuffer(0, this.littleEndian, this.noAssert);
6033 if (copy) {
6034 bb.buffer = new ArrayBuffer(this.buffer.byteLength);
6035 bb.view = new Uint8Array(bb.buffer);
6036 } else {
6037 bb.buffer = this.buffer;
6038 bb.view = this.view;
6039 }
6040 bb.offset = this.offset;
6041 bb.markedOffset = this.markedOffset;
6042 bb.limit = this.limit;
6043 return bb;
6044 };
6045
6046 /**
6047 * Compacts this ByteBuffer to be backed by a {@link ByteBuffer#buffer} of its contents' length. Contents are the bytes
6048 * between {@link ByteBuffer#offset} and {@link ByteBuffer#limit}. Will set `offset = 0` and `limit = capacity` and
6049 * adapt {@link ByteBuffer#markedOffset} to the same relative position if set.
6050 * @param {number=} begin Offset to start at, defaults to {@link ByteBuffer#offset}
6051 * @param {number=} end Offset to end at, defaults to {@link ByteBuffer#limit}
6052 * @returns {!ByteBuffer} this
6053 * @expose
6054 */
6055 ByteBufferPrototype.compact = function(begin, end) {
6056 if (typeof begin === 'undefined') begin = this.offset;
6057 if (typeof end === 'undefined') end = this.limit;
6058 if (!this.noAssert) {
6059 if (typeof begin !== 'number' || begin % 1 !== 0)
6060 throw TypeError("Illegal begin: Not an integer");
6061 begin >>>= 0;
6062 if (typeof end !== 'number' || end % 1 !== 0)
6063 throw TypeError("Illegal end: Not an integer");
6064 end >>>= 0;
6065 if (begin < 0 || begin > end || end > this.buffer.byteLength)
6066 throw RangeError("Illegal range: 0 <= "+begin+" <= "+end+" <= "+this.buffer.byteLength);
6067 }
6068 if (begin === 0 && end === this.buffer.byteLength)
6069 return this; // Already compacted
6070 var len = end - begin;
6071 if (len === 0) {
6072 this.buffer = EMPTY_BUFFER;
6073 this.view = null;
6074 if (this.markedOffset >= 0) this.markedOffset -= begin;
6075 this.offset = 0;
6076 this.limit = 0;
6077 return this;
6078 }
6079 var buffer = new ArrayBuffer(len);
6080 var view = new Uint8Array(buffer);
6081 view.set(this.view.subarray(begin, end));
6082 this.buffer = buffer;
6083 this.view = view;
6084 if (this.markedOffset >= 0) this.markedOffset -= begin;
6085 this.offset = 0;
6086 this.limit = len;
6087 return this;
6088 };
6089
6090 /**
6091 * Creates a copy of this ByteBuffer's contents. Contents are the bytes between {@link ByteBuffer#offset} and
6092 * {@link ByteBuffer#limit}.
6093 * @param {number=} begin Begin offset, defaults to {@link ByteBuffer#offset}.
6094 * @param {number=} end End offset, defaults to {@link ByteBuffer#limit}.
6095 * @returns {!ByteBuffer} Copy
6096 * @expose
6097 */
6098 ByteBufferPrototype.copy = function(begin, end) {
6099 if (typeof begin === 'undefined') begin = this.offset;
6100 if (typeof end === 'undefined') end = this.limit;
6101 if (!this.noAssert) {
6102 if (typeof begin !== 'number' || begin % 1 !== 0)
6103 throw TypeError("Illegal begin: Not an integer");
6104 begin >>>= 0;
6105 if (typeof end !== 'number' || end % 1 !== 0)
6106 throw TypeError("Illegal end: Not an integer");
6107 end >>>= 0;
6108 if (begin < 0 || begin > end || end > this.buffer.byteLength)
6109 throw RangeError("Illegal range: 0 <= "+begin+" <= "+end+" <= "+this.buffer.byteLength);
6110 }
6111 if (begin === end)
6112 return new ByteBuffer(0, this.littleEndian, this.noAssert);
6113 var capacity = end - begin,
6114 bb = new ByteBuffer(capacity, this.littleEndian, this.noAssert);
6115 bb.offset = 0;
6116 bb.limit = capacity;
6117 if (bb.markedOffset >= 0) bb.markedOffset -= begin;
6118 this.copyTo(bb, 0, begin, end);
6119 return bb;
6120 };
6121
6122 /**
6123 * Copies this ByteBuffer's contents to another ByteBuffer. Contents are the bytes between {@link ByteBuffer#offset} and
6124 * {@link ByteBuffer#limit}.
6125 * @param {!ByteBuffer} target Target ByteBuffer
6126 * @param {number=} targetOffset Offset to copy to. Will use and increase the target's {@link ByteBuffer#offset}
6127 * by the number of bytes copied if omitted.
6128 * @param {number=} sourceOffset Offset to start copying from. Will use and increase {@link ByteBuffer#offset} by the
6129 * number of bytes copied if omitted.
6130 * @param {number=} sourceLimit Offset to end copying from, defaults to {@link ByteBuffer#limit}
6131 * @returns {!ByteBuffer} this
6132 * @expose
6133 */
6134 ByteBufferPrototype.copyTo = function(target, targetOffset, sourceOffset, sourceLimit) {
6135 var relative,
6136 targetRelative;
6137 if (!this.noAssert) {
6138 if (!ByteBuffer.isByteBuffer(target))
6139 throw TypeError("Illegal target: Not a ByteBuffer");
6140 }
6141 targetOffset = (targetRelative = typeof targetOffset === 'undefined') ? target.offset : targetOffset | 0;
6142 sourceOffset = (relative = typeof sourceOffset === 'undefined') ? this.offset : sourceOffset | 0;
6143 sourceLimit = typeof sourceLimit === 'undefined' ? this.limit : sourceLimit | 0;
6144
6145 if (targetOffset < 0 || targetOffset > target.buffer.byteLength)
6146 throw RangeError("Illegal target range: 0 <= "+targetOffset+" <= "+target.buffer.byteLength);
6147 if (sourceOffset < 0 || sourceLimit > this.buffer.byteLength)
6148 throw RangeError("Illegal source range: 0 <= "+sourceOffset+" <= "+this.buffer.byteLength);
6149
6150 var len = sourceLimit - sourceOffset;
6151 if (len === 0)
6152 return target; // Nothing to copy
6153
6154 target.ensureCapacity(targetOffset + len);
6155
6156 target.view.set(this.view.subarray(sourceOffset, sourceLimit), targetOffset);
6157
6158 if (relative) this.offset += len;
6159 if (targetRelative) target.offset += len;
6160
6161 return this;
6162 };
6163
6164 /**
6165 * Makes sure that this ByteBuffer is backed by a {@link ByteBuffer#buffer} of at least the specified capacity. If the
6166 * current capacity is exceeded, it will be doubled. If double the current capacity is less than the required capacity,
6167 * the required capacity will be used instead.
6168 * @param {number} capacity Required capacity
6169 * @returns {!ByteBuffer} this
6170 * @expose
6171 */
6172 ByteBufferPrototype.ensureCapacity = function(capacity) {
6173 var current = this.buffer.byteLength;
6174 if (current < capacity)
6175 return this.resize((current *= 2) > capacity ? current : capacity);
6176 return this;
6177 };
6178
6179 /**
6180 * Overwrites this ByteBuffer's contents with the specified value. Contents are the bytes between
6181 * {@link ByteBuffer#offset} and {@link ByteBuffer#limit}.
6182 * @param {number|string} value Byte value to fill with. If given as a string, the first character is used.
6183 * @param {number=} begin Begin offset. Will use and increase {@link ByteBuffer#offset} by the number of bytes
6184 * written if omitted. defaults to {@link ByteBuffer#offset}.
6185 * @param {number=} end End offset, defaults to {@link ByteBuffer#limit}.
6186 * @returns {!ByteBuffer} this
6187 * @expose
6188 * @example `someByteBuffer.clear().fill(0)` fills the entire backing buffer with zeroes
6189 */
6190 ByteBufferPrototype.fill = function(value, begin, end) {
6191 var relative = typeof begin === 'undefined';
6192 if (relative) begin = this.offset;
6193 if (typeof value === 'string' && value.length > 0)
6194 value = value.charCodeAt(0);
6195 if (typeof begin === 'undefined') begin = this.offset;
6196 if (typeof end === 'undefined') end = this.limit;
6197 if (!this.noAssert) {
6198 if (typeof value !== 'number' || value % 1 !== 0)
6199 throw TypeError("Illegal value: "+value+" (not an integer)");
6200 value |= 0;
6201 if (typeof begin !== 'number' || begin % 1 !== 0)
6202 throw TypeError("Illegal begin: Not an integer");
6203 begin >>>= 0;
6204 if (typeof end !== 'number' || end % 1 !== 0)
6205 throw TypeError("Illegal end: Not an integer");
6206 end >>>= 0;
6207 if (begin < 0 || begin > end || end > this.buffer.byteLength)
6208 throw RangeError("Illegal range: 0 <= "+begin+" <= "+end+" <= "+this.buffer.byteLength);
6209 }
6210 if (begin >= end)
6211 return this; // Nothing to fill
6212 while (begin < end) this.view[begin++] = value;
6213 if (relative) this.offset = begin;
6214 return this;
6215 };
6216
6217 /**
6218 * Makes this ByteBuffer ready for a new sequence of write or relative read operations. Sets `limit = offset` and
6219 * `offset = 0`. Make sure always to flip a ByteBuffer when all relative read or write operations are complete.
6220 * @returns {!ByteBuffer} this
6221 * @expose
6222 */
6223 ByteBufferPrototype.flip = function() {
6224 this.limit = this.offset;
6225 this.offset = 0;
6226 return this;
6227 };
6228 /**
6229 * Marks an offset on this ByteBuffer to be used later.
6230 * @param {number=} offset Offset to mark. Defaults to {@link ByteBuffer#offset}.
6231 * @returns {!ByteBuffer} this
6232 * @throws {TypeError} If `offset` is not a valid number
6233 * @throws {RangeError} If `offset` is out of bounds
6234 * @see ByteBuffer#reset
6235 * @expose
6236 */
6237 ByteBufferPrototype.mark = function(offset) {
6238 offset = typeof offset === 'undefined' ? this.offset : offset;
6239 if (!this.noAssert) {
6240 if (typeof offset !== 'number' || offset % 1 !== 0)
6241 throw TypeError("Illegal offset: "+offset+" (not an integer)");
6242 offset >>>= 0;
6243 if (offset < 0 || offset + 0 > this.buffer.byteLength)
6244 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
6245 }
6246 this.markedOffset = offset;
6247 return this;
6248 };
6249 /**
6250 * Sets the byte order.
6251 * @param {boolean} littleEndian `true` for little endian byte order, `false` for big endian
6252 * @returns {!ByteBuffer} this
6253 * @expose
6254 */
6255 ByteBufferPrototype.order = function(littleEndian) {
6256 if (!this.noAssert) {
6257 if (typeof littleEndian !== 'boolean')
6258 throw TypeError("Illegal littleEndian: Not a boolean");
6259 }
6260 this.littleEndian = !!littleEndian;
6261 return this;
6262 };
6263
6264 /**
6265 * Switches (to) little endian byte order.
6266 * @param {boolean=} littleEndian Defaults to `true`, otherwise uses big endian
6267 * @returns {!ByteBuffer} this
6268 * @expose
6269 */
6270 ByteBufferPrototype.LE = function(littleEndian) {
6271 this.littleEndian = typeof littleEndian !== 'undefined' ? !!littleEndian : true;
6272 return this;
6273 };
6274
6275 /**
6276 * Switches (to) big endian byte order.
6277 * @param {boolean=} bigEndian Defaults to `true`, otherwise uses little endian
6278 * @returns {!ByteBuffer} this
6279 * @expose
6280 */
6281 ByteBufferPrototype.BE = function(bigEndian) {
6282 this.littleEndian = typeof bigEndian !== 'undefined' ? !bigEndian : false;
6283 return this;
6284 };
6285 /**
6286 * Prepends some data to this ByteBuffer. This will overwrite any contents before the specified offset up to the
6287 * prepended data's length. If there is not enough space available before the specified `offset`, the backing buffer
6288 * will be resized and its contents moved accordingly.
6289 * @param {!ByteBuffer|string|!ArrayBuffer} source Data to prepend. If `source` is a ByteBuffer, its offset will be
6290 * modified according to the performed read operation.
6291 * @param {(string|number)=} encoding Encoding if `data` is a string ("base64", "hex", "binary", defaults to "utf8")
6292 * @param {number=} offset Offset to prepend at. Will use and decrease {@link ByteBuffer#offset} by the number of bytes
6293 * prepended if omitted.
6294 * @returns {!ByteBuffer} this
6295 * @expose
6296 * @example A relative `00<01 02 03>.prepend(<04 05>)` results in `<04 05 01 02 03>, 04 05|`
6297 * @example An absolute `00<01 02 03>.prepend(<04 05>, 2)` results in `04<05 02 03>, 04 05|`
6298 */
6299 ByteBufferPrototype.prepend = function(source, encoding, offset) {
6300 if (typeof encoding === 'number' || typeof encoding !== 'string') {
6301 offset = encoding;
6302 encoding = undefined;
6303 }
6304 var relative = typeof offset === 'undefined';
6305 if (relative) offset = this.offset;
6306 if (!this.noAssert) {
6307 if (typeof offset !== 'number' || offset % 1 !== 0)
6308 throw TypeError("Illegal offset: "+offset+" (not an integer)");
6309 offset >>>= 0;
6310 if (offset < 0 || offset + 0 > this.buffer.byteLength)
6311 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
6312 }
6313 if (!(source instanceof ByteBuffer))
6314 source = ByteBuffer.wrap(source, encoding);
6315 var len = source.limit - source.offset;
6316 if (len <= 0) return this; // Nothing to prepend
6317 var diff = len - offset;
6318 if (diff > 0) { // Not enough space before offset, so resize + move
6319 var buffer = new ArrayBuffer(this.buffer.byteLength + diff);
6320 var view = new Uint8Array(buffer);
6321 view.set(this.view.subarray(offset, this.buffer.byteLength), len);
6322 this.buffer = buffer;
6323 this.view = view;
6324 this.offset += diff;
6325 if (this.markedOffset >= 0) this.markedOffset += diff;
6326 this.limit += diff;
6327 offset += diff;
6328 } else {
6329 var arrayView = new Uint8Array(this.buffer);
6330 }
6331 this.view.set(source.view.subarray(source.offset, source.limit), offset - len);
6332
6333 source.offset = source.limit;
6334 if (relative)
6335 this.offset -= len;
6336 return this;
6337 };
6338
6339 /**
6340 * Prepends this ByteBuffer to another ByteBuffer. This will overwrite any contents before the specified offset up to the
6341 * prepended data's length. If there is not enough space available before the specified `offset`, the backing buffer
6342 * will be resized and its contents moved accordingly.
6343 * @param {!ByteBuffer} target Target ByteBuffer
6344 * @param {number=} offset Offset to prepend at. Will use and decrease {@link ByteBuffer#offset} by the number of bytes
6345 * prepended if omitted.
6346 * @returns {!ByteBuffer} this
6347 * @expose
6348 * @see ByteBuffer#prepend
6349 */
6350 ByteBufferPrototype.prependTo = function(target, offset) {
6351 target.prepend(this, offset);
6352 return this;
6353 };
6354 /**
6355 * Prints debug information about this ByteBuffer's contents.
6356 * @param {function(string)=} out Output function to call, defaults to console.log
6357 * @expose
6358 */
6359 ByteBufferPrototype.printDebug = function(out) {
6360 if (typeof out !== 'function') out = console.log.bind(console);
6361 out(
6362 this.toString()+"\n"+
6363 "-------------------------------------------------------------------\n"+
6364 this.toDebug(/* columns */ true)
6365 );
6366 };
6367
6368 /**
6369 * Gets the number of remaining readable bytes. Contents are the bytes between {@link ByteBuffer#offset} and
6370 * {@link ByteBuffer#limit}, so this returns `limit - offset`.
6371 * @returns {number} Remaining readable bytes. May be negative if `offset > limit`.
6372 * @expose
6373 */
6374 ByteBufferPrototype.remaining = function() {
6375 return this.limit - this.offset;
6376 };
6377 /**
6378 * Resets this ByteBuffer's {@link ByteBuffer#offset}. If an offset has been marked through {@link ByteBuffer#mark}
6379 * before, `offset` will be set to {@link ByteBuffer#markedOffset}, which will then be discarded. If no offset has been
6380 * marked, sets `offset = 0`.
6381 * @returns {!ByteBuffer} this
6382 * @see ByteBuffer#mark
6383 * @expose
6384 */
6385 ByteBufferPrototype.reset = function() {
6386 if (this.markedOffset >= 0) {
6387 this.offset = this.markedOffset;
6388 this.markedOffset = -1;
6389 } else {
6390 this.offset = 0;
6391 }
6392 return this;
6393 };
6394 /**
6395 * Resizes this ByteBuffer to be backed by a buffer of at least the given capacity. Will do nothing if already that
6396 * large or larger.
6397 * @param {number} capacity Capacity required
6398 * @returns {!ByteBuffer} this
6399 * @throws {TypeError} If `capacity` is not a number
6400 * @throws {RangeError} If `capacity < 0`
6401 * @expose
6402 */
6403 ByteBufferPrototype.resize = function(capacity) {
6404 if (!this.noAssert) {
6405 if (typeof capacity !== 'number' || capacity % 1 !== 0)
6406 throw TypeError("Illegal capacity: "+capacity+" (not an integer)");
6407 capacity |= 0;
6408 if (capacity < 0)
6409 throw RangeError("Illegal capacity: 0 <= "+capacity);
6410 }
6411 if (this.buffer.byteLength < capacity) {
6412 var buffer = new ArrayBuffer(capacity);
6413 var view = new Uint8Array(buffer);
6414 view.set(this.view);
6415 this.buffer = buffer;
6416 this.view = view;
6417 }
6418 return this;
6419 };
6420 /**
6421 * Reverses this ByteBuffer's contents.
6422 * @param {number=} begin Offset to start at, defaults to {@link ByteBuffer#offset}
6423 * @param {number=} end Offset to end at, defaults to {@link ByteBuffer#limit}
6424 * @returns {!ByteBuffer} this
6425 * @expose
6426 */
6427 ByteBufferPrototype.reverse = function(begin, end) {
6428 if (typeof begin === 'undefined') begin = this.offset;
6429 if (typeof end === 'undefined') end = this.limit;
6430 if (!this.noAssert) {
6431 if (typeof begin !== 'number' || begin % 1 !== 0)
6432 throw TypeError("Illegal begin: Not an integer");
6433 begin >>>= 0;
6434 if (typeof end !== 'number' || end % 1 !== 0)
6435 throw TypeError("Illegal end: Not an integer");
6436 end >>>= 0;
6437 if (begin < 0 || begin > end || end > this.buffer.byteLength)
6438 throw RangeError("Illegal range: 0 <= "+begin+" <= "+end+" <= "+this.buffer.byteLength);
6439 }
6440 if (begin === end)
6441 return this; // Nothing to reverse
6442 Array.prototype.reverse.call(this.view.subarray(begin, end));
6443 return this;
6444 };
6445 /**
6446 * Skips the next `length` bytes. This will just advance
6447 * @param {number} length Number of bytes to skip. May also be negative to move the offset back.
6448 * @returns {!ByteBuffer} this
6449 * @expose
6450 */
6451 ByteBufferPrototype.skip = function(length) {
6452 if (!this.noAssert) {
6453 if (typeof length !== 'number' || length % 1 !== 0)
6454 throw TypeError("Illegal length: "+length+" (not an integer)");
6455 length |= 0;
6456 }
6457 var offset = this.offset + length;
6458 if (!this.noAssert) {
6459 if (offset < 0 || offset > this.buffer.byteLength)
6460 throw RangeError("Illegal length: 0 <= "+this.offset+" + "+length+" <= "+this.buffer.byteLength);
6461 }
6462 this.offset = offset;
6463 return this;
6464 };
6465
6466 /**
6467 * Slices this ByteBuffer by creating a cloned instance with `offset = begin` and `limit = end`.
6468 * @param {number=} begin Begin offset, defaults to {@link ByteBuffer#offset}.
6469 * @param {number=} end End offset, defaults to {@link ByteBuffer#limit}.
6470 * @returns {!ByteBuffer} Clone of this ByteBuffer with slicing applied, backed by the same {@link ByteBuffer#buffer}
6471 * @expose
6472 */
6473 ByteBufferPrototype.slice = function(begin, end) {
6474 if (typeof begin === 'undefined') begin = this.offset;
6475 if (typeof end === 'undefined') end = this.limit;
6476 if (!this.noAssert) {
6477 if (typeof begin !== 'number' || begin % 1 !== 0)
6478 throw TypeError("Illegal begin: Not an integer");
6479 begin >>>= 0;
6480 if (typeof end !== 'number' || end % 1 !== 0)
6481 throw TypeError("Illegal end: Not an integer");
6482 end >>>= 0;
6483 if (begin < 0 || begin > end || end > this.buffer.byteLength)
6484 throw RangeError("Illegal range: 0 <= "+begin+" <= "+end+" <= "+this.buffer.byteLength);
6485 }
6486 var bb = this.clone();
6487 bb.offset = begin;
6488 bb.limit = end;
6489 return bb;
6490 };
6491 /**
6492 * Returns a copy of the backing buffer that contains this ByteBuffer's contents. Contents are the bytes between
6493 * {@link ByteBuffer#offset} and {@link ByteBuffer#limit}.
6494 * @param {boolean=} forceCopy If `true` returns a copy, otherwise returns a view referencing the same memory if
6495 * possible. Defaults to `false`
6496 * @returns {!ArrayBuffer} Contents as an ArrayBuffer
6497 * @expose
6498 */
6499 ByteBufferPrototype.toBuffer = function(forceCopy) {
6500 var offset = this.offset,
6501 limit = this.limit;
6502 if (!this.noAssert) {
6503 if (typeof offset !== 'number' || offset % 1 !== 0)
6504 throw TypeError("Illegal offset: Not an integer");
6505 offset >>>= 0;
6506 if (typeof limit !== 'number' || limit % 1 !== 0)
6507 throw TypeError("Illegal limit: Not an integer");
6508 limit >>>= 0;
6509 if (offset < 0 || offset > limit || limit > this.buffer.byteLength)
6510 throw RangeError("Illegal range: 0 <= "+offset+" <= "+limit+" <= "+this.buffer.byteLength);
6511 }
6512 // NOTE: It's not possible to have another ArrayBuffer reference the same memory as the backing buffer. This is
6513 // possible with Uint8Array#subarray only, but we have to return an ArrayBuffer by contract. So:
6514 if (!forceCopy && offset === 0 && limit === this.buffer.byteLength)
6515 return this.buffer;
6516 if (offset === limit)
6517 return EMPTY_BUFFER;
6518 var buffer = new ArrayBuffer(limit - offset);
6519 new Uint8Array(buffer).set(new Uint8Array(this.buffer).subarray(offset, limit), 0);
6520 return buffer;
6521 };
6522
6523 /**
6524 * Returns a raw buffer compacted to contain this ByteBuffer's contents. Contents are the bytes between
6525 * {@link ByteBuffer#offset} and {@link ByteBuffer#limit}. This is an alias of {@link ByteBuffer#toBuffer}.
6526 * @function
6527 * @param {boolean=} forceCopy If `true` returns a copy, otherwise returns a view referencing the same memory.
6528 * Defaults to `false`
6529 * @returns {!ArrayBuffer} Contents as an ArrayBuffer
6530 * @expose
6531 */
6532 ByteBufferPrototype.toArrayBuffer = ByteBufferPrototype.toBuffer;
6533
6534 /**
6535 * Converts the ByteBuffer's contents to a string.
6536 * @param {string=} encoding Output encoding. Returns an informative string representation if omitted but also allows
6537 * direct conversion to "utf8", "hex", "base64" and "binary" encoding. "debug" returns a hex representation with
6538 * highlighted offsets.
6539 * @param {number=} begin Offset to begin at, defaults to {@link ByteBuffer#offset}
6540 * @param {number=} end Offset to end at, defaults to {@link ByteBuffer#limit}
6541 * @returns {string} String representation
6542 * @throws {Error} If `encoding` is invalid
6543 * @expose
6544 */
6545 ByteBufferPrototype.toString = function(encoding, begin, end) {
6546 if (typeof encoding === 'undefined')
6547 return "ByteBufferAB(offset="+this.offset+",markedOffset="+this.markedOffset+",limit="+this.limit+",capacity="+this.capacity()+")";
6548 if (typeof encoding === 'number')
6549 encoding = "utf8",
6550 begin = encoding,
6551 end = begin;
6552 switch (encoding) {
6553 case "utf8":
6554 return this.toUTF8(begin, end);
6555 case "base64":
6556 return this.toBase64(begin, end);
6557 case "hex":
6558 return this.toHex(begin, end);
6559 case "binary":
6560 return this.toBinary(begin, end);
6561 case "debug":
6562 return this.toDebug();
6563 case "columns":
6564 return this.toColumns();
6565 default:
6566 throw Error("Unsupported encoding: "+encoding);
6567 }
6568 };
6569
6570 // lxiv-embeddable
6571
6572 /**
6573 * lxiv-embeddable (c) 2014 Daniel Wirtz <dcode@dcode.io>
6574 * Released under the Apache License, Version 2.0
6575 * see: https://github.com/dcodeIO/lxiv for details
6576 */
6577 var lxiv = function() {
6578
6579 /**
6580 * lxiv namespace.
6581 * @type {!Object.<string,*>}
6582 * @exports lxiv
6583 */
6584 var lxiv = {};
6585
6586 /**
6587 * Character codes for output.
6588 * @type {!Array.<number>}
6589 * @inner
6590 */
6591 var aout = [
6592 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80,
6593 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 97, 98, 99, 100, 101, 102,
6594 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118,
6595 119, 120, 121, 122, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 43, 47
6596 ];
6597
6598 /**
6599 * Character codes for input.
6600 * @type {!Array.<number>}
6601 * @inner
6602 */
6603 var ain = [];
6604 for (var i=0, k=aout.length; i<k; ++i)
6605 ain[aout[i]] = i;
6606
6607 /**
6608 * Encodes bytes to base64 char codes.
6609 * @param {!function():number|null} src Bytes source as a function returning the next byte respectively `null` if
6610 * there are no more bytes left.
6611 * @param {!function(number)} dst Characters destination as a function successively called with each encoded char
6612 * code.
6613 */
6614 lxiv.encode = function(src, dst) {
6615 var b, t;
6616 while ((b = src()) !== null) {
6617 dst(aout[(b>>2)&0x3f]);
6618 t = (b&0x3)<<4;
6619 if ((b = src()) !== null) {
6620 t |= (b>>4)&0xf;
6621 dst(aout[(t|((b>>4)&0xf))&0x3f]);
6622 t = (b&0xf)<<2;
6623 if ((b = src()) !== null)
6624 dst(aout[(t|((b>>6)&0x3))&0x3f]),
6625 dst(aout[b&0x3f]);
6626 else
6627 dst(aout[t&0x3f]),
6628 dst(61);
6629 } else
6630 dst(aout[t&0x3f]),
6631 dst(61),
6632 dst(61);
6633 }
6634 };
6635
6636 /**
6637 * Decodes base64 char codes to bytes.
6638 * @param {!function():number|null} src Characters source as a function returning the next char code respectively
6639 * `null` if there are no more characters left.
6640 * @param {!function(number)} dst Bytes destination as a function successively called with the next byte.
6641 * @throws {Error} If a character code is invalid
6642 */
6643 lxiv.decode = function(src, dst) {
6644 var c, t1, t2;
6645 function fail(c) {
6646 throw Error("Illegal character code: "+c);
6647 }
6648 while ((c = src()) !== null) {
6649 t1 = ain[c];
6650 if (typeof t1 === 'undefined') fail(c);
6651 if ((c = src()) !== null) {
6652 t2 = ain[c];
6653 if (typeof t2 === 'undefined') fail(c);
6654 dst((t1<<2)>>>0|(t2&0x30)>>4);
6655 if ((c = src()) !== null) {
6656 t1 = ain[c];
6657 if (typeof t1 === 'undefined')
6658 if (c === 61) break; else fail(c);
6659 dst(((t2&0xf)<<4)>>>0|(t1&0x3c)>>2);
6660 if ((c = src()) !== null) {
6661 t2 = ain[c];
6662 if (typeof t2 === 'undefined')
6663 if (c === 61) break; else fail(c);
6664 dst(((t1&0x3)<<6)>>>0|t2);
6665 }
6666 }
6667 }
6668 }
6669 };
6670
6671 /**
6672 * Tests if a string is valid base64.
6673 * @param {string} str String to test
6674 * @returns {boolean} `true` if valid, otherwise `false`
6675 */
6676 lxiv.test = function(str) {
6677 return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(str);
6678 };
6679
6680 return lxiv;
6681 }();
6682
6683 // encodings/base64
6684
6685 /**
6686 * Encodes this ByteBuffer's contents to a base64 encoded string.
6687 * @param {number=} begin Offset to begin at, defaults to {@link ByteBuffer#offset}.
6688 * @param {number=} end Offset to end at, defaults to {@link ByteBuffer#limit}.
6689 * @returns {string} Base64 encoded string
6690 * @throws {RangeError} If `begin` or `end` is out of bounds
6691 * @expose
6692 */
6693 ByteBufferPrototype.toBase64 = function(begin, end) {
6694 if (typeof begin === 'undefined')
6695 begin = this.offset;
6696 if (typeof end === 'undefined')
6697 end = this.limit;
6698 begin = begin | 0; end = end | 0;
6699 if (begin < 0 || end > this.capacity || begin > end)
6700 throw RangeError("begin, end");
6701 var sd; lxiv.encode(function() {
6702 return begin < end ? this.view[begin++] : null;
6703 }.bind(this), sd = stringDestination());
6704 return sd();
6705 };
6706
6707 /**
6708 * Decodes a base64 encoded string to a ByteBuffer.
6709 * @param {string} str String to decode
6710 * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
6711 * {@link ByteBuffer.DEFAULT_ENDIAN}.
6712 * @returns {!ByteBuffer} ByteBuffer
6713 * @expose
6714 */
6715 ByteBuffer.fromBase64 = function(str, littleEndian) {
6716 if (typeof str !== 'string')
6717 throw TypeError("str");
6718 var bb = new ByteBuffer(str.length/4*3, littleEndian),
6719 i = 0;
6720 lxiv.decode(stringSource(str), function(b) {
6721 bb.view[i++] = b;
6722 });
6723 bb.limit = i;
6724 return bb;
6725 };
6726
6727 /**
6728 * Encodes a binary string to base64 like `window.btoa` does.
6729 * @param {string} str Binary string
6730 * @returns {string} Base64 encoded string
6731 * @see https://developer.mozilla.org/en-US/docs/Web/API/Window.btoa
6732 * @expose
6733 */
6734 ByteBuffer.btoa = function(str) {
6735 return ByteBuffer.fromBinary(str).toBase64();
6736 };
6737
6738 /**
6739 * Decodes a base64 encoded string to binary like `window.atob` does.
6740 * @param {string} b64 Base64 encoded string
6741 * @returns {string} Binary string
6742 * @see https://developer.mozilla.org/en-US/docs/Web/API/Window.atob
6743 * @expose
6744 */
6745 ByteBuffer.atob = function(b64) {
6746 return ByteBuffer.fromBase64(b64).toBinary();
6747 };
6748
6749 // encodings/binary
6750
6751 /**
6752 * Encodes this ByteBuffer to a binary encoded string, that is using only characters 0x00-0xFF as bytes.
6753 * @param {number=} begin Offset to begin at. Defaults to {@link ByteBuffer#offset}.
6754 * @param {number=} end Offset to end at. Defaults to {@link ByteBuffer#limit}.
6755 * @returns {string} Binary encoded string
6756 * @throws {RangeError} If `offset > limit`
6757 * @expose
6758 */
6759 ByteBufferPrototype.toBinary = function(begin, end) {
6760 if (typeof begin === 'undefined')
6761 begin = this.offset;
6762 if (typeof end === 'undefined')
6763 end = this.limit;
6764 begin |= 0; end |= 0;
6765 if (begin < 0 || end > this.capacity() || begin > end)
6766 throw RangeError("begin, end");
6767 if (begin === end)
6768 return "";
6769 var chars = [],
6770 parts = [];
6771 while (begin < end) {
6772 chars.push(this.view[begin++]);
6773 if (chars.length >= 1024)
6774 parts.push(String.fromCharCode.apply(String, chars)),
6775 chars = [];
6776 }
6777 return parts.join('') + String.fromCharCode.apply(String, chars);
6778 };
6779
6780 /**
6781 * Decodes a binary encoded string, that is using only characters 0x00-0xFF as bytes, to a ByteBuffer.
6782 * @param {string} str String to decode
6783 * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
6784 * {@link ByteBuffer.DEFAULT_ENDIAN}.
6785 * @returns {!ByteBuffer} ByteBuffer
6786 * @expose
6787 */
6788 ByteBuffer.fromBinary = function(str, littleEndian) {
6789 if (typeof str !== 'string')
6790 throw TypeError("str");
6791 var i = 0,
6792 k = str.length,
6793 charCode,
6794 bb = new ByteBuffer(k, littleEndian);
6795 while (i<k) {
6796 charCode = str.charCodeAt(i);
6797 if (charCode > 0xff)
6798 throw RangeError("illegal char code: "+charCode);
6799 bb.view[i++] = charCode;
6800 }
6801 bb.limit = k;
6802 return bb;
6803 };
6804
6805 // encodings/debug
6806
6807 /**
6808 * Encodes this ByteBuffer to a hex encoded string with marked offsets. Offset symbols are:
6809 * * `<` : offset,
6810 * * `'` : markedOffset,
6811 * * `>` : limit,
6812 * * `|` : offset and limit,
6813 * * `[` : offset and markedOffset,
6814 * * `]` : markedOffset and limit,
6815 * * `!` : offset, markedOffset and limit
6816 * @param {boolean=} columns If `true` returns two columns hex + ascii, defaults to `false`
6817 * @returns {string|!Array.<string>} Debug string or array of lines if `asArray = true`
6818 * @expose
6819 * @example `>00'01 02<03` contains four bytes with `limit=0, markedOffset=1, offset=3`
6820 * @example `00[01 02 03>` contains four bytes with `offset=markedOffset=1, limit=4`
6821 * @example `00|01 02 03` contains four bytes with `offset=limit=1, markedOffset=-1`
6822 * @example `|` contains zero bytes with `offset=limit=0, markedOffset=-1`
6823 */
6824 ByteBufferPrototype.toDebug = function(columns) {
6825 var i = -1,
6826 k = this.buffer.byteLength,
6827 b,
6828 hex = "",
6829 asc = "",
6830 out = "";
6831 while (i<k) {
6832 if (i !== -1) {
6833 b = this.view[i];
6834 if (b < 0x10) hex += "0"+b.toString(16).toUpperCase();
6835 else hex += b.toString(16).toUpperCase();
6836 if (columns)
6837 asc += b > 32 && b < 127 ? String.fromCharCode(b) : '.';
6838 }
6839 ++i;
6840 if (columns) {
6841 if (i > 0 && i % 16 === 0 && i !== k) {
6842 while (hex.length < 3*16+3) hex += " ";
6843 out += hex+asc+"\n";
6844 hex = asc = "";
6845 }
6846 }
6847 if (i === this.offset && i === this.limit)
6848 hex += i === this.markedOffset ? "!" : "|";
6849 else if (i === this.offset)
6850 hex += i === this.markedOffset ? "[" : "<";
6851 else if (i === this.limit)
6852 hex += i === this.markedOffset ? "]" : ">";
6853 else
6854 hex += i === this.markedOffset ? "'" : (columns || (i !== 0 && i !== k) ? " " : "");
6855 }
6856 if (columns && hex !== " ") {
6857 while (hex.length < 3*16+3)
6858 hex += " ";
6859 out += hex + asc + "\n";
6860 }
6861 return columns ? out : hex;
6862 };
6863
6864 /**
6865 * Decodes a hex encoded string with marked offsets to a ByteBuffer.
6866 * @param {string} str Debug string to decode (not be generated with `columns = true`)
6867 * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
6868 * {@link ByteBuffer.DEFAULT_ENDIAN}.
6869 * @param {boolean=} noAssert Whether to skip assertions of offsets and values. Defaults to
6870 * {@link ByteBuffer.DEFAULT_NOASSERT}.
6871 * @returns {!ByteBuffer} ByteBuffer
6872 * @expose
6873 * @see ByteBuffer#toDebug
6874 */
6875 ByteBuffer.fromDebug = function(str, littleEndian, noAssert) {
6876 var k = str.length,
6877 bb = new ByteBuffer(((k+1)/3)|0, littleEndian, noAssert);
6878 var i = 0, j = 0, ch, b,
6879 rs = false, // Require symbol next
6880 ho = false, hm = false, hl = false, // Already has offset (ho), markedOffset (hm), limit (hl)?
6881 fail = false;
6882 while (i<k) {
6883 switch (ch = str.charAt(i++)) {
6884 case '!':
6885 if (!noAssert) {
6886 if (ho || hm || hl) {
6887 fail = true;
6888 break;
6889 }
6890 ho = hm = hl = true;
6891 }
6892 bb.offset = bb.markedOffset = bb.limit = j;
6893 rs = false;
6894 break;
6895 case '|':
6896 if (!noAssert) {
6897 if (ho || hl) {
6898 fail = true;
6899 break;
6900 }
6901 ho = hl = true;
6902 }
6903 bb.offset = bb.limit = j;
6904 rs = false;
6905 break;
6906 case '[':
6907 if (!noAssert) {
6908 if (ho || hm) {
6909 fail = true;
6910 break;
6911 }
6912 ho = hm = true;
6913 }
6914 bb.offset = bb.markedOffset = j;
6915 rs = false;
6916 break;
6917 case '<':
6918 if (!noAssert) {
6919 if (ho) {
6920 fail = true;
6921 break;
6922 }
6923 ho = true;
6924 }
6925 bb.offset = j;
6926 rs = false;
6927 break;
6928 case ']':
6929 if (!noAssert) {
6930 if (hl || hm) {
6931 fail = true;
6932 break;
6933 }
6934 hl = hm = true;
6935 }
6936 bb.limit = bb.markedOffset = j;
6937 rs = false;
6938 break;
6939 case '>':
6940 if (!noAssert) {
6941 if (hl) {
6942 fail = true;
6943 break;
6944 }
6945 hl = true;
6946 }
6947 bb.limit = j;
6948 rs = false;
6949 break;
6950 case "'":
6951 if (!noAssert) {
6952 if (hm) {
6953 fail = true;
6954 break;
6955 }
6956 hm = true;
6957 }
6958 bb.markedOffset = j;
6959 rs = false;
6960 break;
6961 case ' ':
6962 rs = false;
6963 break;
6964 default:
6965 if (!noAssert) {
6966 if (rs) {
6967 fail = true;
6968 break;
6969 }
6970 }
6971 b = parseInt(ch+str.charAt(i++), 16);
6972 if (!noAssert) {
6973 if (isNaN(b) || b < 0 || b > 255)
6974 throw TypeError("Illegal str: Not a debug encoded string");
6975 }
6976 bb.view[j++] = b;
6977 rs = true;
6978 }
6979 if (fail)
6980 throw TypeError("Illegal str: Invalid symbol at "+i);
6981 }
6982 if (!noAssert) {
6983 if (!ho || !hl)
6984 throw TypeError("Illegal str: Missing offset or limit");
6985 if (j<bb.buffer.byteLength)
6986 throw TypeError("Illegal str: Not a debug encoded string (is it hex?) "+j+" < "+k);
6987 }
6988 return bb;
6989 };
6990
6991 // encodings/hex
6992
6993 /**
6994 * Encodes this ByteBuffer's contents to a hex encoded string.
6995 * @param {number=} begin Offset to begin at. Defaults to {@link ByteBuffer#offset}.
6996 * @param {number=} end Offset to end at. Defaults to {@link ByteBuffer#limit}.
6997 * @returns {string} Hex encoded string
6998 * @expose
6999 */
7000 ByteBufferPrototype.toHex = function(begin, end) {
7001 begin = typeof begin === 'undefined' ? this.offset : begin;
7002 end = typeof end === 'undefined' ? this.limit : end;
7003 if (!this.noAssert) {
7004 if (typeof begin !== 'number' || begin % 1 !== 0)
7005 throw TypeError("Illegal begin: Not an integer");
7006 begin >>>= 0;
7007 if (typeof end !== 'number' || end % 1 !== 0)
7008 throw TypeError("Illegal end: Not an integer");
7009 end >>>= 0;
7010 if (begin < 0 || begin > end || end > this.buffer.byteLength)
7011 throw RangeError("Illegal range: 0 <= "+begin+" <= "+end+" <= "+this.buffer.byteLength);
7012 }
7013 var out = new Array(end - begin),
7014 b;
7015 while (begin < end) {
7016 b = this.view[begin++];
7017 if (b < 0x10)
7018 out.push("0", b.toString(16));
7019 else out.push(b.toString(16));
7020 }
7021 return out.join('');
7022 };
7023
7024 /**
7025 * Decodes a hex encoded string to a ByteBuffer.
7026 * @param {string} str String to decode
7027 * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
7028 * {@link ByteBuffer.DEFAULT_ENDIAN}.
7029 * @param {boolean=} noAssert Whether to skip assertions of offsets and values. Defaults to
7030 * {@link ByteBuffer.DEFAULT_NOASSERT}.
7031 * @returns {!ByteBuffer} ByteBuffer
7032 * @expose
7033 */
7034 ByteBuffer.fromHex = function(str, littleEndian, noAssert) {
7035 if (!noAssert) {
7036 if (typeof str !== 'string')
7037 throw TypeError("Illegal str: Not a string");
7038 if (str.length % 2 !== 0)
7039 throw TypeError("Illegal str: Length not a multiple of 2");
7040 }
7041 var k = str.length,
7042 bb = new ByteBuffer((k / 2) | 0, littleEndian),
7043 b;
7044 for (var i=0, j=0; i<k; i+=2) {
7045 b = parseInt(str.substring(i, i+2), 16);
7046 if (!noAssert)
7047 if (!isFinite(b) || b < 0 || b > 255)
7048 throw TypeError("Illegal str: Contains non-hex characters");
7049 bb.view[j++] = b;
7050 }
7051 bb.limit = j;
7052 return bb;
7053 };
7054
7055 // utfx-embeddable
7056
7057 /**
7058 * utfx-embeddable (c) 2014 Daniel Wirtz <dcode@dcode.io>
7059 * Released under the Apache License, Version 2.0
7060 * see: https://github.com/dcodeIO/utfx for details
7061 */
7062 var utfx = function() {
7063
7064 /**
7065 * utfx namespace.
7066 * @inner
7067 * @type {!Object.<string,*>}
7068 */
7069 var utfx = {};
7070
7071 /**
7072 * Maximum valid code point.
7073 * @type {number}
7074 * @const
7075 */
7076 utfx.MAX_CODEPOINT = 0x10FFFF;
7077
7078 /**
7079 * Encodes UTF8 code points to UTF8 bytes.
7080 * @param {(!function():number|null) | number} src Code points source, either as a function returning the next code point
7081 * respectively `null` if there are no more code points left or a single numeric code point.
7082 * @param {!function(number)} dst Bytes destination as a function successively called with the next byte
7083 */
7084 utfx.encodeUTF8 = function(src, dst) {
7085 var cp = null;
7086 if (typeof src === 'number')
7087 cp = src,
7088 src = function() { return null; };
7089 while (cp !== null || (cp = src()) !== null) {
7090 if (cp < 0x80)
7091 dst(cp&0x7F);
7092 else if (cp < 0x800)
7093 dst(((cp>>6)&0x1F)|0xC0),
7094 dst((cp&0x3F)|0x80);
7095 else if (cp < 0x10000)
7096 dst(((cp>>12)&0x0F)|0xE0),
7097 dst(((cp>>6)&0x3F)|0x80),
7098 dst((cp&0x3F)|0x80);
7099 else
7100 dst(((cp>>18)&0x07)|0xF0),
7101 dst(((cp>>12)&0x3F)|0x80),
7102 dst(((cp>>6)&0x3F)|0x80),
7103 dst((cp&0x3F)|0x80);
7104 cp = null;
7105 }
7106 };
7107
7108 /**
7109 * Decodes UTF8 bytes to UTF8 code points.
7110 * @param {!function():number|null} src Bytes source as a function returning the next byte respectively `null` if there
7111 * are no more bytes left.
7112 * @param {!function(number)} dst Code points destination as a function successively called with each decoded code point.
7113 * @throws {RangeError} If a starting byte is invalid in UTF8
7114 * @throws {Error} If the last sequence is truncated. Has an array property `bytes` holding the
7115 * remaining bytes.
7116 */
7117 utfx.decodeUTF8 = function(src, dst) {
7118 var a, b, c, d, fail = function(b) {
7119 b = b.slice(0, b.indexOf(null));
7120 var err = Error(b.toString());
7121 err.name = "TruncatedError";
7122 err['bytes'] = b;
7123 throw err;
7124 };
7125 while ((a = src()) !== null) {
7126 if ((a&0x80) === 0)
7127 dst(a);
7128 else if ((a&0xE0) === 0xC0)
7129 ((b = src()) === null) && fail([a, b]),
7130 dst(((a&0x1F)<<6) | (b&0x3F));
7131 else if ((a&0xF0) === 0xE0)
7132 ((b=src()) === null || (c=src()) === null) && fail([a, b, c]),
7133 dst(((a&0x0F)<<12) | ((b&0x3F)<<6) | (c&0x3F));
7134 else if ((a&0xF8) === 0xF0)
7135 ((b=src()) === null || (c=src()) === null || (d=src()) === null) && fail([a, b, c ,d]),
7136 dst(((a&0x07)<<18) | ((b&0x3F)<<12) | ((c&0x3F)<<6) | (d&0x3F));
7137 else throw RangeError("Illegal starting byte: "+a);
7138 }
7139 };
7140
7141 /**
7142 * Converts UTF16 characters to UTF8 code points.
7143 * @param {!function():number|null} src Characters source as a function returning the next char code respectively
7144 * `null` if there are no more characters left.
7145 * @param {!function(number)} dst Code points destination as a function successively called with each converted code
7146 * point.
7147 */
7148 utfx.UTF16toUTF8 = function(src, dst) {
7149 var c1, c2 = null;
7150 while (true) {
7151 if ((c1 = c2 !== null ? c2 : src()) === null)
7152 break;
7153 if (c1 >= 0xD800 && c1 <= 0xDFFF) {
7154 if ((c2 = src()) !== null) {
7155 if (c2 >= 0xDC00 && c2 <= 0xDFFF) {
7156 dst((c1-0xD800)*0x400+c2-0xDC00+0x10000);
7157 c2 = null; continue;
7158 }
7159 }
7160 }
7161 dst(c1);
7162 }
7163 if (c2 !== null) dst(c2);
7164 };
7165
7166 /**
7167 * Converts UTF8 code points to UTF16 characters.
7168 * @param {(!function():number|null) | number} src Code points source, either as a function returning the next code point
7169 * respectively `null` if there are no more code points left or a single numeric code point.
7170 * @param {!function(number)} dst Characters destination as a function successively called with each converted char code.
7171 * @throws {RangeError} If a code point is out of range
7172 */
7173 utfx.UTF8toUTF16 = function(src, dst) {
7174 var cp = null;
7175 if (typeof src === 'number')
7176 cp = src, src = function() { return null; };
7177 while (cp !== null || (cp = src()) !== null) {
7178 if (cp <= 0xFFFF)
7179 dst(cp);
7180 else
7181 cp -= 0x10000,
7182 dst((cp>>10)+0xD800),
7183 dst((cp%0x400)+0xDC00);
7184 cp = null;
7185 }
7186 };
7187
7188 /**
7189 * Converts and encodes UTF16 characters to UTF8 bytes.
7190 * @param {!function():number|null} src Characters source as a function returning the next char code respectively `null`
7191 * if there are no more characters left.
7192 * @param {!function(number)} dst Bytes destination as a function successively called with the next byte.
7193 */
7194 utfx.encodeUTF16toUTF8 = function(src, dst) {
7195 utfx.UTF16toUTF8(src, function(cp) {
7196 utfx.encodeUTF8(cp, dst);
7197 });
7198 };
7199
7200 /**
7201 * Decodes and converts UTF8 bytes to UTF16 characters.
7202 * @param {!function():number|null} src Bytes source as a function returning the next byte respectively `null` if there
7203 * are no more bytes left.
7204 * @param {!function(number)} dst Characters destination as a function successively called with each converted char code.
7205 * @throws {RangeError} If a starting byte is invalid in UTF8
7206 * @throws {Error} If the last sequence is truncated. Has an array property `bytes` holding the remaining bytes.
7207 */
7208 utfx.decodeUTF8toUTF16 = function(src, dst) {
7209 utfx.decodeUTF8(src, function(cp) {
7210 utfx.UTF8toUTF16(cp, dst);
7211 });
7212 };
7213
7214 /**
7215 * Calculates the byte length of an UTF8 code point.
7216 * @param {number} cp UTF8 code point
7217 * @returns {number} Byte length
7218 */
7219 utfx.calculateCodePoint = function(cp) {
7220 return (cp < 0x80) ? 1 : (cp < 0x800) ? 2 : (cp < 0x10000) ? 3 : 4;
7221 };
7222
7223 /**
7224 * Calculates the number of UTF8 bytes required to store UTF8 code points.
7225 * @param {(!function():number|null)} src Code points source as a function returning the next code point respectively
7226 * `null` if there are no more code points left.
7227 * @returns {number} The number of UTF8 bytes required
7228 */
7229 utfx.calculateUTF8 = function(src) {
7230 var cp, l=0;
7231 while ((cp = src()) !== null)
7232 l += (cp < 0x80) ? 1 : (cp < 0x800) ? 2 : (cp < 0x10000) ? 3 : 4;
7233 return l;
7234 };
7235
7236 /**
7237 * Calculates the number of UTF8 code points respectively UTF8 bytes required to store UTF16 char codes.
7238 * @param {(!function():number|null)} src Characters source as a function returning the next char code respectively
7239 * `null` if there are no more characters left.
7240 * @returns {!Array.<number>} The number of UTF8 code points at index 0 and the number of UTF8 bytes required at index 1.
7241 */
7242 utfx.calculateUTF16asUTF8 = function(src) {
7243 var n=0, l=0;
7244 utfx.UTF16toUTF8(src, function(cp) {
7245 ++n; l += (cp < 0x80) ? 1 : (cp < 0x800) ? 2 : (cp < 0x10000) ? 3 : 4;
7246 });
7247 return [n,l];
7248 };
7249
7250 return utfx;
7251 }();
7252
7253 // encodings/utf8
7254
7255 /**
7256 * Encodes this ByteBuffer's contents between {@link ByteBuffer#offset} and {@link ByteBuffer#limit} to an UTF8 encoded
7257 * string.
7258 * @returns {string} Hex encoded string
7259 * @throws {RangeError} If `offset > limit`
7260 * @expose
7261 */
7262 ByteBufferPrototype.toUTF8 = function(begin, end) {
7263 if (typeof begin === 'undefined') begin = this.offset;
7264 if (typeof end === 'undefined') end = this.limit;
7265 if (!this.noAssert) {
7266 if (typeof begin !== 'number' || begin % 1 !== 0)
7267 throw TypeError("Illegal begin: Not an integer");
7268 begin >>>= 0;
7269 if (typeof end !== 'number' || end % 1 !== 0)
7270 throw TypeError("Illegal end: Not an integer");
7271 end >>>= 0;
7272 if (begin < 0 || begin > end || end > this.buffer.byteLength)
7273 throw RangeError("Illegal range: 0 <= "+begin+" <= "+end+" <= "+this.buffer.byteLength);
7274 }
7275 var sd; try {
7276 utfx.decodeUTF8toUTF16(function() {
7277 return begin < end ? this.view[begin++] : null;
7278 }.bind(this), sd = stringDestination());
7279 } catch (e) {
7280 if (begin !== end)
7281 throw RangeError("Illegal range: Truncated data, "+begin+" != "+end);
7282 }
7283 return sd();
7284 };
7285
7286 /**
7287 * Decodes an UTF8 encoded string to a ByteBuffer.
7288 * @param {string} str String to decode
7289 * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
7290 * {@link ByteBuffer.DEFAULT_ENDIAN}.
7291 * @param {boolean=} noAssert Whether to skip assertions of offsets and values. Defaults to
7292 * {@link ByteBuffer.DEFAULT_NOASSERT}.
7293 * @returns {!ByteBuffer} ByteBuffer
7294 * @expose
7295 */
7296 ByteBuffer.fromUTF8 = function(str, littleEndian, noAssert) {
7297 if (!noAssert)
7298 if (typeof str !== 'string')
7299 throw TypeError("Illegal str: Not a string");
7300 var bb = new ByteBuffer(utfx.calculateUTF16asUTF8(stringSource(str), true)[1], littleEndian, noAssert),
7301 i = 0;
7302 utfx.encodeUTF16toUTF8(stringSource(str), function(b) {
7303 bb.view[i++] = b;
7304 });
7305 bb.limit = i;
7306 return bb;
7307 };
7308
7309 return ByteBuffer;
7310 });
7311 });
7312
7313 var _nodeResolve_empty = {};
7314
7315 var _nodeResolve_empty$1 = /*#__PURE__*/Object.freeze({
7316 __proto__: null,
7317 'default': _nodeResolve_empty
7318 });
7319
7320 var require$$2 = getCjsExportFromNamespace(_nodeResolve_empty$1);
7321
7322 var protobufLight = createCommonjsModule(function (module) {
7323 /*
7324 Copyright 2013 Daniel Wirtz <dcode@dcode.io>
7325
7326 Licensed under the Apache License, Version 2.0 (the "License");
7327 you may not use this file except in compliance with the License.
7328 You may obtain a copy of the License at
7329
7330 http://www.apache.org/licenses/LICENSE-2.0
7331
7332 Unless required by applicable law or agreed to in writing, software
7333 distributed under the License is distributed on an "AS IS" BASIS,
7334 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
7335 See the License for the specific language governing permissions and
7336 limitations under the License.
7337 */
7338
7339 /**
7340 * @license protobuf.js (c) 2013 Daniel Wirtz <dcode@dcode.io>
7341 * Released under the Apache License, Version 2.0
7342 * see: https://github.com/dcodeIO/protobuf.js for details
7343 */
7344 (function(global, factory) {
7345
7346 /* AMD */ if (typeof commonjsRequire === "function" && 'object' === "object" && module && module["exports"])
7347 module["exports"] = factory(bytebuffer, true);
7348 /* Global */ else
7349 (global["dcodeIO"] = global["dcodeIO"] || {})["ProtoBuf"] = factory(global["dcodeIO"]["ByteBuffer"]);
7350
7351 })(commonjsGlobal, function(ByteBuffer, isCommonJS) {
7352
7353 /**
7354 * The ProtoBuf namespace.
7355 * @exports ProtoBuf
7356 * @namespace
7357 * @expose
7358 */
7359 var ProtoBuf = {};
7360
7361 /**
7362 * @type {!function(new: ByteBuffer, ...[*])}
7363 * @expose
7364 */
7365 ProtoBuf.ByteBuffer = ByteBuffer;
7366
7367 /**
7368 * @type {?function(new: Long, ...[*])}
7369 * @expose
7370 */
7371 ProtoBuf.Long = ByteBuffer.Long || null;
7372
7373 /**
7374 * ProtoBuf.js version.
7375 * @type {string}
7376 * @const
7377 * @expose
7378 */
7379 ProtoBuf.VERSION = "5.0.3";
7380
7381 /**
7382 * Wire types.
7383 * @type {Object.<string,number>}
7384 * @const
7385 * @expose
7386 */
7387 ProtoBuf.WIRE_TYPES = {};
7388
7389 /**
7390 * Varint wire type.
7391 * @type {number}
7392 * @expose
7393 */
7394 ProtoBuf.WIRE_TYPES.VARINT = 0;
7395
7396 /**
7397 * Fixed 64 bits wire type.
7398 * @type {number}
7399 * @const
7400 * @expose
7401 */
7402 ProtoBuf.WIRE_TYPES.BITS64 = 1;
7403
7404 /**
7405 * Length delimited wire type.
7406 * @type {number}
7407 * @const
7408 * @expose
7409 */
7410 ProtoBuf.WIRE_TYPES.LDELIM = 2;
7411
7412 /**
7413 * Start group wire type.
7414 * @type {number}
7415 * @const
7416 * @expose
7417 */
7418 ProtoBuf.WIRE_TYPES.STARTGROUP = 3;
7419
7420 /**
7421 * End group wire type.
7422 * @type {number}
7423 * @const
7424 * @expose
7425 */
7426 ProtoBuf.WIRE_TYPES.ENDGROUP = 4;
7427
7428 /**
7429 * Fixed 32 bits wire type.
7430 * @type {number}
7431 * @const
7432 * @expose
7433 */
7434 ProtoBuf.WIRE_TYPES.BITS32 = 5;
7435
7436 /**
7437 * Packable wire types.
7438 * @type {!Array.<number>}
7439 * @const
7440 * @expose
7441 */
7442 ProtoBuf.PACKABLE_WIRE_TYPES = [
7443 ProtoBuf.WIRE_TYPES.VARINT,
7444 ProtoBuf.WIRE_TYPES.BITS64,
7445 ProtoBuf.WIRE_TYPES.BITS32
7446 ];
7447
7448 /**
7449 * Types.
7450 * @dict
7451 * @type {!Object.<string,{name: string, wireType: number, defaultValue: *}>}
7452 * @const
7453 * @expose
7454 */
7455 ProtoBuf.TYPES = {
7456 // According to the protobuf spec.
7457 "int32": {
7458 name: "int32",
7459 wireType: ProtoBuf.WIRE_TYPES.VARINT,
7460 defaultValue: 0
7461 },
7462 "uint32": {
7463 name: "uint32",
7464 wireType: ProtoBuf.WIRE_TYPES.VARINT,
7465 defaultValue: 0
7466 },
7467 "sint32": {
7468 name: "sint32",
7469 wireType: ProtoBuf.WIRE_TYPES.VARINT,
7470 defaultValue: 0
7471 },
7472 "int64": {
7473 name: "int64",
7474 wireType: ProtoBuf.WIRE_TYPES.VARINT,
7475 defaultValue: ProtoBuf.Long ? ProtoBuf.Long.ZERO : undefined
7476 },
7477 "uint64": {
7478 name: "uint64",
7479 wireType: ProtoBuf.WIRE_TYPES.VARINT,
7480 defaultValue: ProtoBuf.Long ? ProtoBuf.Long.UZERO : undefined
7481 },
7482 "sint64": {
7483 name: "sint64",
7484 wireType: ProtoBuf.WIRE_TYPES.VARINT,
7485 defaultValue: ProtoBuf.Long ? ProtoBuf.Long.ZERO : undefined
7486 },
7487 "bool": {
7488 name: "bool",
7489 wireType: ProtoBuf.WIRE_TYPES.VARINT,
7490 defaultValue: false
7491 },
7492 "double": {
7493 name: "double",
7494 wireType: ProtoBuf.WIRE_TYPES.BITS64,
7495 defaultValue: 0
7496 },
7497 "string": {
7498 name: "string",
7499 wireType: ProtoBuf.WIRE_TYPES.LDELIM,
7500 defaultValue: ""
7501 },
7502 "bytes": {
7503 name: "bytes",
7504 wireType: ProtoBuf.WIRE_TYPES.LDELIM,
7505 defaultValue: null // overridden in the code, must be a unique instance
7506 },
7507 "fixed32": {
7508 name: "fixed32",
7509 wireType: ProtoBuf.WIRE_TYPES.BITS32,
7510 defaultValue: 0
7511 },
7512 "sfixed32": {
7513 name: "sfixed32",
7514 wireType: ProtoBuf.WIRE_TYPES.BITS32,
7515 defaultValue: 0
7516 },
7517 "fixed64": {
7518 name: "fixed64",
7519 wireType: ProtoBuf.WIRE_TYPES.BITS64,
7520 defaultValue: ProtoBuf.Long ? ProtoBuf.Long.UZERO : undefined
7521 },
7522 "sfixed64": {
7523 name: "sfixed64",
7524 wireType: ProtoBuf.WIRE_TYPES.BITS64,
7525 defaultValue: ProtoBuf.Long ? ProtoBuf.Long.ZERO : undefined
7526 },
7527 "float": {
7528 name: "float",
7529 wireType: ProtoBuf.WIRE_TYPES.BITS32,
7530 defaultValue: 0
7531 },
7532 "enum": {
7533 name: "enum",
7534 wireType: ProtoBuf.WIRE_TYPES.VARINT,
7535 defaultValue: 0
7536 },
7537 "message": {
7538 name: "message",
7539 wireType: ProtoBuf.WIRE_TYPES.LDELIM,
7540 defaultValue: null
7541 },
7542 "group": {
7543 name: "group",
7544 wireType: ProtoBuf.WIRE_TYPES.STARTGROUP,
7545 defaultValue: null
7546 }
7547 };
7548
7549 /**
7550 * Valid map key types.
7551 * @type {!Array.<!Object.<string,{name: string, wireType: number, defaultValue: *}>>}
7552 * @const
7553 * @expose
7554 */
7555 ProtoBuf.MAP_KEY_TYPES = [
7556 ProtoBuf.TYPES["int32"],
7557 ProtoBuf.TYPES["sint32"],
7558 ProtoBuf.TYPES["sfixed32"],
7559 ProtoBuf.TYPES["uint32"],
7560 ProtoBuf.TYPES["fixed32"],
7561 ProtoBuf.TYPES["int64"],
7562 ProtoBuf.TYPES["sint64"],
7563 ProtoBuf.TYPES["sfixed64"],
7564 ProtoBuf.TYPES["uint64"],
7565 ProtoBuf.TYPES["fixed64"],
7566 ProtoBuf.TYPES["bool"],
7567 ProtoBuf.TYPES["string"],
7568 ProtoBuf.TYPES["bytes"]
7569 ];
7570
7571 /**
7572 * Minimum field id.
7573 * @type {number}
7574 * @const
7575 * @expose
7576 */
7577 ProtoBuf.ID_MIN = 1;
7578
7579 /**
7580 * Maximum field id.
7581 * @type {number}
7582 * @const
7583 * @expose
7584 */
7585 ProtoBuf.ID_MAX = 0x1FFFFFFF;
7586
7587 /**
7588 * If set to `true`, field names will be converted from underscore notation to camel case. Defaults to `false`.
7589 * Must be set prior to parsing.
7590 * @type {boolean}
7591 * @expose
7592 */
7593 ProtoBuf.convertFieldsToCamelCase = false;
7594
7595 /**
7596 * By default, messages are populated with (setX, set_x) accessors for each field. This can be disabled by
7597 * setting this to `false` prior to building messages.
7598 * @type {boolean}
7599 * @expose
7600 */
7601 ProtoBuf.populateAccessors = true;
7602
7603 /**
7604 * By default, messages are populated with default values if a field is not present on the wire. To disable
7605 * this behavior, set this setting to `false`.
7606 * @type {boolean}
7607 * @expose
7608 */
7609 ProtoBuf.populateDefaults = true;
7610
7611 /**
7612 * @alias ProtoBuf.Util
7613 * @expose
7614 */
7615 ProtoBuf.Util = (function() {
7616
7617 /**
7618 * ProtoBuf utilities.
7619 * @exports ProtoBuf.Util
7620 * @namespace
7621 */
7622 var Util = {};
7623
7624 /**
7625 * Flag if running in node or not.
7626 * @type {boolean}
7627 * @const
7628 * @expose
7629 */
7630 Util.IS_NODE = !!(
7631 typeof process === 'object' && process+'' === '[object process]' && !process['browser']
7632 );
7633
7634 /**
7635 * Constructs a XMLHttpRequest object.
7636 * @return {XMLHttpRequest}
7637 * @throws {Error} If XMLHttpRequest is not supported
7638 * @expose
7639 */
7640 Util.XHR = function() {
7641 // No dependencies please, ref: http://www.quirksmode.org/js/xmlhttp.html
7642 var XMLHttpFactories = [
7643 function () {return new XMLHttpRequest()},
7644 function () {return new ActiveXObject("Msxml2.XMLHTTP")},
7645 function () {return new ActiveXObject("Msxml3.XMLHTTP")},
7646 function () {return new ActiveXObject("Microsoft.XMLHTTP")}
7647 ];
7648 /** @type {?XMLHttpRequest} */
7649 var xhr = null;
7650 for (var i=0;i<XMLHttpFactories.length;i++) {
7651 try { xhr = XMLHttpFactories[i](); }
7652 catch (e) { continue; }
7653 break;
7654 }
7655 if (!xhr)
7656 throw Error("XMLHttpRequest is not supported");
7657 return xhr;
7658 };
7659
7660 /**
7661 * Fetches a resource.
7662 * @param {string} path Resource path
7663 * @param {function(?string)=} callback Callback receiving the resource's contents. If omitted the resource will
7664 * be fetched synchronously. If the request failed, contents will be null.
7665 * @return {?string|undefined} Resource contents if callback is omitted (null if the request failed), else undefined.
7666 * @expose
7667 */
7668 Util.fetch = function(path, callback) {
7669 if (callback && typeof callback != 'function')
7670 callback = null;
7671 if (Util.IS_NODE) {
7672 var fs = require$$2;
7673 if (callback) {
7674 fs.readFile(path, function(err, data) {
7675 if (err)
7676 callback(null);
7677 else
7678 callback(""+data);
7679 });
7680 } else
7681 try {
7682 return fs.readFileSync(path);
7683 } catch (e) {
7684 return null;
7685 }
7686 } else {
7687 var xhr = Util.XHR();
7688 xhr.open('GET', path, callback ? true : false);
7689 // xhr.setRequestHeader('User-Agent', 'XMLHTTP/1.0');
7690 xhr.setRequestHeader('Accept', 'text/plain');
7691 if (typeof xhr.overrideMimeType === 'function') xhr.overrideMimeType('text/plain');
7692 if (callback) {
7693 xhr.onreadystatechange = function() {
7694 if (xhr.readyState != 4) return;
7695 if (/* remote */ xhr.status == 200 || /* local */ (xhr.status == 0 && typeof xhr.responseText === 'string'))
7696 callback(xhr.responseText);
7697 else
7698 callback(null);
7699 };
7700 if (xhr.readyState == 4)
7701 return;
7702 xhr.send(null);
7703 } else {
7704 xhr.send(null);
7705 if (/* remote */ xhr.status == 200 || /* local */ (xhr.status == 0 && typeof xhr.responseText === 'string'))
7706 return xhr.responseText;
7707 return null;
7708 }
7709 }
7710 };
7711
7712 /**
7713 * Converts a string to camel case.
7714 * @param {string} str
7715 * @returns {string}
7716 * @expose
7717 */
7718 Util.toCamelCase = function(str) {
7719 return str.replace(/_([a-zA-Z])/g, function ($0, $1) {
7720 return $1.toUpperCase();
7721 });
7722 };
7723
7724 return Util;
7725 })();
7726
7727 /**
7728 * Language expressions.
7729 * @type {!Object.<string,!RegExp>}
7730 * @expose
7731 */
7732 ProtoBuf.Lang = {
7733
7734 // Characters always ending a statement
7735 DELIM: /[\s\{\}=;:\[\],'"\(\)<>]/g,
7736
7737 // Field rules
7738 RULE: /^(?:required|optional|repeated|map)$/,
7739
7740 // Field types
7741 TYPE: /^(?:double|float|int32|uint32|sint32|int64|uint64|sint64|fixed32|sfixed32|fixed64|sfixed64|bool|string|bytes)$/,
7742
7743 // Names
7744 NAME: /^[a-zA-Z_][a-zA-Z_0-9]*$/,
7745
7746 // Type definitions
7747 TYPEDEF: /^[a-zA-Z][a-zA-Z_0-9]*$/,
7748
7749 // Type references
7750 TYPEREF: /^(?:\.?[a-zA-Z_][a-zA-Z_0-9]*)(?:\.[a-zA-Z_][a-zA-Z_0-9]*)*$/,
7751
7752 // Fully qualified type references
7753 FQTYPEREF: /^(?:\.[a-zA-Z_][a-zA-Z_0-9]*)+$/,
7754
7755 // All numbers
7756 NUMBER: /^-?(?:[1-9][0-9]*|0|0[xX][0-9a-fA-F]+|0[0-7]+|([0-9]*(\.[0-9]*)?([Ee][+-]?[0-9]+)?)|inf|nan)$/,
7757
7758 // Decimal numbers
7759 NUMBER_DEC: /^(?:[1-9][0-9]*|0)$/,
7760
7761 // Hexadecimal numbers
7762 NUMBER_HEX: /^0[xX][0-9a-fA-F]+$/,
7763
7764 // Octal numbers
7765 NUMBER_OCT: /^0[0-7]+$/,
7766
7767 // Floating point numbers
7768 NUMBER_FLT: /^([0-9]*(\.[0-9]*)?([Ee][+-]?[0-9]+)?|inf|nan)$/,
7769
7770 // Booleans
7771 BOOL: /^(?:true|false)$/i,
7772
7773 // Id numbers
7774 ID: /^(?:[1-9][0-9]*|0|0[xX][0-9a-fA-F]+|0[0-7]+)$/,
7775
7776 // Negative id numbers (enum values)
7777 NEGID: /^\-?(?:[1-9][0-9]*|0|0[xX][0-9a-fA-F]+|0[0-7]+)$/,
7778
7779 // Whitespaces
7780 WHITESPACE: /\s/,
7781
7782 // All strings
7783 STRING: /(?:"([^"\\]*(?:\\.[^"\\]*)*)")|(?:'([^'\\]*(?:\\.[^'\\]*)*)')/g,
7784
7785 // Double quoted strings
7786 STRING_DQ: /(?:"([^"\\]*(?:\\.[^"\\]*)*)")/g,
7787
7788 // Single quoted strings
7789 STRING_SQ: /(?:'([^'\\]*(?:\\.[^'\\]*)*)')/g
7790 };
7791
7792
7793 /**
7794 * @alias ProtoBuf.Reflect
7795 * @expose
7796 */
7797 ProtoBuf.Reflect = (function(ProtoBuf) {
7798
7799 /**
7800 * Reflection types.
7801 * @exports ProtoBuf.Reflect
7802 * @namespace
7803 */
7804 var Reflect = {};
7805
7806 /**
7807 * Constructs a Reflect base class.
7808 * @exports ProtoBuf.Reflect.T
7809 * @constructor
7810 * @abstract
7811 * @param {!ProtoBuf.Builder} builder Builder reference
7812 * @param {?ProtoBuf.Reflect.T} parent Parent object
7813 * @param {string} name Object name
7814 */
7815 var T = function(builder, parent, name) {
7816
7817 /**
7818 * Builder reference.
7819 * @type {!ProtoBuf.Builder}
7820 * @expose
7821 */
7822 this.builder = builder;
7823
7824 /**
7825 * Parent object.
7826 * @type {?ProtoBuf.Reflect.T}
7827 * @expose
7828 */
7829 this.parent = parent;
7830
7831 /**
7832 * Object name in namespace.
7833 * @type {string}
7834 * @expose
7835 */
7836 this.name = name;
7837
7838 /**
7839 * Fully qualified class name
7840 * @type {string}
7841 * @expose
7842 */
7843 this.className;
7844 };
7845
7846 /**
7847 * @alias ProtoBuf.Reflect.T.prototype
7848 * @inner
7849 */
7850 var TPrototype = T.prototype;
7851
7852 /**
7853 * Returns the fully qualified name of this object.
7854 * @returns {string} Fully qualified name as of ".PATH.TO.THIS"
7855 * @expose
7856 */
7857 TPrototype.fqn = function() {
7858 var name = this.name,
7859 ptr = this;
7860 do {
7861 ptr = ptr.parent;
7862 if (ptr == null)
7863 break;
7864 name = ptr.name+"."+name;
7865 } while (true);
7866 return name;
7867 };
7868
7869 /**
7870 * Returns a string representation of this Reflect object (its fully qualified name).
7871 * @param {boolean=} includeClass Set to true to include the class name. Defaults to false.
7872 * @return String representation
7873 * @expose
7874 */
7875 TPrototype.toString = function(includeClass) {
7876 return (includeClass ? this.className + " " : "") + this.fqn();
7877 };
7878
7879 /**
7880 * Builds this type.
7881 * @throws {Error} If this type cannot be built directly
7882 * @expose
7883 */
7884 TPrototype.build = function() {
7885 throw Error(this.toString(true)+" cannot be built directly");
7886 };
7887
7888 /**
7889 * @alias ProtoBuf.Reflect.T
7890 * @expose
7891 */
7892 Reflect.T = T;
7893
7894 /**
7895 * Constructs a new Namespace.
7896 * @exports ProtoBuf.Reflect.Namespace
7897 * @param {!ProtoBuf.Builder} builder Builder reference
7898 * @param {?ProtoBuf.Reflect.Namespace} parent Namespace parent
7899 * @param {string} name Namespace name
7900 * @param {Object.<string,*>=} options Namespace options
7901 * @param {string?} syntax The syntax level of this definition (e.g., proto3)
7902 * @constructor
7903 * @extends ProtoBuf.Reflect.T
7904 */
7905 var Namespace = function(builder, parent, name, options, syntax) {
7906 T.call(this, builder, parent, name);
7907
7908 /**
7909 * @override
7910 */
7911 this.className = "Namespace";
7912
7913 /**
7914 * Children inside the namespace.
7915 * @type {!Array.<ProtoBuf.Reflect.T>}
7916 */
7917 this.children = [];
7918
7919 /**
7920 * Options.
7921 * @type {!Object.<string, *>}
7922 */
7923 this.options = options || {};
7924
7925 /**
7926 * Syntax level (e.g., proto2 or proto3).
7927 * @type {!string}
7928 */
7929 this.syntax = syntax || "proto2";
7930 };
7931
7932 /**
7933 * @alias ProtoBuf.Reflect.Namespace.prototype
7934 * @inner
7935 */
7936 var NamespacePrototype = Namespace.prototype = Object.create(T.prototype);
7937
7938 /**
7939 * Returns an array of the namespace's children.
7940 * @param {ProtoBuf.Reflect.T=} type Filter type (returns instances of this type only). Defaults to null (all children).
7941 * @return {Array.<ProtoBuf.Reflect.T>}
7942 * @expose
7943 */
7944 NamespacePrototype.getChildren = function(type) {
7945 type = type || null;
7946 if (type == null)
7947 return this.children.slice();
7948 var children = [];
7949 for (var i=0, k=this.children.length; i<k; ++i)
7950 if (this.children[i] instanceof type)
7951 children.push(this.children[i]);
7952 return children;
7953 };
7954
7955 /**
7956 * Adds a child to the namespace.
7957 * @param {ProtoBuf.Reflect.T} child Child
7958 * @throws {Error} If the child cannot be added (duplicate)
7959 * @expose
7960 */
7961 NamespacePrototype.addChild = function(child) {
7962 var other;
7963 if (other = this.getChild(child.name)) {
7964 // Try to revert camelcase transformation on collision
7965 if (other instanceof Message.Field && other.name !== other.originalName && this.getChild(other.originalName) === null)
7966 other.name = other.originalName; // Revert previous first (effectively keeps both originals)
7967 else if (child instanceof Message.Field && child.name !== child.originalName && this.getChild(child.originalName) === null)
7968 child.name = child.originalName;
7969 else
7970 throw Error("Duplicate name in namespace "+this.toString(true)+": "+child.name);
7971 }
7972 this.children.push(child);
7973 };
7974
7975 /**
7976 * Gets a child by its name or id.
7977 * @param {string|number} nameOrId Child name or id
7978 * @return {?ProtoBuf.Reflect.T} The child or null if not found
7979 * @expose
7980 */
7981 NamespacePrototype.getChild = function(nameOrId) {
7982 var key = typeof nameOrId === 'number' ? 'id' : 'name';
7983 for (var i=0, k=this.children.length; i<k; ++i)
7984 if (this.children[i][key] === nameOrId)
7985 return this.children[i];
7986 return null;
7987 };
7988
7989 /**
7990 * Resolves a reflect object inside of this namespace.
7991 * @param {string|!Array.<string>} qn Qualified name to resolve
7992 * @param {boolean=} excludeNonNamespace Excludes non-namespace types, defaults to `false`
7993 * @return {?ProtoBuf.Reflect.Namespace} The resolved type or null if not found
7994 * @expose
7995 */
7996 NamespacePrototype.resolve = function(qn, excludeNonNamespace) {
7997 var part = typeof qn === 'string' ? qn.split(".") : qn,
7998 ptr = this,
7999 i = 0;
8000 if (part[i] === "") { // Fully qualified name, e.g. ".My.Message'
8001 while (ptr.parent !== null)
8002 ptr = ptr.parent;
8003 i++;
8004 }
8005 var child;
8006 do {
8007 do {
8008 if (!(ptr instanceof Reflect.Namespace)) {
8009 ptr = null;
8010 break;
8011 }
8012 child = ptr.getChild(part[i]);
8013 if (!child || !(child instanceof Reflect.T) || (excludeNonNamespace && !(child instanceof Reflect.Namespace))) {
8014 ptr = null;
8015 break;
8016 }
8017 ptr = child; i++;
8018 } while (i < part.length);
8019 if (ptr != null)
8020 break; // Found
8021 // Else search the parent
8022 if (this.parent !== null)
8023 return this.parent.resolve(qn, excludeNonNamespace);
8024 } while (ptr != null);
8025 return ptr;
8026 };
8027
8028 /**
8029 * Determines the shortest qualified name of the specified type, if any, relative to this namespace.
8030 * @param {!ProtoBuf.Reflect.T} t Reflection type
8031 * @returns {string} The shortest qualified name or, if there is none, the fqn
8032 * @expose
8033 */
8034 NamespacePrototype.qn = function(t) {
8035 var part = [], ptr = t;
8036 do {
8037 part.unshift(ptr.name);
8038 ptr = ptr.parent;
8039 } while (ptr !== null);
8040 for (var len=1; len <= part.length; len++) {
8041 var qn = part.slice(part.length-len);
8042 if (t === this.resolve(qn, t instanceof Reflect.Namespace))
8043 return qn.join(".");
8044 }
8045 return t.fqn();
8046 };
8047
8048 /**
8049 * Builds the namespace and returns the runtime counterpart.
8050 * @return {Object.<string,Function|Object>} Runtime namespace
8051 * @expose
8052 */
8053 NamespacePrototype.build = function() {
8054 /** @dict */
8055 var ns = {};
8056 var children = this.children;
8057 for (var i=0, k=children.length, child; i<k; ++i) {
8058 child = children[i];
8059 if (child instanceof Namespace)
8060 ns[child.name] = child.build();
8061 }
8062 if (Object.defineProperty)
8063 Object.defineProperty(ns, "$options", { "value": this.buildOpt() });
8064 return ns;
8065 };
8066
8067 /**
8068 * Builds the namespace's '$options' property.
8069 * @return {Object.<string,*>}
8070 */
8071 NamespacePrototype.buildOpt = function() {
8072 var opt = {},
8073 keys = Object.keys(this.options);
8074 for (var i=0, k=keys.length; i<k; ++i) {
8075 var key = keys[i],
8076 val = this.options[keys[i]];
8077 // TODO: Options are not resolved, yet.
8078 // if (val instanceof Namespace) {
8079 // opt[key] = val.build();
8080 // } else {
8081 opt[key] = val;
8082 // }
8083 }
8084 return opt;
8085 };
8086
8087 /**
8088 * Gets the value assigned to the option with the specified name.
8089 * @param {string=} name Returns the option value if specified, otherwise all options are returned.
8090 * @return {*|Object.<string,*>}null} Option value or NULL if there is no such option
8091 */
8092 NamespacePrototype.getOption = function(name) {
8093 if (typeof name === 'undefined')
8094 return this.options;
8095 return typeof this.options[name] !== 'undefined' ? this.options[name] : null;
8096 };
8097
8098 /**
8099 * @alias ProtoBuf.Reflect.Namespace
8100 * @expose
8101 */
8102 Reflect.Namespace = Namespace;
8103
8104 /**
8105 * Constructs a new Element implementation that checks and converts values for a
8106 * particular field type, as appropriate.
8107 *
8108 * An Element represents a single value: either the value of a singular field,
8109 * or a value contained in one entry of a repeated field or map field. This
8110 * class does not implement these higher-level concepts; it only encapsulates
8111 * the low-level typechecking and conversion.
8112 *
8113 * @exports ProtoBuf.Reflect.Element
8114 * @param {{name: string, wireType: number}} type Resolved data type
8115 * @param {ProtoBuf.Reflect.T|null} resolvedType Resolved type, if relevant
8116 * (e.g. submessage field).
8117 * @param {boolean} isMapKey Is this element a Map key? The value will be
8118 * converted to string form if so.
8119 * @param {string} syntax Syntax level of defining message type, e.g.,
8120 * proto2 or proto3.
8121 * @param {string} name Name of the field containing this element (for error
8122 * messages)
8123 * @constructor
8124 */
8125 var Element = function(type, resolvedType, isMapKey, syntax, name) {
8126
8127 /**
8128 * Element type, as a string (e.g., int32).
8129 * @type {{name: string, wireType: number}}
8130 */
8131 this.type = type;
8132
8133 /**
8134 * Element type reference to submessage or enum definition, if needed.
8135 * @type {ProtoBuf.Reflect.T|null}
8136 */
8137 this.resolvedType = resolvedType;
8138
8139 /**
8140 * Element is a map key.
8141 * @type {boolean}
8142 */
8143 this.isMapKey = isMapKey;
8144
8145 /**
8146 * Syntax level of defining message type, e.g., proto2 or proto3.
8147 * @type {string}
8148 */
8149 this.syntax = syntax;
8150
8151 /**
8152 * Name of the field containing this element (for error messages)
8153 * @type {string}
8154 */
8155 this.name = name;
8156
8157 if (isMapKey && ProtoBuf.MAP_KEY_TYPES.indexOf(type) < 0)
8158 throw Error("Invalid map key type: " + type.name);
8159 };
8160
8161 var ElementPrototype = Element.prototype;
8162
8163 /**
8164 * Obtains a (new) default value for the specified type.
8165 * @param type {string|{name: string, wireType: number}} Field type
8166 * @returns {*} Default value
8167 * @inner
8168 */
8169 function mkDefault(type) {
8170 if (typeof type === 'string')
8171 type = ProtoBuf.TYPES[type];
8172 if (typeof type.defaultValue === 'undefined')
8173 throw Error("default value for type "+type.name+" is not supported");
8174 if (type == ProtoBuf.TYPES["bytes"])
8175 return new ByteBuffer(0);
8176 return type.defaultValue;
8177 }
8178
8179 /**
8180 * Returns the default value for this field in proto3.
8181 * @function
8182 * @param type {string|{name: string, wireType: number}} the field type
8183 * @returns {*} Default value
8184 */
8185 Element.defaultFieldValue = mkDefault;
8186
8187 /**
8188 * Makes a Long from a value.
8189 * @param {{low: number, high: number, unsigned: boolean}|string|number} value Value
8190 * @param {boolean=} unsigned Whether unsigned or not, defaults to reuse it from Long-like objects or to signed for
8191 * strings and numbers
8192 * @returns {!Long}
8193 * @throws {Error} If the value cannot be converted to a Long
8194 * @inner
8195 */
8196 function mkLong(value, unsigned) {
8197 if (value && typeof value.low === 'number' && typeof value.high === 'number' && typeof value.unsigned === 'boolean'
8198 && value.low === value.low && value.high === value.high)
8199 return new ProtoBuf.Long(value.low, value.high, typeof unsigned === 'undefined' ? value.unsigned : unsigned);
8200 if (typeof value === 'string')
8201 return ProtoBuf.Long.fromString(value, unsigned || false, 10);
8202 if (typeof value === 'number')
8203 return ProtoBuf.Long.fromNumber(value, unsigned || false);
8204 throw Error("not convertible to Long");
8205 }
8206
8207 ElementPrototype.toString = function() {
8208 return (this.name || '') + (this.isMapKey ? 'map' : 'value') + ' element';
8209 };
8210
8211 /**
8212 * Checks if the given value can be set for an element of this type (singular
8213 * field or one element of a repeated field or map).
8214 * @param {*} value Value to check
8215 * @return {*} Verified, maybe adjusted, value
8216 * @throws {Error} If the value cannot be verified for this element slot
8217 * @expose
8218 */
8219 ElementPrototype.verifyValue = function(value) {
8220 var self = this;
8221 function fail(val, msg) {
8222 throw Error("Illegal value for "+self.toString(true)+" of type "+self.type.name+": "+val+" ("+msg+")");
8223 }
8224 switch (this.type) {
8225 // Signed 32bit
8226 case ProtoBuf.TYPES["int32"]:
8227 case ProtoBuf.TYPES["sint32"]:
8228 case ProtoBuf.TYPES["sfixed32"]:
8229 // Account for !NaN: value === value
8230 if (typeof value !== 'number' || (value === value && value % 1 !== 0))
8231 fail(typeof value, "not an integer");
8232 return value > 4294967295 ? value | 0 : value;
8233
8234 // Unsigned 32bit
8235 case ProtoBuf.TYPES["uint32"]:
8236 case ProtoBuf.TYPES["fixed32"]:
8237 if (typeof value !== 'number' || (value === value && value % 1 !== 0))
8238 fail(typeof value, "not an integer");
8239 return value < 0 ? value >>> 0 : value;
8240
8241 // Signed 64bit
8242 case ProtoBuf.TYPES["int64"]:
8243 case ProtoBuf.TYPES["sint64"]:
8244 case ProtoBuf.TYPES["sfixed64"]: {
8245 if (ProtoBuf.Long)
8246 try {
8247 return mkLong(value, false);
8248 } catch (e) {
8249 fail(typeof value, e.message);
8250 }
8251 else
8252 fail(typeof value, "requires Long.js");
8253 }
8254
8255 // Unsigned 64bit
8256 case ProtoBuf.TYPES["uint64"]:
8257 case ProtoBuf.TYPES["fixed64"]: {
8258 if (ProtoBuf.Long)
8259 try {
8260 return mkLong(value, true);
8261 } catch (e) {
8262 fail(typeof value, e.message);
8263 }
8264 else
8265 fail(typeof value, "requires Long.js");
8266 }
8267
8268 // Bool
8269 case ProtoBuf.TYPES["bool"]:
8270 if (typeof value !== 'boolean')
8271 fail(typeof value, "not a boolean");
8272 return value;
8273
8274 // Float
8275 case ProtoBuf.TYPES["float"]:
8276 case ProtoBuf.TYPES["double"]:
8277 if (typeof value !== 'number')
8278 fail(typeof value, "not a number");
8279 return value;
8280
8281 // Length-delimited string
8282 case ProtoBuf.TYPES["string"]:
8283 if (typeof value !== 'string' && !(value && value instanceof String))
8284 fail(typeof value, "not a string");
8285 return ""+value; // Convert String object to string
8286
8287 // Length-delimited bytes
8288 case ProtoBuf.TYPES["bytes"]:
8289 if (ByteBuffer.isByteBuffer(value))
8290 return value;
8291 return ByteBuffer.wrap(value, "base64");
8292
8293 // Constant enum value
8294 case ProtoBuf.TYPES["enum"]: {
8295 var values = this.resolvedType.getChildren(ProtoBuf.Reflect.Enum.Value);
8296 for (i=0; i<values.length; i++)
8297 if (values[i].name == value)
8298 return values[i].id;
8299 else if (values[i].id == value)
8300 return values[i].id;
8301
8302 if (this.syntax === 'proto3') {
8303 // proto3: just make sure it's an integer.
8304 if (typeof value !== 'number' || (value === value && value % 1 !== 0))
8305 fail(typeof value, "not an integer");
8306 if (value > 4294967295 || value < 0)
8307 fail(typeof value, "not in range for uint32");
8308 return value;
8309 } else {
8310 // proto2 requires enum values to be valid.
8311 fail(value, "not a valid enum value");
8312 }
8313 }
8314 // Embedded message
8315 case ProtoBuf.TYPES["group"]:
8316 case ProtoBuf.TYPES["message"]: {
8317 if (!value || typeof value !== 'object')
8318 fail(typeof value, "object expected");
8319 if (value instanceof this.resolvedType.clazz)
8320 return value;
8321 if (value instanceof ProtoBuf.Builder.Message) {
8322 // Mismatched type: Convert to object (see: https://github.com/dcodeIO/ProtoBuf.js/issues/180)
8323 var obj = {};
8324 for (var i in value)
8325 if (value.hasOwnProperty(i))
8326 obj[i] = value[i];
8327 value = obj;
8328 }
8329 // Else let's try to construct one from a key-value object
8330 return new (this.resolvedType.clazz)(value); // May throw for a hundred of reasons
8331 }
8332 }
8333
8334 // We should never end here
8335 throw Error("[INTERNAL] Illegal value for "+this.toString(true)+": "+value+" (undefined type "+this.type+")");
8336 };
8337
8338 /**
8339 * Calculates the byte length of an element on the wire.
8340 * @param {number} id Field number
8341 * @param {*} value Field value
8342 * @returns {number} Byte length
8343 * @throws {Error} If the value cannot be calculated
8344 * @expose
8345 */
8346 ElementPrototype.calculateLength = function(id, value) {
8347 if (value === null) return 0; // Nothing to encode
8348 // Tag has already been written
8349 var n;
8350 switch (this.type) {
8351 case ProtoBuf.TYPES["int32"]:
8352 return value < 0 ? ByteBuffer.calculateVarint64(value) : ByteBuffer.calculateVarint32(value);
8353 case ProtoBuf.TYPES["uint32"]:
8354 return ByteBuffer.calculateVarint32(value);
8355 case ProtoBuf.TYPES["sint32"]:
8356 return ByteBuffer.calculateVarint32(ByteBuffer.zigZagEncode32(value));
8357 case ProtoBuf.TYPES["fixed32"]:
8358 case ProtoBuf.TYPES["sfixed32"]:
8359 case ProtoBuf.TYPES["float"]:
8360 return 4;
8361 case ProtoBuf.TYPES["int64"]:
8362 case ProtoBuf.TYPES["uint64"]:
8363 return ByteBuffer.calculateVarint64(value);
8364 case ProtoBuf.TYPES["sint64"]:
8365 return ByteBuffer.calculateVarint64(ByteBuffer.zigZagEncode64(value));
8366 case ProtoBuf.TYPES["fixed64"]:
8367 case ProtoBuf.TYPES["sfixed64"]:
8368 return 8;
8369 case ProtoBuf.TYPES["bool"]:
8370 return 1;
8371 case ProtoBuf.TYPES["enum"]:
8372 return ByteBuffer.calculateVarint32(value);
8373 case ProtoBuf.TYPES["double"]:
8374 return 8;
8375 case ProtoBuf.TYPES["string"]:
8376 n = ByteBuffer.calculateUTF8Bytes(value);
8377 return ByteBuffer.calculateVarint32(n) + n;
8378 case ProtoBuf.TYPES["bytes"]:
8379 if (value.remaining() < 0)
8380 throw Error("Illegal value for "+this.toString(true)+": "+value.remaining()+" bytes remaining");
8381 return ByteBuffer.calculateVarint32(value.remaining()) + value.remaining();
8382 case ProtoBuf.TYPES["message"]:
8383 n = this.resolvedType.calculate(value);
8384 return ByteBuffer.calculateVarint32(n) + n;
8385 case ProtoBuf.TYPES["group"]:
8386 n = this.resolvedType.calculate(value);
8387 return n + ByteBuffer.calculateVarint32((id << 3) | ProtoBuf.WIRE_TYPES.ENDGROUP);
8388 }
8389 // We should never end here
8390 throw Error("[INTERNAL] Illegal value to encode in "+this.toString(true)+": "+value+" (unknown type)");
8391 };
8392
8393 /**
8394 * Encodes a value to the specified buffer. Does not encode the key.
8395 * @param {number} id Field number
8396 * @param {*} value Field value
8397 * @param {ByteBuffer} buffer ByteBuffer to encode to
8398 * @return {ByteBuffer} The ByteBuffer for chaining
8399 * @throws {Error} If the value cannot be encoded
8400 * @expose
8401 */
8402 ElementPrototype.encodeValue = function(id, value, buffer) {
8403 if (value === null) return buffer; // Nothing to encode
8404 // Tag has already been written
8405
8406 switch (this.type) {
8407 // 32bit signed varint
8408 case ProtoBuf.TYPES["int32"]:
8409 // "If you use int32 or int64 as the type for a negative number, the resulting varint is always ten bytes
8410 // long – it is, effectively, treated like a very large unsigned integer." (see #122)
8411 if (value < 0)
8412 buffer.writeVarint64(value);
8413 else
8414 buffer.writeVarint32(value);
8415 break;
8416
8417 // 32bit unsigned varint
8418 case ProtoBuf.TYPES["uint32"]:
8419 buffer.writeVarint32(value);
8420 break;
8421
8422 // 32bit varint zig-zag
8423 case ProtoBuf.TYPES["sint32"]:
8424 buffer.writeVarint32ZigZag(value);
8425 break;
8426
8427 // Fixed unsigned 32bit
8428 case ProtoBuf.TYPES["fixed32"]:
8429 buffer.writeUint32(value);
8430 break;
8431
8432 // Fixed signed 32bit
8433 case ProtoBuf.TYPES["sfixed32"]:
8434 buffer.writeInt32(value);
8435 break;
8436
8437 // 64bit varint as-is
8438 case ProtoBuf.TYPES["int64"]:
8439 case ProtoBuf.TYPES["uint64"]:
8440 buffer.writeVarint64(value); // throws
8441 break;
8442
8443 // 64bit varint zig-zag
8444 case ProtoBuf.TYPES["sint64"]:
8445 buffer.writeVarint64ZigZag(value); // throws
8446 break;
8447
8448 // Fixed unsigned 64bit
8449 case ProtoBuf.TYPES["fixed64"]:
8450 buffer.writeUint64(value); // throws
8451 break;
8452
8453 // Fixed signed 64bit
8454 case ProtoBuf.TYPES["sfixed64"]:
8455 buffer.writeInt64(value); // throws
8456 break;
8457
8458 // Bool
8459 case ProtoBuf.TYPES["bool"]:
8460 if (typeof value === 'string')
8461 buffer.writeVarint32(value.toLowerCase() === 'false' ? 0 : !!value);
8462 else
8463 buffer.writeVarint32(value ? 1 : 0);
8464 break;
8465
8466 // Constant enum value
8467 case ProtoBuf.TYPES["enum"]:
8468 buffer.writeVarint32(value);
8469 break;
8470
8471 // 32bit float
8472 case ProtoBuf.TYPES["float"]:
8473 buffer.writeFloat32(value);
8474 break;
8475
8476 // 64bit float
8477 case ProtoBuf.TYPES["double"]:
8478 buffer.writeFloat64(value);
8479 break;
8480
8481 // Length-delimited string
8482 case ProtoBuf.TYPES["string"]:
8483 buffer.writeVString(value);
8484 break;
8485
8486 // Length-delimited bytes
8487 case ProtoBuf.TYPES["bytes"]:
8488 if (value.remaining() < 0)
8489 throw Error("Illegal value for "+this.toString(true)+": "+value.remaining()+" bytes remaining");
8490 var prevOffset = value.offset;
8491 buffer.writeVarint32(value.remaining());
8492 buffer.append(value);
8493 value.offset = prevOffset;
8494 break;
8495
8496 // Embedded message
8497 case ProtoBuf.TYPES["message"]:
8498 var bb = new ByteBuffer().LE();
8499 this.resolvedType.encode(value, bb);
8500 buffer.writeVarint32(bb.offset);
8501 buffer.append(bb.flip());
8502 break;
8503
8504 // Legacy group
8505 case ProtoBuf.TYPES["group"]:
8506 this.resolvedType.encode(value, buffer);
8507 buffer.writeVarint32((id << 3) | ProtoBuf.WIRE_TYPES.ENDGROUP);
8508 break;
8509
8510 default:
8511 // We should never end here
8512 throw Error("[INTERNAL] Illegal value to encode in "+this.toString(true)+": "+value+" (unknown type)");
8513 }
8514 return buffer;
8515 };
8516
8517 /**
8518 * Decode one element value from the specified buffer.
8519 * @param {ByteBuffer} buffer ByteBuffer to decode from
8520 * @param {number} wireType The field wire type
8521 * @param {number} id The field number
8522 * @return {*} Decoded value
8523 * @throws {Error} If the field cannot be decoded
8524 * @expose
8525 */
8526 ElementPrototype.decode = function(buffer, wireType, id) {
8527 if (wireType != this.type.wireType)
8528 throw Error("Unexpected wire type for element");
8529
8530 var value, nBytes;
8531 switch (this.type) {
8532 // 32bit signed varint
8533 case ProtoBuf.TYPES["int32"]:
8534 return buffer.readVarint32() | 0;
8535
8536 // 32bit unsigned varint
8537 case ProtoBuf.TYPES["uint32"]:
8538 return buffer.readVarint32() >>> 0;
8539
8540 // 32bit signed varint zig-zag
8541 case ProtoBuf.TYPES["sint32"]:
8542 return buffer.readVarint32ZigZag() | 0;
8543
8544 // Fixed 32bit unsigned
8545 case ProtoBuf.TYPES["fixed32"]:
8546 return buffer.readUint32() >>> 0;
8547
8548 case ProtoBuf.TYPES["sfixed32"]:
8549 return buffer.readInt32() | 0;
8550
8551 // 64bit signed varint
8552 case ProtoBuf.TYPES["int64"]:
8553 return buffer.readVarint64();
8554
8555 // 64bit unsigned varint
8556 case ProtoBuf.TYPES["uint64"]:
8557 return buffer.readVarint64().toUnsigned();
8558
8559 // 64bit signed varint zig-zag
8560 case ProtoBuf.TYPES["sint64"]:
8561 return buffer.readVarint64ZigZag();
8562
8563 // Fixed 64bit unsigned
8564 case ProtoBuf.TYPES["fixed64"]:
8565 return buffer.readUint64();
8566
8567 // Fixed 64bit signed
8568 case ProtoBuf.TYPES["sfixed64"]:
8569 return buffer.readInt64();
8570
8571 // Bool varint
8572 case ProtoBuf.TYPES["bool"]:
8573 return !!buffer.readVarint32();
8574
8575 // Constant enum value (varint)
8576 case ProtoBuf.TYPES["enum"]:
8577 // The following Builder.Message#set will already throw
8578 return buffer.readVarint32();
8579
8580 // 32bit float
8581 case ProtoBuf.TYPES["float"]:
8582 return buffer.readFloat();
8583
8584 // 64bit float
8585 case ProtoBuf.TYPES["double"]:
8586 return buffer.readDouble();
8587
8588 // Length-delimited string
8589 case ProtoBuf.TYPES["string"]:
8590 return buffer.readVString();
8591
8592 // Length-delimited bytes
8593 case ProtoBuf.TYPES["bytes"]: {
8594 nBytes = buffer.readVarint32();
8595 if (buffer.remaining() < nBytes)
8596 throw Error("Illegal number of bytes for "+this.toString(true)+": "+nBytes+" required but got only "+buffer.remaining());
8597 value = buffer.clone(); // Offset already set
8598 value.limit = value.offset+nBytes;
8599 buffer.offset += nBytes;
8600 return value;
8601 }
8602
8603 // Length-delimited embedded message
8604 case ProtoBuf.TYPES["message"]: {
8605 nBytes = buffer.readVarint32();
8606 return this.resolvedType.decode(buffer, nBytes);
8607 }
8608
8609 // Legacy group
8610 case ProtoBuf.TYPES["group"]:
8611 return this.resolvedType.decode(buffer, -1, id);
8612 }
8613
8614 // We should never end here
8615 throw Error("[INTERNAL] Illegal decode type");
8616 };
8617
8618 /**
8619 * Converts a value from a string to the canonical element type.
8620 *
8621 * Legal only when isMapKey is true.
8622 *
8623 * @param {string} str The string value
8624 * @returns {*} The value
8625 */
8626 ElementPrototype.valueFromString = function(str) {
8627 if (!this.isMapKey) {
8628 throw Error("valueFromString() called on non-map-key element");
8629 }
8630
8631 switch (this.type) {
8632 case ProtoBuf.TYPES["int32"]:
8633 case ProtoBuf.TYPES["sint32"]:
8634 case ProtoBuf.TYPES["sfixed32"]:
8635 case ProtoBuf.TYPES["uint32"]:
8636 case ProtoBuf.TYPES["fixed32"]:
8637 return this.verifyValue(parseInt(str));
8638
8639 case ProtoBuf.TYPES["int64"]:
8640 case ProtoBuf.TYPES["sint64"]:
8641 case ProtoBuf.TYPES["sfixed64"]:
8642 case ProtoBuf.TYPES["uint64"]:
8643 case ProtoBuf.TYPES["fixed64"]:
8644 // Long-based fields support conversions from string already.
8645 return this.verifyValue(str);
8646
8647 case ProtoBuf.TYPES["bool"]:
8648 return str === "true";
8649
8650 case ProtoBuf.TYPES["string"]:
8651 return this.verifyValue(str);
8652
8653 case ProtoBuf.TYPES["bytes"]:
8654 return ByteBuffer.fromBinary(str);
8655 }
8656 };
8657
8658 /**
8659 * Converts a value from the canonical element type to a string.
8660 *
8661 * It should be the case that `valueFromString(valueToString(val))` returns
8662 * a value equivalent to `verifyValue(val)` for every legal value of `val`
8663 * according to this element type.
8664 *
8665 * This may be used when the element must be stored or used as a string,
8666 * e.g., as a map key on an Object.
8667 *
8668 * Legal only when isMapKey is true.
8669 *
8670 * @param {*} val The value
8671 * @returns {string} The string form of the value.
8672 */
8673 ElementPrototype.valueToString = function(value) {
8674 if (!this.isMapKey) {
8675 throw Error("valueToString() called on non-map-key element");
8676 }
8677
8678 if (this.type === ProtoBuf.TYPES["bytes"]) {
8679 return value.toString("binary");
8680 } else {
8681 return value.toString();
8682 }
8683 };
8684
8685 /**
8686 * @alias ProtoBuf.Reflect.Element
8687 * @expose
8688 */
8689 Reflect.Element = Element;
8690
8691 /**
8692 * Constructs a new Message.
8693 * @exports ProtoBuf.Reflect.Message
8694 * @param {!ProtoBuf.Builder} builder Builder reference
8695 * @param {!ProtoBuf.Reflect.Namespace} parent Parent message or namespace
8696 * @param {string} name Message name
8697 * @param {Object.<string,*>=} options Message options
8698 * @param {boolean=} isGroup `true` if this is a legacy group
8699 * @param {string?} syntax The syntax level of this definition (e.g., proto3)
8700 * @constructor
8701 * @extends ProtoBuf.Reflect.Namespace
8702 */
8703 var Message = function(builder, parent, name, options, isGroup, syntax) {
8704 Namespace.call(this, builder, parent, name, options, syntax);
8705
8706 /**
8707 * @override
8708 */
8709 this.className = "Message";
8710
8711 /**
8712 * Extensions range.
8713 * @type {!Array.<number>|undefined}
8714 * @expose
8715 */
8716 this.extensions = undefined;
8717
8718 /**
8719 * Runtime message class.
8720 * @type {?function(new:ProtoBuf.Builder.Message)}
8721 * @expose
8722 */
8723 this.clazz = null;
8724
8725 /**
8726 * Whether this is a legacy group or not.
8727 * @type {boolean}
8728 * @expose
8729 */
8730 this.isGroup = !!isGroup;
8731
8732 // The following cached collections are used to efficiently iterate over or look up fields when decoding.
8733
8734 /**
8735 * Cached fields.
8736 * @type {?Array.<!ProtoBuf.Reflect.Message.Field>}
8737 * @private
8738 */
8739 this._fields = null;
8740
8741 /**
8742 * Cached fields by id.
8743 * @type {?Object.<number,!ProtoBuf.Reflect.Message.Field>}
8744 * @private
8745 */
8746 this._fieldsById = null;
8747
8748 /**
8749 * Cached fields by name.
8750 * @type {?Object.<string,!ProtoBuf.Reflect.Message.Field>}
8751 * @private
8752 */
8753 this._fieldsByName = null;
8754 };
8755
8756 /**
8757 * @alias ProtoBuf.Reflect.Message.prototype
8758 * @inner
8759 */
8760 var MessagePrototype = Message.prototype = Object.create(Namespace.prototype);
8761
8762 /**
8763 * Builds the message and returns the runtime counterpart, which is a fully functional class.
8764 * @see ProtoBuf.Builder.Message
8765 * @param {boolean=} rebuild Whether to rebuild or not, defaults to false
8766 * @return {ProtoBuf.Reflect.Message} Message class
8767 * @throws {Error} If the message cannot be built
8768 * @expose
8769 */
8770 MessagePrototype.build = function(rebuild) {
8771 if (this.clazz && !rebuild)
8772 return this.clazz;
8773
8774 // Create the runtime Message class in its own scope
8775 var clazz = (function(ProtoBuf, T) {
8776
8777 var fields = T.getChildren(ProtoBuf.Reflect.Message.Field),
8778 oneofs = T.getChildren(ProtoBuf.Reflect.Message.OneOf);
8779
8780 /**
8781 * Constructs a new runtime Message.
8782 * @name ProtoBuf.Builder.Message
8783 * @class Barebone of all runtime messages.
8784 * @param {!Object.<string,*>|string} values Preset values
8785 * @param {...string} var_args
8786 * @constructor
8787 * @throws {Error} If the message cannot be created
8788 */
8789 var Message = function(values, var_args) {
8790 ProtoBuf.Builder.Message.call(this);
8791
8792 // Create virtual oneof properties
8793 for (var i=0, k=oneofs.length; i<k; ++i)
8794 this[oneofs[i].name] = null;
8795 // Create fields and set default values
8796 for (i=0, k=fields.length; i<k; ++i) {
8797 var field = fields[i];
8798 this[field.name] =
8799 field.repeated ? [] :
8800 (field.map ? new ProtoBuf.Map(field) : null);
8801 if ((field.required || T.syntax === 'proto3') &&
8802 field.defaultValue !== null)
8803 this[field.name] = field.defaultValue;
8804 }
8805
8806 if (arguments.length > 0) {
8807 var value;
8808 // Set field values from a values object
8809 if (arguments.length === 1 && values !== null && typeof values === 'object' &&
8810 /* not _another_ Message */ (typeof values.encode !== 'function' || values instanceof Message) &&
8811 /* not a repeated field */ !Array.isArray(values) &&
8812 /* not a Map */ !(values instanceof ProtoBuf.Map) &&
8813 /* not a ByteBuffer */ !ByteBuffer.isByteBuffer(values) &&
8814 /* not an ArrayBuffer */ !(values instanceof ArrayBuffer) &&
8815 /* not a Long */ !(ProtoBuf.Long && values instanceof ProtoBuf.Long)) {
8816 this.$set(values);
8817 } else // Set field values from arguments, in declaration order
8818 for (i=0, k=arguments.length; i<k; ++i)
8819 if (typeof (value = arguments[i]) !== 'undefined')
8820 this.$set(fields[i].name, value); // May throw
8821 }
8822 };
8823
8824 /**
8825 * @alias ProtoBuf.Builder.Message.prototype
8826 * @inner
8827 */
8828 var MessagePrototype = Message.prototype = Object.create(ProtoBuf.Builder.Message.prototype);
8829
8830 /**
8831 * Adds a value to a repeated field.
8832 * @name ProtoBuf.Builder.Message#add
8833 * @function
8834 * @param {string} key Field name
8835 * @param {*} value Value to add
8836 * @param {boolean=} noAssert Whether to assert the value or not (asserts by default)
8837 * @returns {!ProtoBuf.Builder.Message} this
8838 * @throws {Error} If the value cannot be added
8839 * @expose
8840 */
8841 MessagePrototype.add = function(key, value, noAssert) {
8842 var field = T._fieldsByName[key];
8843 if (!noAssert) {
8844 if (!field)
8845 throw Error(this+"#"+key+" is undefined");
8846 if (!(field instanceof ProtoBuf.Reflect.Message.Field))
8847 throw Error(this+"#"+key+" is not a field: "+field.toString(true)); // May throw if it's an enum or embedded message
8848 if (!field.repeated)
8849 throw Error(this+"#"+key+" is not a repeated field");
8850 value = field.verifyValue(value, true);
8851 }
8852 if (this[key] === null)
8853 this[key] = [];
8854 this[key].push(value);
8855 return this;
8856 };
8857
8858 /**
8859 * Adds a value to a repeated field. This is an alias for {@link ProtoBuf.Builder.Message#add}.
8860 * @name ProtoBuf.Builder.Message#$add
8861 * @function
8862 * @param {string} key Field name
8863 * @param {*} value Value to add
8864 * @param {boolean=} noAssert Whether to assert the value or not (asserts by default)
8865 * @returns {!ProtoBuf.Builder.Message} this
8866 * @throws {Error} If the value cannot be added
8867 * @expose
8868 */
8869 MessagePrototype.$add = MessagePrototype.add;
8870
8871 /**
8872 * Sets a field's value.
8873 * @name ProtoBuf.Builder.Message#set
8874 * @function
8875 * @param {string|!Object.<string,*>} keyOrObj String key or plain object holding multiple values
8876 * @param {(*|boolean)=} value Value to set if key is a string, otherwise omitted
8877 * @param {boolean=} noAssert Whether to not assert for an actual field / proper value type, defaults to `false`
8878 * @returns {!ProtoBuf.Builder.Message} this
8879 * @throws {Error} If the value cannot be set
8880 * @expose
8881 */
8882 MessagePrototype.set = function(keyOrObj, value, noAssert) {
8883 if (keyOrObj && typeof keyOrObj === 'object') {
8884 noAssert = value;
8885 for (var ikey in keyOrObj) {
8886 // Check if virtual oneof field - don't set these
8887 if (keyOrObj.hasOwnProperty(ikey) && typeof (value = keyOrObj[ikey]) !== 'undefined' && T._oneofsByName[ikey] === undefined)
8888 this.$set(ikey, value, noAssert);
8889 }
8890 return this;
8891 }
8892 var field = T._fieldsByName[keyOrObj];
8893 if (!noAssert) {
8894 if (!field)
8895 throw Error(this+"#"+keyOrObj+" is not a field: undefined");
8896 if (!(field instanceof ProtoBuf.Reflect.Message.Field))
8897 throw Error(this+"#"+keyOrObj+" is not a field: "+field.toString(true));
8898 this[field.name] = (value = field.verifyValue(value)); // May throw
8899 } else
8900 this[keyOrObj] = value;
8901 if (field && field.oneof) { // Field is part of an OneOf (not a virtual OneOf field)
8902 var currentField = this[field.oneof.name]; // Virtual field references currently set field
8903 if (value !== null) {
8904 if (currentField !== null && currentField !== field.name)
8905 this[currentField] = null; // Clear currently set field
8906 this[field.oneof.name] = field.name; // Point virtual field at this field
8907 } else if (/* value === null && */currentField === keyOrObj)
8908 this[field.oneof.name] = null; // Clear virtual field (current field explicitly cleared)
8909 }
8910 return this;
8911 };
8912
8913 /**
8914 * Sets a field's value. This is an alias for [@link ProtoBuf.Builder.Message#set}.
8915 * @name ProtoBuf.Builder.Message#$set
8916 * @function
8917 * @param {string|!Object.<string,*>} keyOrObj String key or plain object holding multiple values
8918 * @param {(*|boolean)=} value Value to set if key is a string, otherwise omitted
8919 * @param {boolean=} noAssert Whether to not assert the value, defaults to `false`
8920 * @throws {Error} If the value cannot be set
8921 * @expose
8922 */
8923 MessagePrototype.$set = MessagePrototype.set;
8924
8925 /**
8926 * Gets a field's value.
8927 * @name ProtoBuf.Builder.Message#get
8928 * @function
8929 * @param {string} key Key
8930 * @param {boolean=} noAssert Whether to not assert for an actual field, defaults to `false`
8931 * @return {*} Value
8932 * @throws {Error} If there is no such field
8933 * @expose
8934 */
8935 MessagePrototype.get = function(key, noAssert) {
8936 if (noAssert)
8937 return this[key];
8938 var field = T._fieldsByName[key];
8939 if (!field || !(field instanceof ProtoBuf.Reflect.Message.Field))
8940 throw Error(this+"#"+key+" is not a field: undefined");
8941 if (!(field instanceof ProtoBuf.Reflect.Message.Field))
8942 throw Error(this+"#"+key+" is not a field: "+field.toString(true));
8943 return this[field.name];
8944 };
8945
8946 /**
8947 * Gets a field's value. This is an alias for {@link ProtoBuf.Builder.Message#$get}.
8948 * @name ProtoBuf.Builder.Message#$get
8949 * @function
8950 * @param {string} key Key
8951 * @return {*} Value
8952 * @throws {Error} If there is no such field
8953 * @expose
8954 */
8955 MessagePrototype.$get = MessagePrototype.get;
8956
8957 // Getters and setters
8958
8959 for (var i=0; i<fields.length; i++) {
8960 var field = fields[i];
8961 // no setters for extension fields as these are named by their fqn
8962 if (field instanceof ProtoBuf.Reflect.Message.ExtensionField)
8963 continue;
8964
8965 if (T.builder.options['populateAccessors'])
8966 (function(field) {
8967 // set/get[SomeValue]
8968 var Name = field.originalName.replace(/(_[a-zA-Z])/g, function(match) {
8969 return match.toUpperCase().replace('_','');
8970 });
8971 Name = Name.substring(0,1).toUpperCase() + Name.substring(1);
8972
8973 // set/get_[some_value] FIXME: Do we really need these?
8974 var name = field.originalName.replace(/([A-Z])/g, function(match) {
8975 return "_"+match;
8976 });
8977
8978 /**
8979 * The current field's unbound setter function.
8980 * @function
8981 * @param {*} value
8982 * @param {boolean=} noAssert
8983 * @returns {!ProtoBuf.Builder.Message}
8984 * @inner
8985 */
8986 var setter = function(value, noAssert) {
8987 this[field.name] = noAssert ? value : field.verifyValue(value);
8988 return this;
8989 };
8990
8991 /**
8992 * The current field's unbound getter function.
8993 * @function
8994 * @returns {*}
8995 * @inner
8996 */
8997 var getter = function() {
8998 return this[field.name];
8999 };
9000
9001 if (T.getChild("set"+Name) === null)
9002 /**
9003 * Sets a value. This method is present for each field, but only if there is no name conflict with
9004 * another field.
9005 * @name ProtoBuf.Builder.Message#set[SomeField]
9006 * @function
9007 * @param {*} value Value to set
9008 * @param {boolean=} noAssert Whether to not assert the value, defaults to `false`
9009 * @returns {!ProtoBuf.Builder.Message} this
9010 * @abstract
9011 * @throws {Error} If the value cannot be set
9012 */
9013 MessagePrototype["set"+Name] = setter;
9014
9015 if (T.getChild("set_"+name) === null)
9016 /**
9017 * Sets a value. This method is present for each field, but only if there is no name conflict with
9018 * another field.
9019 * @name ProtoBuf.Builder.Message#set_[some_field]
9020 * @function
9021 * @param {*} value Value to set
9022 * @param {boolean=} noAssert Whether to not assert the value, defaults to `false`
9023 * @returns {!ProtoBuf.Builder.Message} this
9024 * @abstract
9025 * @throws {Error} If the value cannot be set
9026 */
9027 MessagePrototype["set_"+name] = setter;
9028
9029 if (T.getChild("get"+Name) === null)
9030 /**
9031 * Gets a value. This method is present for each field, but only if there is no name conflict with
9032 * another field.
9033 * @name ProtoBuf.Builder.Message#get[SomeField]
9034 * @function
9035 * @abstract
9036 * @return {*} The value
9037 */
9038 MessagePrototype["get"+Name] = getter;
9039
9040 if (T.getChild("get_"+name) === null)
9041 /**
9042 * Gets a value. This method is present for each field, but only if there is no name conflict with
9043 * another field.
9044 * @name ProtoBuf.Builder.Message#get_[some_field]
9045 * @function
9046 * @return {*} The value
9047 * @abstract
9048 */
9049 MessagePrototype["get_"+name] = getter;
9050
9051 })(field);
9052 }
9053
9054 // En-/decoding
9055
9056 /**
9057 * Encodes the message.
9058 * @name ProtoBuf.Builder.Message#$encode
9059 * @function
9060 * @param {(!ByteBuffer|boolean)=} buffer ByteBuffer to encode to. Will create a new one and flip it if omitted.
9061 * @param {boolean=} noVerify Whether to not verify field values, defaults to `false`
9062 * @return {!ByteBuffer} Encoded message as a ByteBuffer
9063 * @throws {Error} If the message cannot be encoded or if required fields are missing. The later still
9064 * returns the encoded ByteBuffer in the `encoded` property on the error.
9065 * @expose
9066 * @see ProtoBuf.Builder.Message#encode64
9067 * @see ProtoBuf.Builder.Message#encodeHex
9068 * @see ProtoBuf.Builder.Message#encodeAB
9069 */
9070 MessagePrototype.encode = function(buffer, noVerify) {
9071 if (typeof buffer === 'boolean')
9072 noVerify = buffer,
9073 buffer = undefined;
9074 var isNew = false;
9075 if (!buffer)
9076 buffer = new ByteBuffer(),
9077 isNew = true;
9078 var le = buffer.littleEndian;
9079 try {
9080 T.encode(this, buffer.LE(), noVerify);
9081 return (isNew ? buffer.flip() : buffer).LE(le);
9082 } catch (e) {
9083 buffer.LE(le);
9084 throw(e);
9085 }
9086 };
9087
9088 /**
9089 * Encodes a message using the specified data payload.
9090 * @param {!Object.<string,*>} data Data payload
9091 * @param {(!ByteBuffer|boolean)=} buffer ByteBuffer to encode to. Will create a new one and flip it if omitted.
9092 * @param {boolean=} noVerify Whether to not verify field values, defaults to `false`
9093 * @return {!ByteBuffer} Encoded message as a ByteBuffer
9094 * @expose
9095 */
9096 Message.encode = function(data, buffer, noVerify) {
9097 return new Message(data).encode(buffer, noVerify);
9098 };
9099
9100 /**
9101 * Calculates the byte length of the message.
9102 * @name ProtoBuf.Builder.Message#calculate
9103 * @function
9104 * @returns {number} Byte length
9105 * @throws {Error} If the message cannot be calculated or if required fields are missing.
9106 * @expose
9107 */
9108 MessagePrototype.calculate = function() {
9109 return T.calculate(this);
9110 };
9111
9112 /**
9113 * Encodes the varint32 length-delimited message.
9114 * @name ProtoBuf.Builder.Message#encodeDelimited
9115 * @function
9116 * @param {(!ByteBuffer|boolean)=} buffer ByteBuffer to encode to. Will create a new one and flip it if omitted.
9117 * @param {boolean=} noVerify Whether to not verify field values, defaults to `false`
9118 * @return {!ByteBuffer} Encoded message as a ByteBuffer
9119 * @throws {Error} If the message cannot be encoded or if required fields are missing. The later still
9120 * returns the encoded ByteBuffer in the `encoded` property on the error.
9121 * @expose
9122 */
9123 MessagePrototype.encodeDelimited = function(buffer, noVerify) {
9124 var isNew = false;
9125 if (!buffer)
9126 buffer = new ByteBuffer(),
9127 isNew = true;
9128 var enc = new ByteBuffer().LE();
9129 T.encode(this, enc, noVerify).flip();
9130 buffer.writeVarint32(enc.remaining());
9131 buffer.append(enc);
9132 return isNew ? buffer.flip() : buffer;
9133 };
9134
9135 /**
9136 * Directly encodes the message to an ArrayBuffer.
9137 * @name ProtoBuf.Builder.Message#encodeAB
9138 * @function
9139 * @return {ArrayBuffer} Encoded message as ArrayBuffer
9140 * @throws {Error} If the message cannot be encoded or if required fields are missing. The later still
9141 * returns the encoded ArrayBuffer in the `encoded` property on the error.
9142 * @expose
9143 */
9144 MessagePrototype.encodeAB = function() {
9145 try {
9146 return this.encode().toArrayBuffer();
9147 } catch (e) {
9148 if (e["encoded"]) e["encoded"] = e["encoded"].toArrayBuffer();
9149 throw(e);
9150 }
9151 };
9152
9153 /**
9154 * Returns the message as an ArrayBuffer. This is an alias for {@link ProtoBuf.Builder.Message#encodeAB}.
9155 * @name ProtoBuf.Builder.Message#toArrayBuffer
9156 * @function
9157 * @return {ArrayBuffer} Encoded message as ArrayBuffer
9158 * @throws {Error} If the message cannot be encoded or if required fields are missing. The later still
9159 * returns the encoded ArrayBuffer in the `encoded` property on the error.
9160 * @expose
9161 */
9162 MessagePrototype.toArrayBuffer = MessagePrototype.encodeAB;
9163
9164 /**
9165 * Directly encodes the message to a node Buffer.
9166 * @name ProtoBuf.Builder.Message#encodeNB
9167 * @function
9168 * @return {!Buffer}
9169 * @throws {Error} If the message cannot be encoded, not running under node.js or if required fields are
9170 * missing. The later still returns the encoded node Buffer in the `encoded` property on the error.
9171 * @expose
9172 */
9173 MessagePrototype.encodeNB = function() {
9174 try {
9175 return this.encode().toBuffer();
9176 } catch (e) {
9177 if (e["encoded"]) e["encoded"] = e["encoded"].toBuffer();
9178 throw(e);
9179 }
9180 };
9181
9182 /**
9183 * Returns the message as a node Buffer. This is an alias for {@link ProtoBuf.Builder.Message#encodeNB}.
9184 * @name ProtoBuf.Builder.Message#toBuffer
9185 * @function
9186 * @return {!Buffer}
9187 * @throws {Error} If the message cannot be encoded or if required fields are missing. The later still
9188 * returns the encoded node Buffer in the `encoded` property on the error.
9189 * @expose
9190 */
9191 MessagePrototype.toBuffer = MessagePrototype.encodeNB;
9192
9193 /**
9194 * Directly encodes the message to a base64 encoded string.
9195 * @name ProtoBuf.Builder.Message#encode64
9196 * @function
9197 * @return {string} Base64 encoded string
9198 * @throws {Error} If the underlying buffer cannot be encoded or if required fields are missing. The later
9199 * still returns the encoded base64 string in the `encoded` property on the error.
9200 * @expose
9201 */
9202 MessagePrototype.encode64 = function() {
9203 try {
9204 return this.encode().toBase64();
9205 } catch (e) {
9206 if (e["encoded"]) e["encoded"] = e["encoded"].toBase64();
9207 throw(e);
9208 }
9209 };
9210
9211 /**
9212 * Returns the message as a base64 encoded string. This is an alias for {@link ProtoBuf.Builder.Message#encode64}.
9213 * @name ProtoBuf.Builder.Message#toBase64
9214 * @function
9215 * @return {string} Base64 encoded string
9216 * @throws {Error} If the message cannot be encoded or if required fields are missing. The later still
9217 * returns the encoded base64 string in the `encoded` property on the error.
9218 * @expose
9219 */
9220 MessagePrototype.toBase64 = MessagePrototype.encode64;
9221
9222 /**
9223 * Directly encodes the message to a hex encoded string.
9224 * @name ProtoBuf.Builder.Message#encodeHex
9225 * @function
9226 * @return {string} Hex encoded string
9227 * @throws {Error} If the underlying buffer cannot be encoded or if required fields are missing. The later
9228 * still returns the encoded hex string in the `encoded` property on the error.
9229 * @expose
9230 */
9231 MessagePrototype.encodeHex = function() {
9232 try {
9233 return this.encode().toHex();
9234 } catch (e) {
9235 if (e["encoded"]) e["encoded"] = e["encoded"].toHex();
9236 throw(e);
9237 }
9238 };
9239
9240 /**
9241 * Returns the message as a hex encoded string. This is an alias for {@link ProtoBuf.Builder.Message#encodeHex}.
9242 * @name ProtoBuf.Builder.Message#toHex
9243 * @function
9244 * @return {string} Hex encoded string
9245 * @throws {Error} If the message cannot be encoded or if required fields are missing. The later still
9246 * returns the encoded hex string in the `encoded` property on the error.
9247 * @expose
9248 */
9249 MessagePrototype.toHex = MessagePrototype.encodeHex;
9250
9251 /**
9252 * Clones a message object or field value to a raw object.
9253 * @param {*} obj Object to clone
9254 * @param {boolean} binaryAsBase64 Whether to include binary data as base64 strings or as a buffer otherwise
9255 * @param {boolean} longsAsStrings Whether to encode longs as strings
9256 * @param {!ProtoBuf.Reflect.T=} resolvedType The resolved field type if a field
9257 * @returns {*} Cloned object
9258 * @inner
9259 */
9260 function cloneRaw(obj, binaryAsBase64, longsAsStrings, resolvedType) {
9261 if (obj === null || typeof obj !== 'object') {
9262 // Convert enum values to their respective names
9263 if (resolvedType && resolvedType instanceof ProtoBuf.Reflect.Enum) {
9264 var name = ProtoBuf.Reflect.Enum.getName(resolvedType.object, obj);
9265 if (name !== null)
9266 return name;
9267 }
9268 // Pass-through string, number, boolean, null...
9269 return obj;
9270 }
9271 // Convert ByteBuffers to raw buffer or strings
9272 if (ByteBuffer.isByteBuffer(obj))
9273 return binaryAsBase64 ? obj.toBase64() : obj.toBuffer();
9274 // Convert Longs to proper objects or strings
9275 if (ProtoBuf.Long.isLong(obj))
9276 return longsAsStrings ? obj.toString() : ProtoBuf.Long.fromValue(obj);
9277 var clone;
9278 // Clone arrays
9279 if (Array.isArray(obj)) {
9280 clone = [];
9281 obj.forEach(function(v, k) {
9282 clone[k] = cloneRaw(v, binaryAsBase64, longsAsStrings, resolvedType);
9283 });
9284 return clone;
9285 }
9286 clone = {};
9287 // Convert maps to objects
9288 if (obj instanceof ProtoBuf.Map) {
9289 var it = obj.entries();
9290 for (var e = it.next(); !e.done; e = it.next())
9291 clone[obj.keyElem.valueToString(e.value[0])] = cloneRaw(e.value[1], binaryAsBase64, longsAsStrings, obj.valueElem.resolvedType);
9292 return clone;
9293 }
9294 // Everything else is a non-null object
9295 var type = obj.$type,
9296 field = undefined;
9297 for (var i in obj)
9298 if (obj.hasOwnProperty(i)) {
9299 if (type && (field = type.getChild(i)))
9300 clone[i] = cloneRaw(obj[i], binaryAsBase64, longsAsStrings, field.resolvedType);
9301 else
9302 clone[i] = cloneRaw(obj[i], binaryAsBase64, longsAsStrings);
9303 }
9304 return clone;
9305 }
9306
9307 /**
9308 * Returns the message's raw payload.
9309 * @param {boolean=} binaryAsBase64 Whether to include binary data as base64 strings instead of Buffers, defaults to `false`
9310 * @param {boolean} longsAsStrings Whether to encode longs as strings
9311 * @returns {Object.<string,*>} Raw payload
9312 * @expose
9313 */
9314 MessagePrototype.toRaw = function(binaryAsBase64, longsAsStrings) {
9315 return cloneRaw(this, !!binaryAsBase64, !!longsAsStrings, this.$type);
9316 };
9317
9318 /**
9319 * Encodes a message to JSON.
9320 * @returns {string} JSON string
9321 * @expose
9322 */
9323 MessagePrototype.encodeJSON = function() {
9324 return JSON.stringify(
9325 cloneRaw(this,
9326 /* binary-as-base64 */ true,
9327 /* longs-as-strings */ true,
9328 this.$type
9329 )
9330 );
9331 };
9332
9333 /**
9334 * Decodes a message from the specified buffer or string.
9335 * @name ProtoBuf.Builder.Message.decode
9336 * @function
9337 * @param {!ByteBuffer|!ArrayBuffer|!Buffer|string} buffer Buffer to decode from
9338 * @param {(number|string)=} length Message length. Defaults to decode all the remainig data.
9339 * @param {string=} enc Encoding if buffer is a string: hex, utf8 (not recommended), defaults to base64
9340 * @return {!ProtoBuf.Builder.Message} Decoded message
9341 * @throws {Error} If the message cannot be decoded or if required fields are missing. The later still
9342 * returns the decoded message with missing fields in the `decoded` property on the error.
9343 * @expose
9344 * @see ProtoBuf.Builder.Message.decode64
9345 * @see ProtoBuf.Builder.Message.decodeHex
9346 */
9347 Message.decode = function(buffer, length, enc) {
9348 if (typeof length === 'string')
9349 enc = length,
9350 length = -1;
9351 if (typeof buffer === 'string')
9352 buffer = ByteBuffer.wrap(buffer, enc ? enc : "base64");
9353 else if (!ByteBuffer.isByteBuffer(buffer))
9354 buffer = ByteBuffer.wrap(buffer); // May throw
9355 var le = buffer.littleEndian;
9356 try {
9357 var msg = T.decode(buffer.LE(), length);
9358 buffer.LE(le);
9359 return msg;
9360 } catch (e) {
9361 buffer.LE(le);
9362 throw(e);
9363 }
9364 };
9365
9366 /**
9367 * Decodes a varint32 length-delimited message from the specified buffer or string.
9368 * @name ProtoBuf.Builder.Message.decodeDelimited
9369 * @function
9370 * @param {!ByteBuffer|!ArrayBuffer|!Buffer|string} buffer Buffer to decode from
9371 * @param {string=} enc Encoding if buffer is a string: hex, utf8 (not recommended), defaults to base64
9372 * @return {ProtoBuf.Builder.Message} Decoded message or `null` if not enough bytes are available yet
9373 * @throws {Error} If the message cannot be decoded or if required fields are missing. The later still
9374 * returns the decoded message with missing fields in the `decoded` property on the error.
9375 * @expose
9376 */
9377 Message.decodeDelimited = function(buffer, enc) {
9378 if (typeof buffer === 'string')
9379 buffer = ByteBuffer.wrap(buffer, enc ? enc : "base64");
9380 else if (!ByteBuffer.isByteBuffer(buffer))
9381 buffer = ByteBuffer.wrap(buffer); // May throw
9382 if (buffer.remaining() < 1)
9383 return null;
9384 var off = buffer.offset,
9385 len = buffer.readVarint32();
9386 if (buffer.remaining() < len) {
9387 buffer.offset = off;
9388 return null;
9389 }
9390 try {
9391 var msg = T.decode(buffer.slice(buffer.offset, buffer.offset + len).LE());
9392 buffer.offset += len;
9393 return msg;
9394 } catch (err) {
9395 buffer.offset += len;
9396 throw err;
9397 }
9398 };
9399
9400 /**
9401 * Decodes the message from the specified base64 encoded string.
9402 * @name ProtoBuf.Builder.Message.decode64
9403 * @function
9404 * @param {string} str String to decode from
9405 * @return {!ProtoBuf.Builder.Message} Decoded message
9406 * @throws {Error} If the message cannot be decoded or if required fields are missing. The later still
9407 * returns the decoded message with missing fields in the `decoded` property on the error.
9408 * @expose
9409 */
9410 Message.decode64 = function(str) {
9411 return Message.decode(str, "base64");
9412 };
9413
9414 /**
9415 * Decodes the message from the specified hex encoded string.
9416 * @name ProtoBuf.Builder.Message.decodeHex
9417 * @function
9418 * @param {string} str String to decode from
9419 * @return {!ProtoBuf.Builder.Message} Decoded message
9420 * @throws {Error} If the message cannot be decoded or if required fields are missing. The later still
9421 * returns the decoded message with missing fields in the `decoded` property on the error.
9422 * @expose
9423 */
9424 Message.decodeHex = function(str) {
9425 return Message.decode(str, "hex");
9426 };
9427
9428 /**
9429 * Decodes the message from a JSON string.
9430 * @name ProtoBuf.Builder.Message.decodeJSON
9431 * @function
9432 * @param {string} str String to decode from
9433 * @return {!ProtoBuf.Builder.Message} Decoded message
9434 * @throws {Error} If the message cannot be decoded or if required fields are
9435 * missing.
9436 * @expose
9437 */
9438 Message.decodeJSON = function(str) {
9439 return new Message(JSON.parse(str));
9440 };
9441
9442 // Utility
9443
9444 /**
9445 * Returns a string representation of this Message.
9446 * @name ProtoBuf.Builder.Message#toString
9447 * @function
9448 * @return {string} String representation as of ".Fully.Qualified.MessageName"
9449 * @expose
9450 */
9451 MessagePrototype.toString = function() {
9452 return T.toString();
9453 };
9454
9455 if (Object.defineProperty)
9456 Object.defineProperty(Message, '$options', { "value": T.buildOpt() }),
9457 Object.defineProperty(MessagePrototype, "$options", { "value": Message["$options"] }),
9458 Object.defineProperty(Message, "$type", { "value": T }),
9459 Object.defineProperty(MessagePrototype, "$type", { "value": T });
9460
9461 return Message;
9462
9463 })(ProtoBuf, this);
9464
9465 // Static enums and prototyped sub-messages / cached collections
9466 this._fields = [];
9467 this._fieldsById = {};
9468 this._fieldsByName = {};
9469 this._oneofsByName = {};
9470 for (var i=0, k=this.children.length, child; i<k; i++) {
9471 child = this.children[i];
9472 if (child instanceof Enum || child instanceof Message || child instanceof Service) {
9473 if (clazz.hasOwnProperty(child.name))
9474 throw Error("Illegal reflect child of "+this.toString(true)+": "+child.toString(true)+" cannot override static property '"+child.name+"'");
9475 clazz[child.name] = child.build();
9476 } else if (child instanceof Message.Field)
9477 child.build(),
9478 this._fields.push(child),
9479 this._fieldsById[child.id] = child,
9480 this._fieldsByName[child.name] = child;
9481 else if (child instanceof Message.OneOf) {
9482 this._oneofsByName[child.name] = child;
9483 }
9484 else if (!(child instanceof Message.OneOf) && !(child instanceof Extension)) // Not built
9485 throw Error("Illegal reflect child of "+this.toString(true)+": "+this.children[i].toString(true));
9486 }
9487
9488 return this.clazz = clazz;
9489 };
9490
9491 /**
9492 * Encodes a runtime message's contents to the specified buffer.
9493 * @param {!ProtoBuf.Builder.Message} message Runtime message to encode
9494 * @param {ByteBuffer} buffer ByteBuffer to write to
9495 * @param {boolean=} noVerify Whether to not verify field values, defaults to `false`
9496 * @return {ByteBuffer} The ByteBuffer for chaining
9497 * @throws {Error} If required fields are missing or the message cannot be encoded for another reason
9498 * @expose
9499 */
9500 MessagePrototype.encode = function(message, buffer, noVerify) {
9501 var fieldMissing = null,
9502 field;
9503 for (var i=0, k=this._fields.length, val; i<k; ++i) {
9504 field = this._fields[i];
9505 val = message[field.name];
9506 if (field.required && val === null) {
9507 if (fieldMissing === null)
9508 fieldMissing = field;
9509 } else
9510 field.encode(noVerify ? val : field.verifyValue(val), buffer, message);
9511 }
9512 if (fieldMissing !== null) {
9513 var err = Error("Missing at least one required field for "+this.toString(true)+": "+fieldMissing);
9514 err["encoded"] = buffer; // Still expose what we got
9515 throw(err);
9516 }
9517 return buffer;
9518 };
9519
9520 /**
9521 * Calculates a runtime message's byte length.
9522 * @param {!ProtoBuf.Builder.Message} message Runtime message to encode
9523 * @returns {number} Byte length
9524 * @throws {Error} If required fields are missing or the message cannot be calculated for another reason
9525 * @expose
9526 */
9527 MessagePrototype.calculate = function(message) {
9528 for (var n=0, i=0, k=this._fields.length, field, val; i<k; ++i) {
9529 field = this._fields[i];
9530 val = message[field.name];
9531 if (field.required && val === null)
9532 throw Error("Missing at least one required field for "+this.toString(true)+": "+field);
9533 else
9534 n += field.calculate(val, message);
9535 }
9536 return n;
9537 };
9538
9539 /**
9540 * Skips all data until the end of the specified group has been reached.
9541 * @param {number} expectedId Expected GROUPEND id
9542 * @param {!ByteBuffer} buf ByteBuffer
9543 * @returns {boolean} `true` if a value as been skipped, `false` if the end has been reached
9544 * @throws {Error} If it wasn't possible to find the end of the group (buffer overrun or end tag mismatch)
9545 * @inner
9546 */
9547 function skipTillGroupEnd(expectedId, buf) {
9548 var tag = buf.readVarint32(), // Throws on OOB
9549 wireType = tag & 0x07,
9550 id = tag >>> 3;
9551 switch (wireType) {
9552 case ProtoBuf.WIRE_TYPES.VARINT:
9553 do tag = buf.readUint8();
9554 while ((tag & 0x80) === 0x80);
9555 break;
9556 case ProtoBuf.WIRE_TYPES.BITS64:
9557 buf.offset += 8;
9558 break;
9559 case ProtoBuf.WIRE_TYPES.LDELIM:
9560 tag = buf.readVarint32(); // reads the varint
9561 buf.offset += tag; // skips n bytes
9562 break;
9563 case ProtoBuf.WIRE_TYPES.STARTGROUP:
9564 skipTillGroupEnd(id, buf);
9565 break;
9566 case ProtoBuf.WIRE_TYPES.ENDGROUP:
9567 if (id === expectedId)
9568 return false;
9569 else
9570 throw Error("Illegal GROUPEND after unknown group: "+id+" ("+expectedId+" expected)");
9571 case ProtoBuf.WIRE_TYPES.BITS32:
9572 buf.offset += 4;
9573 break;
9574 default:
9575 throw Error("Illegal wire type in unknown group "+expectedId+": "+wireType);
9576 }
9577 return true;
9578 }
9579
9580 /**
9581 * Decodes an encoded message and returns the decoded message.
9582 * @param {ByteBuffer} buffer ByteBuffer to decode from
9583 * @param {number=} length Message length. Defaults to decode all remaining data.
9584 * @param {number=} expectedGroupEndId Expected GROUPEND id if this is a legacy group
9585 * @return {ProtoBuf.Builder.Message} Decoded message
9586 * @throws {Error} If the message cannot be decoded
9587 * @expose
9588 */
9589 MessagePrototype.decode = function(buffer, length, expectedGroupEndId) {
9590 if (typeof length !== 'number')
9591 length = -1;
9592 var start = buffer.offset,
9593 msg = new (this.clazz)(),
9594 tag, wireType, id, field;
9595 while (buffer.offset < start+length || (length === -1 && buffer.remaining() > 0)) {
9596 tag = buffer.readVarint32();
9597 wireType = tag & 0x07;
9598 id = tag >>> 3;
9599 if (wireType === ProtoBuf.WIRE_TYPES.ENDGROUP) {
9600 if (id !== expectedGroupEndId)
9601 throw Error("Illegal group end indicator for "+this.toString(true)+": "+id+" ("+(expectedGroupEndId ? expectedGroupEndId+" expected" : "not a group")+")");
9602 break;
9603 }
9604 if (!(field = this._fieldsById[id])) {
9605 // "messages created by your new code can be parsed by your old code: old binaries simply ignore the new field when parsing."
9606 switch (wireType) {
9607 case ProtoBuf.WIRE_TYPES.VARINT:
9608 buffer.readVarint32();
9609 break;
9610 case ProtoBuf.WIRE_TYPES.BITS32:
9611 buffer.offset += 4;
9612 break;
9613 case ProtoBuf.WIRE_TYPES.BITS64:
9614 buffer.offset += 8;
9615 break;
9616 case ProtoBuf.WIRE_TYPES.LDELIM:
9617 var len = buffer.readVarint32();
9618 buffer.offset += len;
9619 break;
9620 case ProtoBuf.WIRE_TYPES.STARTGROUP:
9621 while (skipTillGroupEnd(id, buffer)) {}
9622 break;
9623 default:
9624 throw Error("Illegal wire type for unknown field "+id+" in "+this.toString(true)+"#decode: "+wireType);
9625 }
9626 continue;
9627 }
9628 if (field.repeated && !field.options["packed"]) {
9629 msg[field.name].push(field.decode(wireType, buffer));
9630 } else if (field.map) {
9631 var keyval = field.decode(wireType, buffer);
9632 msg[field.name].set(keyval[0], keyval[1]);
9633 } else {
9634 msg[field.name] = field.decode(wireType, buffer);
9635 if (field.oneof) { // Field is part of an OneOf (not a virtual OneOf field)
9636 var currentField = msg[field.oneof.name]; // Virtual field references currently set field
9637 if (currentField !== null && currentField !== field.name)
9638 msg[currentField] = null; // Clear currently set field
9639 msg[field.oneof.name] = field.name; // Point virtual field at this field
9640 }
9641 }
9642 }
9643
9644 // Check if all required fields are present and set default values for optional fields that are not
9645 for (var i=0, k=this._fields.length; i<k; ++i) {
9646 field = this._fields[i];
9647 if (msg[field.name] === null) {
9648 if (this.syntax === "proto3") { // Proto3 sets default values by specification
9649 msg[field.name] = field.defaultValue;
9650 } else if (field.required) {
9651 var err = Error("Missing at least one required field for " + this.toString(true) + ": " + field.name);
9652 err["decoded"] = msg; // Still expose what we got
9653 throw(err);
9654 } else if (ProtoBuf.populateDefaults && field.defaultValue !== null)
9655 msg[field.name] = field.defaultValue;
9656 }
9657 }
9658 return msg;
9659 };
9660
9661 /**
9662 * @alias ProtoBuf.Reflect.Message
9663 * @expose
9664 */
9665 Reflect.Message = Message;
9666
9667 /**
9668 * Constructs a new Message Field.
9669 * @exports ProtoBuf.Reflect.Message.Field
9670 * @param {!ProtoBuf.Builder} builder Builder reference
9671 * @param {!ProtoBuf.Reflect.Message} message Message reference
9672 * @param {string} rule Rule, one of requried, optional, repeated
9673 * @param {string?} keytype Key data type, if any.
9674 * @param {string} type Data type, e.g. int32
9675 * @param {string} name Field name
9676 * @param {number} id Unique field id
9677 * @param {Object.<string,*>=} options Options
9678 * @param {!ProtoBuf.Reflect.Message.OneOf=} oneof Enclosing OneOf
9679 * @param {string?} syntax The syntax level of this definition (e.g., proto3)
9680 * @constructor
9681 * @extends ProtoBuf.Reflect.T
9682 */
9683 var Field = function(builder, message, rule, keytype, type, name, id, options, oneof, syntax) {
9684 T.call(this, builder, message, name);
9685
9686 /**
9687 * @override
9688 */
9689 this.className = "Message.Field";
9690
9691 /**
9692 * Message field required flag.
9693 * @type {boolean}
9694 * @expose
9695 */
9696 this.required = rule === "required";
9697
9698 /**
9699 * Message field repeated flag.
9700 * @type {boolean}
9701 * @expose
9702 */
9703 this.repeated = rule === "repeated";
9704
9705 /**
9706 * Message field map flag.
9707 * @type {boolean}
9708 * @expose
9709 */
9710 this.map = rule === "map";
9711
9712 /**
9713 * Message field key type. Type reference string if unresolved, protobuf
9714 * type if resolved. Valid only if this.map === true, null otherwise.
9715 * @type {string|{name: string, wireType: number}|null}
9716 * @expose
9717 */
9718 this.keyType = keytype || null;
9719
9720 /**
9721 * Message field type. Type reference string if unresolved, protobuf type if
9722 * resolved. In a map field, this is the value type.
9723 * @type {string|{name: string, wireType: number}}
9724 * @expose
9725 */
9726 this.type = type;
9727
9728 /**
9729 * Resolved type reference inside the global namespace.
9730 * @type {ProtoBuf.Reflect.T|null}
9731 * @expose
9732 */
9733 this.resolvedType = null;
9734
9735 /**
9736 * Unique message field id.
9737 * @type {number}
9738 * @expose
9739 */
9740 this.id = id;
9741
9742 /**
9743 * Message field options.
9744 * @type {!Object.<string,*>}
9745 * @dict
9746 * @expose
9747 */
9748 this.options = options || {};
9749
9750 /**
9751 * Default value.
9752 * @type {*}
9753 * @expose
9754 */
9755 this.defaultValue = null;
9756
9757 /**
9758 * Enclosing OneOf.
9759 * @type {?ProtoBuf.Reflect.Message.OneOf}
9760 * @expose
9761 */
9762 this.oneof = oneof || null;
9763
9764 /**
9765 * Syntax level of this definition (e.g., proto3).
9766 * @type {string}
9767 * @expose
9768 */
9769 this.syntax = syntax || 'proto2';
9770
9771 /**
9772 * Original field name.
9773 * @type {string}
9774 * @expose
9775 */
9776 this.originalName = this.name; // Used to revert camelcase transformation on naming collisions
9777
9778 /**
9779 * Element implementation. Created in build() after types are resolved.
9780 * @type {ProtoBuf.Element}
9781 * @expose
9782 */
9783 this.element = null;
9784
9785 /**
9786 * Key element implementation, for map fields. Created in build() after
9787 * types are resolved.
9788 * @type {ProtoBuf.Element}
9789 * @expose
9790 */
9791 this.keyElement = null;
9792
9793 // Convert field names to camel case notation if the override is set
9794 if (this.builder.options['convertFieldsToCamelCase'] && !(this instanceof Message.ExtensionField))
9795 this.name = ProtoBuf.Util.toCamelCase(this.name);
9796 };
9797
9798 /**
9799 * @alias ProtoBuf.Reflect.Message.Field.prototype
9800 * @inner
9801 */
9802 var FieldPrototype = Field.prototype = Object.create(T.prototype);
9803
9804 /**
9805 * Builds the field.
9806 * @override
9807 * @expose
9808 */
9809 FieldPrototype.build = function() {
9810 this.element = new Element(this.type, this.resolvedType, false, this.syntax, this.name);
9811 if (this.map)
9812 this.keyElement = new Element(this.keyType, undefined, true, this.syntax, this.name);
9813
9814 // In proto3, fields do not have field presence, and every field is set to
9815 // its type's default value ("", 0, 0.0, or false).
9816 if (this.syntax === 'proto3' && !this.repeated && !this.map)
9817 this.defaultValue = Element.defaultFieldValue(this.type);
9818
9819 // Otherwise, default values are present when explicitly specified
9820 else if (typeof this.options['default'] !== 'undefined')
9821 this.defaultValue = this.verifyValue(this.options['default']);
9822 };
9823
9824 /**
9825 * Checks if the given value can be set for this field.
9826 * @param {*} value Value to check
9827 * @param {boolean=} skipRepeated Whether to skip the repeated value check or not. Defaults to false.
9828 * @return {*} Verified, maybe adjusted, value
9829 * @throws {Error} If the value cannot be set for this field
9830 * @expose
9831 */
9832 FieldPrototype.verifyValue = function(value, skipRepeated) {
9833 skipRepeated = skipRepeated || false;
9834 var self = this;
9835 function fail(val, msg) {
9836 throw Error("Illegal value for "+self.toString(true)+" of type "+self.type.name+": "+val+" ("+msg+")");
9837 }
9838 if (value === null) { // NULL values for optional fields
9839 if (this.required)
9840 fail(typeof value, "required");
9841 if (this.syntax === 'proto3' && this.type !== ProtoBuf.TYPES["message"])
9842 fail(typeof value, "proto3 field without field presence cannot be null");
9843 return null;
9844 }
9845 var i;
9846 if (this.repeated && !skipRepeated) { // Repeated values as arrays
9847 if (!Array.isArray(value))
9848 value = [value];
9849 var res = [];
9850 for (i=0; i<value.length; i++)
9851 res.push(this.element.verifyValue(value[i]));
9852 return res;
9853 }
9854 if (this.map && !skipRepeated) { // Map values as objects
9855 if (!(value instanceof ProtoBuf.Map)) {
9856 // If not already a Map, attempt to convert.
9857 if (!(value instanceof Object)) {
9858 fail(typeof value,
9859 "expected ProtoBuf.Map or raw object for map field");
9860 }
9861 return new ProtoBuf.Map(this, value);
9862 } else {
9863 return value;
9864 }
9865 }
9866 // All non-repeated fields expect no array
9867 if (!this.repeated && Array.isArray(value))
9868 fail(typeof value, "no array expected");
9869
9870 return this.element.verifyValue(value);
9871 };
9872
9873 /**
9874 * Determines whether the field will have a presence on the wire given its
9875 * value.
9876 * @param {*} value Verified field value
9877 * @param {!ProtoBuf.Builder.Message} message Runtime message
9878 * @return {boolean} Whether the field will be present on the wire
9879 */
9880 FieldPrototype.hasWirePresence = function(value, message) {
9881 if (this.syntax !== 'proto3')
9882 return (value !== null);
9883 if (this.oneof && message[this.oneof.name] === this.name)
9884 return true;
9885 switch (this.type) {
9886 case ProtoBuf.TYPES["int32"]:
9887 case ProtoBuf.TYPES["sint32"]:
9888 case ProtoBuf.TYPES["sfixed32"]:
9889 case ProtoBuf.TYPES["uint32"]:
9890 case ProtoBuf.TYPES["fixed32"]:
9891 return value !== 0;
9892
9893 case ProtoBuf.TYPES["int64"]:
9894 case ProtoBuf.TYPES["sint64"]:
9895 case ProtoBuf.TYPES["sfixed64"]:
9896 case ProtoBuf.TYPES["uint64"]:
9897 case ProtoBuf.TYPES["fixed64"]:
9898 return value.low !== 0 || value.high !== 0;
9899
9900 case ProtoBuf.TYPES["bool"]:
9901 return value;
9902
9903 case ProtoBuf.TYPES["float"]:
9904 case ProtoBuf.TYPES["double"]:
9905 return value !== 0.0;
9906
9907 case ProtoBuf.TYPES["string"]:
9908 return value.length > 0;
9909
9910 case ProtoBuf.TYPES["bytes"]:
9911 return value.remaining() > 0;
9912
9913 case ProtoBuf.TYPES["enum"]:
9914 return value !== 0;
9915
9916 case ProtoBuf.TYPES["message"]:
9917 return value !== null;
9918 default:
9919 return true;
9920 }
9921 };
9922
9923 /**
9924 * Encodes the specified field value to the specified buffer.
9925 * @param {*} value Verified field value
9926 * @param {ByteBuffer} buffer ByteBuffer to encode to
9927 * @param {!ProtoBuf.Builder.Message} message Runtime message
9928 * @return {ByteBuffer} The ByteBuffer for chaining
9929 * @throws {Error} If the field cannot be encoded
9930 * @expose
9931 */
9932 FieldPrototype.encode = function(value, buffer, message) {
9933 if (this.type === null || typeof this.type !== 'object')
9934 throw Error("[INTERNAL] Unresolved type in "+this.toString(true)+": "+this.type);
9935 if (value === null || (this.repeated && value.length == 0))
9936 return buffer; // Optional omitted
9937 try {
9938 if (this.repeated) {
9939 var i;
9940 // "Only repeated fields of primitive numeric types (types which use the varint, 32-bit, or 64-bit wire
9941 // types) can be declared 'packed'."
9942 if (this.options["packed"] && ProtoBuf.PACKABLE_WIRE_TYPES.indexOf(this.type.wireType) >= 0) {
9943 // "All of the elements of the field are packed into a single key-value pair with wire type 2
9944 // (length-delimited). Each element is encoded the same way it would be normally, except without a
9945 // tag preceding it."
9946 buffer.writeVarint32((this.id << 3) | ProtoBuf.WIRE_TYPES.LDELIM);
9947 buffer.ensureCapacity(buffer.offset += 1); // We do not know the length yet, so let's assume a varint of length 1
9948 var start = buffer.offset; // Remember where the contents begin
9949 for (i=0; i<value.length; i++)
9950 this.element.encodeValue(this.id, value[i], buffer);
9951 var len = buffer.offset-start,
9952 varintLen = ByteBuffer.calculateVarint32(len);
9953 if (varintLen > 1) { // We need to move the contents
9954 var contents = buffer.slice(start, buffer.offset);
9955 start += varintLen-1;
9956 buffer.offset = start;
9957 buffer.append(contents);
9958 }
9959 buffer.writeVarint32(len, start-varintLen);
9960 } else {
9961 // "If your message definition has repeated elements (without the [packed=true] option), the encoded
9962 // message has zero or more key-value pairs with the same tag number"
9963 for (i=0; i<value.length; i++)
9964 buffer.writeVarint32((this.id << 3) | this.type.wireType),
9965 this.element.encodeValue(this.id, value[i], buffer);
9966 }
9967 } else if (this.map) {
9968 // Write out each map entry as a submessage.
9969 value.forEach(function(val, key, m) {
9970 // Compute the length of the submessage (key, val) pair.
9971 var length =
9972 ByteBuffer.calculateVarint32((1 << 3) | this.keyType.wireType) +
9973 this.keyElement.calculateLength(1, key) +
9974 ByteBuffer.calculateVarint32((2 << 3) | this.type.wireType) +
9975 this.element.calculateLength(2, val);
9976
9977 // Submessage with wire type of length-delimited.
9978 buffer.writeVarint32((this.id << 3) | ProtoBuf.WIRE_TYPES.LDELIM);
9979 buffer.writeVarint32(length);
9980
9981 // Write out the key and val.
9982 buffer.writeVarint32((1 << 3) | this.keyType.wireType);
9983 this.keyElement.encodeValue(1, key, buffer);
9984 buffer.writeVarint32((2 << 3) | this.type.wireType);
9985 this.element.encodeValue(2, val, buffer);
9986 }, this);
9987 } else {
9988 if (this.hasWirePresence(value, message)) {
9989 buffer.writeVarint32((this.id << 3) | this.type.wireType);
9990 this.element.encodeValue(this.id, value, buffer);
9991 }
9992 }
9993 } catch (e) {
9994 throw Error("Illegal value for "+this.toString(true)+": "+value+" ("+e+")");
9995 }
9996 return buffer;
9997 };
9998
9999 /**
10000 * Calculates the length of this field's value on the network level.
10001 * @param {*} value Field value
10002 * @param {!ProtoBuf.Builder.Message} message Runtime message
10003 * @returns {number} Byte length
10004 * @expose
10005 */
10006 FieldPrototype.calculate = function(value, message) {
10007 value = this.verifyValue(value); // May throw
10008 if (this.type === null || typeof this.type !== 'object')
10009 throw Error("[INTERNAL] Unresolved type in "+this.toString(true)+": "+this.type);
10010 if (value === null || (this.repeated && value.length == 0))
10011 return 0; // Optional omitted
10012 var n = 0;
10013 try {
10014 if (this.repeated) {
10015 var i, ni;
10016 if (this.options["packed"] && ProtoBuf.PACKABLE_WIRE_TYPES.indexOf(this.type.wireType) >= 0) {
10017 n += ByteBuffer.calculateVarint32((this.id << 3) | ProtoBuf.WIRE_TYPES.LDELIM);
10018 ni = 0;
10019 for (i=0; i<value.length; i++)
10020 ni += this.element.calculateLength(this.id, value[i]);
10021 n += ByteBuffer.calculateVarint32(ni);
10022 n += ni;
10023 } else {
10024 for (i=0; i<value.length; i++)
10025 n += ByteBuffer.calculateVarint32((this.id << 3) | this.type.wireType),
10026 n += this.element.calculateLength(this.id, value[i]);
10027 }
10028 } else if (this.map) {
10029 // Each map entry becomes a submessage.
10030 value.forEach(function(val, key, m) {
10031 // Compute the length of the submessage (key, val) pair.
10032 var length =
10033 ByteBuffer.calculateVarint32((1 << 3) | this.keyType.wireType) +
10034 this.keyElement.calculateLength(1, key) +
10035 ByteBuffer.calculateVarint32((2 << 3) | this.type.wireType) +
10036 this.element.calculateLength(2, val);
10037
10038 n += ByteBuffer.calculateVarint32((this.id << 3) | ProtoBuf.WIRE_TYPES.LDELIM);
10039 n += ByteBuffer.calculateVarint32(length);
10040 n += length;
10041 }, this);
10042 } else {
10043 if (this.hasWirePresence(value, message)) {
10044 n += ByteBuffer.calculateVarint32((this.id << 3) | this.type.wireType);
10045 n += this.element.calculateLength(this.id, value);
10046 }
10047 }
10048 } catch (e) {
10049 throw Error("Illegal value for "+this.toString(true)+": "+value+" ("+e+")");
10050 }
10051 return n;
10052 };
10053
10054 /**
10055 * Decode the field value from the specified buffer.
10056 * @param {number} wireType Leading wire type
10057 * @param {ByteBuffer} buffer ByteBuffer to decode from
10058 * @param {boolean=} skipRepeated Whether to skip the repeated check or not. Defaults to false.
10059 * @return {*} Decoded value: array for packed repeated fields, [key, value] for
10060 * map fields, or an individual value otherwise.
10061 * @throws {Error} If the field cannot be decoded
10062 * @expose
10063 */
10064 FieldPrototype.decode = function(wireType, buffer, skipRepeated) {
10065 var value, nBytes;
10066
10067 // We expect wireType to match the underlying type's wireType unless we see
10068 // a packed repeated field, or unless this is a map field.
10069 var wireTypeOK =
10070 (!this.map && wireType == this.type.wireType) ||
10071 (!skipRepeated && this.repeated && this.options["packed"] &&
10072 wireType == ProtoBuf.WIRE_TYPES.LDELIM) ||
10073 (this.map && wireType == ProtoBuf.WIRE_TYPES.LDELIM);
10074 if (!wireTypeOK)
10075 throw Error("Illegal wire type for field "+this.toString(true)+": "+wireType+" ("+this.type.wireType+" expected)");
10076
10077 // Handle packed repeated fields.
10078 if (wireType == ProtoBuf.WIRE_TYPES.LDELIM && this.repeated && this.options["packed"] && ProtoBuf.PACKABLE_WIRE_TYPES.indexOf(this.type.wireType) >= 0) {
10079 if (!skipRepeated) {
10080 nBytes = buffer.readVarint32();
10081 nBytes = buffer.offset + nBytes; // Limit
10082 var values = [];
10083 while (buffer.offset < nBytes)
10084 values.push(this.decode(this.type.wireType, buffer, true));
10085 return values;
10086 }
10087 // Read the next value otherwise...
10088 }
10089
10090 // Handle maps.
10091 if (this.map) {
10092 // Read one (key, value) submessage, and return [key, value]
10093 var key = Element.defaultFieldValue(this.keyType);
10094 value = Element.defaultFieldValue(this.type);
10095
10096 // Read the length
10097 nBytes = buffer.readVarint32();
10098 if (buffer.remaining() < nBytes)
10099 throw Error("Illegal number of bytes for "+this.toString(true)+": "+nBytes+" required but got only "+buffer.remaining());
10100
10101 // Get a sub-buffer of this key/value submessage
10102 var msgbuf = buffer.clone();
10103 msgbuf.limit = msgbuf.offset + nBytes;
10104 buffer.offset += nBytes;
10105
10106 while (msgbuf.remaining() > 0) {
10107 var tag = msgbuf.readVarint32();
10108 wireType = tag & 0x07;
10109 var id = tag >>> 3;
10110 if (id === 1) {
10111 key = this.keyElement.decode(msgbuf, wireType, id);
10112 } else if (id === 2) {
10113 value = this.element.decode(msgbuf, wireType, id);
10114 } else {
10115 throw Error("Unexpected tag in map field key/value submessage");
10116 }
10117 }
10118
10119 return [key, value];
10120 }
10121
10122 // Handle singular and non-packed repeated field values.
10123 return this.element.decode(buffer, wireType, this.id);
10124 };
10125
10126 /**
10127 * @alias ProtoBuf.Reflect.Message.Field
10128 * @expose
10129 */
10130 Reflect.Message.Field = Field;
10131
10132 /**
10133 * Constructs a new Message ExtensionField.
10134 * @exports ProtoBuf.Reflect.Message.ExtensionField
10135 * @param {!ProtoBuf.Builder} builder Builder reference
10136 * @param {!ProtoBuf.Reflect.Message} message Message reference
10137 * @param {string} rule Rule, one of requried, optional, repeated
10138 * @param {string} type Data type, e.g. int32
10139 * @param {string} name Field name
10140 * @param {number} id Unique field id
10141 * @param {!Object.<string,*>=} options Options
10142 * @constructor
10143 * @extends ProtoBuf.Reflect.Message.Field
10144 */
10145 var ExtensionField = function(builder, message, rule, type, name, id, options) {
10146 Field.call(this, builder, message, rule, /* keytype = */ null, type, name, id, options);
10147
10148 /**
10149 * Extension reference.
10150 * @type {!ProtoBuf.Reflect.Extension}
10151 * @expose
10152 */
10153 this.extension;
10154 };
10155
10156 // Extends Field
10157 ExtensionField.prototype = Object.create(Field.prototype);
10158
10159 /**
10160 * @alias ProtoBuf.Reflect.Message.ExtensionField
10161 * @expose
10162 */
10163 Reflect.Message.ExtensionField = ExtensionField;
10164
10165 /**
10166 * Constructs a new Message OneOf.
10167 * @exports ProtoBuf.Reflect.Message.OneOf
10168 * @param {!ProtoBuf.Builder} builder Builder reference
10169 * @param {!ProtoBuf.Reflect.Message} message Message reference
10170 * @param {string} name OneOf name
10171 * @constructor
10172 * @extends ProtoBuf.Reflect.T
10173 */
10174 var OneOf = function(builder, message, name) {
10175 T.call(this, builder, message, name);
10176
10177 /**
10178 * Enclosed fields.
10179 * @type {!Array.<!ProtoBuf.Reflect.Message.Field>}
10180 * @expose
10181 */
10182 this.fields = [];
10183 };
10184
10185 /**
10186 * @alias ProtoBuf.Reflect.Message.OneOf
10187 * @expose
10188 */
10189 Reflect.Message.OneOf = OneOf;
10190
10191 /**
10192 * Constructs a new Enum.
10193 * @exports ProtoBuf.Reflect.Enum
10194 * @param {!ProtoBuf.Builder} builder Builder reference
10195 * @param {!ProtoBuf.Reflect.T} parent Parent Reflect object
10196 * @param {string} name Enum name
10197 * @param {Object.<string,*>=} options Enum options
10198 * @param {string?} syntax The syntax level (e.g., proto3)
10199 * @constructor
10200 * @extends ProtoBuf.Reflect.Namespace
10201 */
10202 var Enum = function(builder, parent, name, options, syntax) {
10203 Namespace.call(this, builder, parent, name, options, syntax);
10204
10205 /**
10206 * @override
10207 */
10208 this.className = "Enum";
10209
10210 /**
10211 * Runtime enum object.
10212 * @type {Object.<string,number>|null}
10213 * @expose
10214 */
10215 this.object = null;
10216 };
10217
10218 /**
10219 * Gets the string name of an enum value.
10220 * @param {!ProtoBuf.Builder.Enum} enm Runtime enum
10221 * @param {number} value Enum value
10222 * @returns {?string} Name or `null` if not present
10223 * @expose
10224 */
10225 Enum.getName = function(enm, value) {
10226 var keys = Object.keys(enm);
10227 for (var i=0, key; i<keys.length; ++i)
10228 if (enm[key = keys[i]] === value)
10229 return key;
10230 return null;
10231 };
10232
10233 /**
10234 * @alias ProtoBuf.Reflect.Enum.prototype
10235 * @inner
10236 */
10237 var EnumPrototype = Enum.prototype = Object.create(Namespace.prototype);
10238
10239 /**
10240 * Builds this enum and returns the runtime counterpart.
10241 * @param {boolean} rebuild Whether to rebuild or not, defaults to false
10242 * @returns {!Object.<string,number>}
10243 * @expose
10244 */
10245 EnumPrototype.build = function(rebuild) {
10246 if (this.object && !rebuild)
10247 return this.object;
10248 var enm = new ProtoBuf.Builder.Enum(),
10249 values = this.getChildren(Enum.Value);
10250 for (var i=0, k=values.length; i<k; ++i)
10251 enm[values[i]['name']] = values[i]['id'];
10252 if (Object.defineProperty)
10253 Object.defineProperty(enm, '$options', {
10254 "value": this.buildOpt(),
10255 "enumerable": false
10256 });
10257 return this.object = enm;
10258 };
10259
10260 /**
10261 * @alias ProtoBuf.Reflect.Enum
10262 * @expose
10263 */
10264 Reflect.Enum = Enum;
10265
10266 /**
10267 * Constructs a new Enum Value.
10268 * @exports ProtoBuf.Reflect.Enum.Value
10269 * @param {!ProtoBuf.Builder} builder Builder reference
10270 * @param {!ProtoBuf.Reflect.Enum} enm Enum reference
10271 * @param {string} name Field name
10272 * @param {number} id Unique field id
10273 * @constructor
10274 * @extends ProtoBuf.Reflect.T
10275 */
10276 var Value = function(builder, enm, name, id) {
10277 T.call(this, builder, enm, name);
10278
10279 /**
10280 * @override
10281 */
10282 this.className = "Enum.Value";
10283
10284 /**
10285 * Unique enum value id.
10286 * @type {number}
10287 * @expose
10288 */
10289 this.id = id;
10290 };
10291
10292 // Extends T
10293 Value.prototype = Object.create(T.prototype);
10294
10295 /**
10296 * @alias ProtoBuf.Reflect.Enum.Value
10297 * @expose
10298 */
10299 Reflect.Enum.Value = Value;
10300
10301 /**
10302 * An extension (field).
10303 * @exports ProtoBuf.Reflect.Extension
10304 * @constructor
10305 * @param {!ProtoBuf.Builder} builder Builder reference
10306 * @param {!ProtoBuf.Reflect.T} parent Parent object
10307 * @param {string} name Object name
10308 * @param {!ProtoBuf.Reflect.Message.Field} field Extension field
10309 */
10310 var Extension = function(builder, parent, name, field) {
10311 T.call(this, builder, parent, name);
10312
10313 /**
10314 * Extended message field.
10315 * @type {!ProtoBuf.Reflect.Message.Field}
10316 * @expose
10317 */
10318 this.field = field;
10319 };
10320
10321 // Extends T
10322 Extension.prototype = Object.create(T.prototype);
10323
10324 /**
10325 * @alias ProtoBuf.Reflect.Extension
10326 * @expose
10327 */
10328 Reflect.Extension = Extension;
10329
10330 /**
10331 * Constructs a new Service.
10332 * @exports ProtoBuf.Reflect.Service
10333 * @param {!ProtoBuf.Builder} builder Builder reference
10334 * @param {!ProtoBuf.Reflect.Namespace} root Root
10335 * @param {string} name Service name
10336 * @param {Object.<string,*>=} options Options
10337 * @constructor
10338 * @extends ProtoBuf.Reflect.Namespace
10339 */
10340 var Service = function(builder, root, name, options) {
10341 Namespace.call(this, builder, root, name, options);
10342
10343 /**
10344 * @override
10345 */
10346 this.className = "Service";
10347
10348 /**
10349 * Built runtime service class.
10350 * @type {?function(new:ProtoBuf.Builder.Service)}
10351 */
10352 this.clazz = null;
10353 };
10354
10355 /**
10356 * @alias ProtoBuf.Reflect.Service.prototype
10357 * @inner
10358 */
10359 var ServicePrototype = Service.prototype = Object.create(Namespace.prototype);
10360
10361 /**
10362 * Builds the service and returns the runtime counterpart, which is a fully functional class.
10363 * @see ProtoBuf.Builder.Service
10364 * @param {boolean=} rebuild Whether to rebuild or not
10365 * @return {Function} Service class
10366 * @throws {Error} If the message cannot be built
10367 * @expose
10368 */
10369 ServicePrototype.build = function(rebuild) {
10370 if (this.clazz && !rebuild)
10371 return this.clazz;
10372
10373 // Create the runtime Service class in its own scope
10374 return this.clazz = (function(ProtoBuf, T) {
10375
10376 /**
10377 * Constructs a new runtime Service.
10378 * @name ProtoBuf.Builder.Service
10379 * @param {function(string, ProtoBuf.Builder.Message, function(Error, ProtoBuf.Builder.Message=))=} rpcImpl RPC implementation receiving the method name and the message
10380 * @class Barebone of all runtime services.
10381 * @constructor
10382 * @throws {Error} If the service cannot be created
10383 */
10384 var Service = function(rpcImpl) {
10385 ProtoBuf.Builder.Service.call(this);
10386
10387 /**
10388 * Service implementation.
10389 * @name ProtoBuf.Builder.Service#rpcImpl
10390 * @type {!function(string, ProtoBuf.Builder.Message, function(Error, ProtoBuf.Builder.Message=))}
10391 * @expose
10392 */
10393 this.rpcImpl = rpcImpl || function(name, msg, callback) {
10394 // This is what a user has to implement: A function receiving the method name, the actual message to
10395 // send (type checked) and the callback that's either provided with the error as its first
10396 // argument or null and the actual response message.
10397 setTimeout(callback.bind(this, Error("Not implemented, see: https://github.com/dcodeIO/ProtoBuf.js/wiki/Services")), 0); // Must be async!
10398 };
10399 };
10400
10401 /**
10402 * @alias ProtoBuf.Builder.Service.prototype
10403 * @inner
10404 */
10405 var ServicePrototype = Service.prototype = Object.create(ProtoBuf.Builder.Service.prototype);
10406
10407 /**
10408 * Asynchronously performs an RPC call using the given RPC implementation.
10409 * @name ProtoBuf.Builder.Service.[Method]
10410 * @function
10411 * @param {!function(string, ProtoBuf.Builder.Message, function(Error, ProtoBuf.Builder.Message=))} rpcImpl RPC implementation
10412 * @param {ProtoBuf.Builder.Message} req Request
10413 * @param {function(Error, (ProtoBuf.Builder.Message|ByteBuffer|Buffer|string)=)} callback Callback receiving
10414 * the error if any and the response either as a pre-parsed message or as its raw bytes
10415 * @abstract
10416 */
10417
10418 /**
10419 * Asynchronously performs an RPC call using the instance's RPC implementation.
10420 * @name ProtoBuf.Builder.Service#[Method]
10421 * @function
10422 * @param {ProtoBuf.Builder.Message} req Request
10423 * @param {function(Error, (ProtoBuf.Builder.Message|ByteBuffer|Buffer|string)=)} callback Callback receiving
10424 * the error if any and the response either as a pre-parsed message or as its raw bytes
10425 * @abstract
10426 */
10427
10428 var rpc = T.getChildren(ProtoBuf.Reflect.Service.RPCMethod);
10429 for (var i=0; i<rpc.length; i++) {
10430 (function(method) {
10431
10432 // service#Method(message, callback)
10433 ServicePrototype[method.name] = function(req, callback) {
10434 try {
10435 try {
10436 // If given as a buffer, decode the request. Will throw a TypeError if not a valid buffer.
10437 req = method.resolvedRequestType.clazz.decode(ByteBuffer.wrap(req));
10438 } catch (err) {
10439 if (!(err instanceof TypeError))
10440 throw err;
10441 }
10442 if (req === null || typeof req !== 'object')
10443 throw Error("Illegal arguments");
10444 if (!(req instanceof method.resolvedRequestType.clazz))
10445 req = new method.resolvedRequestType.clazz(req);
10446 this.rpcImpl(method.fqn(), req, function(err, res) { // Assumes that this is properly async
10447 if (err) {
10448 callback(err);
10449 return;
10450 }
10451 // Coalesce to empty string when service response has empty content
10452 if (res === null)
10453 res = '';
10454 try { res = method.resolvedResponseType.clazz.decode(res); } catch (notABuffer) {}
10455 if (!res || !(res instanceof method.resolvedResponseType.clazz)) {
10456 callback(Error("Illegal response type received in service method "+ T.name+"#"+method.name));
10457 return;
10458 }
10459 callback(null, res);
10460 });
10461 } catch (err) {
10462 setTimeout(callback.bind(this, err), 0);
10463 }
10464 };
10465
10466 // Service.Method(rpcImpl, message, callback)
10467 Service[method.name] = function(rpcImpl, req, callback) {
10468 new Service(rpcImpl)[method.name](req, callback);
10469 };
10470
10471 if (Object.defineProperty)
10472 Object.defineProperty(Service[method.name], "$options", { "value": method.buildOpt() }),
10473 Object.defineProperty(ServicePrototype[method.name], "$options", { "value": Service[method.name]["$options"] });
10474 })(rpc[i]);
10475 }
10476
10477 if (Object.defineProperty)
10478 Object.defineProperty(Service, "$options", { "value": T.buildOpt() }),
10479 Object.defineProperty(ServicePrototype, "$options", { "value": Service["$options"] }),
10480 Object.defineProperty(Service, "$type", { "value": T }),
10481 Object.defineProperty(ServicePrototype, "$type", { "value": T });
10482
10483 return Service;
10484
10485 })(ProtoBuf, this);
10486 };
10487
10488 /**
10489 * @alias ProtoBuf.Reflect.Service
10490 * @expose
10491 */
10492 Reflect.Service = Service;
10493
10494 /**
10495 * Abstract service method.
10496 * @exports ProtoBuf.Reflect.Service.Method
10497 * @param {!ProtoBuf.Builder} builder Builder reference
10498 * @param {!ProtoBuf.Reflect.Service} svc Service
10499 * @param {string} name Method name
10500 * @param {Object.<string,*>=} options Options
10501 * @constructor
10502 * @extends ProtoBuf.Reflect.T
10503 */
10504 var Method = function(builder, svc, name, options) {
10505 T.call(this, builder, svc, name);
10506
10507 /**
10508 * @override
10509 */
10510 this.className = "Service.Method";
10511
10512 /**
10513 * Options.
10514 * @type {Object.<string, *>}
10515 * @expose
10516 */
10517 this.options = options || {};
10518 };
10519
10520 /**
10521 * @alias ProtoBuf.Reflect.Service.Method.prototype
10522 * @inner
10523 */
10524 var MethodPrototype = Method.prototype = Object.create(T.prototype);
10525
10526 /**
10527 * Builds the method's '$options' property.
10528 * @name ProtoBuf.Reflect.Service.Method#buildOpt
10529 * @function
10530 * @return {Object.<string,*>}
10531 */
10532 MethodPrototype.buildOpt = NamespacePrototype.buildOpt;
10533
10534 /**
10535 * @alias ProtoBuf.Reflect.Service.Method
10536 * @expose
10537 */
10538 Reflect.Service.Method = Method;
10539
10540 /**
10541 * RPC service method.
10542 * @exports ProtoBuf.Reflect.Service.RPCMethod
10543 * @param {!ProtoBuf.Builder} builder Builder reference
10544 * @param {!ProtoBuf.Reflect.Service} svc Service
10545 * @param {string} name Method name
10546 * @param {string} request Request message name
10547 * @param {string} response Response message name
10548 * @param {boolean} request_stream Whether requests are streamed
10549 * @param {boolean} response_stream Whether responses are streamed
10550 * @param {Object.<string,*>=} options Options
10551 * @constructor
10552 * @extends ProtoBuf.Reflect.Service.Method
10553 */
10554 var RPCMethod = function(builder, svc, name, request, response, request_stream, response_stream, options) {
10555 Method.call(this, builder, svc, name, options);
10556
10557 /**
10558 * @override
10559 */
10560 this.className = "Service.RPCMethod";
10561
10562 /**
10563 * Request message name.
10564 * @type {string}
10565 * @expose
10566 */
10567 this.requestName = request;
10568
10569 /**
10570 * Response message name.
10571 * @type {string}
10572 * @expose
10573 */
10574 this.responseName = response;
10575
10576 /**
10577 * Whether requests are streamed
10578 * @type {bool}
10579 * @expose
10580 */
10581 this.requestStream = request_stream;
10582
10583 /**
10584 * Whether responses are streamed
10585 * @type {bool}
10586 * @expose
10587 */
10588 this.responseStream = response_stream;
10589
10590 /**
10591 * Resolved request message type.
10592 * @type {ProtoBuf.Reflect.Message}
10593 * @expose
10594 */
10595 this.resolvedRequestType = null;
10596
10597 /**
10598 * Resolved response message type.
10599 * @type {ProtoBuf.Reflect.Message}
10600 * @expose
10601 */
10602 this.resolvedResponseType = null;
10603 };
10604
10605 // Extends Method
10606 RPCMethod.prototype = Object.create(Method.prototype);
10607
10608 /**
10609 * @alias ProtoBuf.Reflect.Service.RPCMethod
10610 * @expose
10611 */
10612 Reflect.Service.RPCMethod = RPCMethod;
10613
10614 return Reflect;
10615
10616 })(ProtoBuf);
10617
10618 /**
10619 * @alias ProtoBuf.Builder
10620 * @expose
10621 */
10622 ProtoBuf.Builder = (function(ProtoBuf, Lang, Reflect) {
10623
10624 /**
10625 * Constructs a new Builder.
10626 * @exports ProtoBuf.Builder
10627 * @class Provides the functionality to build protocol messages.
10628 * @param {Object.<string,*>=} options Options
10629 * @constructor
10630 */
10631 var Builder = function(options) {
10632
10633 /**
10634 * Namespace.
10635 * @type {ProtoBuf.Reflect.Namespace}
10636 * @expose
10637 */
10638 this.ns = new Reflect.Namespace(this, null, ""); // Global namespace
10639
10640 /**
10641 * Namespace pointer.
10642 * @type {ProtoBuf.Reflect.T}
10643 * @expose
10644 */
10645 this.ptr = this.ns;
10646
10647 /**
10648 * Resolved flag.
10649 * @type {boolean}
10650 * @expose
10651 */
10652 this.resolved = false;
10653
10654 /**
10655 * The current building result.
10656 * @type {Object.<string,ProtoBuf.Builder.Message|Object>|null}
10657 * @expose
10658 */
10659 this.result = null;
10660
10661 /**
10662 * Imported files.
10663 * @type {Array.<string>}
10664 * @expose
10665 */
10666 this.files = {};
10667
10668 /**
10669 * Import root override.
10670 * @type {?string}
10671 * @expose
10672 */
10673 this.importRoot = null;
10674
10675 /**
10676 * Options.
10677 * @type {!Object.<string, *>}
10678 * @expose
10679 */
10680 this.options = options || {};
10681 };
10682
10683 /**
10684 * @alias ProtoBuf.Builder.prototype
10685 * @inner
10686 */
10687 var BuilderPrototype = Builder.prototype;
10688
10689 // ----- Definition tests -----
10690
10691 /**
10692 * Tests if a definition most likely describes a message.
10693 * @param {!Object} def
10694 * @returns {boolean}
10695 * @expose
10696 */
10697 Builder.isMessage = function(def) {
10698 // Messages require a string name
10699 if (typeof def["name"] !== 'string')
10700 return false;
10701 // Messages do not contain values (enum) or rpc methods (service)
10702 if (typeof def["values"] !== 'undefined' || typeof def["rpc"] !== 'undefined')
10703 return false;
10704 return true;
10705 };
10706
10707 /**
10708 * Tests if a definition most likely describes a message field.
10709 * @param {!Object} def
10710 * @returns {boolean}
10711 * @expose
10712 */
10713 Builder.isMessageField = function(def) {
10714 // Message fields require a string rule, name and type and an id
10715 if (typeof def["rule"] !== 'string' || typeof def["name"] !== 'string' || typeof def["type"] !== 'string' || typeof def["id"] === 'undefined')
10716 return false;
10717 return true;
10718 };
10719
10720 /**
10721 * Tests if a definition most likely describes an enum.
10722 * @param {!Object} def
10723 * @returns {boolean}
10724 * @expose
10725 */
10726 Builder.isEnum = function(def) {
10727 // Enums require a string name
10728 if (typeof def["name"] !== 'string')
10729 return false;
10730 // Enums require at least one value
10731 if (typeof def["values"] === 'undefined' || !Array.isArray(def["values"]) || def["values"].length === 0)
10732 return false;
10733 return true;
10734 };
10735
10736 /**
10737 * Tests if a definition most likely describes a service.
10738 * @param {!Object} def
10739 * @returns {boolean}
10740 * @expose
10741 */
10742 Builder.isService = function(def) {
10743 // Services require a string name and an rpc object
10744 if (typeof def["name"] !== 'string' || typeof def["rpc"] !== 'object' || !def["rpc"])
10745 return false;
10746 return true;
10747 };
10748
10749 /**
10750 * Tests if a definition most likely describes an extended message
10751 * @param {!Object} def
10752 * @returns {boolean}
10753 * @expose
10754 */
10755 Builder.isExtend = function(def) {
10756 // Extends rquire a string ref
10757 if (typeof def["ref"] !== 'string')
10758 return false;
10759 return true;
10760 };
10761
10762 // ----- Building -----
10763
10764 /**
10765 * Resets the pointer to the root namespace.
10766 * @returns {!ProtoBuf.Builder} this
10767 * @expose
10768 */
10769 BuilderPrototype.reset = function() {
10770 this.ptr = this.ns;
10771 return this;
10772 };
10773
10774 /**
10775 * Defines a namespace on top of the current pointer position and places the pointer on it.
10776 * @param {string} namespace
10777 * @return {!ProtoBuf.Builder} this
10778 * @expose
10779 */
10780 BuilderPrototype.define = function(namespace) {
10781 if (typeof namespace !== 'string' || !Lang.TYPEREF.test(namespace))
10782 throw Error("illegal namespace: "+namespace);
10783 namespace.split(".").forEach(function(part) {
10784 var ns = this.ptr.getChild(part);
10785 if (ns === null) // Keep existing
10786 this.ptr.addChild(ns = new Reflect.Namespace(this, this.ptr, part));
10787 this.ptr = ns;
10788 }, this);
10789 return this;
10790 };
10791
10792 /**
10793 * Creates the specified definitions at the current pointer position.
10794 * @param {!Array.<!Object>} defs Messages, enums or services to create
10795 * @returns {!ProtoBuf.Builder} this
10796 * @throws {Error} If a message definition is invalid
10797 * @expose
10798 */
10799 BuilderPrototype.create = function(defs) {
10800 if (!defs)
10801 return this; // Nothing to create
10802 if (!Array.isArray(defs))
10803 defs = [defs];
10804 else {
10805 if (defs.length === 0)
10806 return this;
10807 defs = defs.slice();
10808 }
10809
10810 // It's quite hard to keep track of scopes and memory here, so let's do this iteratively.
10811 var stack = [defs];
10812 while (stack.length > 0) {
10813 defs = stack.pop();
10814
10815 if (!Array.isArray(defs)) // Stack always contains entire namespaces
10816 throw Error("not a valid namespace: "+JSON.stringify(defs));
10817
10818 while (defs.length > 0) {
10819 var def = defs.shift(); // Namespaces always contain an array of messages, enums and services
10820
10821 if (Builder.isMessage(def)) {
10822 var obj = new Reflect.Message(this, this.ptr, def["name"], def["options"], def["isGroup"], def["syntax"]);
10823
10824 // Create OneOfs
10825 var oneofs = {};
10826 if (def["oneofs"])
10827 Object.keys(def["oneofs"]).forEach(function(name) {
10828 obj.addChild(oneofs[name] = new Reflect.Message.OneOf(this, obj, name));
10829 }, this);
10830
10831 // Create fields
10832 if (def["fields"])
10833 def["fields"].forEach(function(fld) {
10834 if (obj.getChild(fld["id"]|0) !== null)
10835 throw Error("duplicate or invalid field id in "+obj.name+": "+fld['id']);
10836 if (fld["options"] && typeof fld["options"] !== 'object')
10837 throw Error("illegal field options in "+obj.name+"#"+fld["name"]);
10838 var oneof = null;
10839 if (typeof fld["oneof"] === 'string' && !(oneof = oneofs[fld["oneof"]]))
10840 throw Error("illegal oneof in "+obj.name+"#"+fld["name"]+": "+fld["oneof"]);
10841 fld = new Reflect.Message.Field(this, obj, fld["rule"], fld["keytype"], fld["type"], fld["name"], fld["id"], fld["options"], oneof, def["syntax"]);
10842 if (oneof)
10843 oneof.fields.push(fld);
10844 obj.addChild(fld);
10845 }, this);
10846
10847 // Push children to stack
10848 var subObj = [];
10849 if (def["enums"])
10850 def["enums"].forEach(function(enm) {
10851 subObj.push(enm);
10852 });
10853 if (def["messages"])
10854 def["messages"].forEach(function(msg) {
10855 subObj.push(msg);
10856 });
10857 if (def["services"])
10858 def["services"].forEach(function(svc) {
10859 subObj.push(svc);
10860 });
10861
10862 // Set extension ranges
10863 if (def["extensions"]) {
10864 if (typeof def["extensions"][0] === 'number') // pre 5.0.1
10865 obj.extensions = [ def["extensions"] ];
10866 else
10867 obj.extensions = def["extensions"];
10868 }
10869
10870 // Create on top of current namespace
10871 this.ptr.addChild(obj);
10872 if (subObj.length > 0) {
10873 stack.push(defs); // Push the current level back
10874 defs = subObj; // Continue processing sub level
10875 subObj = null;
10876 this.ptr = obj; // And move the pointer to this namespace
10877 obj = null;
10878 continue;
10879 }
10880 subObj = null;
10881
10882 } else if (Builder.isEnum(def)) {
10883
10884 obj = new Reflect.Enum(this, this.ptr, def["name"], def["options"], def["syntax"]);
10885 def["values"].forEach(function(val) {
10886 obj.addChild(new Reflect.Enum.Value(this, obj, val["name"], val["id"]));
10887 }, this);
10888 this.ptr.addChild(obj);
10889
10890 } else if (Builder.isService(def)) {
10891
10892 obj = new Reflect.Service(this, this.ptr, def["name"], def["options"]);
10893 Object.keys(def["rpc"]).forEach(function(name) {
10894 var mtd = def["rpc"][name];
10895 obj.addChild(new Reflect.Service.RPCMethod(this, obj, name, mtd["request"], mtd["response"], !!mtd["request_stream"], !!mtd["response_stream"], mtd["options"]));
10896 }, this);
10897 this.ptr.addChild(obj);
10898
10899 } else if (Builder.isExtend(def)) {
10900
10901 obj = this.ptr.resolve(def["ref"], true);
10902 if (obj) {
10903 def["fields"].forEach(function(fld) {
10904 if (obj.getChild(fld['id']|0) !== null)
10905 throw Error("duplicate extended field id in "+obj.name+": "+fld['id']);
10906 // Check if field id is allowed to be extended
10907 if (obj.extensions) {
10908 var valid = false;
10909 obj.extensions.forEach(function(range) {
10910 if (fld["id"] >= range[0] && fld["id"] <= range[1])
10911 valid = true;
10912 });
10913 if (!valid)
10914 throw Error("illegal extended field id in "+obj.name+": "+fld['id']+" (not within valid ranges)");
10915 }
10916 // Convert extension field names to camel case notation if the override is set
10917 var name = fld["name"];
10918 if (this.options['convertFieldsToCamelCase'])
10919 name = ProtoBuf.Util.toCamelCase(name);
10920 // see #161: Extensions use their fully qualified name as their runtime key and...
10921 var field = new Reflect.Message.ExtensionField(this, obj, fld["rule"], fld["type"], this.ptr.fqn()+'.'+name, fld["id"], fld["options"]);
10922 // ...are added on top of the current namespace as an extension which is used for
10923 // resolving their type later on (the extension always keeps the original name to
10924 // prevent naming collisions)
10925 var ext = new Reflect.Extension(this, this.ptr, fld["name"], field);
10926 field.extension = ext;
10927 this.ptr.addChild(ext);
10928 obj.addChild(field);
10929 }, this);
10930
10931 } else if (!/\.?google\.protobuf\./.test(def["ref"])) // Silently skip internal extensions
10932 throw Error("extended message "+def["ref"]+" is not defined");
10933
10934 } else
10935 throw Error("not a valid definition: "+JSON.stringify(def));
10936
10937 def = null;
10938 obj = null;
10939 }
10940 // Break goes here
10941 defs = null;
10942 this.ptr = this.ptr.parent; // Namespace done, continue at parent
10943 }
10944 this.resolved = false; // Require re-resolve
10945 this.result = null; // Require re-build
10946 return this;
10947 };
10948
10949 /**
10950 * Propagates syntax to all children.
10951 * @param {!Object} parent
10952 * @inner
10953 */
10954 function propagateSyntax(parent) {
10955 if (parent['messages']) {
10956 parent['messages'].forEach(function(child) {
10957 child["syntax"] = parent["syntax"];
10958 propagateSyntax(child);
10959 });
10960 }
10961 if (parent['enums']) {
10962 parent['enums'].forEach(function(child) {
10963 child["syntax"] = parent["syntax"];
10964 });
10965 }
10966 }
10967
10968 /**
10969 * Imports another definition into this builder.
10970 * @param {Object.<string,*>} json Parsed import
10971 * @param {(string|{root: string, file: string})=} filename Imported file name
10972 * @returns {!ProtoBuf.Builder} this
10973 * @throws {Error} If the definition or file cannot be imported
10974 * @expose
10975 */
10976 BuilderPrototype["import"] = function(json, filename) {
10977 var delim = '/';
10978
10979 // Make sure to skip duplicate imports
10980
10981 if (typeof filename === 'string') {
10982
10983 if (ProtoBuf.Util.IS_NODE)
10984 filename = require$$2['resolve'](filename);
10985 if (this.files[filename] === true)
10986 return this.reset();
10987 this.files[filename] = true;
10988
10989 } else if (typeof filename === 'object') { // Object with root, file.
10990
10991 var root = filename.root;
10992 if (ProtoBuf.Util.IS_NODE)
10993 root = require$$2['resolve'](root);
10994 if (root.indexOf("\\") >= 0 || filename.file.indexOf("\\") >= 0)
10995 delim = '\\';
10996 var fname;
10997 if (ProtoBuf.Util.IS_NODE)
10998 fname = require$$2['join'](root, filename.file);
10999 else
11000 fname = root + delim + filename.file;
11001 if (this.files[fname] === true)
11002 return this.reset();
11003 this.files[fname] = true;
11004 }
11005
11006 // Import imports
11007
11008 if (json['imports'] && json['imports'].length > 0) {
11009 var importRoot,
11010 resetRoot = false;
11011
11012 if (typeof filename === 'object') { // If an import root is specified, override
11013
11014 this.importRoot = filename["root"]; resetRoot = true; // ... and reset afterwards
11015 importRoot = this.importRoot;
11016 filename = filename["file"];
11017 if (importRoot.indexOf("\\") >= 0 || filename.indexOf("\\") >= 0)
11018 delim = '\\';
11019
11020 } else if (typeof filename === 'string') {
11021
11022 if (this.importRoot) // If import root is overridden, use it
11023 importRoot = this.importRoot;
11024 else { // Otherwise compute from filename
11025 if (filename.indexOf("/") >= 0) { // Unix
11026 importRoot = filename.replace(/\/[^\/]*$/, "");
11027 if (/* /file.proto */ importRoot === "")
11028 importRoot = "/";
11029 } else if (filename.indexOf("\\") >= 0) { // Windows
11030 importRoot = filename.replace(/\\[^\\]*$/, "");
11031 delim = '\\';
11032 } else
11033 importRoot = ".";
11034 }
11035
11036 } else
11037 importRoot = null;
11038
11039 for (var i=0; i<json['imports'].length; i++) {
11040 if (typeof json['imports'][i] === 'string') { // Import file
11041 if (!importRoot)
11042 throw Error("cannot determine import root");
11043 var importFilename = json['imports'][i];
11044 if (importFilename === "google/protobuf/descriptor.proto")
11045 continue; // Not needed and therefore not used
11046 if (ProtoBuf.Util.IS_NODE)
11047 importFilename = require$$2['join'](importRoot, importFilename);
11048 else
11049 importFilename = importRoot + delim + importFilename;
11050 if (this.files[importFilename] === true)
11051 continue; // Already imported
11052 if (/\.proto$/i.test(importFilename) && !ProtoBuf.DotProto) // If this is a light build
11053 importFilename = importFilename.replace(/\.proto$/, ".json"); // always load the JSON file
11054 var contents = ProtoBuf.Util.fetch(importFilename);
11055 if (contents === null)
11056 throw Error("failed to import '"+importFilename+"' in '"+filename+"': file not found");
11057 if (/\.json$/i.test(importFilename)) // Always possible
11058 this["import"](JSON.parse(contents+""), importFilename); // May throw
11059 else
11060 this["import"](ProtoBuf.DotProto.Parser.parse(contents), importFilename); // May throw
11061 } else // Import structure
11062 if (!filename)
11063 this["import"](json['imports'][i]);
11064 else if (/\.(\w+)$/.test(filename)) // With extension: Append _importN to the name portion to make it unique
11065 this["import"](json['imports'][i], filename.replace(/^(.+)\.(\w+)$/, function($0, $1, $2) { return $1+"_import"+i+"."+$2; }));
11066 else // Without extension: Append _importN to make it unique
11067 this["import"](json['imports'][i], filename+"_import"+i);
11068 }
11069 if (resetRoot) // Reset import root override when all imports are done
11070 this.importRoot = null;
11071 }
11072
11073 // Import structures
11074
11075 if (json['package'])
11076 this.define(json['package']);
11077 if (json['syntax'])
11078 propagateSyntax(json);
11079 var base = this.ptr;
11080 if (json['options'])
11081 Object.keys(json['options']).forEach(function(key) {
11082 base.options[key] = json['options'][key];
11083 });
11084 if (json['messages'])
11085 this.create(json['messages']),
11086 this.ptr = base;
11087 if (json['enums'])
11088 this.create(json['enums']),
11089 this.ptr = base;
11090 if (json['services'])
11091 this.create(json['services']),
11092 this.ptr = base;
11093 if (json['extends'])
11094 this.create(json['extends']);
11095
11096 return this.reset();
11097 };
11098
11099 /**
11100 * Resolves all namespace objects.
11101 * @throws {Error} If a type cannot be resolved
11102 * @returns {!ProtoBuf.Builder} this
11103 * @expose
11104 */
11105 BuilderPrototype.resolveAll = function() {
11106 // Resolve all reflected objects
11107 var res;
11108 if (this.ptr == null || typeof this.ptr.type === 'object')
11109 return this; // Done (already resolved)
11110
11111 if (this.ptr instanceof Reflect.Namespace) { // Resolve children
11112
11113 this.ptr.children.forEach(function(child) {
11114 this.ptr = child;
11115 this.resolveAll();
11116 }, this);
11117
11118 } else if (this.ptr instanceof Reflect.Message.Field) { // Resolve type
11119
11120 if (!Lang.TYPE.test(this.ptr.type)) {
11121 if (!Lang.TYPEREF.test(this.ptr.type))
11122 throw Error("illegal type reference in "+this.ptr.toString(true)+": "+this.ptr.type);
11123 res = (this.ptr instanceof Reflect.Message.ExtensionField ? this.ptr.extension.parent : this.ptr.parent).resolve(this.ptr.type, true);
11124 if (!res)
11125 throw Error("unresolvable type reference in "+this.ptr.toString(true)+": "+this.ptr.type);
11126 this.ptr.resolvedType = res;
11127 if (res instanceof Reflect.Enum) {
11128 this.ptr.type = ProtoBuf.TYPES["enum"];
11129 if (this.ptr.syntax === 'proto3' && res.syntax !== 'proto3')
11130 throw Error("proto3 message cannot reference proto2 enum");
11131 }
11132 else if (res instanceof Reflect.Message)
11133 this.ptr.type = res.isGroup ? ProtoBuf.TYPES["group"] : ProtoBuf.TYPES["message"];
11134 else
11135 throw Error("illegal type reference in "+this.ptr.toString(true)+": "+this.ptr.type);
11136 } else
11137 this.ptr.type = ProtoBuf.TYPES[this.ptr.type];
11138
11139 // If it's a map field, also resolve the key type. The key type can be only a numeric, string, or bool type
11140 // (i.e., no enums or messages), so we don't need to resolve against the current namespace.
11141 if (this.ptr.map) {
11142 if (!Lang.TYPE.test(this.ptr.keyType))
11143 throw Error("illegal key type for map field in "+this.ptr.toString(true)+": "+this.ptr.keyType);
11144 this.ptr.keyType = ProtoBuf.TYPES[this.ptr.keyType];
11145 }
11146
11147 // If it's a repeated and packable field then proto3 mandates it should be packed by
11148 // default
11149 if (
11150 this.ptr.syntax === 'proto3' &&
11151 this.ptr.repeated && this.ptr.options.packed === undefined &&
11152 ProtoBuf.PACKABLE_WIRE_TYPES.indexOf(this.ptr.type.wireType) !== -1
11153 ) {
11154 this.ptr.options.packed = true;
11155 }
11156
11157 } else if (this.ptr instanceof ProtoBuf.Reflect.Service.Method) {
11158
11159 if (this.ptr instanceof ProtoBuf.Reflect.Service.RPCMethod) {
11160 res = this.ptr.parent.resolve(this.ptr.requestName, true);
11161 if (!res || !(res instanceof ProtoBuf.Reflect.Message))
11162 throw Error("Illegal type reference in "+this.ptr.toString(true)+": "+this.ptr.requestName);
11163 this.ptr.resolvedRequestType = res;
11164 res = this.ptr.parent.resolve(this.ptr.responseName, true);
11165 if (!res || !(res instanceof ProtoBuf.Reflect.Message))
11166 throw Error("Illegal type reference in "+this.ptr.toString(true)+": "+this.ptr.responseName);
11167 this.ptr.resolvedResponseType = res;
11168 } else // Should not happen as nothing else is implemented
11169 throw Error("illegal service type in "+this.ptr.toString(true));
11170
11171 } else if (
11172 !(this.ptr instanceof ProtoBuf.Reflect.Message.OneOf) && // Not built
11173 !(this.ptr instanceof ProtoBuf.Reflect.Extension) && // Not built
11174 !(this.ptr instanceof ProtoBuf.Reflect.Enum.Value) // Built in enum
11175 )
11176 throw Error("illegal object in namespace: "+typeof(this.ptr)+": "+this.ptr);
11177
11178 return this.reset();
11179 };
11180
11181 /**
11182 * Builds the protocol. This will first try to resolve all definitions and, if this has been successful,
11183 * return the built package.
11184 * @param {(string|Array.<string>)=} path Specifies what to return. If omitted, the entire namespace will be returned.
11185 * @returns {!ProtoBuf.Builder.Message|!Object.<string,*>}
11186 * @throws {Error} If a type could not be resolved
11187 * @expose
11188 */
11189 BuilderPrototype.build = function(path) {
11190 this.reset();
11191 if (!this.resolved)
11192 this.resolveAll(),
11193 this.resolved = true,
11194 this.result = null; // Require re-build
11195 if (this.result === null) // (Re-)Build
11196 this.result = this.ns.build();
11197 if (!path)
11198 return this.result;
11199 var part = typeof path === 'string' ? path.split(".") : path,
11200 ptr = this.result; // Build namespace pointer (no hasChild etc.)
11201 for (var i=0; i<part.length; i++)
11202 if (ptr[part[i]])
11203 ptr = ptr[part[i]];
11204 else {
11205 ptr = null;
11206 break;
11207 }
11208 return ptr;
11209 };
11210
11211 /**
11212 * Similar to {@link ProtoBuf.Builder#build}, but looks up the internal reflection descriptor.
11213 * @param {string=} path Specifies what to return. If omitted, the entire namespace wiil be returned.
11214 * @param {boolean=} excludeNonNamespace Excludes non-namespace types like fields, defaults to `false`
11215 * @returns {?ProtoBuf.Reflect.T} Reflection descriptor or `null` if not found
11216 */
11217 BuilderPrototype.lookup = function(path, excludeNonNamespace) {
11218 return path ? this.ns.resolve(path, excludeNonNamespace) : this.ns;
11219 };
11220
11221 /**
11222 * Returns a string representation of this object.
11223 * @return {string} String representation as of "Builder"
11224 * @expose
11225 */
11226 BuilderPrototype.toString = function() {
11227 return "Builder";
11228 };
11229
11230 // ----- Base classes -----
11231 // Exist for the sole purpose of being able to "... instanceof ProtoBuf.Builder.Message" etc.
11232
11233 /**
11234 * @alias ProtoBuf.Builder.Message
11235 */
11236 Builder.Message = function() {};
11237
11238 /**
11239 * @alias ProtoBuf.Builder.Enum
11240 */
11241 Builder.Enum = function() {};
11242
11243 /**
11244 * @alias ProtoBuf.Builder.Message
11245 */
11246 Builder.Service = function() {};
11247
11248 return Builder;
11249
11250 })(ProtoBuf, ProtoBuf.Lang, ProtoBuf.Reflect);
11251
11252 /**
11253 * @alias ProtoBuf.Map
11254 * @expose
11255 */
11256 ProtoBuf.Map = (function(ProtoBuf, Reflect) {
11257
11258 /**
11259 * Constructs a new Map. A Map is a container that is used to implement map
11260 * fields on message objects. It closely follows the ES6 Map API; however,
11261 * it is distinct because we do not want to depend on external polyfills or
11262 * on ES6 itself.
11263 *
11264 * @exports ProtoBuf.Map
11265 * @param {!ProtoBuf.Reflect.Field} field Map field
11266 * @param {Object.<string,*>=} contents Initial contents
11267 * @constructor
11268 */
11269 var Map = function(field, contents) {
11270 if (!field.map)
11271 throw Error("field is not a map");
11272
11273 /**
11274 * The field corresponding to this map.
11275 * @type {!ProtoBuf.Reflect.Field}
11276 */
11277 this.field = field;
11278
11279 /**
11280 * Element instance corresponding to key type.
11281 * @type {!ProtoBuf.Reflect.Element}
11282 */
11283 this.keyElem = new Reflect.Element(field.keyType, null, true, field.syntax);
11284
11285 /**
11286 * Element instance corresponding to value type.
11287 * @type {!ProtoBuf.Reflect.Element}
11288 */
11289 this.valueElem = new Reflect.Element(field.type, field.resolvedType, false, field.syntax);
11290
11291 /**
11292 * Internal map: stores mapping of (string form of key) -> (key, value)
11293 * pair.
11294 *
11295 * We provide map semantics for arbitrary key types, but we build on top
11296 * of an Object, which has only string keys. In order to avoid the need
11297 * to convert a string key back to its native type in many situations,
11298 * we store the native key value alongside the value. Thus, we only need
11299 * a one-way mapping from a key type to its string form that guarantees
11300 * uniqueness and equality (i.e., str(K1) === str(K2) if and only if K1
11301 * === K2).
11302 *
11303 * @type {!Object<string, {key: *, value: *}>}
11304 */
11305 this.map = {};
11306
11307 /**
11308 * Returns the number of elements in the map.
11309 */
11310 Object.defineProperty(this, "size", {
11311 get: function() { return Object.keys(this.map).length; }
11312 });
11313
11314 // Fill initial contents from a raw object.
11315 if (contents) {
11316 var keys = Object.keys(contents);
11317 for (var i = 0; i < keys.length; i++) {
11318 var key = this.keyElem.valueFromString(keys[i]);
11319 var val = this.valueElem.verifyValue(contents[keys[i]]);
11320 this.map[this.keyElem.valueToString(key)] =
11321 { key: key, value: val };
11322 }
11323 }
11324 };
11325
11326 var MapPrototype = Map.prototype;
11327
11328 /**
11329 * Helper: return an iterator over an array.
11330 * @param {!Array<*>} arr the array
11331 * @returns {!Object} an iterator
11332 * @inner
11333 */
11334 function arrayIterator(arr) {
11335 var idx = 0;
11336 return {
11337 next: function() {
11338 if (idx < arr.length)
11339 return { done: false, value: arr[idx++] };
11340 return { done: true };
11341 }
11342 }
11343 }
11344
11345 /**
11346 * Clears the map.
11347 */
11348 MapPrototype.clear = function() {
11349 this.map = {};
11350 };
11351
11352 /**
11353 * Deletes a particular key from the map.
11354 * @returns {boolean} Whether any entry with this key was deleted.
11355 */
11356 MapPrototype["delete"] = function(key) {
11357 var keyValue = this.keyElem.valueToString(this.keyElem.verifyValue(key));
11358 var hadKey = keyValue in this.map;
11359 delete this.map[keyValue];
11360 return hadKey;
11361 };
11362
11363 /**
11364 * Returns an iterator over [key, value] pairs in the map.
11365 * @returns {Object} The iterator
11366 */
11367 MapPrototype.entries = function() {
11368 var entries = [];
11369 var strKeys = Object.keys(this.map);
11370 for (var i = 0, entry; i < strKeys.length; i++)
11371 entries.push([(entry=this.map[strKeys[i]]).key, entry.value]);
11372 return arrayIterator(entries);
11373 };
11374
11375 /**
11376 * Returns an iterator over keys in the map.
11377 * @returns {Object} The iterator
11378 */
11379 MapPrototype.keys = function() {
11380 var keys = [];
11381 var strKeys = Object.keys(this.map);
11382 for (var i = 0; i < strKeys.length; i++)
11383 keys.push(this.map[strKeys[i]].key);
11384 return arrayIterator(keys);
11385 };
11386
11387 /**
11388 * Returns an iterator over values in the map.
11389 * @returns {!Object} The iterator
11390 */
11391 MapPrototype.values = function() {
11392 var values = [];
11393 var strKeys = Object.keys(this.map);
11394 for (var i = 0; i < strKeys.length; i++)
11395 values.push(this.map[strKeys[i]].value);
11396 return arrayIterator(values);
11397 };
11398
11399 /**
11400 * Iterates over entries in the map, calling a function on each.
11401 * @param {function(this:*, *, *, *)} cb The callback to invoke with value, key, and map arguments.
11402 * @param {Object=} thisArg The `this` value for the callback
11403 */
11404 MapPrototype.forEach = function(cb, thisArg) {
11405 var strKeys = Object.keys(this.map);
11406 for (var i = 0, entry; i < strKeys.length; i++)
11407 cb.call(thisArg, (entry=this.map[strKeys[i]]).value, entry.key, this);
11408 };
11409
11410 /**
11411 * Sets a key in the map to the given value.
11412 * @param {*} key The key
11413 * @param {*} value The value
11414 * @returns {!ProtoBuf.Map} The map instance
11415 */
11416 MapPrototype.set = function(key, value) {
11417 var keyValue = this.keyElem.verifyValue(key);
11418 var valValue = this.valueElem.verifyValue(value);
11419 this.map[this.keyElem.valueToString(keyValue)] =
11420 { key: keyValue, value: valValue };
11421 return this;
11422 };
11423
11424 /**
11425 * Gets the value corresponding to a key in the map.
11426 * @param {*} key The key
11427 * @returns {*|undefined} The value, or `undefined` if key not present
11428 */
11429 MapPrototype.get = function(key) {
11430 var keyValue = this.keyElem.valueToString(this.keyElem.verifyValue(key));
11431 if (!(keyValue in this.map))
11432 return undefined;
11433 return this.map[keyValue].value;
11434 };
11435
11436 /**
11437 * Determines whether the given key is present in the map.
11438 * @param {*} key The key
11439 * @returns {boolean} `true` if the key is present
11440 */
11441 MapPrototype.has = function(key) {
11442 var keyValue = this.keyElem.valueToString(this.keyElem.verifyValue(key));
11443 return (keyValue in this.map);
11444 };
11445
11446 return Map;
11447 })(ProtoBuf, ProtoBuf.Reflect);
11448
11449
11450 /**
11451 * Constructs a new empty Builder.
11452 * @param {Object.<string,*>=} options Builder options, defaults to global options set on ProtoBuf
11453 * @return {!ProtoBuf.Builder} Builder
11454 * @expose
11455 */
11456 ProtoBuf.newBuilder = function(options) {
11457 options = options || {};
11458 if (typeof options['convertFieldsToCamelCase'] === 'undefined')
11459 options['convertFieldsToCamelCase'] = ProtoBuf.convertFieldsToCamelCase;
11460 if (typeof options['populateAccessors'] === 'undefined')
11461 options['populateAccessors'] = ProtoBuf.populateAccessors;
11462 return new ProtoBuf.Builder(options);
11463 };
11464
11465 /**
11466 * Loads a .json definition and returns the Builder.
11467 * @param {!*|string} json JSON definition
11468 * @param {(ProtoBuf.Builder|string|{root: string, file: string})=} builder Builder to append to. Will create a new one if omitted.
11469 * @param {(string|{root: string, file: string})=} filename The corresponding file name if known. Must be specified for imports.
11470 * @return {ProtoBuf.Builder} Builder to create new messages
11471 * @throws {Error} If the definition cannot be parsed or built
11472 * @expose
11473 */
11474 ProtoBuf.loadJson = function(json, builder, filename) {
11475 if (typeof builder === 'string' || (builder && typeof builder["file"] === 'string' && typeof builder["root"] === 'string'))
11476 filename = builder,
11477 builder = null;
11478 if (!builder || typeof builder !== 'object')
11479 builder = ProtoBuf.newBuilder();
11480 if (typeof json === 'string')
11481 json = JSON.parse(json);
11482 builder["import"](json, filename);
11483 builder.resolveAll();
11484 return builder;
11485 };
11486
11487 /**
11488 * Loads a .json file and returns the Builder.
11489 * @param {string|!{root: string, file: string}} filename Path to json file or an object specifying 'file' with
11490 * an overridden 'root' path for all imported files.
11491 * @param {function(?Error, !ProtoBuf.Builder=)=} callback Callback that will receive `null` as the first and
11492 * the Builder as its second argument on success, otherwise the error as its first argument. If omitted, the
11493 * file will be read synchronously and this function will return the Builder.
11494 * @param {ProtoBuf.Builder=} builder Builder to append to. Will create a new one if omitted.
11495 * @return {?ProtoBuf.Builder|undefined} The Builder if synchronous (no callback specified, will be NULL if the
11496 * request has failed), else undefined
11497 * @expose
11498 */
11499 ProtoBuf.loadJsonFile = function(filename, callback, builder) {
11500 if (callback && typeof callback === 'object')
11501 builder = callback,
11502 callback = null;
11503 else if (!callback || typeof callback !== 'function')
11504 callback = null;
11505 if (callback)
11506 return ProtoBuf.Util.fetch(typeof filename === 'string' ? filename : filename["root"]+"/"+filename["file"], function(contents) {
11507 if (contents === null) {
11508 callback(Error("Failed to fetch file"));
11509 return;
11510 }
11511 try {
11512 callback(null, ProtoBuf.loadJson(JSON.parse(contents), builder, filename));
11513 } catch (e) {
11514 callback(e);
11515 }
11516 });
11517 var contents = ProtoBuf.Util.fetch(typeof filename === 'object' ? filename["root"]+"/"+filename["file"] : filename);
11518 return contents === null ? null : ProtoBuf.loadJson(JSON.parse(contents), builder, filename);
11519 };
11520
11521 return ProtoBuf;
11522 });
11523 });
11524
11525 var messageCompiled = protobufLight.newBuilder({})['import']({
11526 "package": 'push_server.messages2',
11527 syntax: 'proto2',
11528 options: {
11529 objc_class_prefix: 'AVIM'
11530 },
11531 messages: [{
11532 name: 'JsonObjectMessage',
11533 syntax: 'proto2',
11534 fields: [{
11535 rule: 'required',
11536 type: 'string',
11537 name: 'data',
11538 id: 1
11539 }]
11540 }, {
11541 name: 'UnreadTuple',
11542 syntax: 'proto2',
11543 fields: [{
11544 rule: 'required',
11545 type: 'string',
11546 name: 'cid',
11547 id: 1
11548 }, {
11549 rule: 'required',
11550 type: 'int32',
11551 name: 'unread',
11552 id: 2
11553 }, {
11554 rule: 'optional',
11555 type: 'string',
11556 name: 'mid',
11557 id: 3
11558 }, {
11559 rule: 'optional',
11560 type: 'int64',
11561 name: 'timestamp',
11562 id: 4
11563 }, {
11564 rule: 'optional',
11565 type: 'string',
11566 name: 'from',
11567 id: 5
11568 }, {
11569 rule: 'optional',
11570 type: 'string',
11571 name: 'data',
11572 id: 6
11573 }, {
11574 rule: 'optional',
11575 type: 'int64',
11576 name: 'patchTimestamp',
11577 id: 7
11578 }, {
11579 rule: 'optional',
11580 type: 'bool',
11581 name: 'mentioned',
11582 id: 8
11583 }, {
11584 rule: 'optional',
11585 type: 'bytes',
11586 name: 'binaryMsg',
11587 id: 9
11588 }, {
11589 rule: 'optional',
11590 type: 'int32',
11591 name: 'convType',
11592 id: 10
11593 }]
11594 }, {
11595 name: 'LogItem',
11596 syntax: 'proto2',
11597 fields: [{
11598 rule: 'optional',
11599 type: 'string',
11600 name: 'from',
11601 id: 1
11602 }, {
11603 rule: 'optional',
11604 type: 'string',
11605 name: 'data',
11606 id: 2
11607 }, {
11608 rule: 'optional',
11609 type: 'int64',
11610 name: 'timestamp',
11611 id: 3
11612 }, {
11613 rule: 'optional',
11614 type: 'string',
11615 name: 'msgId',
11616 id: 4
11617 }, {
11618 rule: 'optional',
11619 type: 'int64',
11620 name: 'ackAt',
11621 id: 5
11622 }, {
11623 rule: 'optional',
11624 type: 'int64',
11625 name: 'readAt',
11626 id: 6
11627 }, {
11628 rule: 'optional',
11629 type: 'int64',
11630 name: 'patchTimestamp',
11631 id: 7
11632 }, {
11633 rule: 'optional',
11634 type: 'bool',
11635 name: 'mentionAll',
11636 id: 8
11637 }, {
11638 rule: 'repeated',
11639 type: 'string',
11640 name: 'mentionPids',
11641 id: 9
11642 }, {
11643 rule: 'optional',
11644 type: 'bool',
11645 name: 'bin',
11646 id: 10
11647 }, {
11648 rule: 'optional',
11649 type: 'int32',
11650 name: 'convType',
11651 id: 11
11652 }]
11653 }, {
11654 name: 'ConvMemberInfo',
11655 syntax: 'proto2',
11656 fields: [{
11657 rule: 'optional',
11658 type: 'string',
11659 name: 'pid',
11660 id: 1
11661 }, {
11662 rule: 'optional',
11663 type: 'string',
11664 name: 'role',
11665 id: 2
11666 }, {
11667 rule: 'optional',
11668 type: 'string',
11669 name: 'infoId',
11670 id: 3
11671 }]
11672 }, {
11673 name: 'DataCommand',
11674 syntax: 'proto2',
11675 fields: [{
11676 rule: 'repeated',
11677 type: 'string',
11678 name: 'ids',
11679 id: 1
11680 }, {
11681 rule: 'repeated',
11682 type: 'JsonObjectMessage',
11683 name: 'msg',
11684 id: 2
11685 }, {
11686 rule: 'optional',
11687 type: 'bool',
11688 name: 'offline',
11689 id: 3
11690 }]
11691 }, {
11692 name: 'SessionCommand',
11693 syntax: 'proto2',
11694 fields: [{
11695 rule: 'optional',
11696 type: 'int64',
11697 name: 't',
11698 id: 1
11699 }, {
11700 rule: 'optional',
11701 type: 'string',
11702 name: 'n',
11703 id: 2
11704 }, {
11705 rule: 'optional',
11706 type: 'string',
11707 name: 's',
11708 id: 3
11709 }, {
11710 rule: 'optional',
11711 type: 'string',
11712 name: 'ua',
11713 id: 4
11714 }, {
11715 rule: 'optional',
11716 type: 'bool',
11717 name: 'r',
11718 id: 5
11719 }, {
11720 rule: 'optional',
11721 type: 'string',
11722 name: 'tag',
11723 id: 6
11724 }, {
11725 rule: 'optional',
11726 type: 'string',
11727 name: 'deviceId',
11728 id: 7
11729 }, {
11730 rule: 'repeated',
11731 type: 'string',
11732 name: 'sessionPeerIds',
11733 id: 8
11734 }, {
11735 rule: 'repeated',
11736 type: 'string',
11737 name: 'onlineSessionPeerIds',
11738 id: 9
11739 }, {
11740 rule: 'optional',
11741 type: 'string',
11742 name: 'st',
11743 id: 10
11744 }, {
11745 rule: 'optional',
11746 type: 'int32',
11747 name: 'stTtl',
11748 id: 11
11749 }, {
11750 rule: 'optional',
11751 type: 'int32',
11752 name: 'code',
11753 id: 12
11754 }, {
11755 rule: 'optional',
11756 type: 'string',
11757 name: 'reason',
11758 id: 13
11759 }, {
11760 rule: 'optional',
11761 type: 'string',
11762 name: 'deviceToken',
11763 id: 14
11764 }, {
11765 rule: 'optional',
11766 type: 'bool',
11767 name: 'sp',
11768 id: 15
11769 }, {
11770 rule: 'optional',
11771 type: 'string',
11772 name: 'detail',
11773 id: 16
11774 }, {
11775 rule: 'optional',
11776 type: 'int64',
11777 name: 'lastUnreadNotifTime',
11778 id: 17
11779 }, {
11780 rule: 'optional',
11781 type: 'int64',
11782 name: 'lastPatchTime',
11783 id: 18
11784 }, {
11785 rule: 'optional',
11786 type: 'int64',
11787 name: 'configBitmap',
11788 id: 19
11789 }]
11790 }, {
11791 name: 'ErrorCommand',
11792 syntax: 'proto2',
11793 fields: [{
11794 rule: 'required',
11795 type: 'int32',
11796 name: 'code',
11797 id: 1
11798 }, {
11799 rule: 'required',
11800 type: 'string',
11801 name: 'reason',
11802 id: 2
11803 }, {
11804 rule: 'optional',
11805 type: 'int32',
11806 name: 'appCode',
11807 id: 3
11808 }, {
11809 rule: 'optional',
11810 type: 'string',
11811 name: 'detail',
11812 id: 4
11813 }, {
11814 rule: 'repeated',
11815 type: 'string',
11816 name: 'pids',
11817 id: 5
11818 }, {
11819 rule: 'optional',
11820 type: 'string',
11821 name: 'appMsg',
11822 id: 6
11823 }]
11824 }, {
11825 name: 'DirectCommand',
11826 syntax: 'proto2',
11827 fields: [{
11828 rule: 'optional',
11829 type: 'string',
11830 name: 'msg',
11831 id: 1
11832 }, {
11833 rule: 'optional',
11834 type: 'string',
11835 name: 'uid',
11836 id: 2
11837 }, {
11838 rule: 'optional',
11839 type: 'string',
11840 name: 'fromPeerId',
11841 id: 3
11842 }, {
11843 rule: 'optional',
11844 type: 'int64',
11845 name: 'timestamp',
11846 id: 4
11847 }, {
11848 rule: 'optional',
11849 type: 'bool',
11850 name: 'offline',
11851 id: 5
11852 }, {
11853 rule: 'optional',
11854 type: 'bool',
11855 name: 'hasMore',
11856 id: 6
11857 }, {
11858 rule: 'repeated',
11859 type: 'string',
11860 name: 'toPeerIds',
11861 id: 7
11862 }, {
11863 rule: 'optional',
11864 type: 'bool',
11865 name: 'r',
11866 id: 10
11867 }, {
11868 rule: 'optional',
11869 type: 'string',
11870 name: 'cid',
11871 id: 11
11872 }, {
11873 rule: 'optional',
11874 type: 'string',
11875 name: 'id',
11876 id: 12
11877 }, {
11878 rule: 'optional',
11879 type: 'bool',
11880 name: 'transient',
11881 id: 13
11882 }, {
11883 rule: 'optional',
11884 type: 'string',
11885 name: 'dt',
11886 id: 14
11887 }, {
11888 rule: 'optional',
11889 type: 'string',
11890 name: 'roomId',
11891 id: 15
11892 }, {
11893 rule: 'optional',
11894 type: 'string',
11895 name: 'pushData',
11896 id: 16
11897 }, {
11898 rule: 'optional',
11899 type: 'bool',
11900 name: 'will',
11901 id: 17
11902 }, {
11903 rule: 'optional',
11904 type: 'int64',
11905 name: 'patchTimestamp',
11906 id: 18
11907 }, {
11908 rule: 'optional',
11909 type: 'bytes',
11910 name: 'binaryMsg',
11911 id: 19
11912 }, {
11913 rule: 'repeated',
11914 type: 'string',
11915 name: 'mentionPids',
11916 id: 20
11917 }, {
11918 rule: 'optional',
11919 type: 'bool',
11920 name: 'mentionAll',
11921 id: 21
11922 }, {
11923 rule: 'optional',
11924 type: 'int32',
11925 name: 'convType',
11926 id: 22
11927 }]
11928 }, {
11929 name: 'AckCommand',
11930 syntax: 'proto2',
11931 fields: [{
11932 rule: 'optional',
11933 type: 'int32',
11934 name: 'code',
11935 id: 1
11936 }, {
11937 rule: 'optional',
11938 type: 'string',
11939 name: 'reason',
11940 id: 2
11941 }, {
11942 rule: 'optional',
11943 type: 'string',
11944 name: 'mid',
11945 id: 3
11946 }, {
11947 rule: 'optional',
11948 type: 'string',
11949 name: 'cid',
11950 id: 4
11951 }, {
11952 rule: 'optional',
11953 type: 'int64',
11954 name: 't',
11955 id: 5
11956 }, {
11957 rule: 'optional',
11958 type: 'string',
11959 name: 'uid',
11960 id: 6
11961 }, {
11962 rule: 'optional',
11963 type: 'int64',
11964 name: 'fromts',
11965 id: 7
11966 }, {
11967 rule: 'optional',
11968 type: 'int64',
11969 name: 'tots',
11970 id: 8
11971 }, {
11972 rule: 'optional',
11973 type: 'string',
11974 name: 'type',
11975 id: 9
11976 }, {
11977 rule: 'repeated',
11978 type: 'string',
11979 name: 'ids',
11980 id: 10
11981 }, {
11982 rule: 'optional',
11983 type: 'int32',
11984 name: 'appCode',
11985 id: 11
11986 }, {
11987 rule: 'optional',
11988 type: 'string',
11989 name: 'appMsg',
11990 id: 12
11991 }]
11992 }, {
11993 name: 'UnreadCommand',
11994 syntax: 'proto2',
11995 fields: [{
11996 rule: 'repeated',
11997 type: 'UnreadTuple',
11998 name: 'convs',
11999 id: 1
12000 }, {
12001 rule: 'optional',
12002 type: 'int64',
12003 name: 'notifTime',
12004 id: 2
12005 }]
12006 }, {
12007 name: 'ConvCommand',
12008 syntax: 'proto2',
12009 fields: [{
12010 rule: 'repeated',
12011 type: 'string',
12012 name: 'm',
12013 id: 1
12014 }, {
12015 rule: 'optional',
12016 type: 'bool',
12017 name: 'transient',
12018 id: 2
12019 }, {
12020 rule: 'optional',
12021 type: 'bool',
12022 name: 'unique',
12023 id: 3
12024 }, {
12025 rule: 'optional',
12026 type: 'string',
12027 name: 'cid',
12028 id: 4
12029 }, {
12030 rule: 'optional',
12031 type: 'string',
12032 name: 'cdate',
12033 id: 5
12034 }, {
12035 rule: 'optional',
12036 type: 'string',
12037 name: 'initBy',
12038 id: 6
12039 }, {
12040 rule: 'optional',
12041 type: 'string',
12042 name: 'sort',
12043 id: 7
12044 }, {
12045 rule: 'optional',
12046 type: 'int32',
12047 name: 'limit',
12048 id: 8
12049 }, {
12050 rule: 'optional',
12051 type: 'int32',
12052 name: 'skip',
12053 id: 9
12054 }, {
12055 rule: 'optional',
12056 type: 'int32',
12057 name: 'flag',
12058 id: 10
12059 }, {
12060 rule: 'optional',
12061 type: 'int32',
12062 name: 'count',
12063 id: 11
12064 }, {
12065 rule: 'optional',
12066 type: 'string',
12067 name: 'udate',
12068 id: 12
12069 }, {
12070 rule: 'optional',
12071 type: 'int64',
12072 name: 't',
12073 id: 13
12074 }, {
12075 rule: 'optional',
12076 type: 'string',
12077 name: 'n',
12078 id: 14
12079 }, {
12080 rule: 'optional',
12081 type: 'string',
12082 name: 's',
12083 id: 15
12084 }, {
12085 rule: 'optional',
12086 type: 'bool',
12087 name: 'statusSub',
12088 id: 16
12089 }, {
12090 rule: 'optional',
12091 type: 'bool',
12092 name: 'statusPub',
12093 id: 17
12094 }, {
12095 rule: 'optional',
12096 type: 'int32',
12097 name: 'statusTTL',
12098 id: 18
12099 }, {
12100 rule: 'optional',
12101 type: 'string',
12102 name: 'uniqueId',
12103 id: 19
12104 }, {
12105 rule: 'optional',
12106 type: 'string',
12107 name: 'targetClientId',
12108 id: 20
12109 }, {
12110 rule: 'optional',
12111 type: 'int64',
12112 name: 'maxReadTimestamp',
12113 id: 21
12114 }, {
12115 rule: 'optional',
12116 type: 'int64',
12117 name: 'maxAckTimestamp',
12118 id: 22
12119 }, {
12120 rule: 'optional',
12121 type: 'bool',
12122 name: 'queryAllMembers',
12123 id: 23
12124 }, {
12125 rule: 'repeated',
12126 type: 'MaxReadTuple',
12127 name: 'maxReadTuples',
12128 id: 24
12129 }, {
12130 rule: 'repeated',
12131 type: 'string',
12132 name: 'cids',
12133 id: 25
12134 }, {
12135 rule: 'optional',
12136 type: 'ConvMemberInfo',
12137 name: 'info',
12138 id: 26
12139 }, {
12140 rule: 'optional',
12141 type: 'bool',
12142 name: 'tempConv',
12143 id: 27
12144 }, {
12145 rule: 'optional',
12146 type: 'int32',
12147 name: 'tempConvTTL',
12148 id: 28
12149 }, {
12150 rule: 'repeated',
12151 type: 'string',
12152 name: 'tempConvIds',
12153 id: 29
12154 }, {
12155 rule: 'repeated',
12156 type: 'string',
12157 name: 'allowedPids',
12158 id: 30
12159 }, {
12160 rule: 'repeated',
12161 type: 'ErrorCommand',
12162 name: 'failedPids',
12163 id: 31
12164 }, {
12165 rule: 'optional',
12166 type: 'string',
12167 name: 'next',
12168 id: 40
12169 }, {
12170 rule: 'optional',
12171 type: 'JsonObjectMessage',
12172 name: 'results',
12173 id: 100
12174 }, {
12175 rule: 'optional',
12176 type: 'JsonObjectMessage',
12177 name: 'where',
12178 id: 101
12179 }, {
12180 rule: 'optional',
12181 type: 'JsonObjectMessage',
12182 name: 'attr',
12183 id: 103
12184 }, {
12185 rule: 'optional',
12186 type: 'JsonObjectMessage',
12187 name: 'attrModified',
12188 id: 104
12189 }]
12190 }, {
12191 name: 'RoomCommand',
12192 syntax: 'proto2',
12193 fields: [{
12194 rule: 'optional',
12195 type: 'string',
12196 name: 'roomId',
12197 id: 1
12198 }, {
12199 rule: 'optional',
12200 type: 'string',
12201 name: 's',
12202 id: 2
12203 }, {
12204 rule: 'optional',
12205 type: 'int64',
12206 name: 't',
12207 id: 3
12208 }, {
12209 rule: 'optional',
12210 type: 'string',
12211 name: 'n',
12212 id: 4
12213 }, {
12214 rule: 'optional',
12215 type: 'bool',
12216 name: 'transient',
12217 id: 5
12218 }, {
12219 rule: 'repeated',
12220 type: 'string',
12221 name: 'roomPeerIds',
12222 id: 6
12223 }, {
12224 rule: 'optional',
12225 type: 'string',
12226 name: 'byPeerId',
12227 id: 7
12228 }]
12229 }, {
12230 name: 'LogsCommand',
12231 syntax: 'proto2',
12232 fields: [{
12233 rule: 'optional',
12234 type: 'string',
12235 name: 'cid',
12236 id: 1
12237 }, {
12238 rule: 'optional',
12239 type: 'int32',
12240 name: 'l',
12241 id: 2
12242 }, {
12243 rule: 'optional',
12244 type: 'int32',
12245 name: 'limit',
12246 id: 3
12247 }, {
12248 rule: 'optional',
12249 type: 'int64',
12250 name: 't',
12251 id: 4
12252 }, {
12253 rule: 'optional',
12254 type: 'int64',
12255 name: 'tt',
12256 id: 5
12257 }, {
12258 rule: 'optional',
12259 type: 'string',
12260 name: 'tmid',
12261 id: 6
12262 }, {
12263 rule: 'optional',
12264 type: 'string',
12265 name: 'mid',
12266 id: 7
12267 }, {
12268 rule: 'optional',
12269 type: 'string',
12270 name: 'checksum',
12271 id: 8
12272 }, {
12273 rule: 'optional',
12274 type: 'bool',
12275 name: 'stored',
12276 id: 9
12277 }, {
12278 rule: 'optional',
12279 type: 'QueryDirection',
12280 name: 'direction',
12281 id: 10,
12282 options: {
12283 "default": 'OLD'
12284 }
12285 }, {
12286 rule: 'optional',
12287 type: 'bool',
12288 name: 'tIncluded',
12289 id: 11
12290 }, {
12291 rule: 'optional',
12292 type: 'bool',
12293 name: 'ttIncluded',
12294 id: 12
12295 }, {
12296 rule: 'optional',
12297 type: 'int32',
12298 name: 'lctype',
12299 id: 13
12300 }, {
12301 rule: 'repeated',
12302 type: 'LogItem',
12303 name: 'logs',
12304 id: 105
12305 }],
12306 enums: [{
12307 name: 'QueryDirection',
12308 syntax: 'proto2',
12309 values: [{
12310 name: 'OLD',
12311 id: 1
12312 }, {
12313 name: 'NEW',
12314 id: 2
12315 }]
12316 }]
12317 }, {
12318 name: 'RcpCommand',
12319 syntax: 'proto2',
12320 fields: [{
12321 rule: 'optional',
12322 type: 'string',
12323 name: 'id',
12324 id: 1
12325 }, {
12326 rule: 'optional',
12327 type: 'string',
12328 name: 'cid',
12329 id: 2
12330 }, {
12331 rule: 'optional',
12332 type: 'int64',
12333 name: 't',
12334 id: 3
12335 }, {
12336 rule: 'optional',
12337 type: 'bool',
12338 name: 'read',
12339 id: 4
12340 }, {
12341 rule: 'optional',
12342 type: 'string',
12343 name: 'from',
12344 id: 5
12345 }]
12346 }, {
12347 name: 'ReadTuple',
12348 syntax: 'proto2',
12349 fields: [{
12350 rule: 'required',
12351 type: 'string',
12352 name: 'cid',
12353 id: 1
12354 }, {
12355 rule: 'optional',
12356 type: 'int64',
12357 name: 'timestamp',
12358 id: 2
12359 }, {
12360 rule: 'optional',
12361 type: 'string',
12362 name: 'mid',
12363 id: 3
12364 }]
12365 }, {
12366 name: 'MaxReadTuple',
12367 syntax: 'proto2',
12368 fields: [{
12369 rule: 'optional',
12370 type: 'string',
12371 name: 'pid',
12372 id: 1
12373 }, {
12374 rule: 'optional',
12375 type: 'int64',
12376 name: 'maxAckTimestamp',
12377 id: 2
12378 }, {
12379 rule: 'optional',
12380 type: 'int64',
12381 name: 'maxReadTimestamp',
12382 id: 3
12383 }]
12384 }, {
12385 name: 'ReadCommand',
12386 syntax: 'proto2',
12387 fields: [{
12388 rule: 'optional',
12389 type: 'string',
12390 name: 'cid',
12391 id: 1
12392 }, {
12393 rule: 'repeated',
12394 type: 'string',
12395 name: 'cids',
12396 id: 2
12397 }, {
12398 rule: 'repeated',
12399 type: 'ReadTuple',
12400 name: 'convs',
12401 id: 3
12402 }]
12403 }, {
12404 name: 'PresenceCommand',
12405 syntax: 'proto2',
12406 fields: [{
12407 rule: 'optional',
12408 type: 'StatusType',
12409 name: 'status',
12410 id: 1
12411 }, {
12412 rule: 'repeated',
12413 type: 'string',
12414 name: 'sessionPeerIds',
12415 id: 2
12416 }, {
12417 rule: 'optional',
12418 type: 'string',
12419 name: 'cid',
12420 id: 3
12421 }]
12422 }, {
12423 name: 'ReportCommand',
12424 syntax: 'proto2',
12425 fields: [{
12426 rule: 'optional',
12427 type: 'bool',
12428 name: 'initiative',
12429 id: 1
12430 }, {
12431 rule: 'optional',
12432 type: 'string',
12433 name: 'type',
12434 id: 2
12435 }, {
12436 rule: 'optional',
12437 type: 'string',
12438 name: 'data',
12439 id: 3
12440 }]
12441 }, {
12442 name: 'PatchItem',
12443 syntax: 'proto2',
12444 fields: [{
12445 rule: 'optional',
12446 type: 'string',
12447 name: 'cid',
12448 id: 1
12449 }, {
12450 rule: 'optional',
12451 type: 'string',
12452 name: 'mid',
12453 id: 2
12454 }, {
12455 rule: 'optional',
12456 type: 'int64',
12457 name: 'timestamp',
12458 id: 3
12459 }, {
12460 rule: 'optional',
12461 type: 'bool',
12462 name: 'recall',
12463 id: 4
12464 }, {
12465 rule: 'optional',
12466 type: 'string',
12467 name: 'data',
12468 id: 5
12469 }, {
12470 rule: 'optional',
12471 type: 'int64',
12472 name: 'patchTimestamp',
12473 id: 6
12474 }, {
12475 rule: 'optional',
12476 type: 'string',
12477 name: 'from',
12478 id: 7
12479 }, {
12480 rule: 'optional',
12481 type: 'bytes',
12482 name: 'binaryMsg',
12483 id: 8
12484 }, {
12485 rule: 'optional',
12486 type: 'bool',
12487 name: 'mentionAll',
12488 id: 9
12489 }, {
12490 rule: 'repeated',
12491 type: 'string',
12492 name: 'mentionPids',
12493 id: 10
12494 }, {
12495 rule: 'optional',
12496 type: 'int64',
12497 name: 'patchCode',
12498 id: 11
12499 }, {
12500 rule: 'optional',
12501 type: 'string',
12502 name: 'patchReason',
12503 id: 12
12504 }]
12505 }, {
12506 name: 'PatchCommand',
12507 syntax: 'proto2',
12508 fields: [{
12509 rule: 'repeated',
12510 type: 'PatchItem',
12511 name: 'patches',
12512 id: 1
12513 }, {
12514 rule: 'optional',
12515 type: 'int64',
12516 name: 'lastPatchTime',
12517 id: 2
12518 }]
12519 }, {
12520 name: 'PubsubCommand',
12521 syntax: 'proto2',
12522 fields: [{
12523 rule: 'optional',
12524 type: 'string',
12525 name: 'cid',
12526 id: 1
12527 }, {
12528 rule: 'repeated',
12529 type: 'string',
12530 name: 'cids',
12531 id: 2
12532 }, {
12533 rule: 'optional',
12534 type: 'string',
12535 name: 'topic',
12536 id: 3
12537 }, {
12538 rule: 'optional',
12539 type: 'string',
12540 name: 'subtopic',
12541 id: 4
12542 }, {
12543 rule: 'repeated',
12544 type: 'string',
12545 name: 'topics',
12546 id: 5
12547 }, {
12548 rule: 'repeated',
12549 type: 'string',
12550 name: 'subtopics',
12551 id: 6
12552 }, {
12553 rule: 'optional',
12554 type: 'JsonObjectMessage',
12555 name: 'results',
12556 id: 7
12557 }]
12558 }, {
12559 name: 'BlacklistCommand',
12560 syntax: 'proto2',
12561 fields: [{
12562 rule: 'optional',
12563 type: 'string',
12564 name: 'srcCid',
12565 id: 1
12566 }, {
12567 rule: 'repeated',
12568 type: 'string',
12569 name: 'toPids',
12570 id: 2
12571 }, {
12572 rule: 'optional',
12573 type: 'string',
12574 name: 'srcPid',
12575 id: 3
12576 }, {
12577 rule: 'repeated',
12578 type: 'string',
12579 name: 'toCids',
12580 id: 4
12581 }, {
12582 rule: 'optional',
12583 type: 'int32',
12584 name: 'limit',
12585 id: 5
12586 }, {
12587 rule: 'optional',
12588 type: 'string',
12589 name: 'next',
12590 id: 6
12591 }, {
12592 rule: 'repeated',
12593 type: 'string',
12594 name: 'blockedPids',
12595 id: 8
12596 }, {
12597 rule: 'repeated',
12598 type: 'string',
12599 name: 'blockedCids',
12600 id: 9
12601 }, {
12602 rule: 'repeated',
12603 type: 'string',
12604 name: 'allowedPids',
12605 id: 10
12606 }, {
12607 rule: 'repeated',
12608 type: 'ErrorCommand',
12609 name: 'failedPids',
12610 id: 11
12611 }, {
12612 rule: 'optional',
12613 type: 'int64',
12614 name: 't',
12615 id: 12
12616 }, {
12617 rule: 'optional',
12618 type: 'string',
12619 name: 'n',
12620 id: 13
12621 }, {
12622 rule: 'optional',
12623 type: 'string',
12624 name: 's',
12625 id: 14
12626 }]
12627 }, {
12628 name: 'GenericCommand',
12629 syntax: 'proto2',
12630 fields: [{
12631 rule: 'optional',
12632 type: 'CommandType',
12633 name: 'cmd',
12634 id: 1
12635 }, {
12636 rule: 'optional',
12637 type: 'OpType',
12638 name: 'op',
12639 id: 2
12640 }, {
12641 rule: 'optional',
12642 type: 'string',
12643 name: 'appId',
12644 id: 3
12645 }, {
12646 rule: 'optional',
12647 type: 'string',
12648 name: 'peerId',
12649 id: 4
12650 }, {
12651 rule: 'optional',
12652 type: 'int32',
12653 name: 'i',
12654 id: 5
12655 }, {
12656 rule: 'optional',
12657 type: 'string',
12658 name: 'installationId',
12659 id: 6
12660 }, {
12661 rule: 'optional',
12662 type: 'int32',
12663 name: 'priority',
12664 id: 7
12665 }, {
12666 rule: 'optional',
12667 type: 'int32',
12668 name: 'service',
12669 id: 8
12670 }, {
12671 rule: 'optional',
12672 type: 'int64',
12673 name: 'serverTs',
12674 id: 9
12675 }, {
12676 rule: 'optional',
12677 type: 'int64',
12678 name: 'clientTs',
12679 id: 10
12680 }, {
12681 rule: 'optional',
12682 type: 'int32',
12683 name: 'notificationType',
12684 id: 11
12685 }, {
12686 rule: 'optional',
12687 type: 'DataCommand',
12688 name: 'dataMessage',
12689 id: 101
12690 }, {
12691 rule: 'optional',
12692 type: 'SessionCommand',
12693 name: 'sessionMessage',
12694 id: 102
12695 }, {
12696 rule: 'optional',
12697 type: 'ErrorCommand',
12698 name: 'errorMessage',
12699 id: 103
12700 }, {
12701 rule: 'optional',
12702 type: 'DirectCommand',
12703 name: 'directMessage',
12704 id: 104
12705 }, {
12706 rule: 'optional',
12707 type: 'AckCommand',
12708 name: 'ackMessage',
12709 id: 105
12710 }, {
12711 rule: 'optional',
12712 type: 'UnreadCommand',
12713 name: 'unreadMessage',
12714 id: 106
12715 }, {
12716 rule: 'optional',
12717 type: 'ReadCommand',
12718 name: 'readMessage',
12719 id: 107
12720 }, {
12721 rule: 'optional',
12722 type: 'RcpCommand',
12723 name: 'rcpMessage',
12724 id: 108
12725 }, {
12726 rule: 'optional',
12727 type: 'LogsCommand',
12728 name: 'logsMessage',
12729 id: 109
12730 }, {
12731 rule: 'optional',
12732 type: 'ConvCommand',
12733 name: 'convMessage',
12734 id: 110
12735 }, {
12736 rule: 'optional',
12737 type: 'RoomCommand',
12738 name: 'roomMessage',
12739 id: 111
12740 }, {
12741 rule: 'optional',
12742 type: 'PresenceCommand',
12743 name: 'presenceMessage',
12744 id: 112
12745 }, {
12746 rule: 'optional',
12747 type: 'ReportCommand',
12748 name: 'reportMessage',
12749 id: 113
12750 }, {
12751 rule: 'optional',
12752 type: 'PatchCommand',
12753 name: 'patchMessage',
12754 id: 114
12755 }, {
12756 rule: 'optional',
12757 type: 'PubsubCommand',
12758 name: 'pubsubMessage',
12759 id: 115
12760 }, {
12761 rule: 'optional',
12762 type: 'BlacklistCommand',
12763 name: 'blacklistMessage',
12764 id: 116
12765 }]
12766 }],
12767 enums: [{
12768 name: 'CommandType',
12769 syntax: 'proto2',
12770 values: [{
12771 name: 'session',
12772 id: 0
12773 }, {
12774 name: 'conv',
12775 id: 1
12776 }, {
12777 name: 'direct',
12778 id: 2
12779 }, {
12780 name: 'ack',
12781 id: 3
12782 }, {
12783 name: 'rcp',
12784 id: 4
12785 }, {
12786 name: 'unread',
12787 id: 5
12788 }, {
12789 name: 'logs',
12790 id: 6
12791 }, {
12792 name: 'error',
12793 id: 7
12794 }, {
12795 name: 'login',
12796 id: 8
12797 }, {
12798 name: 'data',
12799 id: 9
12800 }, {
12801 name: 'room',
12802 id: 10
12803 }, {
12804 name: 'read',
12805 id: 11
12806 }, {
12807 name: 'presence',
12808 id: 12
12809 }, {
12810 name: 'report',
12811 id: 13
12812 }, {
12813 name: 'echo',
12814 id: 14
12815 }, {
12816 name: 'loggedin',
12817 id: 15
12818 }, {
12819 name: 'logout',
12820 id: 16
12821 }, {
12822 name: 'loggedout',
12823 id: 17
12824 }, {
12825 name: 'patch',
12826 id: 18
12827 }, {
12828 name: 'pubsub',
12829 id: 19
12830 }, {
12831 name: 'blacklist',
12832 id: 20
12833 }, {
12834 name: 'goaway',
12835 id: 21
12836 }]
12837 }, {
12838 name: 'OpType',
12839 syntax: 'proto2',
12840 values: [{
12841 name: 'open',
12842 id: 1
12843 }, {
12844 name: 'add',
12845 id: 2
12846 }, {
12847 name: 'remove',
12848 id: 3
12849 }, {
12850 name: 'close',
12851 id: 4
12852 }, {
12853 name: 'opened',
12854 id: 5
12855 }, {
12856 name: 'closed',
12857 id: 6
12858 }, {
12859 name: 'query',
12860 id: 7
12861 }, {
12862 name: 'query_result',
12863 id: 8
12864 }, {
12865 name: 'conflict',
12866 id: 9
12867 }, {
12868 name: 'added',
12869 id: 10
12870 }, {
12871 name: 'removed',
12872 id: 11
12873 }, {
12874 name: 'refresh',
12875 id: 12
12876 }, {
12877 name: 'refreshed',
12878 id: 13
12879 }, {
12880 name: 'start',
12881 id: 30
12882 }, {
12883 name: 'started',
12884 id: 31
12885 }, {
12886 name: 'joined',
12887 id: 32
12888 }, {
12889 name: 'members_joined',
12890 id: 33
12891 }, {
12892 name: 'left',
12893 id: 39
12894 }, {
12895 name: 'members_left',
12896 id: 40
12897 }, {
12898 name: 'results',
12899 id: 42
12900 }, {
12901 name: 'count',
12902 id: 43
12903 }, {
12904 name: 'result',
12905 id: 44
12906 }, {
12907 name: 'update',
12908 id: 45
12909 }, {
12910 name: 'updated',
12911 id: 46
12912 }, {
12913 name: 'mute',
12914 id: 47
12915 }, {
12916 name: 'unmute',
12917 id: 48
12918 }, {
12919 name: 'status',
12920 id: 49
12921 }, {
12922 name: 'members',
12923 id: 50
12924 }, {
12925 name: 'max_read',
12926 id: 51
12927 }, {
12928 name: 'is_member',
12929 id: 52
12930 }, {
12931 name: 'member_info_update',
12932 id: 53
12933 }, {
12934 name: 'member_info_updated',
12935 id: 54
12936 }, {
12937 name: 'member_info_changed',
12938 id: 55
12939 }, {
12940 name: 'join',
12941 id: 80
12942 }, {
12943 name: 'invite',
12944 id: 81
12945 }, {
12946 name: 'leave',
12947 id: 82
12948 }, {
12949 name: 'kick',
12950 id: 83
12951 }, {
12952 name: 'reject',
12953 id: 84
12954 }, {
12955 name: 'invited',
12956 id: 85
12957 }, {
12958 name: 'kicked',
12959 id: 86
12960 }, {
12961 name: 'upload',
12962 id: 100
12963 }, {
12964 name: 'uploaded',
12965 id: 101
12966 }, {
12967 name: 'subscribe',
12968 id: 120
12969 }, {
12970 name: 'subscribed',
12971 id: 121
12972 }, {
12973 name: 'unsubscribe',
12974 id: 122
12975 }, {
12976 name: 'unsubscribed',
12977 id: 123
12978 }, {
12979 name: 'is_subscribed',
12980 id: 124
12981 }, {
12982 name: 'modify',
12983 id: 150
12984 }, {
12985 name: 'modified',
12986 id: 151
12987 }, {
12988 name: 'block',
12989 id: 170
12990 }, {
12991 name: 'unblock',
12992 id: 171
12993 }, {
12994 name: 'blocked',
12995 id: 172
12996 }, {
12997 name: 'unblocked',
12998 id: 173
12999 }, {
13000 name: 'members_blocked',
13001 id: 174
13002 }, {
13003 name: 'members_unblocked',
13004 id: 175
13005 }, {
13006 name: 'check_block',
13007 id: 176
13008 }, {
13009 name: 'check_result',
13010 id: 177
13011 }, {
13012 name: 'add_shutup',
13013 id: 180
13014 }, {
13015 name: 'remove_shutup',
13016 id: 181
13017 }, {
13018 name: 'query_shutup',
13019 id: 182
13020 }, {
13021 name: 'shutup_added',
13022 id: 183
13023 }, {
13024 name: 'shutup_removed',
13025 id: 184
13026 }, {
13027 name: 'shutup_result',
13028 id: 185
13029 }, {
13030 name: 'shutuped',
13031 id: 186
13032 }, {
13033 name: 'unshutuped',
13034 id: 187
13035 }, {
13036 name: 'members_shutuped',
13037 id: 188
13038 }, {
13039 name: 'members_unshutuped',
13040 id: 189
13041 }, {
13042 name: 'check_shutup',
13043 id: 190
13044 }]
13045 }, {
13046 name: 'StatusType',
13047 syntax: 'proto2',
13048 values: [{
13049 name: 'on',
13050 id: 1
13051 }, {
13052 name: 'off',
13053 id: 2
13054 }]
13055 }],
13056 isNamespace: true
13057 }).build();
13058
13059 var _messages$push_server = messageCompiled.push_server.messages2,
13060 JsonObjectMessage = _messages$push_server.JsonObjectMessage,
13061 UnreadTuple = _messages$push_server.UnreadTuple,
13062 LogItem = _messages$push_server.LogItem,
13063 DataCommand = _messages$push_server.DataCommand,
13064 SessionCommand = _messages$push_server.SessionCommand,
13065 ErrorCommand = _messages$push_server.ErrorCommand,
13066 DirectCommand = _messages$push_server.DirectCommand,
13067 AckCommand = _messages$push_server.AckCommand,
13068 UnreadCommand = _messages$push_server.UnreadCommand,
13069 ConvCommand = _messages$push_server.ConvCommand,
13070 RoomCommand = _messages$push_server.RoomCommand,
13071 LogsCommand = _messages$push_server.LogsCommand,
13072 RcpCommand = _messages$push_server.RcpCommand,
13073 ReadTuple = _messages$push_server.ReadTuple,
13074 MaxReadTuple = _messages$push_server.MaxReadTuple,
13075 ReadCommand = _messages$push_server.ReadCommand,
13076 PresenceCommand = _messages$push_server.PresenceCommand,
13077 ReportCommand = _messages$push_server.ReportCommand,
13078 GenericCommand = _messages$push_server.GenericCommand,
13079 BlacklistCommand = _messages$push_server.BlacklistCommand,
13080 PatchCommand = _messages$push_server.PatchCommand,
13081 PatchItem = _messages$push_server.PatchItem,
13082 ConvMemberInfo = _messages$push_server.ConvMemberInfo,
13083 CommandType = _messages$push_server.CommandType,
13084 OpType = _messages$push_server.OpType,
13085 StatusType = _messages$push_server.StatusType;
13086
13087 var message = /*#__PURE__*/Object.freeze({
13088 __proto__: null,
13089 JsonObjectMessage: JsonObjectMessage,
13090 UnreadTuple: UnreadTuple,
13091 LogItem: LogItem,
13092 DataCommand: DataCommand,
13093 SessionCommand: SessionCommand,
13094 ErrorCommand: ErrorCommand,
13095 DirectCommand: DirectCommand,
13096 AckCommand: AckCommand,
13097 UnreadCommand: UnreadCommand,
13098 ConvCommand: ConvCommand,
13099 RoomCommand: RoomCommand,
13100 LogsCommand: LogsCommand,
13101 RcpCommand: RcpCommand,
13102 ReadTuple: ReadTuple,
13103 MaxReadTuple: MaxReadTuple,
13104 ReadCommand: ReadCommand,
13105 PresenceCommand: PresenceCommand,
13106 ReportCommand: ReportCommand,
13107 GenericCommand: GenericCommand,
13108 BlacklistCommand: BlacklistCommand,
13109 PatchCommand: PatchCommand,
13110 PatchItem: PatchItem,
13111 ConvMemberInfo: ConvMemberInfo,
13112 CommandType: CommandType,
13113 OpType: OpType,
13114 StatusType: StatusType
13115 });
13116
13117 var eventemitter3 = createCommonjsModule(function (module) {
13118
13119 var has = Object.prototype.hasOwnProperty
13120 , prefix = '~';
13121
13122 /**
13123 * Constructor to create a storage for our `EE` objects.
13124 * An `Events` instance is a plain object whose properties are event names.
13125 *
13126 * @constructor
13127 * @private
13128 */
13129 function Events() {}
13130
13131 //
13132 // We try to not inherit from `Object.prototype`. In some engines creating an
13133 // instance in this way is faster than calling `Object.create(null)` directly.
13134 // If `Object.create(null)` is not supported we prefix the event names with a
13135 // character to make sure that the built-in object properties are not
13136 // overridden or used as an attack vector.
13137 //
13138 if (Object.create) {
13139 Events.prototype = Object.create(null);
13140
13141 //
13142 // This hack is needed because the `__proto__` property is still inherited in
13143 // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.
13144 //
13145 if (!new Events().__proto__) prefix = false;
13146 }
13147
13148 /**
13149 * Representation of a single event listener.
13150 *
13151 * @param {Function} fn The listener function.
13152 * @param {*} context The context to invoke the listener with.
13153 * @param {Boolean} [once=false] Specify if the listener is a one-time listener.
13154 * @constructor
13155 * @private
13156 */
13157 function EE(fn, context, once) {
13158 this.fn = fn;
13159 this.context = context;
13160 this.once = once || false;
13161 }
13162
13163 /**
13164 * Add a listener for a given event.
13165 *
13166 * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
13167 * @param {(String|Symbol)} event The event name.
13168 * @param {Function} fn The listener function.
13169 * @param {*} context The context to invoke the listener with.
13170 * @param {Boolean} once Specify if the listener is a one-time listener.
13171 * @returns {EventEmitter}
13172 * @private
13173 */
13174 function addListener(emitter, event, fn, context, once) {
13175 if (typeof fn !== 'function') {
13176 throw new TypeError('The listener must be a function');
13177 }
13178
13179 var listener = new EE(fn, context || emitter, once)
13180 , evt = prefix ? prefix + event : event;
13181
13182 if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;
13183 else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);
13184 else emitter._events[evt] = [emitter._events[evt], listener];
13185
13186 return emitter;
13187 }
13188
13189 /**
13190 * Clear event by name.
13191 *
13192 * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
13193 * @param {(String|Symbol)} evt The Event name.
13194 * @private
13195 */
13196 function clearEvent(emitter, evt) {
13197 if (--emitter._eventsCount === 0) emitter._events = new Events();
13198 else delete emitter._events[evt];
13199 }
13200
13201 /**
13202 * Minimal `EventEmitter` interface that is molded against the Node.js
13203 * `EventEmitter` interface.
13204 *
13205 * @constructor
13206 * @public
13207 */
13208 function EventEmitter() {
13209 this._events = new Events();
13210 this._eventsCount = 0;
13211 }
13212
13213 /**
13214 * Return an array listing the events for which the emitter has registered
13215 * listeners.
13216 *
13217 * @returns {Array}
13218 * @public
13219 */
13220 EventEmitter.prototype.eventNames = function eventNames() {
13221 var names = []
13222 , events
13223 , name;
13224
13225 if (this._eventsCount === 0) return names;
13226
13227 for (name in (events = this._events)) {
13228 if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);
13229 }
13230
13231 if (Object.getOwnPropertySymbols) {
13232 return names.concat(Object.getOwnPropertySymbols(events));
13233 }
13234
13235 return names;
13236 };
13237
13238 /**
13239 * Return the listeners registered for a given event.
13240 *
13241 * @param {(String|Symbol)} event The event name.
13242 * @returns {Array} The registered listeners.
13243 * @public
13244 */
13245 EventEmitter.prototype.listeners = function listeners(event) {
13246 var evt = prefix ? prefix + event : event
13247 , handlers = this._events[evt];
13248
13249 if (!handlers) return [];
13250 if (handlers.fn) return [handlers.fn];
13251
13252 for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {
13253 ee[i] = handlers[i].fn;
13254 }
13255
13256 return ee;
13257 };
13258
13259 /**
13260 * Return the number of listeners listening to a given event.
13261 *
13262 * @param {(String|Symbol)} event The event name.
13263 * @returns {Number} The number of listeners.
13264 * @public
13265 */
13266 EventEmitter.prototype.listenerCount = function listenerCount(event) {
13267 var evt = prefix ? prefix + event : event
13268 , listeners = this._events[evt];
13269
13270 if (!listeners) return 0;
13271 if (listeners.fn) return 1;
13272 return listeners.length;
13273 };
13274
13275 /**
13276 * Calls each of the listeners registered for a given event.
13277 *
13278 * @param {(String|Symbol)} event The event name.
13279 * @returns {Boolean} `true` if the event had listeners, else `false`.
13280 * @public
13281 */
13282 EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {
13283 var evt = prefix ? prefix + event : event;
13284
13285 if (!this._events[evt]) return false;
13286
13287 var listeners = this._events[evt]
13288 , len = arguments.length
13289 , args
13290 , i;
13291
13292 if (listeners.fn) {
13293 if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);
13294
13295 switch (len) {
13296 case 1: return listeners.fn.call(listeners.context), true;
13297 case 2: return listeners.fn.call(listeners.context, a1), true;
13298 case 3: return listeners.fn.call(listeners.context, a1, a2), true;
13299 case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;
13300 case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;
13301 case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;
13302 }
13303
13304 for (i = 1, args = new Array(len -1); i < len; i++) {
13305 args[i - 1] = arguments[i];
13306 }
13307
13308 listeners.fn.apply(listeners.context, args);
13309 } else {
13310 var length = listeners.length
13311 , j;
13312
13313 for (i = 0; i < length; i++) {
13314 if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);
13315
13316 switch (len) {
13317 case 1: listeners[i].fn.call(listeners[i].context); break;
13318 case 2: listeners[i].fn.call(listeners[i].context, a1); break;
13319 case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;
13320 case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;
13321 default:
13322 if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {
13323 args[j - 1] = arguments[j];
13324 }
13325
13326 listeners[i].fn.apply(listeners[i].context, args);
13327 }
13328 }
13329 }
13330
13331 return true;
13332 };
13333
13334 /**
13335 * Add a listener for a given event.
13336 *
13337 * @param {(String|Symbol)} event The event name.
13338 * @param {Function} fn The listener function.
13339 * @param {*} [context=this] The context to invoke the listener with.
13340 * @returns {EventEmitter} `this`.
13341 * @public
13342 */
13343 EventEmitter.prototype.on = function on(event, fn, context) {
13344 return addListener(this, event, fn, context, false);
13345 };
13346
13347 /**
13348 * Add a one-time listener for a given event.
13349 *
13350 * @param {(String|Symbol)} event The event name.
13351 * @param {Function} fn The listener function.
13352 * @param {*} [context=this] The context to invoke the listener with.
13353 * @returns {EventEmitter} `this`.
13354 * @public
13355 */
13356 EventEmitter.prototype.once = function once(event, fn, context) {
13357 return addListener(this, event, fn, context, true);
13358 };
13359
13360 /**
13361 * Remove the listeners of a given event.
13362 *
13363 * @param {(String|Symbol)} event The event name.
13364 * @param {Function} fn Only remove the listeners that match this function.
13365 * @param {*} context Only remove the listeners that have this context.
13366 * @param {Boolean} once Only remove one-time listeners.
13367 * @returns {EventEmitter} `this`.
13368 * @public
13369 */
13370 EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {
13371 var evt = prefix ? prefix + event : event;
13372
13373 if (!this._events[evt]) return this;
13374 if (!fn) {
13375 clearEvent(this, evt);
13376 return this;
13377 }
13378
13379 var listeners = this._events[evt];
13380
13381 if (listeners.fn) {
13382 if (
13383 listeners.fn === fn &&
13384 (!once || listeners.once) &&
13385 (!context || listeners.context === context)
13386 ) {
13387 clearEvent(this, evt);
13388 }
13389 } else {
13390 for (var i = 0, events = [], length = listeners.length; i < length; i++) {
13391 if (
13392 listeners[i].fn !== fn ||
13393 (once && !listeners[i].once) ||
13394 (context && listeners[i].context !== context)
13395 ) {
13396 events.push(listeners[i]);
13397 }
13398 }
13399
13400 //
13401 // Reset the array, or remove it completely if we have no more listeners.
13402 //
13403 if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;
13404 else clearEvent(this, evt);
13405 }
13406
13407 return this;
13408 };
13409
13410 /**
13411 * Remove all listeners, or those of the specified event.
13412 *
13413 * @param {(String|Symbol)} [event] The event name.
13414 * @returns {EventEmitter} `this`.
13415 * @public
13416 */
13417 EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {
13418 var evt;
13419
13420 if (event) {
13421 evt = prefix ? prefix + event : event;
13422 if (this._events[evt]) clearEvent(this, evt);
13423 } else {
13424 this._events = new Events();
13425 this._eventsCount = 0;
13426 }
13427
13428 return this;
13429 };
13430
13431 //
13432 // Alias methods names because people roll like that.
13433 //
13434 EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
13435 EventEmitter.prototype.addListener = EventEmitter.prototype.on;
13436
13437 //
13438 // Expose the prefix.
13439 //
13440 EventEmitter.prefixed = prefix;
13441
13442 //
13443 // Allow `EventEmitter` to be imported as module namespace.
13444 //
13445 EventEmitter.EventEmitter = EventEmitter;
13446
13447 //
13448 // Expose the module.
13449 //
13450 {
13451 module.exports = EventEmitter;
13452 }
13453 });
13454
13455 var asyncToGenerator = createCommonjsModule(function (module) {
13456 function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
13457 try {
13458 var info = gen[key](arg);
13459 var value = info.value;
13460 } catch (error) {
13461 reject(error);
13462 return;
13463 }
13464 if (info.done) {
13465 resolve(value);
13466 } else {
13467 Promise.resolve(value).then(_next, _throw);
13468 }
13469 }
13470 function _asyncToGenerator(fn) {
13471 return function () {
13472 var self = this,
13473 args = arguments;
13474 return new Promise(function (resolve, reject) {
13475 var gen = fn.apply(self, args);
13476 function _next(value) {
13477 asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
13478 }
13479 function _throw(err) {
13480 asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
13481 }
13482 _next(undefined);
13483 });
13484 };
13485 }
13486 module.exports = _asyncToGenerator, module.exports.__esModule = true, module.exports["default"] = module.exports;
13487 });
13488
13489 var _asyncToGenerator = unwrapExports(asyncToGenerator);
13490
13491 var arrayLikeToArray = createCommonjsModule(function (module) {
13492 function _arrayLikeToArray(arr, len) {
13493 if (len == null || len > arr.length) len = arr.length;
13494 for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
13495 return arr2;
13496 }
13497 module.exports = _arrayLikeToArray, module.exports.__esModule = true, module.exports["default"] = module.exports;
13498 });
13499
13500 unwrapExports(arrayLikeToArray);
13501
13502 var arrayWithoutHoles = createCommonjsModule(function (module) {
13503 function _arrayWithoutHoles(arr) {
13504 if (Array.isArray(arr)) return arrayLikeToArray(arr);
13505 }
13506 module.exports = _arrayWithoutHoles, module.exports.__esModule = true, module.exports["default"] = module.exports;
13507 });
13508
13509 unwrapExports(arrayWithoutHoles);
13510
13511 var iterableToArray = createCommonjsModule(function (module) {
13512 function _iterableToArray(iter) {
13513 if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
13514 }
13515 module.exports = _iterableToArray, module.exports.__esModule = true, module.exports["default"] = module.exports;
13516 });
13517
13518 unwrapExports(iterableToArray);
13519
13520 var unsupportedIterableToArray = createCommonjsModule(function (module) {
13521 function _unsupportedIterableToArray(o, minLen) {
13522 if (!o) return;
13523 if (typeof o === "string") return arrayLikeToArray(o, minLen);
13524 var n = Object.prototype.toString.call(o).slice(8, -1);
13525 if (n === "Object" && o.constructor) n = o.constructor.name;
13526 if (n === "Map" || n === "Set") return Array.from(o);
13527 if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return arrayLikeToArray(o, minLen);
13528 }
13529 module.exports = _unsupportedIterableToArray, module.exports.__esModule = true, module.exports["default"] = module.exports;
13530 });
13531
13532 unwrapExports(unsupportedIterableToArray);
13533
13534 var nonIterableSpread = createCommonjsModule(function (module) {
13535 function _nonIterableSpread() {
13536 throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
13537 }
13538 module.exports = _nonIterableSpread, module.exports.__esModule = true, module.exports["default"] = module.exports;
13539 });
13540
13541 unwrapExports(nonIterableSpread);
13542
13543 var toConsumableArray = createCommonjsModule(function (module) {
13544 function _toConsumableArray(arr) {
13545 return arrayWithoutHoles(arr) || iterableToArray(arr) || unsupportedIterableToArray(arr) || nonIterableSpread();
13546 }
13547 module.exports = _toConsumableArray, module.exports.__esModule = true, module.exports["default"] = module.exports;
13548 });
13549
13550 var _toConsumableArray$1 = unwrapExports(toConsumableArray);
13551
13552 var objectWithoutPropertiesLoose = createCommonjsModule(function (module) {
13553 function _objectWithoutPropertiesLoose(source, excluded) {
13554 if (source == null) return {};
13555 var target = {};
13556 var sourceKeys = Object.keys(source);
13557 var key, i;
13558 for (i = 0; i < sourceKeys.length; i++) {
13559 key = sourceKeys[i];
13560 if (excluded.indexOf(key) >= 0) continue;
13561 target[key] = source[key];
13562 }
13563 return target;
13564 }
13565 module.exports = _objectWithoutPropertiesLoose, module.exports.__esModule = true, module.exports["default"] = module.exports;
13566 });
13567
13568 unwrapExports(objectWithoutPropertiesLoose);
13569
13570 var objectWithoutProperties = createCommonjsModule(function (module) {
13571 function _objectWithoutProperties(source, excluded) {
13572 if (source == null) return {};
13573 var target = objectWithoutPropertiesLoose(source, excluded);
13574 var key, i;
13575 if (Object.getOwnPropertySymbols) {
13576 var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
13577 for (i = 0; i < sourceSymbolKeys.length; i++) {
13578 key = sourceSymbolKeys[i];
13579 if (excluded.indexOf(key) >= 0) continue;
13580 if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
13581 target[key] = source[key];
13582 }
13583 }
13584 return target;
13585 }
13586 module.exports = _objectWithoutProperties, module.exports.__esModule = true, module.exports["default"] = module.exports;
13587 });
13588
13589 var _objectWithoutProperties = unwrapExports(objectWithoutProperties);
13590
13591 var assertThisInitialized = createCommonjsModule(function (module) {
13592 function _assertThisInitialized(self) {
13593 if (self === void 0) {
13594 throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
13595 }
13596 return self;
13597 }
13598 module.exports = _assertThisInitialized, module.exports.__esModule = true, module.exports["default"] = module.exports;
13599 });
13600
13601 var _assertThisInitialized = unwrapExports(assertThisInitialized);
13602
13603 var setPrototypeOf = createCommonjsModule(function (module) {
13604 function _setPrototypeOf(o, p) {
13605 module.exports = _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
13606 o.__proto__ = p;
13607 return o;
13608 }, module.exports.__esModule = true, module.exports["default"] = module.exports;
13609 return _setPrototypeOf(o, p);
13610 }
13611 module.exports = _setPrototypeOf, module.exports.__esModule = true, module.exports["default"] = module.exports;
13612 });
13613
13614 unwrapExports(setPrototypeOf);
13615
13616 var inheritsLoose = createCommonjsModule(function (module) {
13617 function _inheritsLoose(subClass, superClass) {
13618 subClass.prototype = Object.create(superClass.prototype);
13619 subClass.prototype.constructor = subClass;
13620 setPrototypeOf(subClass, superClass);
13621 }
13622 module.exports = _inheritsLoose, module.exports.__esModule = true, module.exports["default"] = module.exports;
13623 });
13624
13625 var _inheritsLoose = unwrapExports(inheritsLoose);
13626
13627 var regeneratorRuntime$1 = createCommonjsModule(function (module) {
13628 var _typeof = _typeof_1["default"];
13629 function _regeneratorRuntime() {
13630 module.exports = _regeneratorRuntime = function _regeneratorRuntime() {
13631 return exports;
13632 }, module.exports.__esModule = true, module.exports["default"] = module.exports;
13633 var exports = {},
13634 Op = Object.prototype,
13635 hasOwn = Op.hasOwnProperty,
13636 defineProperty = Object.defineProperty || function (obj, key, desc) {
13637 obj[key] = desc.value;
13638 },
13639 $Symbol = "function" == typeof Symbol ? Symbol : {},
13640 iteratorSymbol = $Symbol.iterator || "@@iterator",
13641 asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator",
13642 toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";
13643 function define(obj, key, value) {
13644 return Object.defineProperty(obj, key, {
13645 value: value,
13646 enumerable: !0,
13647 configurable: !0,
13648 writable: !0
13649 }), obj[key];
13650 }
13651 try {
13652 define({}, "");
13653 } catch (err) {
13654 define = function define(obj, key, value) {
13655 return obj[key] = value;
13656 };
13657 }
13658 function wrap(innerFn, outerFn, self, tryLocsList) {
13659 var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator,
13660 generator = Object.create(protoGenerator.prototype),
13661 context = new Context(tryLocsList || []);
13662 return defineProperty(generator, "_invoke", {
13663 value: makeInvokeMethod(innerFn, self, context)
13664 }), generator;
13665 }
13666 function tryCatch(fn, obj, arg) {
13667 try {
13668 return {
13669 type: "normal",
13670 arg: fn.call(obj, arg)
13671 };
13672 } catch (err) {
13673 return {
13674 type: "throw",
13675 arg: err
13676 };
13677 }
13678 }
13679 exports.wrap = wrap;
13680 var ContinueSentinel = {};
13681 function Generator() {}
13682 function GeneratorFunction() {}
13683 function GeneratorFunctionPrototype() {}
13684 var IteratorPrototype = {};
13685 define(IteratorPrototype, iteratorSymbol, function () {
13686 return this;
13687 });
13688 var getProto = Object.getPrototypeOf,
13689 NativeIteratorPrototype = getProto && getProto(getProto(values([])));
13690 NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype);
13691 var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype);
13692 function defineIteratorMethods(prototype) {
13693 ["next", "throw", "return"].forEach(function (method) {
13694 define(prototype, method, function (arg) {
13695 return this._invoke(method, arg);
13696 });
13697 });
13698 }
13699 function AsyncIterator(generator, PromiseImpl) {
13700 function invoke(method, arg, resolve, reject) {
13701 var record = tryCatch(generator[method], generator, arg);
13702 if ("throw" !== record.type) {
13703 var result = record.arg,
13704 value = result.value;
13705 return value && "object" == _typeof(value) && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function (value) {
13706 invoke("next", value, resolve, reject);
13707 }, function (err) {
13708 invoke("throw", err, resolve, reject);
13709 }) : PromiseImpl.resolve(value).then(function (unwrapped) {
13710 result.value = unwrapped, resolve(result);
13711 }, function (error) {
13712 return invoke("throw", error, resolve, reject);
13713 });
13714 }
13715 reject(record.arg);
13716 }
13717 var previousPromise;
13718 defineProperty(this, "_invoke", {
13719 value: function value(method, arg) {
13720 function callInvokeWithMethodAndArg() {
13721 return new PromiseImpl(function (resolve, reject) {
13722 invoke(method, arg, resolve, reject);
13723 });
13724 }
13725 return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg();
13726 }
13727 });
13728 }
13729 function makeInvokeMethod(innerFn, self, context) {
13730 var state = "suspendedStart";
13731 return function (method, arg) {
13732 if ("executing" === state) throw new Error("Generator is already running");
13733 if ("completed" === state) {
13734 if ("throw" === method) throw arg;
13735 return doneResult();
13736 }
13737 for (context.method = method, context.arg = arg;;) {
13738 var delegate = context.delegate;
13739 if (delegate) {
13740 var delegateResult = maybeInvokeDelegate(delegate, context);
13741 if (delegateResult) {
13742 if (delegateResult === ContinueSentinel) continue;
13743 return delegateResult;
13744 }
13745 }
13746 if ("next" === context.method) context.sent = context._sent = context.arg;else if ("throw" === context.method) {
13747 if ("suspendedStart" === state) throw state = "completed", context.arg;
13748 context.dispatchException(context.arg);
13749 } else "return" === context.method && context.abrupt("return", context.arg);
13750 state = "executing";
13751 var record = tryCatch(innerFn, self, context);
13752 if ("normal" === record.type) {
13753 if (state = context.done ? "completed" : "suspendedYield", record.arg === ContinueSentinel) continue;
13754 return {
13755 value: record.arg,
13756 done: context.done
13757 };
13758 }
13759 "throw" === record.type && (state = "completed", context.method = "throw", context.arg = record.arg);
13760 }
13761 };
13762 }
13763 function maybeInvokeDelegate(delegate, context) {
13764 var methodName = context.method,
13765 method = delegate.iterator[methodName];
13766 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;
13767 var record = tryCatch(method, delegate.iterator, context.arg);
13768 if ("throw" === record.type) return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel;
13769 var info = record.arg;
13770 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);
13771 }
13772 function pushTryEntry(locs) {
13773 var entry = {
13774 tryLoc: locs[0]
13775 };
13776 1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry);
13777 }
13778 function resetTryEntry(entry) {
13779 var record = entry.completion || {};
13780 record.type = "normal", delete record.arg, entry.completion = record;
13781 }
13782 function Context(tryLocsList) {
13783 this.tryEntries = [{
13784 tryLoc: "root"
13785 }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0);
13786 }
13787 function values(iterable) {
13788 if (iterable) {
13789 var iteratorMethod = iterable[iteratorSymbol];
13790 if (iteratorMethod) return iteratorMethod.call(iterable);
13791 if ("function" == typeof iterable.next) return iterable;
13792 if (!isNaN(iterable.length)) {
13793 var i = -1,
13794 next = function next() {
13795 for (; ++i < iterable.length;) if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next;
13796 return next.value = undefined, next.done = !0, next;
13797 };
13798 return next.next = next;
13799 }
13800 }
13801 return {
13802 next: doneResult
13803 };
13804 }
13805 function doneResult() {
13806 return {
13807 value: undefined,
13808 done: !0
13809 };
13810 }
13811 return GeneratorFunction.prototype = GeneratorFunctionPrototype, defineProperty(Gp, "constructor", {
13812 value: GeneratorFunctionPrototype,
13813 configurable: !0
13814 }), defineProperty(GeneratorFunctionPrototype, "constructor", {
13815 value: GeneratorFunction,
13816 configurable: !0
13817 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"), exports.isGeneratorFunction = function (genFun) {
13818 var ctor = "function" == typeof genFun && genFun.constructor;
13819 return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === (ctor.displayName || ctor.name));
13820 }, exports.mark = function (genFun) {
13821 return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, "GeneratorFunction")), genFun.prototype = Object.create(Gp), genFun;
13822 }, exports.awrap = function (arg) {
13823 return {
13824 __await: arg
13825 };
13826 }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () {
13827 return this;
13828 }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) {
13829 void 0 === PromiseImpl && (PromiseImpl = Promise);
13830 var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl);
13831 return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) {
13832 return result.done ? result.value : iter.next();
13833 });
13834 }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, "Generator"), define(Gp, iteratorSymbol, function () {
13835 return this;
13836 }), define(Gp, "toString", function () {
13837 return "[object Generator]";
13838 }), exports.keys = function (val) {
13839 var object = Object(val),
13840 keys = [];
13841 for (var key in object) keys.push(key);
13842 return keys.reverse(), function next() {
13843 for (; keys.length;) {
13844 var key = keys.pop();
13845 if (key in object) return next.value = key, next.done = !1, next;
13846 }
13847 return next.done = !0, next;
13848 };
13849 }, exports.values = values, Context.prototype = {
13850 constructor: Context,
13851 reset: function reset(skipTempReset) {
13852 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);
13853 },
13854 stop: function stop() {
13855 this.done = !0;
13856 var rootRecord = this.tryEntries[0].completion;
13857 if ("throw" === rootRecord.type) throw rootRecord.arg;
13858 return this.rval;
13859 },
13860 dispatchException: function dispatchException(exception) {
13861 if (this.done) throw exception;
13862 var context = this;
13863 function handle(loc, caught) {
13864 return record.type = "throw", record.arg = exception, context.next = loc, caught && (context.method = "next", context.arg = undefined), !!caught;
13865 }
13866 for (var i = this.tryEntries.length - 1; i >= 0; --i) {
13867 var entry = this.tryEntries[i],
13868 record = entry.completion;
13869 if ("root" === entry.tryLoc) return handle("end");
13870 if (entry.tryLoc <= this.prev) {
13871 var hasCatch = hasOwn.call(entry, "catchLoc"),
13872 hasFinally = hasOwn.call(entry, "finallyLoc");
13873 if (hasCatch && hasFinally) {
13874 if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0);
13875 if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc);
13876 } else if (hasCatch) {
13877 if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0);
13878 } else {
13879 if (!hasFinally) throw new Error("try statement without catch or finally");
13880 if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc);
13881 }
13882 }
13883 }
13884 },
13885 abrupt: function abrupt(type, arg) {
13886 for (var i = this.tryEntries.length - 1; i >= 0; --i) {
13887 var entry = this.tryEntries[i];
13888 if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) {
13889 var finallyEntry = entry;
13890 break;
13891 }
13892 }
13893 finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null);
13894 var record = finallyEntry ? finallyEntry.completion : {};
13895 return record.type = type, record.arg = arg, finallyEntry ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record);
13896 },
13897 complete: function complete(record, afterLoc) {
13898 if ("throw" === record.type) throw record.arg;
13899 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;
13900 },
13901 finish: function finish(finallyLoc) {
13902 for (var i = this.tryEntries.length - 1; i >= 0; --i) {
13903 var entry = this.tryEntries[i];
13904 if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel;
13905 }
13906 },
13907 "catch": function _catch(tryLoc) {
13908 for (var i = this.tryEntries.length - 1; i >= 0; --i) {
13909 var entry = this.tryEntries[i];
13910 if (entry.tryLoc === tryLoc) {
13911 var record = entry.completion;
13912 if ("throw" === record.type) {
13913 var thrown = record.arg;
13914 resetTryEntry(entry);
13915 }
13916 return thrown;
13917 }
13918 }
13919 throw new Error("illegal catch attempt");
13920 },
13921 delegateYield: function delegateYield(iterable, resultName, nextLoc) {
13922 return this.delegate = {
13923 iterator: values(iterable),
13924 resultName: resultName,
13925 nextLoc: nextLoc
13926 }, "next" === this.method && (this.arg = undefined), ContinueSentinel;
13927 }
13928 }, exports;
13929 }
13930 module.exports = _regeneratorRuntime, module.exports.__esModule = true, module.exports["default"] = module.exports;
13931 });
13932
13933 unwrapExports(regeneratorRuntime$1);
13934
13935 // TODO(Babel 8): Remove this file.
13936
13937 var runtime = regeneratorRuntime$1();
13938 var regenerator = runtime;
13939
13940 // Copied from https://github.com/facebook/regenerator/blob/main/packages/runtime/runtime.js#L736=
13941 try {
13942 regeneratorRuntime = runtime;
13943 } catch (accidentalStrictMode) {
13944 if (typeof globalThis === "object") {
13945 globalThis.regeneratorRuntime = runtime;
13946 } else {
13947 Function("r", "regeneratorRuntime = r")(runtime);
13948 }
13949 }
13950
13951 /**
13952 * Helpers.
13953 */
13954
13955 var s = 1000;
13956 var m = s * 60;
13957 var h = m * 60;
13958 var d = h * 24;
13959 var w = d * 7;
13960 var y = d * 365.25;
13961
13962 /**
13963 * Parse or format the given `val`.
13964 *
13965 * Options:
13966 *
13967 * - `long` verbose formatting [false]
13968 *
13969 * @param {String|Number} val
13970 * @param {Object} [options]
13971 * @throws {Error} throw an error if val is not a non-empty string or a number
13972 * @return {String|Number}
13973 * @api public
13974 */
13975
13976 var ms = function(val, options) {
13977 options = options || {};
13978 var type = typeof val;
13979 if (type === 'string' && val.length > 0) {
13980 return parse(val);
13981 } else if (type === 'number' && isNaN(val) === false) {
13982 return options.long ? fmtLong(val) : fmtShort(val);
13983 }
13984 throw new Error(
13985 'val is not a non-empty string or a valid number. val=' +
13986 JSON.stringify(val)
13987 );
13988 };
13989
13990 /**
13991 * Parse the given `str` and return milliseconds.
13992 *
13993 * @param {String} str
13994 * @return {Number}
13995 * @api private
13996 */
13997
13998 function parse(str) {
13999 str = String(str);
14000 if (str.length > 100) {
14001 return;
14002 }
14003 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(
14004 str
14005 );
14006 if (!match) {
14007 return;
14008 }
14009 var n = parseFloat(match[1]);
14010 var type = (match[2] || 'ms').toLowerCase();
14011 switch (type) {
14012 case 'years':
14013 case 'year':
14014 case 'yrs':
14015 case 'yr':
14016 case 'y':
14017 return n * y;
14018 case 'weeks':
14019 case 'week':
14020 case 'w':
14021 return n * w;
14022 case 'days':
14023 case 'day':
14024 case 'd':
14025 return n * d;
14026 case 'hours':
14027 case 'hour':
14028 case 'hrs':
14029 case 'hr':
14030 case 'h':
14031 return n * h;
14032 case 'minutes':
14033 case 'minute':
14034 case 'mins':
14035 case 'min':
14036 case 'm':
14037 return n * m;
14038 case 'seconds':
14039 case 'second':
14040 case 'secs':
14041 case 'sec':
14042 case 's':
14043 return n * s;
14044 case 'milliseconds':
14045 case 'millisecond':
14046 case 'msecs':
14047 case 'msec':
14048 case 'ms':
14049 return n;
14050 default:
14051 return undefined;
14052 }
14053 }
14054
14055 /**
14056 * Short format for `ms`.
14057 *
14058 * @param {Number} ms
14059 * @return {String}
14060 * @api private
14061 */
14062
14063 function fmtShort(ms) {
14064 var msAbs = Math.abs(ms);
14065 if (msAbs >= d) {
14066 return Math.round(ms / d) + 'd';
14067 }
14068 if (msAbs >= h) {
14069 return Math.round(ms / h) + 'h';
14070 }
14071 if (msAbs >= m) {
14072 return Math.round(ms / m) + 'm';
14073 }
14074 if (msAbs >= s) {
14075 return Math.round(ms / s) + 's';
14076 }
14077 return ms + 'ms';
14078 }
14079
14080 /**
14081 * Long format for `ms`.
14082 *
14083 * @param {Number} ms
14084 * @return {String}
14085 * @api private
14086 */
14087
14088 function fmtLong(ms) {
14089 var msAbs = Math.abs(ms);
14090 if (msAbs >= d) {
14091 return plural(ms, msAbs, d, 'day');
14092 }
14093 if (msAbs >= h) {
14094 return plural(ms, msAbs, h, 'hour');
14095 }
14096 if (msAbs >= m) {
14097 return plural(ms, msAbs, m, 'minute');
14098 }
14099 if (msAbs >= s) {
14100 return plural(ms, msAbs, s, 'second');
14101 }
14102 return ms + ' ms';
14103 }
14104
14105 /**
14106 * Pluralization helper.
14107 */
14108
14109 function plural(ms, msAbs, n, name) {
14110 var isPlural = msAbs >= n * 1.5;
14111 return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');
14112 }
14113
14114 /**
14115 * This is the common logic for both the Node.js and web browser
14116 * implementations of `debug()`.
14117 */
14118 function setup(env) {
14119 createDebug.debug = createDebug;
14120 createDebug.default = createDebug;
14121 createDebug.coerce = coerce;
14122 createDebug.disable = disable;
14123 createDebug.enable = enable;
14124 createDebug.enabled = enabled;
14125 createDebug.humanize = ms;
14126 Object.keys(env).forEach(function (key) {
14127 createDebug[key] = env[key];
14128 });
14129 /**
14130 * Active `debug` instances.
14131 */
14132
14133 createDebug.instances = [];
14134 /**
14135 * The currently active debug mode names, and names to skip.
14136 */
14137
14138 createDebug.names = [];
14139 createDebug.skips = [];
14140 /**
14141 * Map of special "%n" handling functions, for the debug "format" argument.
14142 *
14143 * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
14144 */
14145
14146 createDebug.formatters = {};
14147 /**
14148 * Selects a color for a debug namespace
14149 * @param {String} namespace The namespace string for the for the debug instance to be colored
14150 * @return {Number|String} An ANSI color code for the given namespace
14151 * @api private
14152 */
14153
14154 function selectColor(namespace) {
14155 var hash = 0;
14156
14157 for (var i = 0; i < namespace.length; i++) {
14158 hash = (hash << 5) - hash + namespace.charCodeAt(i);
14159 hash |= 0; // Convert to 32bit integer
14160 }
14161
14162 return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
14163 }
14164
14165 createDebug.selectColor = selectColor;
14166 /**
14167 * Create a debugger with the given `namespace`.
14168 *
14169 * @param {String} namespace
14170 * @return {Function}
14171 * @api public
14172 */
14173
14174 function createDebug(namespace) {
14175 var prevTime;
14176
14177 function debug() {
14178 // Disabled?
14179 if (!debug.enabled) {
14180 return;
14181 }
14182
14183 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
14184 args[_key] = arguments[_key];
14185 }
14186
14187 var self = debug; // Set `diff` timestamp
14188
14189 var curr = Number(new Date());
14190 var ms = curr - (prevTime || curr);
14191 self.diff = ms;
14192 self.prev = prevTime;
14193 self.curr = curr;
14194 prevTime = curr;
14195 args[0] = createDebug.coerce(args[0]);
14196
14197 if (typeof args[0] !== 'string') {
14198 // Anything else let's inspect with %O
14199 args.unshift('%O');
14200 } // Apply any `formatters` transformations
14201
14202
14203 var index = 0;
14204 args[0] = args[0].replace(/%([a-zA-Z%])/g, function (match, format) {
14205 // If we encounter an escaped % then don't increase the array index
14206 if (match === '%%') {
14207 return match;
14208 }
14209
14210 index++;
14211 var formatter = createDebug.formatters[format];
14212
14213 if (typeof formatter === 'function') {
14214 var val = args[index];
14215 match = formatter.call(self, val); // Now we need to remove `args[index]` since it's inlined in the `format`
14216
14217 args.splice(index, 1);
14218 index--;
14219 }
14220
14221 return match;
14222 }); // Apply env-specific formatting (colors, etc.)
14223
14224 createDebug.formatArgs.call(self, args);
14225 var logFn = self.log || createDebug.log;
14226 logFn.apply(self, args);
14227 }
14228
14229 debug.namespace = namespace;
14230 debug.enabled = createDebug.enabled(namespace);
14231 debug.useColors = createDebug.useColors();
14232 debug.color = selectColor(namespace);
14233 debug.destroy = destroy;
14234 debug.extend = extend; // Debug.formatArgs = formatArgs;
14235 // debug.rawLog = rawLog;
14236 // env-specific initialization logic for debug instances
14237
14238 if (typeof createDebug.init === 'function') {
14239 createDebug.init(debug);
14240 }
14241
14242 createDebug.instances.push(debug);
14243 return debug;
14244 }
14245
14246 function destroy() {
14247 var index = createDebug.instances.indexOf(this);
14248
14249 if (index !== -1) {
14250 createDebug.instances.splice(index, 1);
14251 return true;
14252 }
14253
14254 return false;
14255 }
14256
14257 function extend(namespace, delimiter) {
14258 return createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);
14259 }
14260 /**
14261 * Enables a debug mode by namespaces. This can include modes
14262 * separated by a colon and wildcards.
14263 *
14264 * @param {String} namespaces
14265 * @api public
14266 */
14267
14268
14269 function enable(namespaces) {
14270 createDebug.save(namespaces);
14271 createDebug.names = [];
14272 createDebug.skips = [];
14273 var i;
14274 var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
14275 var len = split.length;
14276
14277 for (i = 0; i < len; i++) {
14278 if (!split[i]) {
14279 // ignore empty strings
14280 continue;
14281 }
14282
14283 namespaces = split[i].replace(/\*/g, '.*?');
14284
14285 if (namespaces[0] === '-') {
14286 createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
14287 } else {
14288 createDebug.names.push(new RegExp('^' + namespaces + '$'));
14289 }
14290 }
14291
14292 for (i = 0; i < createDebug.instances.length; i++) {
14293 var instance = createDebug.instances[i];
14294 instance.enabled = createDebug.enabled(instance.namespace);
14295 }
14296 }
14297 /**
14298 * Disable debug output.
14299 *
14300 * @api public
14301 */
14302
14303
14304 function disable() {
14305 createDebug.enable('');
14306 }
14307 /**
14308 * Returns true if the given mode name is enabled, false otherwise.
14309 *
14310 * @param {String} name
14311 * @return {Boolean}
14312 * @api public
14313 */
14314
14315
14316 function enabled(name) {
14317 if (name[name.length - 1] === '*') {
14318 return true;
14319 }
14320
14321 var i;
14322 var len;
14323
14324 for (i = 0, len = createDebug.skips.length; i < len; i++) {
14325 if (createDebug.skips[i].test(name)) {
14326 return false;
14327 }
14328 }
14329
14330 for (i = 0, len = createDebug.names.length; i < len; i++) {
14331 if (createDebug.names[i].test(name)) {
14332 return true;
14333 }
14334 }
14335
14336 return false;
14337 }
14338 /**
14339 * Coerce `val`.
14340 *
14341 * @param {Mixed} val
14342 * @return {Mixed}
14343 * @api private
14344 */
14345
14346
14347 function coerce(val) {
14348 if (val instanceof Error) {
14349 return val.stack || val.message;
14350 }
14351
14352 return val;
14353 }
14354
14355 createDebug.enable(createDebug.load());
14356 return createDebug;
14357 }
14358
14359 var common = setup;
14360
14361 var browser = createCommonjsModule(function (module, exports) {
14362
14363 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); }
14364
14365 /* eslint-env browser */
14366
14367 /**
14368 * This is the web browser implementation of `debug()`.
14369 */
14370 exports.log = log;
14371 exports.formatArgs = formatArgs;
14372 exports.save = save;
14373 exports.load = load;
14374 exports.useColors = useColors;
14375 exports.storage = localstorage();
14376 /**
14377 * Colors.
14378 */
14379
14380 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'];
14381 /**
14382 * Currently only WebKit-based Web Inspectors, Firefox >= v31,
14383 * and the Firebug extension (any Firefox version) are known
14384 * to support "%c" CSS customizations.
14385 *
14386 * TODO: add a `localStorage` variable to explicitly enable/disable colors
14387 */
14388 // eslint-disable-next-line complexity
14389
14390 function useColors() {
14391 // NB: In an Electron preload script, document will be defined but not fully
14392 // initialized. Since we know we're in Chrome, we'll just detect this case
14393 // explicitly
14394 if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {
14395 return true;
14396 } // Internet Explorer and Edge do not support colors.
14397
14398
14399 if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
14400 return false;
14401 } // Is webkit? http://stackoverflow.com/a/16459606/376773
14402 // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
14403
14404
14405 return typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || // Is firebug? http://stackoverflow.com/a/398120/376773
14406 typeof window !== 'undefined' && window.console && (window.console.firebug || window.console.exception && window.console.table) || // Is firefox >= v31?
14407 // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
14408 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
14409 typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/);
14410 }
14411 /**
14412 * Colorize log arguments if enabled.
14413 *
14414 * @api public
14415 */
14416
14417
14418 function formatArgs(args) {
14419 args[0] = (this.useColors ? '%c' : '') + this.namespace + (this.useColors ? ' %c' : ' ') + args[0] + (this.useColors ? '%c ' : ' ') + '+' + module.exports.humanize(this.diff);
14420
14421 if (!this.useColors) {
14422 return;
14423 }
14424
14425 var c = 'color: ' + this.color;
14426 args.splice(1, 0, c, 'color: inherit'); // The final "%c" is somewhat tricky, because there could be other
14427 // arguments passed either before or after the %c, so we need to
14428 // figure out the correct index to insert the CSS into
14429
14430 var index = 0;
14431 var lastC = 0;
14432 args[0].replace(/%[a-zA-Z%]/g, function (match) {
14433 if (match === '%%') {
14434 return;
14435 }
14436
14437 index++;
14438
14439 if (match === '%c') {
14440 // We only are interested in the *last* %c
14441 // (the user may have provided their own)
14442 lastC = index;
14443 }
14444 });
14445 args.splice(lastC, 0, c);
14446 }
14447 /**
14448 * Invokes `console.log()` when available.
14449 * No-op when `console.log` is not a "function".
14450 *
14451 * @api public
14452 */
14453
14454
14455 function log() {
14456 var _console;
14457
14458 // This hackery is required for IE8/9, where
14459 // the `console.log` function doesn't have 'apply'
14460 return (typeof console === "undefined" ? "undefined" : _typeof(console)) === 'object' && console.log && (_console = console).log.apply(_console, arguments);
14461 }
14462 /**
14463 * Save `namespaces`.
14464 *
14465 * @param {String} namespaces
14466 * @api private
14467 */
14468
14469
14470 function save(namespaces) {
14471 try {
14472 if (namespaces) {
14473 exports.storage.setItem('debug', namespaces);
14474 } else {
14475 exports.storage.removeItem('debug');
14476 }
14477 } catch (error) {// Swallow
14478 // XXX (@Qix-) should we be logging these?
14479 }
14480 }
14481 /**
14482 * Load `namespaces`.
14483 *
14484 * @return {String} returns the previously persisted debug modes
14485 * @api private
14486 */
14487
14488
14489 function load() {
14490 var r;
14491
14492 try {
14493 r = exports.storage.getItem('debug');
14494 } catch (error) {} // Swallow
14495 // XXX (@Qix-) should we be logging these?
14496 // If debug isn't set in LS, and we're in Electron, try to load $DEBUG
14497
14498
14499 if (!r && typeof process !== 'undefined' && 'env' in process) {
14500 r = process.env.DEBUG;
14501 }
14502
14503 return r;
14504 }
14505 /**
14506 * Localstorage attempts to return the localstorage.
14507 *
14508 * This is necessary because safari throws
14509 * when a user disables cookies/localstorage
14510 * and you attempt to access it.
14511 *
14512 * @return {LocalStorage}
14513 * @api private
14514 */
14515
14516
14517 function localstorage() {
14518 try {
14519 // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context
14520 // The Browser also has localStorage in the global context.
14521 return localStorage;
14522 } catch (error) {// Swallow
14523 // XXX (@Qix-) should we be logging these?
14524 }
14525 }
14526
14527 module.exports = common(exports);
14528 var formatters = module.exports.formatters;
14529 /**
14530 * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
14531 */
14532
14533 formatters.j = function (v) {
14534 try {
14535 return JSON.stringify(v);
14536 } catch (error) {
14537 return '[UnexpectedJSONParseError]: ' + error.message;
14538 }
14539 };
14540 });
14541 var browser_1 = browser.log;
14542 var browser_2 = browser.formatArgs;
14543 var browser_3 = browser.save;
14544 var browser_4 = browser.load;
14545 var browser_5 = browser.useColors;
14546 var browser_6 = browser.storage;
14547 var browser_7 = browser.colors;
14548
14549 /**
14550 * Copies the values of `source` to `array`.
14551 *
14552 * @private
14553 * @param {Array} source The array to copy values from.
14554 * @param {Array} [array=[]] The array to copy values to.
14555 * @returns {Array} Returns `array`.
14556 */
14557 function copyArray(source, array) {
14558 var index = -1,
14559 length = source.length;
14560
14561 array || (array = Array(length));
14562 while (++index < length) {
14563 array[index] = source[index];
14564 }
14565 return array;
14566 }
14567
14568 var _copyArray = copyArray;
14569
14570 /* Built-in method references for those with the same name as other `lodash` methods. */
14571 var nativeFloor = Math.floor,
14572 nativeRandom = Math.random;
14573
14574 /**
14575 * The base implementation of `_.random` without support for returning
14576 * floating-point numbers.
14577 *
14578 * @private
14579 * @param {number} lower The lower bound.
14580 * @param {number} upper The upper bound.
14581 * @returns {number} Returns the random number.
14582 */
14583 function baseRandom(lower, upper) {
14584 return lower + nativeFloor(nativeRandom() * (upper - lower + 1));
14585 }
14586
14587 var _baseRandom = baseRandom;
14588
14589 /**
14590 * A specialized version of `_.shuffle` which mutates and sets the size of `array`.
14591 *
14592 * @private
14593 * @param {Array} array The array to shuffle.
14594 * @param {number} [size=array.length] The size of `array`.
14595 * @returns {Array} Returns `array`.
14596 */
14597 function shuffleSelf(array, size) {
14598 var index = -1,
14599 length = array.length,
14600 lastIndex = length - 1;
14601
14602 size = size === undefined ? length : size;
14603 while (++index < size) {
14604 var rand = _baseRandom(index, lastIndex),
14605 value = array[rand];
14606
14607 array[rand] = array[index];
14608 array[index] = value;
14609 }
14610 array.length = size;
14611 return array;
14612 }
14613
14614 var _shuffleSelf = shuffleSelf;
14615
14616 /**
14617 * A specialized version of `_.shuffle` for arrays.
14618 *
14619 * @private
14620 * @param {Array} array The array to shuffle.
14621 * @returns {Array} Returns the new shuffled array.
14622 */
14623 function arrayShuffle(array) {
14624 return _shuffleSelf(_copyArray(array));
14625 }
14626
14627 var _arrayShuffle = arrayShuffle;
14628
14629 /**
14630 * A specialized version of `_.map` for arrays without support for iteratee
14631 * shorthands.
14632 *
14633 * @private
14634 * @param {Array} [array] The array to iterate over.
14635 * @param {Function} iteratee The function invoked per iteration.
14636 * @returns {Array} Returns the new mapped array.
14637 */
14638 function arrayMap(array, iteratee) {
14639 var index = -1,
14640 length = array == null ? 0 : array.length,
14641 result = Array(length);
14642
14643 while (++index < length) {
14644 result[index] = iteratee(array[index], index, array);
14645 }
14646 return result;
14647 }
14648
14649 var _arrayMap = arrayMap;
14650
14651 /**
14652 * The base implementation of `_.values` and `_.valuesIn` which creates an
14653 * array of `object` property values corresponding to the property names
14654 * of `props`.
14655 *
14656 * @private
14657 * @param {Object} object The object to query.
14658 * @param {Array} props The property names to get values for.
14659 * @returns {Object} Returns the array of property values.
14660 */
14661 function baseValues(object, props) {
14662 return _arrayMap(props, function(key) {
14663 return object[key];
14664 });
14665 }
14666
14667 var _baseValues = baseValues;
14668
14669 /**
14670 * The base implementation of `_.times` without support for iteratee shorthands
14671 * or max array length checks.
14672 *
14673 * @private
14674 * @param {number} n The number of times to invoke `iteratee`.
14675 * @param {Function} iteratee The function invoked per iteration.
14676 * @returns {Array} Returns the array of results.
14677 */
14678 function baseTimes(n, iteratee) {
14679 var index = -1,
14680 result = Array(n);
14681
14682 while (++index < n) {
14683 result[index] = iteratee(index);
14684 }
14685 return result;
14686 }
14687
14688 var _baseTimes = baseTimes;
14689
14690 /** Detect free variable `global` from Node.js. */
14691 var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal;
14692
14693 var _freeGlobal = freeGlobal;
14694
14695 /** Detect free variable `self`. */
14696 var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
14697
14698 /** Used as a reference to the global object. */
14699 var root = _freeGlobal || freeSelf || Function('return this')();
14700
14701 var _root = root;
14702
14703 /** Built-in value references. */
14704 var Symbol$1 = _root.Symbol;
14705
14706 var _Symbol = Symbol$1;
14707
14708 /** Used for built-in method references. */
14709 var objectProto = Object.prototype;
14710
14711 /** Used to check objects for own properties. */
14712 var hasOwnProperty = objectProto.hasOwnProperty;
14713
14714 /**
14715 * Used to resolve the
14716 * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
14717 * of values.
14718 */
14719 var nativeObjectToString = objectProto.toString;
14720
14721 /** Built-in value references. */
14722 var symToStringTag = _Symbol ? _Symbol.toStringTag : undefined;
14723
14724 /**
14725 * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
14726 *
14727 * @private
14728 * @param {*} value The value to query.
14729 * @returns {string} Returns the raw `toStringTag`.
14730 */
14731 function getRawTag(value) {
14732 var isOwn = hasOwnProperty.call(value, symToStringTag),
14733 tag = value[symToStringTag];
14734
14735 try {
14736 value[symToStringTag] = undefined;
14737 var unmasked = true;
14738 } catch (e) {}
14739
14740 var result = nativeObjectToString.call(value);
14741 if (unmasked) {
14742 if (isOwn) {
14743 value[symToStringTag] = tag;
14744 } else {
14745 delete value[symToStringTag];
14746 }
14747 }
14748 return result;
14749 }
14750
14751 var _getRawTag = getRawTag;
14752
14753 /** Used for built-in method references. */
14754 var objectProto$1 = Object.prototype;
14755
14756 /**
14757 * Used to resolve the
14758 * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
14759 * of values.
14760 */
14761 var nativeObjectToString$1 = objectProto$1.toString;
14762
14763 /**
14764 * Converts `value` to a string using `Object.prototype.toString`.
14765 *
14766 * @private
14767 * @param {*} value The value to convert.
14768 * @returns {string} Returns the converted string.
14769 */
14770 function objectToString(value) {
14771 return nativeObjectToString$1.call(value);
14772 }
14773
14774 var _objectToString = objectToString;
14775
14776 /** `Object#toString` result references. */
14777 var nullTag = '[object Null]',
14778 undefinedTag = '[object Undefined]';
14779
14780 /** Built-in value references. */
14781 var symToStringTag$1 = _Symbol ? _Symbol.toStringTag : undefined;
14782
14783 /**
14784 * The base implementation of `getTag` without fallbacks for buggy environments.
14785 *
14786 * @private
14787 * @param {*} value The value to query.
14788 * @returns {string} Returns the `toStringTag`.
14789 */
14790 function baseGetTag(value) {
14791 if (value == null) {
14792 return value === undefined ? undefinedTag : nullTag;
14793 }
14794 return (symToStringTag$1 && symToStringTag$1 in Object(value))
14795 ? _getRawTag(value)
14796 : _objectToString(value);
14797 }
14798
14799 var _baseGetTag = baseGetTag;
14800
14801 /**
14802 * Checks if `value` is object-like. A value is object-like if it's not `null`
14803 * and has a `typeof` result of "object".
14804 *
14805 * @static
14806 * @memberOf _
14807 * @since 4.0.0
14808 * @category Lang
14809 * @param {*} value The value to check.
14810 * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
14811 * @example
14812 *
14813 * _.isObjectLike({});
14814 * // => true
14815 *
14816 * _.isObjectLike([1, 2, 3]);
14817 * // => true
14818 *
14819 * _.isObjectLike(_.noop);
14820 * // => false
14821 *
14822 * _.isObjectLike(null);
14823 * // => false
14824 */
14825 function isObjectLike(value) {
14826 return value != null && typeof value == 'object';
14827 }
14828
14829 var isObjectLike_1 = isObjectLike;
14830
14831 /** `Object#toString` result references. */
14832 var argsTag = '[object Arguments]';
14833
14834 /**
14835 * The base implementation of `_.isArguments`.
14836 *
14837 * @private
14838 * @param {*} value The value to check.
14839 * @returns {boolean} Returns `true` if `value` is an `arguments` object,
14840 */
14841 function baseIsArguments(value) {
14842 return isObjectLike_1(value) && _baseGetTag(value) == argsTag;
14843 }
14844
14845 var _baseIsArguments = baseIsArguments;
14846
14847 /** Used for built-in method references. */
14848 var objectProto$2 = Object.prototype;
14849
14850 /** Used to check objects for own properties. */
14851 var hasOwnProperty$1 = objectProto$2.hasOwnProperty;
14852
14853 /** Built-in value references. */
14854 var propertyIsEnumerable = objectProto$2.propertyIsEnumerable;
14855
14856 /**
14857 * Checks if `value` is likely an `arguments` object.
14858 *
14859 * @static
14860 * @memberOf _
14861 * @since 0.1.0
14862 * @category Lang
14863 * @param {*} value The value to check.
14864 * @returns {boolean} Returns `true` if `value` is an `arguments` object,
14865 * else `false`.
14866 * @example
14867 *
14868 * _.isArguments(function() { return arguments; }());
14869 * // => true
14870 *
14871 * _.isArguments([1, 2, 3]);
14872 * // => false
14873 */
14874 var isArguments = _baseIsArguments(function() { return arguments; }()) ? _baseIsArguments : function(value) {
14875 return isObjectLike_1(value) && hasOwnProperty$1.call(value, 'callee') &&
14876 !propertyIsEnumerable.call(value, 'callee');
14877 };
14878
14879 var isArguments_1 = isArguments;
14880
14881 /**
14882 * Checks if `value` is classified as an `Array` object.
14883 *
14884 * @static
14885 * @memberOf _
14886 * @since 0.1.0
14887 * @category Lang
14888 * @param {*} value The value to check.
14889 * @returns {boolean} Returns `true` if `value` is an array, else `false`.
14890 * @example
14891 *
14892 * _.isArray([1, 2, 3]);
14893 * // => true
14894 *
14895 * _.isArray(document.body.children);
14896 * // => false
14897 *
14898 * _.isArray('abc');
14899 * // => false
14900 *
14901 * _.isArray(_.noop);
14902 * // => false
14903 */
14904 var isArray = Array.isArray;
14905
14906 var isArray_1 = isArray;
14907
14908 /**
14909 * This method returns `false`.
14910 *
14911 * @static
14912 * @memberOf _
14913 * @since 4.13.0
14914 * @category Util
14915 * @returns {boolean} Returns `false`.
14916 * @example
14917 *
14918 * _.times(2, _.stubFalse);
14919 * // => [false, false]
14920 */
14921 function stubFalse() {
14922 return false;
14923 }
14924
14925 var stubFalse_1 = stubFalse;
14926
14927 var isBuffer_1 = createCommonjsModule(function (module, exports) {
14928 /** Detect free variable `exports`. */
14929 var freeExports = exports && !exports.nodeType && exports;
14930
14931 /** Detect free variable `module`. */
14932 var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module;
14933
14934 /** Detect the popular CommonJS extension `module.exports`. */
14935 var moduleExports = freeModule && freeModule.exports === freeExports;
14936
14937 /** Built-in value references. */
14938 var Buffer = moduleExports ? _root.Buffer : undefined;
14939
14940 /* Built-in method references for those with the same name as other `lodash` methods. */
14941 var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined;
14942
14943 /**
14944 * Checks if `value` is a buffer.
14945 *
14946 * @static
14947 * @memberOf _
14948 * @since 4.3.0
14949 * @category Lang
14950 * @param {*} value The value to check.
14951 * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.
14952 * @example
14953 *
14954 * _.isBuffer(new Buffer(2));
14955 * // => true
14956 *
14957 * _.isBuffer(new Uint8Array(2));
14958 * // => false
14959 */
14960 var isBuffer = nativeIsBuffer || stubFalse_1;
14961
14962 module.exports = isBuffer;
14963 });
14964
14965 /** Used as references for various `Number` constants. */
14966 var MAX_SAFE_INTEGER = 9007199254740991;
14967
14968 /** Used to detect unsigned integer values. */
14969 var reIsUint = /^(?:0|[1-9]\d*)$/;
14970
14971 /**
14972 * Checks if `value` is a valid array-like index.
14973 *
14974 * @private
14975 * @param {*} value The value to check.
14976 * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
14977 * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
14978 */
14979 function isIndex(value, length) {
14980 var type = typeof value;
14981 length = length == null ? MAX_SAFE_INTEGER : length;
14982
14983 return !!length &&
14984 (type == 'number' ||
14985 (type != 'symbol' && reIsUint.test(value))) &&
14986 (value > -1 && value % 1 == 0 && value < length);
14987 }
14988
14989 var _isIndex = isIndex;
14990
14991 /** Used as references for various `Number` constants. */
14992 var MAX_SAFE_INTEGER$1 = 9007199254740991;
14993
14994 /**
14995 * Checks if `value` is a valid array-like length.
14996 *
14997 * **Note:** This method is loosely based on
14998 * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
14999 *
15000 * @static
15001 * @memberOf _
15002 * @since 4.0.0
15003 * @category Lang
15004 * @param {*} value The value to check.
15005 * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
15006 * @example
15007 *
15008 * _.isLength(3);
15009 * // => true
15010 *
15011 * _.isLength(Number.MIN_VALUE);
15012 * // => false
15013 *
15014 * _.isLength(Infinity);
15015 * // => false
15016 *
15017 * _.isLength('3');
15018 * // => false
15019 */
15020 function isLength(value) {
15021 return typeof value == 'number' &&
15022 value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER$1;
15023 }
15024
15025 var isLength_1 = isLength;
15026
15027 /** `Object#toString` result references. */
15028 var argsTag$1 = '[object Arguments]',
15029 arrayTag = '[object Array]',
15030 boolTag = '[object Boolean]',
15031 dateTag = '[object Date]',
15032 errorTag = '[object Error]',
15033 funcTag = '[object Function]',
15034 mapTag = '[object Map]',
15035 numberTag = '[object Number]',
15036 objectTag = '[object Object]',
15037 regexpTag = '[object RegExp]',
15038 setTag = '[object Set]',
15039 stringTag = '[object String]',
15040 weakMapTag = '[object WeakMap]';
15041
15042 var arrayBufferTag = '[object ArrayBuffer]',
15043 dataViewTag = '[object DataView]',
15044 float32Tag = '[object Float32Array]',
15045 float64Tag = '[object Float64Array]',
15046 int8Tag = '[object Int8Array]',
15047 int16Tag = '[object Int16Array]',
15048 int32Tag = '[object Int32Array]',
15049 uint8Tag = '[object Uint8Array]',
15050 uint8ClampedTag = '[object Uint8ClampedArray]',
15051 uint16Tag = '[object Uint16Array]',
15052 uint32Tag = '[object Uint32Array]';
15053
15054 /** Used to identify `toStringTag` values of typed arrays. */
15055 var typedArrayTags = {};
15056 typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =
15057 typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =
15058 typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =
15059 typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =
15060 typedArrayTags[uint32Tag] = true;
15061 typedArrayTags[argsTag$1] = typedArrayTags[arrayTag] =
15062 typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =
15063 typedArrayTags[dataViewTag] = typedArrayTags[dateTag] =
15064 typedArrayTags[errorTag] = typedArrayTags[funcTag] =
15065 typedArrayTags[mapTag] = typedArrayTags[numberTag] =
15066 typedArrayTags[objectTag] = typedArrayTags[regexpTag] =
15067 typedArrayTags[setTag] = typedArrayTags[stringTag] =
15068 typedArrayTags[weakMapTag] = false;
15069
15070 /**
15071 * The base implementation of `_.isTypedArray` without Node.js optimizations.
15072 *
15073 * @private
15074 * @param {*} value The value to check.
15075 * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
15076 */
15077 function baseIsTypedArray(value) {
15078 return isObjectLike_1(value) &&
15079 isLength_1(value.length) && !!typedArrayTags[_baseGetTag(value)];
15080 }
15081
15082 var _baseIsTypedArray = baseIsTypedArray;
15083
15084 /**
15085 * The base implementation of `_.unary` without support for storing metadata.
15086 *
15087 * @private
15088 * @param {Function} func The function to cap arguments for.
15089 * @returns {Function} Returns the new capped function.
15090 */
15091 function baseUnary(func) {
15092 return function(value) {
15093 return func(value);
15094 };
15095 }
15096
15097 var _baseUnary = baseUnary;
15098
15099 var _nodeUtil = createCommonjsModule(function (module, exports) {
15100 /** Detect free variable `exports`. */
15101 var freeExports = exports && !exports.nodeType && exports;
15102
15103 /** Detect free variable `module`. */
15104 var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module;
15105
15106 /** Detect the popular CommonJS extension `module.exports`. */
15107 var moduleExports = freeModule && freeModule.exports === freeExports;
15108
15109 /** Detect free variable `process` from Node.js. */
15110 var freeProcess = moduleExports && _freeGlobal.process;
15111
15112 /** Used to access faster Node.js helpers. */
15113 var nodeUtil = (function() {
15114 try {
15115 // Use `util.types` for Node.js 10+.
15116 var types = freeModule && freeModule.require && freeModule.require('util').types;
15117
15118 if (types) {
15119 return types;
15120 }
15121
15122 // Legacy `process.binding('util')` for Node.js < 10.
15123 return freeProcess && freeProcess.binding && freeProcess.binding('util');
15124 } catch (e) {}
15125 }());
15126
15127 module.exports = nodeUtil;
15128 });
15129
15130 /* Node.js helper references. */
15131 var nodeIsTypedArray = _nodeUtil && _nodeUtil.isTypedArray;
15132
15133 /**
15134 * Checks if `value` is classified as a typed array.
15135 *
15136 * @static
15137 * @memberOf _
15138 * @since 3.0.0
15139 * @category Lang
15140 * @param {*} value The value to check.
15141 * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
15142 * @example
15143 *
15144 * _.isTypedArray(new Uint8Array);
15145 * // => true
15146 *
15147 * _.isTypedArray([]);
15148 * // => false
15149 */
15150 var isTypedArray = nodeIsTypedArray ? _baseUnary(nodeIsTypedArray) : _baseIsTypedArray;
15151
15152 var isTypedArray_1 = isTypedArray;
15153
15154 /** Used for built-in method references. */
15155 var objectProto$3 = Object.prototype;
15156
15157 /** Used to check objects for own properties. */
15158 var hasOwnProperty$2 = objectProto$3.hasOwnProperty;
15159
15160 /**
15161 * Creates an array of the enumerable property names of the array-like `value`.
15162 *
15163 * @private
15164 * @param {*} value The value to query.
15165 * @param {boolean} inherited Specify returning inherited property names.
15166 * @returns {Array} Returns the array of property names.
15167 */
15168 function arrayLikeKeys(value, inherited) {
15169 var isArr = isArray_1(value),
15170 isArg = !isArr && isArguments_1(value),
15171 isBuff = !isArr && !isArg && isBuffer_1(value),
15172 isType = !isArr && !isArg && !isBuff && isTypedArray_1(value),
15173 skipIndexes = isArr || isArg || isBuff || isType,
15174 result = skipIndexes ? _baseTimes(value.length, String) : [],
15175 length = result.length;
15176
15177 for (var key in value) {
15178 if ((inherited || hasOwnProperty$2.call(value, key)) &&
15179 !(skipIndexes && (
15180 // Safari 9 has enumerable `arguments.length` in strict mode.
15181 key == 'length' ||
15182 // Node.js 0.10 has enumerable non-index properties on buffers.
15183 (isBuff && (key == 'offset' || key == 'parent')) ||
15184 // PhantomJS 2 has enumerable non-index properties on typed arrays.
15185 (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) ||
15186 // Skip index properties.
15187 _isIndex(key, length)
15188 ))) {
15189 result.push(key);
15190 }
15191 }
15192 return result;
15193 }
15194
15195 var _arrayLikeKeys = arrayLikeKeys;
15196
15197 /** Used for built-in method references. */
15198 var objectProto$4 = Object.prototype;
15199
15200 /**
15201 * Checks if `value` is likely a prototype object.
15202 *
15203 * @private
15204 * @param {*} value The value to check.
15205 * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
15206 */
15207 function isPrototype(value) {
15208 var Ctor = value && value.constructor,
15209 proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto$4;
15210
15211 return value === proto;
15212 }
15213
15214 var _isPrototype = isPrototype;
15215
15216 /**
15217 * Creates a unary function that invokes `func` with its argument transformed.
15218 *
15219 * @private
15220 * @param {Function} func The function to wrap.
15221 * @param {Function} transform The argument transform.
15222 * @returns {Function} Returns the new function.
15223 */
15224 function overArg(func, transform) {
15225 return function(arg) {
15226 return func(transform(arg));
15227 };
15228 }
15229
15230 var _overArg = overArg;
15231
15232 /* Built-in method references for those with the same name as other `lodash` methods. */
15233 var nativeKeys = _overArg(Object.keys, Object);
15234
15235 var _nativeKeys = nativeKeys;
15236
15237 /** Used for built-in method references. */
15238 var objectProto$5 = Object.prototype;
15239
15240 /** Used to check objects for own properties. */
15241 var hasOwnProperty$3 = objectProto$5.hasOwnProperty;
15242
15243 /**
15244 * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
15245 *
15246 * @private
15247 * @param {Object} object The object to query.
15248 * @returns {Array} Returns the array of property names.
15249 */
15250 function baseKeys(object) {
15251 if (!_isPrototype(object)) {
15252 return _nativeKeys(object);
15253 }
15254 var result = [];
15255 for (var key in Object(object)) {
15256 if (hasOwnProperty$3.call(object, key) && key != 'constructor') {
15257 result.push(key);
15258 }
15259 }
15260 return result;
15261 }
15262
15263 var _baseKeys = baseKeys;
15264
15265 /**
15266 * Checks if `value` is the
15267 * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
15268 * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
15269 *
15270 * @static
15271 * @memberOf _
15272 * @since 0.1.0
15273 * @category Lang
15274 * @param {*} value The value to check.
15275 * @returns {boolean} Returns `true` if `value` is an object, else `false`.
15276 * @example
15277 *
15278 * _.isObject({});
15279 * // => true
15280 *
15281 * _.isObject([1, 2, 3]);
15282 * // => true
15283 *
15284 * _.isObject(_.noop);
15285 * // => true
15286 *
15287 * _.isObject(null);
15288 * // => false
15289 */
15290 function isObject$1(value) {
15291 var type = typeof value;
15292 return value != null && (type == 'object' || type == 'function');
15293 }
15294
15295 var isObject_1$1 = isObject$1;
15296
15297 /** `Object#toString` result references. */
15298 var asyncTag = '[object AsyncFunction]',
15299 funcTag$1 = '[object Function]',
15300 genTag = '[object GeneratorFunction]',
15301 proxyTag = '[object Proxy]';
15302
15303 /**
15304 * Checks if `value` is classified as a `Function` object.
15305 *
15306 * @static
15307 * @memberOf _
15308 * @since 0.1.0
15309 * @category Lang
15310 * @param {*} value The value to check.
15311 * @returns {boolean} Returns `true` if `value` is a function, else `false`.
15312 * @example
15313 *
15314 * _.isFunction(_);
15315 * // => true
15316 *
15317 * _.isFunction(/abc/);
15318 * // => false
15319 */
15320 function isFunction(value) {
15321 if (!isObject_1$1(value)) {
15322 return false;
15323 }
15324 // The use of `Object#toString` avoids issues with the `typeof` operator
15325 // in Safari 9 which returns 'object' for typed arrays and other constructors.
15326 var tag = _baseGetTag(value);
15327 return tag == funcTag$1 || tag == genTag || tag == asyncTag || tag == proxyTag;
15328 }
15329
15330 var isFunction_1 = isFunction;
15331
15332 /**
15333 * Checks if `value` is array-like. A value is considered array-like if it's
15334 * not a function and has a `value.length` that's an integer greater than or
15335 * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
15336 *
15337 * @static
15338 * @memberOf _
15339 * @since 4.0.0
15340 * @category Lang
15341 * @param {*} value The value to check.
15342 * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
15343 * @example
15344 *
15345 * _.isArrayLike([1, 2, 3]);
15346 * // => true
15347 *
15348 * _.isArrayLike(document.body.children);
15349 * // => true
15350 *
15351 * _.isArrayLike('abc');
15352 * // => true
15353 *
15354 * _.isArrayLike(_.noop);
15355 * // => false
15356 */
15357 function isArrayLike(value) {
15358 return value != null && isLength_1(value.length) && !isFunction_1(value);
15359 }
15360
15361 var isArrayLike_1 = isArrayLike;
15362
15363 /**
15364 * Creates an array of the own enumerable property names of `object`.
15365 *
15366 * **Note:** Non-object values are coerced to objects. See the
15367 * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
15368 * for more details.
15369 *
15370 * @static
15371 * @since 0.1.0
15372 * @memberOf _
15373 * @category Object
15374 * @param {Object} object The object to query.
15375 * @returns {Array} Returns the array of property names.
15376 * @example
15377 *
15378 * function Foo() {
15379 * this.a = 1;
15380 * this.b = 2;
15381 * }
15382 *
15383 * Foo.prototype.c = 3;
15384 *
15385 * _.keys(new Foo);
15386 * // => ['a', 'b'] (iteration order is not guaranteed)
15387 *
15388 * _.keys('hi');
15389 * // => ['0', '1']
15390 */
15391 function keys(object) {
15392 return isArrayLike_1(object) ? _arrayLikeKeys(object) : _baseKeys(object);
15393 }
15394
15395 var keys_1 = keys;
15396
15397 /**
15398 * Creates an array of the own enumerable string keyed property values of `object`.
15399 *
15400 * **Note:** Non-object values are coerced to objects.
15401 *
15402 * @static
15403 * @since 0.1.0
15404 * @memberOf _
15405 * @category Object
15406 * @param {Object} object The object to query.
15407 * @returns {Array} Returns the array of property values.
15408 * @example
15409 *
15410 * function Foo() {
15411 * this.a = 1;
15412 * this.b = 2;
15413 * }
15414 *
15415 * Foo.prototype.c = 3;
15416 *
15417 * _.values(new Foo);
15418 * // => [1, 2] (iteration order is not guaranteed)
15419 *
15420 * _.values('hi');
15421 * // => ['h', 'i']
15422 */
15423 function values(object) {
15424 return object == null ? [] : _baseValues(object, keys_1(object));
15425 }
15426
15427 var values_1 = values;
15428
15429 /**
15430 * The base implementation of `_.shuffle`.
15431 *
15432 * @private
15433 * @param {Array|Object} collection The collection to shuffle.
15434 * @returns {Array} Returns the new shuffled array.
15435 */
15436 function baseShuffle(collection) {
15437 return _shuffleSelf(values_1(collection));
15438 }
15439
15440 var _baseShuffle = baseShuffle;
15441
15442 /**
15443 * Creates an array of shuffled values, using a version of the
15444 * [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle).
15445 *
15446 * @static
15447 * @memberOf _
15448 * @since 0.1.0
15449 * @category Collection
15450 * @param {Array|Object} collection The collection to shuffle.
15451 * @returns {Array} Returns the new shuffled array.
15452 * @example
15453 *
15454 * _.shuffle([1, 2, 3, 4]);
15455 * // => [4, 1, 3, 2]
15456 */
15457 function shuffle(collection) {
15458 var func = isArray_1(collection) ? _arrayShuffle : _baseShuffle;
15459 return func(collection);
15460 }
15461
15462 var shuffle_1 = shuffle;
15463
15464 var arrayWithHoles = createCommonjsModule(function (module) {
15465 function _arrayWithHoles(arr) {
15466 if (Array.isArray(arr)) return arr;
15467 }
15468 module.exports = _arrayWithHoles, module.exports.__esModule = true, module.exports["default"] = module.exports;
15469 });
15470
15471 unwrapExports(arrayWithHoles);
15472
15473 var nonIterableRest = createCommonjsModule(function (module) {
15474 function _nonIterableRest() {
15475 throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
15476 }
15477 module.exports = _nonIterableRest, module.exports.__esModule = true, module.exports["default"] = module.exports;
15478 });
15479
15480 unwrapExports(nonIterableRest);
15481
15482 var toArray = createCommonjsModule(function (module) {
15483 function _toArray(arr) {
15484 return arrayWithHoles(arr) || iterableToArray(arr) || unsupportedIterableToArray(arr) || nonIterableRest();
15485 }
15486 module.exports = _toArray, module.exports.__esModule = true, module.exports["default"] = module.exports;
15487 });
15488
15489 var _toArray = unwrapExports(toArray);
15490
15491 var createClass = createCommonjsModule(function (module) {
15492 function _defineProperties(target, props) {
15493 for (var i = 0; i < props.length; i++) {
15494 var descriptor = props[i];
15495 descriptor.enumerable = descriptor.enumerable || false;
15496 descriptor.configurable = true;
15497 if ("value" in descriptor) descriptor.writable = true;
15498 Object.defineProperty(target, toPropertyKey(descriptor.key), descriptor);
15499 }
15500 }
15501 function _createClass(Constructor, protoProps, staticProps) {
15502 if (protoProps) _defineProperties(Constructor.prototype, protoProps);
15503 if (staticProps) _defineProperties(Constructor, staticProps);
15504 Object.defineProperty(Constructor, "prototype", {
15505 writable: false
15506 });
15507 return Constructor;
15508 }
15509 module.exports = _createClass, module.exports.__esModule = true, module.exports["default"] = module.exports;
15510 });
15511
15512 var _createClass = unwrapExports(createClass);
15513
15514 var applyDecoratedDescriptor = createCommonjsModule(function (module) {
15515 function _applyDecoratedDescriptor(target, property, decorators, descriptor, context) {
15516 var desc = {};
15517 Object.keys(descriptor).forEach(function (key) {
15518 desc[key] = descriptor[key];
15519 });
15520 desc.enumerable = !!desc.enumerable;
15521 desc.configurable = !!desc.configurable;
15522 if ('value' in desc || desc.initializer) {
15523 desc.writable = true;
15524 }
15525 desc = decorators.slice().reverse().reduce(function (desc, decorator) {
15526 return decorator(target, property, desc) || desc;
15527 }, desc);
15528 if (context && desc.initializer !== void 0) {
15529 desc.value = desc.initializer ? desc.initializer.call(context) : void 0;
15530 desc.initializer = undefined;
15531 }
15532 if (desc.initializer === void 0) {
15533 Object.defineProperty(target, property, desc);
15534 desc = null;
15535 }
15536 return desc;
15537 }
15538 module.exports = _applyDecoratedDescriptor, module.exports.__esModule = true, module.exports["default"] = module.exports;
15539 });
15540
15541 var _applyDecoratedDescriptor = unwrapExports(applyDecoratedDescriptor);
15542
15543 var stateMachine = createCommonjsModule(function (module, exports) {
15544 /*
15545
15546 Javascript State Machine Library - https://github.com/jakesgordon/javascript-state-machine
15547
15548 Copyright (c) 2012, 2013, 2014, 2015, Jake Gordon and contributors
15549 Released under the MIT license - https://github.com/jakesgordon/javascript-state-machine/blob/master/LICENSE
15550
15551 */
15552
15553 (function () {
15554
15555 var StateMachine = {
15556
15557 //---------------------------------------------------------------------------
15558
15559 VERSION: "2.4.0",
15560
15561 //---------------------------------------------------------------------------
15562
15563 Result: {
15564 SUCCEEDED: 1, // the event transitioned successfully from one state to another
15565 NOTRANSITION: 2, // the event was successfull but no state transition was necessary
15566 CANCELLED: 3, // the event was cancelled by the caller in a beforeEvent callback
15567 PENDING: 4 // the event is asynchronous and the caller is in control of when the transition occurs
15568 },
15569
15570 Error: {
15571 INVALID_TRANSITION: 100, // caller tried to fire an event that was innapropriate in the current state
15572 PENDING_TRANSITION: 200, // caller tried to fire an event while an async transition was still pending
15573 INVALID_CALLBACK: 300 // caller provided callback function threw an exception
15574 },
15575
15576 WILDCARD: '*',
15577 ASYNC: 'async',
15578
15579 //---------------------------------------------------------------------------
15580
15581 create: function(cfg, target) {
15582
15583 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 }
15584 var terminal = cfg.terminal || cfg['final'];
15585 var fsm = target || cfg.target || {};
15586 var events = cfg.events || [];
15587 var callbacks = cfg.callbacks || {};
15588 var map = {}; // track state transitions allowed for an event { event: { from: [ to ] } }
15589 var transitions = {}; // track events allowed from a state { state: [ event ] }
15590
15591 var add = function(e) {
15592 var from = Array.isArray(e.from) ? e.from : (e.from ? [e.from] : [StateMachine.WILDCARD]); // allow 'wildcard' transition if 'from' is not specified
15593 map[e.name] = map[e.name] || {};
15594 for (var n = 0 ; n < from.length ; n++) {
15595 transitions[from[n]] = transitions[from[n]] || [];
15596 transitions[from[n]].push(e.name);
15597
15598 map[e.name][from[n]] = e.to || from[n]; // allow no-op transition if 'to' is not specified
15599 }
15600 if (e.to)
15601 transitions[e.to] = transitions[e.to] || [];
15602 };
15603
15604 if (initial) {
15605 initial.event = initial.event || 'startup';
15606 add({ name: initial.event, from: 'none', to: initial.state });
15607 }
15608
15609 for(var n = 0 ; n < events.length ; n++)
15610 add(events[n]);
15611
15612 for(var name in map) {
15613 if (map.hasOwnProperty(name))
15614 fsm[name] = StateMachine.buildEvent(name, map[name]);
15615 }
15616
15617 for(var name in callbacks) {
15618 if (callbacks.hasOwnProperty(name))
15619 fsm[name] = callbacks[name];
15620 }
15621
15622 fsm.current = 'none';
15623 fsm.is = function(state) { return Array.isArray(state) ? (state.indexOf(this.current) >= 0) : (this.current === state); };
15624 fsm.can = function(event) { return !this.transition && (map[event] !== undefined) && (map[event].hasOwnProperty(this.current) || map[event].hasOwnProperty(StateMachine.WILDCARD)); };
15625 fsm.cannot = function(event) { return !this.can(event); };
15626 fsm.transitions = function() { return (transitions[this.current] || []).concat(transitions[StateMachine.WILDCARD] || []); };
15627 fsm.isFinished = function() { return this.is(terminal); };
15628 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)
15629 fsm.states = function() { return Object.keys(transitions).sort() };
15630
15631 if (initial && !initial.defer)
15632 fsm[initial.event]();
15633
15634 return fsm;
15635
15636 },
15637
15638 //===========================================================================
15639
15640 doCallback: function(fsm, func, name, from, to, args) {
15641 if (func) {
15642 try {
15643 return func.apply(fsm, [name, from, to].concat(args));
15644 }
15645 catch(e) {
15646 return fsm.error(name, from, to, args, StateMachine.Error.INVALID_CALLBACK, "an exception occurred in a caller-provided callback function", e);
15647 }
15648 }
15649 },
15650
15651 beforeAnyEvent: function(fsm, name, from, to, args) { return StateMachine.doCallback(fsm, fsm['onbeforeevent'], name, from, to, args); },
15652 afterAnyEvent: function(fsm, name, from, to, args) { return StateMachine.doCallback(fsm, fsm['onafterevent'] || fsm['onevent'], name, from, to, args); },
15653 leaveAnyState: function(fsm, name, from, to, args) { return StateMachine.doCallback(fsm, fsm['onleavestate'], name, from, to, args); },
15654 enterAnyState: function(fsm, name, from, to, args) { return StateMachine.doCallback(fsm, fsm['onenterstate'] || fsm['onstate'], name, from, to, args); },
15655 changeState: function(fsm, name, from, to, args) { return StateMachine.doCallback(fsm, fsm['onchangestate'], name, from, to, args); },
15656
15657 beforeThisEvent: function(fsm, name, from, to, args) { return StateMachine.doCallback(fsm, fsm['onbefore' + name], name, from, to, args); },
15658 afterThisEvent: function(fsm, name, from, to, args) { return StateMachine.doCallback(fsm, fsm['onafter' + name] || fsm['on' + name], name, from, to, args); },
15659 leaveThisState: function(fsm, name, from, to, args) { return StateMachine.doCallback(fsm, fsm['onleave' + from], name, from, to, args); },
15660 enterThisState: function(fsm, name, from, to, args) { return StateMachine.doCallback(fsm, fsm['onenter' + to] || fsm['on' + to], name, from, to, args); },
15661
15662 beforeEvent: function(fsm, name, from, to, args) {
15663 if ((false === StateMachine.beforeThisEvent(fsm, name, from, to, args)) ||
15664 (false === StateMachine.beforeAnyEvent( fsm, name, from, to, args)))
15665 return false;
15666 },
15667
15668 afterEvent: function(fsm, name, from, to, args) {
15669 StateMachine.afterThisEvent(fsm, name, from, to, args);
15670 StateMachine.afterAnyEvent( fsm, name, from, to, args);
15671 },
15672
15673 leaveState: function(fsm, name, from, to, args) {
15674 var specific = StateMachine.leaveThisState(fsm, name, from, to, args),
15675 general = StateMachine.leaveAnyState( fsm, name, from, to, args);
15676 if ((false === specific) || (false === general))
15677 return false;
15678 else if ((StateMachine.ASYNC === specific) || (StateMachine.ASYNC === general))
15679 return StateMachine.ASYNC;
15680 },
15681
15682 enterState: function(fsm, name, from, to, args) {
15683 StateMachine.enterThisState(fsm, name, from, to, args);
15684 StateMachine.enterAnyState( fsm, name, from, to, args);
15685 },
15686
15687 //===========================================================================
15688
15689 buildEvent: function(name, map) {
15690 return function() {
15691
15692 var from = this.current;
15693 var to = map[from] || (map[StateMachine.WILDCARD] != StateMachine.WILDCARD ? map[StateMachine.WILDCARD] : from) || from;
15694 var args = Array.prototype.slice.call(arguments); // turn arguments into pure array
15695
15696 if (this.transition)
15697 return this.error(name, from, to, args, StateMachine.Error.PENDING_TRANSITION, "event " + name + " inappropriate because previous transition did not complete");
15698
15699 if (this.cannot(name))
15700 return this.error(name, from, to, args, StateMachine.Error.INVALID_TRANSITION, "event " + name + " inappropriate in current state " + this.current);
15701
15702 if (false === StateMachine.beforeEvent(this, name, from, to, args))
15703 return StateMachine.Result.CANCELLED;
15704
15705 if (from === to) {
15706 StateMachine.afterEvent(this, name, from, to, args);
15707 return StateMachine.Result.NOTRANSITION;
15708 }
15709
15710 // 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)
15711 var fsm = this;
15712 this.transition = function() {
15713 fsm.transition = null; // this method should only ever be called once
15714 fsm.current = to;
15715 StateMachine.enterState( fsm, name, from, to, args);
15716 StateMachine.changeState(fsm, name, from, to, args);
15717 StateMachine.afterEvent( fsm, name, from, to, args);
15718 return StateMachine.Result.SUCCEEDED;
15719 };
15720 this.transition.cancel = function() { // provide a way for caller to cancel async transition if desired (issue #22)
15721 fsm.transition = null;
15722 StateMachine.afterEvent(fsm, name, from, to, args);
15723 };
15724
15725 var leave = StateMachine.leaveState(this, name, from, to, args);
15726 if (false === leave) {
15727 this.transition = null;
15728 return StateMachine.Result.CANCELLED;
15729 }
15730 else if (StateMachine.ASYNC === leave) {
15731 return StateMachine.Result.PENDING;
15732 }
15733 else {
15734 if (this.transition) // need to check in case user manually called transition() but forgot to return StateMachine.ASYNC
15735 return this.transition();
15736 }
15737
15738 };
15739 }
15740
15741 }; // StateMachine
15742
15743 //===========================================================================
15744
15745 //======
15746 // NODE
15747 //======
15748 {
15749 if ( module.exports) {
15750 exports = module.exports = StateMachine;
15751 }
15752 exports.StateMachine = StateMachine;
15753 }
15754
15755 }());
15756 });
15757 var stateMachine_1 = stateMachine.StateMachine;
15758
15759 var adapters = {};
15760 var getAdapter = function getAdapter(name) {
15761 var adapter = adapters[name];
15762 if (adapter === undefined) {
15763 throw new Error("".concat(name, " adapter is not configured"));
15764 }
15765 return adapter;
15766 };
15767
15768 /**
15769 * 指定 Adapters
15770 * @function
15771 * @memberof module:leancloud-realtime
15772 * @param {Adapters} newAdapters Adapters 的类型请参考 {@link https://url.leanapp.cn/adapter-type-definitions @leancloud/adapter-types} 中的定义
15773 */
15774 var setAdapters = function setAdapters(newAdapters) {
15775 Object.assign(adapters, newAdapters);
15776 };
15777
15778 /** Built-in value references. */
15779 var getPrototype = _overArg(Object.getPrototypeOf, Object);
15780
15781 var _getPrototype = getPrototype;
15782
15783 /** `Object#toString` result references. */
15784 var objectTag$1 = '[object Object]';
15785
15786 /** Used for built-in method references. */
15787 var funcProto = Function.prototype,
15788 objectProto$6 = Object.prototype;
15789
15790 /** Used to resolve the decompiled source of functions. */
15791 var funcToString = funcProto.toString;
15792
15793 /** Used to check objects for own properties. */
15794 var hasOwnProperty$4 = objectProto$6.hasOwnProperty;
15795
15796 /** Used to infer the `Object` constructor. */
15797 var objectCtorString = funcToString.call(Object);
15798
15799 /**
15800 * Checks if `value` is a plain object, that is, an object created by the
15801 * `Object` constructor or one with a `[[Prototype]]` of `null`.
15802 *
15803 * @static
15804 * @memberOf _
15805 * @since 0.8.0
15806 * @category Lang
15807 * @param {*} value The value to check.
15808 * @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
15809 * @example
15810 *
15811 * function Foo() {
15812 * this.a = 1;
15813 * }
15814 *
15815 * _.isPlainObject(new Foo);
15816 * // => false
15817 *
15818 * _.isPlainObject([1, 2, 3]);
15819 * // => false
15820 *
15821 * _.isPlainObject({ 'x': 0, 'y': 0 });
15822 * // => true
15823 *
15824 * _.isPlainObject(Object.create(null));
15825 * // => true
15826 */
15827 function isPlainObject(value) {
15828 if (!isObjectLike_1(value) || _baseGetTag(value) != objectTag$1) {
15829 return false;
15830 }
15831 var proto = _getPrototype(value);
15832 if (proto === null) {
15833 return true;
15834 }
15835 var Ctor = hasOwnProperty$4.call(proto, 'constructor') && proto.constructor;
15836 return typeof Ctor == 'function' && Ctor instanceof Ctor &&
15837 funcToString.call(Ctor) == objectCtorString;
15838 }
15839
15840 var isPlainObject_1 = isPlainObject;
15841
15842 /* eslint-disable */
15843 var global$1 = typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : {};
15844
15845 var EXPIRED = Symbol('expired');
15846 var debug = browser('LC:Expirable');
15847 var Expirable = /*#__PURE__*/function () {
15848 function Expirable(value, ttl) {
15849 this.originalValue = value;
15850 if (typeof ttl === 'number') {
15851 this.expiredAt = Date.now() + ttl;
15852 }
15853 }
15854 _createClass(Expirable, [{
15855 key: "value",
15856 get: function get() {
15857 var expired = this.expiredAt && this.expiredAt <= Date.now();
15858 if (expired) debug("expired: ".concat(this.originalValue));
15859 return expired ? EXPIRED : this.originalValue;
15860 }
15861 }]);
15862 return Expirable;
15863 }();
15864 Expirable.EXPIRED = EXPIRED;
15865
15866 var debug$1 = browser('LC:Cache');
15867 var Cache = /*#__PURE__*/function () {
15868 function Cache() {
15869 var name = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'anonymous';
15870 this.name = name;
15871 this._map = {};
15872 }
15873 var _proto = Cache.prototype;
15874 _proto.get = function get(key) {
15875 var cache = this._map[key];
15876 if (cache) {
15877 var value = cache.value;
15878 if (value !== Expirable.EXPIRED) {
15879 debug$1('[%s] hit: %s', this.name, key);
15880 return value;
15881 }
15882 delete this._map[key];
15883 }
15884 debug$1("[".concat(this.name, "] missed: ").concat(key));
15885 return null;
15886 };
15887 _proto.set = function set(key, value, ttl) {
15888 debug$1('[%s] set: %s %d', this.name, key, ttl);
15889 this._map[key] = new Expirable(value, ttl);
15890 };
15891 return Cache;
15892 }();
15893
15894 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; }
15895 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; }
15896
15897 /**
15898 * 调试日志控制器
15899 * @const
15900 * @memberof module:leancloud-realtime
15901 * @example
15902 * debug.enable(); // 启用调试日志
15903 * debug.disable(); // 关闭调试日志
15904 */
15905 var debug$2 = {
15906 enable: function enable() {
15907 var namespaces = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'LC*';
15908 return browser.enable(namespaces);
15909 },
15910 disable: browser.disable
15911 };
15912 var tryAll = function tryAll(promiseConstructors) {
15913 var promise = new Promise(promiseConstructors[0]);
15914 if (promiseConstructors.length === 1) {
15915 return promise;
15916 }
15917 return promise["catch"](function () {
15918 return tryAll(promiseConstructors.slice(1));
15919 });
15920 };
15921
15922 // eslint-disable-next-line no-sequences
15923 var tap = function tap(interceptor) {
15924 return function (value) {
15925 return interceptor(value), value;
15926 };
15927 };
15928 var finalize = function finalize(callback) {
15929 return [
15930 // eslint-disable-next-line no-sequences
15931 function (value) {
15932 return callback(), value;
15933 }, function (error) {
15934 callback();
15935 throw error;
15936 }];
15937 };
15938
15939 /**
15940 * 将对象转换为 Date,支持 string、number、ProtoBuf Long 以及 LeanCloud 的 Date 类型,
15941 * 其他情况下(包括对象为 falsy)返回原值。
15942 * @private
15943 */
15944 var decodeDate = function decodeDate(date) {
15945 if (!date) return date;
15946 if (typeof date === 'string' || typeof date === 'number') {
15947 return new Date(date);
15948 }
15949 if (date.__type === 'Date' && date.iso) {
15950 return new Date(date.iso);
15951 }
15952 // Long
15953 if (typeof date.toNumber === 'function') {
15954 return new Date(date.toNumber());
15955 }
15956 return date;
15957 };
15958 /**
15959 * 获取 Date 的毫秒数,如果不是一个 Date 返回 undefined。
15960 * @private
15961 */
15962 var getTime = function getTime(date) {
15963 return date && date.getTime ? date.getTime() : undefined;
15964 };
15965
15966 /**
15967 * 解码对象中的 LeanCloud 数据结构。
15968 * 目前仅会处理 Date 类型。
15969 * @private
15970 */
15971 var decode = function decode(value) {
15972 if (!value) return value;
15973 if (value.__type === 'Date' && value.iso) {
15974 return new Date(value.iso);
15975 }
15976 if (Array.isArray(value)) {
15977 return value.map(decode);
15978 }
15979 if (isPlainObject_1(value)) {
15980 return Object.keys(value).reduce(function (result, key) {
15981 return _objectSpread(_objectSpread({}, result), {}, _defineProperty({}, key, decode(value[key])));
15982 }, {});
15983 }
15984 return value;
15985 };
15986 /**
15987 * 将对象中的特殊类型编码为 LeanCloud 数据结构。
15988 * 目前仅会处理 Date 类型。
15989 * @private
15990 */
15991 var encode = function encode(value) {
15992 if (value instanceof Date) return {
15993 __type: 'Date',
15994 iso: value.toJSON()
15995 };
15996 if (Array.isArray(value)) {
15997 return value.map(encode);
15998 }
15999 if (isPlainObject_1(value)) {
16000 return Object.keys(value).reduce(function (result, key) {
16001 return _objectSpread(_objectSpread({}, result), {}, _defineProperty({}, key, encode(value[key])));
16002 }, {});
16003 }
16004 return value;
16005 };
16006 var keyRemap = function keyRemap(keymap, obj) {
16007 return Object.keys(obj).reduce(function (newObj, key) {
16008 var newKey = keymap[key] || key;
16009 return Object.assign(newObj, _defineProperty({}, newKey, obj[key]));
16010 }, {});
16011 };
16012 var isIE10 = global$1.navigator && global$1.navigator.userAgent && global$1.navigator.userAgent.indexOf('MSIE 10.') !== -1;
16013
16014 /* eslint-disable no-proto */
16015 var getStaticProperty = function getStaticProperty(klass, property) {
16016 return klass[property] || (klass.__proto__ ? getStaticProperty(klass.__proto__, property) : undefined);
16017 };
16018 /* eslint-enable no-proto */
16019
16020 var union = function union(a, b) {
16021 return Array.from(new Set([].concat(_toConsumableArray$1(a), _toConsumableArray$1(b))));
16022 };
16023 var difference = function difference(a, b) {
16024 return Array.from(function (bSet) {
16025 return new Set(a.filter(function (x) {
16026 return !bSet.has(x);
16027 }));
16028 }(new Set(b)));
16029 };
16030 var map = new WeakMap();
16031
16032 // protected property helper
16033 var internal = function internal(object) {
16034 if (!map.has(object)) {
16035 map.set(object, {});
16036 }
16037 return map.get(object);
16038 };
16039 var compact = function compact(obj, filter) {
16040 if (!isPlainObject_1(obj)) return obj;
16041 var object = _objectSpread({}, obj);
16042 Object.keys(object).forEach(function (prop) {
16043 var value = object[prop];
16044 if (value === filter) {
16045 delete object[prop];
16046 } else {
16047 object[prop] = compact(value, filter);
16048 }
16049 });
16050 return object;
16051 };
16052
16053 // debug utility
16054 var removeNull = function removeNull(obj) {
16055 return compact(obj, null);
16056 };
16057 var trim = function trim(message) {
16058 return removeNull(JSON.parse(JSON.stringify(message)));
16059 };
16060 var ensureArray = function ensureArray(target) {
16061 if (Array.isArray(target)) {
16062 return target;
16063 }
16064 if (target === undefined || target === null) {
16065 return [];
16066 }
16067 return [target];
16068 };
16069 var setValue = function setValue(target, key, value) {
16070 // '.' is not allowed in Class keys, escaping is not in concern now.
16071 var segs = key.split('.');
16072 var lastSeg = segs.pop();
16073 var currentTarget = target;
16074 segs.forEach(function (seg) {
16075 if (currentTarget[seg] === undefined) currentTarget[seg] = {};
16076 currentTarget = currentTarget[seg];
16077 });
16078 currentTarget[lastSeg] = value;
16079 return target;
16080 };
16081 var isWeapp =
16082 // eslint-disable-next-line no-undef
16083 (typeof wx === "undefined" ? "undefined" : _typeof(wx)) === 'object' && typeof wx.connectSocket === 'function';
16084
16085 // throttle decorator
16086 var throttle = function throttle(wait) {
16087 return function (target, property, descriptor) {
16088 var callback = descriptor.value;
16089 // very naive, internal use only
16090 if (callback.length) {
16091 throw new Error('throttled function should not accept any arguments');
16092 }
16093 return _objectSpread(_objectSpread({}, descriptor), {}, {
16094 value: function value() {
16095 var _this = this;
16096 var _internal = internal(this),
16097 throttleMeta = _internal.throttleMeta;
16098 if (!throttleMeta) {
16099 throttleMeta = {};
16100 internal(this).throttleMeta = throttleMeta;
16101 }
16102 var _throttleMeta = throttleMeta,
16103 propertyMeta = _throttleMeta[property];
16104 if (!propertyMeta) {
16105 propertyMeta = {};
16106 throttleMeta[property] = propertyMeta;
16107 }
16108 var _propertyMeta = propertyMeta,
16109 _propertyMeta$previou = _propertyMeta.previouseTimestamp,
16110 previouseTimestamp = _propertyMeta$previou === void 0 ? 0 : _propertyMeta$previou,
16111 timeout = _propertyMeta.timeout;
16112 var now = Date.now();
16113 var remainingTime = wait - (now - previouseTimestamp);
16114 if (remainingTime <= 0) {
16115 throttleMeta[property].previouseTimestamp = now;
16116 callback.apply(this);
16117 } else if (!timeout) {
16118 propertyMeta.timeout = setTimeout(function () {
16119 propertyMeta.previouseTimestamp = Date.now();
16120 delete propertyMeta.timeout;
16121 callback.apply(_this);
16122 }, remainingTime);
16123 }
16124 }
16125 });
16126 };
16127 };
16128 var isCNApp = function isCNApp(appId) {
16129 return appId.slice(-9) !== '-MdYXbMMI';
16130 };
16131 var equalBuffer = function equalBuffer(buffer1, buffer2) {
16132 if (!buffer1 || !buffer2) return false;
16133 if (buffer1.byteLength !== buffer2.byteLength) return false;
16134 var a = new Uint8Array(buffer1);
16135 var b = new Uint8Array(buffer2);
16136 return !a.some(function (value, index) {
16137 return value !== b[index];
16138 });
16139 };
16140
16141 var _class;
16142 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; }
16143 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; }
16144 var debug$3 = browser('LC:WebSocketPlus');
16145 var OPEN = 'open';
16146 var DISCONNECT = 'disconnect';
16147 var RECONNECT = 'reconnect';
16148 var RETRY = 'retry';
16149 var SCHEDULE = 'schedule';
16150 var OFFLINE = 'offline';
16151 var ONLINE = 'online';
16152 var ERROR = 'error';
16153 var MESSAGE = 'message';
16154 var HEARTBEAT_TIME = 180000;
16155 var TIMEOUT_TIME = 380000;
16156 var DEFAULT_RETRY_STRATEGY = function DEFAULT_RETRY_STRATEGY(attempt) {
16157 return Math.min(1000 * Math.pow(2, attempt), 300000);
16158 };
16159 var requireConnected = function requireConnected(target, name, descriptor) {
16160 return _objectSpread$1(_objectSpread$1({}, descriptor), {}, {
16161 value: function requireConnectedWrapper() {
16162 var _descriptor$value;
16163 this.checkConnectionAvailability(name);
16164 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
16165 args[_key] = arguments[_key];
16166 }
16167 return (_descriptor$value = descriptor.value).call.apply(_descriptor$value, [this].concat(args));
16168 }
16169 });
16170 };
16171 var WebSocketPlus = (_class = /*#__PURE__*/function (_EventEmitter) {
16172 _inheritsLoose(WebSocketPlus, _EventEmitter);
16173 function WebSocketPlus(getUrls, protocol) {
16174 var _this;
16175 _this = _EventEmitter.call(this) || this;
16176 _this.init();
16177 _this._protocol = protocol;
16178 Promise.resolve(typeof getUrls === 'function' ? getUrls() : getUrls).then(ensureArray).then(function (urls) {
16179 _this._urls = urls;
16180 return _this._open();
16181 }).then(function () {
16182 _this.__postponeTimeoutTimer = _this._postponeTimeoutTimer.bind(_assertThisInitialized(_this));
16183 if (global$1.addEventListener) {
16184 _this.__pause = function () {
16185 if (_this.can('pause')) _this.pause();
16186 };
16187 _this.__resume = function () {
16188 if (_this.can('resume')) _this.resume();
16189 };
16190 global$1.addEventListener('offline', _this.__pause);
16191 global$1.addEventListener('online', _this.__resume);
16192 }
16193 _this.open();
16194 })["catch"](_this["throw"].bind(_assertThisInitialized(_this)));
16195 return _this;
16196 }
16197 var _proto = WebSocketPlus.prototype;
16198 _proto._open = function _open() {
16199 var _this2 = this;
16200 return this._createWs(this._urls, this._protocol).then(function (ws) {
16201 var _this2$_urls = _toArray(_this2._urls),
16202 first = _this2$_urls[0],
16203 reset = _this2$_urls.slice(1);
16204 _this2._urls = [].concat(_toConsumableArray$1(reset), [first]);
16205 return ws;
16206 });
16207 };
16208 _proto._createWs = function _createWs(urls, protocol) {
16209 var _this3 = this;
16210 return tryAll(urls.map(function (url) {
16211 return function (resolve, reject) {
16212 debug$3("connect [".concat(url, "] ").concat(protocol));
16213 var WebSocket = getAdapter('WebSocket');
16214 var ws = protocol ? new WebSocket(url, protocol) : new WebSocket(url);
16215 ws.binaryType = _this3.binaryType || 'arraybuffer';
16216 ws.onopen = function () {
16217 return resolve(ws);
16218 };
16219 ws.onclose = function (error) {
16220 if (error instanceof Error) {
16221 return reject(error);
16222 }
16223 // in browser, error event is useless
16224 return reject(new Error("Failed to connect [".concat(url, "]")));
16225 };
16226 ws.onerror = ws.onclose;
16227 };
16228 })).then(function (ws) {
16229 _this3._ws = ws;
16230 _this3._ws.onclose = _this3._handleClose.bind(_this3);
16231 _this3._ws.onmessage = _this3._handleMessage.bind(_this3);
16232 return ws;
16233 });
16234 };
16235 _proto._destroyWs = function _destroyWs() {
16236 var ws = this._ws;
16237 if (!ws) return;
16238 ws.onopen = null;
16239 ws.onclose = null;
16240 ws.onerror = null;
16241 ws.onmessage = null;
16242 this._ws = null;
16243 ws.close();
16244 }
16245
16246 // eslint-disable-next-line class-methods-use-this
16247 ;
16248 _proto.onbeforeevent = function onbeforeevent(event, from, to) {
16249 for (var _len2 = arguments.length, payload = new Array(_len2 > 3 ? _len2 - 3 : 0), _key2 = 3; _key2 < _len2; _key2++) {
16250 payload[_key2 - 3] = arguments[_key2];
16251 }
16252 debug$3("".concat(event, ": ").concat(from, " -> ").concat(to, " %o"), payload);
16253 };
16254 _proto.onopen = function onopen() {
16255 this.emit(OPEN);
16256 };
16257 _proto.onconnected = function onconnected() {
16258 this._startConnectionKeeper();
16259 };
16260 _proto.onleaveconnected = function onleaveconnected(event, from, to) {
16261 this._stopConnectionKeeper();
16262 this._destroyWs();
16263 if (to === 'offline' || to === 'disconnected') {
16264 this.emit(DISCONNECT);
16265 }
16266 };
16267 _proto.onpause = function onpause() {
16268 this.emit(OFFLINE);
16269 };
16270 _proto.onbeforeresume = function onbeforeresume() {
16271 this.emit(ONLINE);
16272 };
16273 _proto.onreconnect = function onreconnect() {
16274 this.emit(RECONNECT);
16275 };
16276 _proto.ondisconnected = function ondisconnected(event, from, to) {
16277 var _this4 = this;
16278 var attempt = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;
16279 var delay = from === OFFLINE ? 0 : DEFAULT_RETRY_STRATEGY.call(null, attempt);
16280 debug$3("schedule attempt=".concat(attempt, " delay=").concat(delay));
16281 this.emit(SCHEDULE, attempt, delay);
16282 if (this.__scheduledRetry) {
16283 clearTimeout(this.__scheduledRetry);
16284 }
16285 this.__scheduledRetry = setTimeout(function () {
16286 if (_this4.is('disconnected')) {
16287 _this4.retry(attempt);
16288 }
16289 }, delay);
16290 };
16291 _proto.onretry = function onretry(event, from, to) {
16292 var _this5 = this;
16293 var attempt = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;
16294 this.emit(RETRY, attempt);
16295 this._open().then(function () {
16296 return _this5.can('reconnect') && _this5.reconnect();
16297 }, function () {
16298 return _this5.can('fail') && _this5.fail(attempt + 1);
16299 });
16300 };
16301 _proto.onerror = function onerror(event, from, to, error) {
16302 this.emit(ERROR, error);
16303 };
16304 _proto.onclose = function onclose() {
16305 if (global$1.removeEventListener) {
16306 if (this.__pause) global$1.removeEventListener('offline', this.__pause);
16307 if (this.__resume) global$1.removeEventListener('online', this.__resume);
16308 }
16309 };
16310 _proto.checkConnectionAvailability = function checkConnectionAvailability() {
16311 var name = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'API';
16312 if (!this.is('connected')) {
16313 var currentState = this.current;
16314 console.warn("".concat(name, " should not be called when the connection is ").concat(currentState));
16315 if (this.is('disconnected') || this.is('reconnecting')) {
16316 console.warn('disconnect and reconnect event should be handled to avoid such calls.');
16317 }
16318 throw new Error('Connection unavailable');
16319 }
16320 }
16321
16322 // jsdoc-ignore-start
16323 ;
16324 _proto.
16325 // jsdoc-ignore-end
16326 _ping = function _ping() {
16327 debug$3('ping');
16328 try {
16329 this.ping();
16330 } catch (error) {
16331 console.warn("websocket ping error: ".concat(error.message));
16332 }
16333 };
16334 _proto.ping = function ping() {
16335 if (this._ws.ping) {
16336 this._ws.ping();
16337 } else {
16338 console.warn("The WebSocket implement does not support sending ping frame.\n Override ping method to use application defined ping/pong mechanism.");
16339 }
16340 };
16341 _proto._postponeTimeoutTimer = function _postponeTimeoutTimer() {
16342 var _this6 = this;
16343 debug$3('_postponeTimeoutTimer');
16344 this._clearTimeoutTimers();
16345 this._timeoutTimer = setTimeout(function () {
16346 debug$3('timeout');
16347 _this6.disconnect();
16348 }, TIMEOUT_TIME);
16349 };
16350 _proto._clearTimeoutTimers = function _clearTimeoutTimers() {
16351 if (this._timeoutTimer) {
16352 clearTimeout(this._timeoutTimer);
16353 }
16354 };
16355 _proto._startConnectionKeeper = function _startConnectionKeeper() {
16356 debug$3('start connection keeper');
16357 this._heartbeatTimer = setInterval(this._ping.bind(this), HEARTBEAT_TIME);
16358 var addListener = this._ws.addListener || this._ws.addEventListener;
16359 if (!addListener) {
16360 debug$3('connection keeper disabled due to the lack of #addEventListener.');
16361 return;
16362 }
16363 addListener.call(this._ws, 'message', this.__postponeTimeoutTimer);
16364 addListener.call(this._ws, 'pong', this.__postponeTimeoutTimer);
16365 this._postponeTimeoutTimer();
16366 };
16367 _proto._stopConnectionKeeper = function _stopConnectionKeeper() {
16368 debug$3('stop connection keeper');
16369 // websockets/ws#489
16370 var removeListener = this._ws.removeListener || this._ws.removeEventListener;
16371 if (removeListener) {
16372 removeListener.call(this._ws, 'message', this.__postponeTimeoutTimer);
16373 removeListener.call(this._ws, 'pong', this.__postponeTimeoutTimer);
16374 this._clearTimeoutTimers();
16375 }
16376 if (this._heartbeatTimer) {
16377 clearInterval(this._heartbeatTimer);
16378 }
16379 };
16380 _proto._handleClose = function _handleClose(event) {
16381 debug$3("ws closed [".concat(event.code, "] ").concat(event.reason));
16382 // socket closed manually, ignore close event.
16383 if (this.isFinished()) return;
16384 this.handleClose(event);
16385 };
16386 _proto.handleClose = function handleClose() {
16387 // reconnect
16388 this.disconnect();
16389 }
16390
16391 // jsdoc-ignore-start
16392 ;
16393 _proto.
16394 // jsdoc-ignore-end
16395 send = function send(data) {
16396 debug$3('send', data);
16397 this._ws.send(data);
16398 };
16399 _proto._handleMessage = function _handleMessage(event) {
16400 debug$3('message', event.data);
16401 this.handleMessage(event.data);
16402 };
16403 _proto.handleMessage = function handleMessage(message) {
16404 this.emit(MESSAGE, message);
16405 };
16406 _createClass(WebSocketPlus, [{
16407 key: "urls",
16408 get: function get() {
16409 return this._urls;
16410 },
16411 set: function set(urls) {
16412 this._urls = ensureArray(urls);
16413 }
16414 }]);
16415 return WebSocketPlus;
16416 }(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);
16417 stateMachine.create({
16418 target: WebSocketPlus.prototype,
16419 initial: {
16420 state: 'initialized',
16421 event: 'init',
16422 defer: true
16423 },
16424 terminal: 'closed',
16425 events: [{
16426 name: 'open',
16427 from: 'initialized',
16428 to: 'connected'
16429 }, {
16430 name: 'disconnect',
16431 from: 'connected',
16432 to: 'disconnected'
16433 }, {
16434 name: 'retry',
16435 from: 'disconnected',
16436 to: 'reconnecting'
16437 }, {
16438 name: 'fail',
16439 from: 'reconnecting',
16440 to: 'disconnected'
16441 }, {
16442 name: 'reconnect',
16443 from: 'reconnecting',
16444 to: 'connected'
16445 }, {
16446 name: 'pause',
16447 from: ['connected', 'disconnected', 'reconnecting'],
16448 to: 'offline'
16449 }, {}, {
16450 name: 'resume',
16451 from: 'offline',
16452 to: 'disconnected'
16453 }, {
16454 name: 'close',
16455 from: ['connected', 'disconnected', 'reconnecting', 'offline'],
16456 to: 'closed'
16457 }, {
16458 name: 'throw',
16459 from: '*',
16460 to: 'error'
16461 }]
16462 });
16463
16464 var error = Object.freeze({
16465 1000: {
16466 name: 'CLOSE_NORMAL'
16467 },
16468 1006: {
16469 name: 'CLOSE_ABNORMAL'
16470 },
16471 4100: {
16472 name: 'APP_NOT_AVAILABLE',
16473 message: 'App not exists or realtime message service is disabled.'
16474 },
16475 4102: {
16476 name: 'SIGNATURE_FAILED',
16477 message: 'Login signature mismatch.'
16478 },
16479 4103: {
16480 name: 'INVALID_LOGIN',
16481 message: 'Malformed clientId.'
16482 },
16483 4105: {
16484 name: 'SESSION_REQUIRED',
16485 message: 'Message sent before session opened.'
16486 },
16487 4107: {
16488 name: 'READ_TIMEOUT'
16489 },
16490 4108: {
16491 name: 'LOGIN_TIMEOUT'
16492 },
16493 4109: {
16494 name: 'FRAME_TOO_LONG'
16495 },
16496 4110: {
16497 name: 'INVALID_ORIGIN',
16498 message: 'Access denied by domain whitelist.'
16499 },
16500 4111: {
16501 name: 'SESSION_CONFLICT'
16502 },
16503 4112: {
16504 name: 'SESSION_TOKEN_EXPIRED'
16505 },
16506 4113: {
16507 name: 'APP_QUOTA_EXCEEDED',
16508 message: 'The daily active users limit exceeded.'
16509 },
16510 4116: {
16511 name: 'MESSAGE_SENT_QUOTA_EXCEEDED',
16512 message: 'Command sent too fast.'
16513 },
16514 4200: {
16515 name: 'INTERNAL_ERROR',
16516 message: 'Internal error, please contact LeanCloud for support.'
16517 },
16518 4301: {
16519 name: 'CONVERSATION_API_FAILED',
16520 message: 'Upstream Conversatoin API failed, see error.detail for details.'
16521 },
16522 4302: {
16523 name: 'CONVERSATION_SIGNATURE_FAILED',
16524 message: 'Conversation action signature mismatch.'
16525 },
16526 4303: {
16527 name: 'CONVERSATION_NOT_FOUND'
16528 },
16529 4304: {
16530 name: 'CONVERSATION_FULL'
16531 },
16532 4305: {
16533 name: 'CONVERSATION_REJECTED_BY_APP',
16534 message: 'Conversation action rejected by hook.'
16535 },
16536 4306: {
16537 name: 'CONVERSATION_UPDATE_FAILED'
16538 },
16539 4307: {
16540 name: 'CONVERSATION_READ_ONLY'
16541 },
16542 4308: {
16543 name: 'CONVERSATION_NOT_ALLOWED'
16544 },
16545 4309: {
16546 name: 'CONVERSATION_UPDATE_REJECTED',
16547 message: 'Conversation update rejected because the client is not a member.'
16548 },
16549 4310: {
16550 name: 'CONVERSATION_QUERY_FAILED',
16551 message: 'Conversation query failed because it is too expansive.'
16552 },
16553 4311: {
16554 name: 'CONVERSATION_LOG_FAILED'
16555 },
16556 4312: {
16557 name: 'CONVERSATION_LOG_REJECTED',
16558 message: 'Message query rejected because the client is not a member of the conversation.'
16559 },
16560 4313: {
16561 name: 'SYSTEM_CONVERSATION_REQUIRED'
16562 },
16563 4314: {
16564 name: 'NORMAL_CONVERSATION_REQUIRED'
16565 },
16566 4315: {
16567 name: 'CONVERSATION_BLACKLISTED',
16568 message: 'Blacklisted in the conversation.'
16569 },
16570 4316: {
16571 name: 'TRANSIENT_CONVERSATION_REQUIRED'
16572 },
16573 4317: {
16574 name: 'CONVERSATION_MEMBERSHIP_REQUIRED'
16575 },
16576 4318: {
16577 name: 'CONVERSATION_API_QUOTA_EXCEEDED',
16578 message: 'LeanCloud API quota exceeded. You may upgrade your plan.'
16579 },
16580 4323: {
16581 name: 'TEMPORARY_CONVERSATION_EXPIRED',
16582 message: 'Temporary conversation expired or does not exist.'
16583 },
16584 4401: {
16585 name: 'INVALID_MESSAGING_TARGET',
16586 message: 'Conversation does not exist or client is not a member.'
16587 },
16588 4402: {
16589 name: 'MESSAGE_REJECTED_BY_APP',
16590 message: 'Message rejected by hook.'
16591 },
16592 4403: {
16593 name: 'MESSAGE_OWNERSHIP_REQUIRED'
16594 },
16595 4404: {
16596 name: 'MESSAGE_NOT_FOUND'
16597 },
16598 4405: {
16599 name: 'MESSAGE_UPDATE_REJECTED_BY_APP',
16600 message: 'Message update rejected by hook.'
16601 },
16602 4406: {
16603 name: 'MESSAGE_EDIT_DISABLED'
16604 },
16605 4407: {
16606 name: 'MESSAGE_RECALL_DISABLED'
16607 },
16608 5130: {
16609 name: 'OWNER_PROMOTION_NOT_ALLOWED',
16610 message: "Updating a member's role to owner is not allowed."
16611 }
16612 });
16613 var ErrorCode = Object.freeze(Object.keys(error).reduce(function (result, code) {
16614 return Object.assign(result, _defineProperty({}, error[code].name, Number(code)));
16615 }, {}));
16616 var createError = function createError(_ref) {
16617 var code = _ref.code,
16618 reason = _ref.reason,
16619 appCode = _ref.appCode,
16620 detail = _ref.detail,
16621 errorMessage = _ref.error;
16622 var message = reason || detail || errorMessage;
16623 var name = reason;
16624 if (!message && error[code]) {
16625 name = error[code].name;
16626 message = error[code].message || name;
16627 }
16628 if (!message) {
16629 message = "Unknow Error: ".concat(code);
16630 }
16631 var err = new Error(message);
16632 return Object.assign(err, {
16633 code: code,
16634 appCode: appCode,
16635 detail: detail,
16636 name: name
16637 });
16638 };
16639
16640 var debug$4 = browser('LC:Connection');
16641 var COMMAND_TIMEOUT = 20000;
16642 var EXPIRE = Symbol('expire');
16643 var isIdempotentCommand = function isIdempotentCommand(command) {
16644 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));
16645 };
16646 var Connection = /*#__PURE__*/function (_WebSocketPlus) {
16647 _inheritsLoose(Connection, _WebSocketPlus);
16648 function Connection(getUrl, _ref) {
16649 var _this;
16650 var format = _ref.format,
16651 version = _ref.version;
16652 debug$4('initializing Connection');
16653 var protocolString = "lc.".concat(format, ".").concat(version);
16654 _this = _WebSocketPlus.call(this, getUrl, protocolString) || this;
16655 _this._protocolFormat = format;
16656 _this._commands = {};
16657 _this._serialId = 0;
16658 return _this;
16659 }
16660 var _proto = Connection.prototype;
16661 _proto.send = /*#__PURE__*/function () {
16662 var _send = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee(command) {
16663 var _this2 = this;
16664 var waitingForRespond,
16665 buffer,
16666 serialId,
16667 duplicatedCommand,
16668 message,
16669 promise,
16670 _args = arguments;
16671 return regenerator.wrap(function _callee$(_context) {
16672 while (1) switch (_context.prev = _context.next) {
16673 case 0:
16674 waitingForRespond = _args.length > 1 && _args[1] !== undefined ? _args[1] : true;
16675 if (!waitingForRespond) {
16676 _context.next = 11;
16677 break;
16678 }
16679 if (!isIdempotentCommand(command)) {
16680 _context.next = 8;
16681 break;
16682 }
16683 buffer = command.toArrayBuffer();
16684 duplicatedCommand = values_1(this._commands).find(function (_ref2) {
16685 var targetBuffer = _ref2.buffer,
16686 targetCommand = _ref2.command;
16687 return targetCommand.cmd === command.cmd && targetCommand.op === command.op && equalBuffer(targetBuffer, buffer);
16688 });
16689 if (!duplicatedCommand) {
16690 _context.next = 8;
16691 break;
16692 }
16693 console.warn("Duplicated command [cmd:".concat(command.cmd, " op:").concat(command.op, "] is throttled."));
16694 return _context.abrupt("return", duplicatedCommand.promise);
16695 case 8:
16696 this._serialId += 1;
16697 serialId = this._serialId;
16698 command.i = serialId; // eslint-disable-line no-param-reassign
16699 case 11:
16700 if (debug$4.enabled) debug$4('↑ %O sent', trim(command));
16701 if (this._protocolFormat === 'proto2base64') {
16702 message = command.toBase64();
16703 } else if (command.toArrayBuffer) {
16704 message = command.toArrayBuffer();
16705 }
16706 if (message) {
16707 _context.next = 15;
16708 break;
16709 }
16710 throw new TypeError("".concat(command, " is not a GenericCommand"));
16711 case 15:
16712 _WebSocketPlus.prototype.send.call(this, message);
16713 if (waitingForRespond) {
16714 _context.next = 18;
16715 break;
16716 }
16717 return _context.abrupt("return", undefined);
16718 case 18:
16719 promise = new Promise(function (resolve, reject) {
16720 _this2._commands[serialId] = {
16721 command: command,
16722 buffer: buffer,
16723 resolve: resolve,
16724 reject: reject,
16725 timeout: setTimeout(function () {
16726 if (_this2._commands[serialId]) {
16727 if (debug$4.enabled) debug$4('✗ %O timeout', trim(command));
16728 reject(createError({
16729 error: "Command Timeout [cmd:".concat(command.cmd, " op:").concat(command.op, "]"),
16730 name: 'COMMAND_TIMEOUT'
16731 }));
16732 delete _this2._commands[serialId];
16733 }
16734 }, COMMAND_TIMEOUT)
16735 };
16736 });
16737 this._commands[serialId].promise = promise;
16738 return _context.abrupt("return", promise);
16739 case 21:
16740 case "end":
16741 return _context.stop();
16742 }
16743 }, _callee, this);
16744 }));
16745 function send(_x) {
16746 return _send.apply(this, arguments);
16747 }
16748 return send;
16749 }();
16750 _proto.handleMessage = function handleMessage(msg) {
16751 var message;
16752 try {
16753 message = GenericCommand.decode(msg);
16754 if (debug$4.enabled) debug$4('↓ %O received', trim(message));
16755 } catch (e) {
16756 console.warn('Decode message failed:', e.message, msg);
16757 return;
16758 }
16759 var serialId = message.i;
16760 if (serialId) {
16761 if (this._commands[serialId]) {
16762 clearTimeout(this._commands[serialId].timeout);
16763 if (message.cmd === CommandType.error) {
16764 this._commands[serialId].reject(createError(message.errorMessage));
16765 } else {
16766 this._commands[serialId].resolve(message);
16767 }
16768 delete this._commands[serialId];
16769 } else {
16770 console.warn("Unexpected command received with serialId [".concat(serialId, "],\n which have timed out or never been requested."));
16771 }
16772 } else {
16773 switch (message.cmd) {
16774 case CommandType.error:
16775 {
16776 this.emit(ERROR, createError(message.errorMessage));
16777 return;
16778 }
16779 case CommandType.goaway:
16780 {
16781 this.emit(EXPIRE);
16782 return;
16783 }
16784 default:
16785 {
16786 this.emit(MESSAGE, message);
16787 }
16788 }
16789 }
16790 };
16791 _proto.ping = function ping() {
16792 return this.send(new GenericCommand({
16793 cmd: CommandType.echo
16794 }))["catch"](function (error) {
16795 return debug$4('ping failed:', error);
16796 });
16797 };
16798 return Connection;
16799 }(WebSocketPlus);
16800
16801 var promiseTimeout = createCommonjsModule(function (module) {
16802
16803 /**
16804 * Local reference to TimeoutError
16805 * @private
16806 */
16807 var TimeoutError;
16808
16809 /**
16810 * Rejects a promise with a {@link TimeoutError} if it does not settle within
16811 * the specified timeout.
16812 *
16813 * @param {Promise} promise The promise.
16814 * @param {number} timeoutMillis Number of milliseconds to wait on settling.
16815 * @returns {Promise} Either resolves/rejects with `promise`, or rejects with
16816 * `TimeoutError`, whichever settles first.
16817 */
16818 var timeout = module.exports.timeout = function (promise, timeoutMillis) {
16819 var error = new TimeoutError(),
16820 timeout;
16821 return Promise.race([promise, new Promise(function (resolve, reject) {
16822 timeout = setTimeout(function () {
16823 reject(error);
16824 }, timeoutMillis);
16825 })]).then(function (v) {
16826 clearTimeout(timeout);
16827 return v;
16828 }, function (err) {
16829 clearTimeout(timeout);
16830 throw err;
16831 });
16832 };
16833
16834 /**
16835 * Exception indicating that the timeout expired.
16836 */
16837 TimeoutError = module.exports.TimeoutError = function () {
16838 Error.call(this);
16839 this.stack = Error().stack;
16840 this.message = 'Timeout';
16841 };
16842 TimeoutError.prototype = Object.create(Error.prototype);
16843 TimeoutError.prototype.name = "TimeoutError";
16844 });
16845 var promiseTimeout_1 = promiseTimeout.timeout;
16846 var promiseTimeout_2 = promiseTimeout.TimeoutError;
16847
16848 var debug$5 = browser('LC:request');
16849 var request = (function (_ref) {
16850 var _ref$method = _ref.method,
16851 method = _ref$method === void 0 ? 'GET' : _ref$method,
16852 _url = _ref.url,
16853 query = _ref.query,
16854 headers = _ref.headers,
16855 data = _ref.data,
16856 time = _ref.timeout;
16857 var url = _url;
16858 if (query) {
16859 var queryString = Object.keys(query).map(function (key) {
16860 var value = query[key];
16861 if (value === undefined) return undefined;
16862 var v = isPlainObject_1(value) ? JSON.stringify(value) : value;
16863 return "".concat(encodeURIComponent(key), "=").concat(encodeURIComponent(v));
16864 }).filter(function (qs) {
16865 return qs;
16866 }).join('&');
16867 url = "".concat(url, "?").concat(queryString);
16868 }
16869 debug$5('Req: %O %O %O', method, url, {
16870 headers: headers,
16871 data: data
16872 });
16873 var request = getAdapter('request');
16874 var promise = request(url, {
16875 method: method,
16876 headers: headers,
16877 data: data
16878 }).then(function (response) {
16879 if (response.ok === false) {
16880 var error = createError(response.data);
16881 error.response = response;
16882 throw error;
16883 }
16884 debug$5('Res: %O %O %O', url, response.status, response.data);
16885 return response.data;
16886 })["catch"](function (error) {
16887 if (error.response) {
16888 debug$5('Error: %O %O %O', url, error.response.status, error.response.data);
16889 }
16890 throw error;
16891 });
16892 return time ? promiseTimeout_1(promise, time) : promise;
16893 });
16894
16895 var checkType = function checkType(middleware) {
16896 return function (param) {
16897 var constructor = param.constructor;
16898 return Promise.resolve(param).then(middleware).then(tap(function (result) {
16899 if (result === undefined || result === null) {
16900 // eslint-disable-next-line max-len
16901 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."));
16902 }
16903 if (!(result instanceof constructor)) {
16904 // eslint-disable-next-line max-len
16905 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."));
16906 }
16907 return 0;
16908 }));
16909 };
16910 };
16911 var applyDecorators = function applyDecorators(decorators, target) {
16912 if (decorators) {
16913 decorators.forEach(function (decorator) {
16914 try {
16915 decorator(target);
16916 } catch (error) {
16917 if (decorator._pluginName) {
16918 error.message += "[".concat(decorator._pluginName, "]");
16919 }
16920 throw error;
16921 }
16922 });
16923 }
16924 };
16925 var applyMiddlewares = function applyMiddlewares(middlewares) {
16926 return function (target) {
16927 return ensureArray(middlewares).reduce(function (previousPromise, middleware) {
16928 return previousPromise.then(checkType(middleware))["catch"](function (error) {
16929 if (middleware._pluginName) {
16930 // eslint-disable-next-line no-param-reassign
16931 error.message += "[".concat(middleware._pluginName, "]");
16932 }
16933 throw error;
16934 });
16935 }, Promise.resolve(target));
16936 };
16937 };
16938 var applyDispatcher = function applyDispatcher(dispatchers, payload) {
16939 return ensureArray(dispatchers).reduce(function (resultPromise, dispatcher) {
16940 return resultPromise.then(function (shouldDispatch) {
16941 return shouldDispatch === false ? false : dispatcher.apply(void 0, _toConsumableArray$1(payload));
16942 })["catch"](function (error) {
16943 if (dispatcher._pluginName) {
16944 // eslint-disable-next-line no-param-reassign
16945 error.message += "[".concat(dispatcher._pluginName, "]");
16946 }
16947 throw error;
16948 });
16949 }, Promise.resolve(true));
16950 };
16951
16952 var version = "5.0.0-rc.8";
16953
16954 var _excluded = ["plugins"];
16955 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; }
16956 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; }
16957 var debug$6 = browser('LC:Realtime');
16958 var routerCache = new Cache('push-router');
16959 var initializedApp = {};
16960 var Realtime = /*#__PURE__*/function (_EventEmitter) {
16961 _inheritsLoose(Realtime, _EventEmitter);
16962 /**
16963 * @extends EventEmitter
16964 * @param {Object} options
16965 * @param {String} options.appId
16966 * @param {String} options.appKey (since 4.0.0)
16967 * @param {String|Object} [options.server] 指定服务器域名,中国节点应用此参数必填(since 4.0.0)
16968 * @param {Boolean} [options.noBinary=false] 设置 WebSocket 使用字符串格式收发消息(默认为二进制格式)。
16969 * 适用于 WebSocket 实现不支持二进制数据格式的情况
16970 * @param {Boolean} [options.ssl=true] 使用 wss 进行连接
16971 * @param {String|String[]} [options.RTMServers] 指定私有部署的 RTM 服务器地址(since 4.0.0)
16972 * @param {Plugin[]} [options.plugins] 加载插件(since 3.1.0)
16973 */
16974 function Realtime(_ref) {
16975 var _this2;
16976 var plugins = _ref.plugins,
16977 options = _objectWithoutProperties(_ref, _excluded);
16978 debug$6('initializing Realtime %s %O', version, options);
16979 _this2 = _EventEmitter.call(this) || this;
16980 var appId = options.appId;
16981 if (typeof appId !== 'string') {
16982 throw new TypeError("appId [".concat(appId, "] is not a string"));
16983 }
16984 if (initializedApp[appId]) {
16985 throw new Error("App [".concat(appId, "] is already initialized."));
16986 }
16987 initializedApp[appId] = true;
16988 if (typeof options.appKey !== 'string') {
16989 throw new TypeError("appKey [".concat(options.appKey, "] is not a string"));
16990 }
16991 if (isCNApp(appId)) {
16992 if (!options.server) {
16993 throw new TypeError("server option is required for apps from CN region");
16994 }
16995 }
16996 _this2._options = _objectSpread$2({
16997 appId: undefined,
16998 appKey: undefined,
16999 noBinary: false,
17000 ssl: true,
17001 RTMServerName: typeof process !== 'undefined' ? process.env.RTM_SERVER_NAME : undefined
17002 }, options);
17003 _this2._cache = new Cache('endpoints');
17004 var _this = internal(_assertThisInitialized(_this2));
17005 _this.clients = new Set();
17006 _this.pendingClients = new Set();
17007 var mergedPlugins = [].concat(_toConsumableArray$1(ensureArray(Realtime.__preRegisteredPlugins)), _toConsumableArray$1(ensureArray(plugins)));
17008 debug$6('Using plugins %o', mergedPlugins.map(function (plugin) {
17009 return plugin.name;
17010 }));
17011 _this2._plugins = mergedPlugins.reduce(function (result, plugin) {
17012 Object.keys(plugin).forEach(function (hook) {
17013 if ({}.hasOwnProperty.call(plugin, hook) && hook !== 'name') {
17014 if (plugin.name) {
17015 ensureArray(plugin[hook]).forEach(function (value) {
17016 // eslint-disable-next-line no-param-reassign
17017 value._pluginName = plugin.name;
17018 });
17019 }
17020 // eslint-disable-next-line no-param-reassign
17021 result[hook] = ensureArray(result[hook]).concat(plugin[hook]);
17022 }
17023 });
17024 return result;
17025 }, {});
17026 // onRealtimeCreate hook
17027 applyDecorators(_this2._plugins.onRealtimeCreate, _assertThisInitialized(_this2));
17028 return _this2;
17029 }
17030 var _proto = Realtime.prototype;
17031 _proto._request = /*#__PURE__*/function () {
17032 var _request2 = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee(_ref2) {
17033 var method, _url, _ref2$version, version, path, query, headers, data, url, _this$_options, appId, server, _yield$this$construct, api;
17034 return regenerator.wrap(function _callee$(_context) {
17035 while (1) switch (_context.prev = _context.next) {
17036 case 0:
17037 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;
17038 url = _url;
17039 if (url) {
17040 _context.next = 9;
17041 break;
17042 }
17043 _this$_options = this._options, appId = _this$_options.appId, server = _this$_options.server;
17044 _context.next = 6;
17045 return this.constructor._getServerUrls({
17046 appId: appId,
17047 server: server
17048 });
17049 case 6:
17050 _yield$this$construct = _context.sent;
17051 api = _yield$this$construct.api;
17052 url = "".concat(api, "/").concat(version).concat(path);
17053 case 9:
17054 return _context.abrupt("return", request({
17055 url: url,
17056 method: method,
17057 query: query,
17058 headers: _objectSpread$2({
17059 'X-LC-Id': this._options.appId,
17060 'X-LC-Key': this._options.appKey
17061 }, headers),
17062 data: data
17063 }));
17064 case 10:
17065 case "end":
17066 return _context.stop();
17067 }
17068 }, _callee, this);
17069 }));
17070 function _request(_x) {
17071 return _request2.apply(this, arguments);
17072 }
17073 return _request;
17074 }();
17075 _proto._open = function _open() {
17076 var _this3 = this;
17077 if (this._openPromise) return this._openPromise;
17078 var format = 'protobuf2';
17079 if (this._options.noBinary) {
17080 // 不发送 binary data,fallback to base64 string
17081 format = 'proto2base64';
17082 }
17083 var version = 3;
17084 var protocol = {
17085 format: format,
17086 version: version
17087 };
17088 this._openPromise = new Promise(function (resolve, reject) {
17089 debug$6('No connection established, create a new one.');
17090 var connection = new Connection(function () {
17091 return _this3._getRTMServers(_this3._options);
17092 }, protocol);
17093 connection.on(OPEN, function () {
17094 return resolve(connection);
17095 }).on(ERROR, function (error) {
17096 delete _this3._openPromise;
17097 reject(error);
17098 }).on(EXPIRE, /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee2() {
17099 return regenerator.wrap(function _callee2$(_context2) {
17100 while (1) switch (_context2.prev = _context2.next) {
17101 case 0:
17102 debug$6('Connection expired. Refresh endpoints.');
17103 _this3._cache.set('endpoints', null, 0);
17104 _context2.next = 4;
17105 return _this3._getRTMServers(_this3._options);
17106 case 4:
17107 connection.urls = _context2.sent;
17108 connection.disconnect();
17109 case 6:
17110 case "end":
17111 return _context2.stop();
17112 }
17113 }, _callee2);
17114 }))).on(MESSAGE, _this3._dispatchCommand.bind(_this3));
17115 /**
17116 * 连接断开。
17117 * 连接断开可能是因为 SDK 进入了离线状态(see {@link Realtime#event:OFFLINE}),或长时间没有收到服务器心跳。
17118 * 连接断开后所有的网络操作都会失败,请在连接断开后禁用相关的 UI 元素。
17119 * @event Realtime#DISCONNECT
17120 */
17121 /**
17122 * 计划在一段时间后尝试重新连接
17123 * @event Realtime#SCHEDULE
17124 * @param {Number} attempt 尝试重连的次数
17125 * @param {Number} delay 延迟的毫秒数
17126 */
17127 /**
17128 * 正在尝试重新连接
17129 * @event Realtime#RETRY
17130 * @param {Number} attempt 尝试重连的次数
17131 */
17132 /**
17133 * 连接恢复正常。
17134 * 请重新启用在 {@link Realtime#event:DISCONNECT} 事件中禁用的相关 UI 元素
17135 * @event Realtime#RECONNECT
17136 */
17137
17138 /**
17139 * 客户端连接断开
17140 * @event IMClient#DISCONNECT
17141 * @see Realtime#event:DISCONNECT
17142 * @since 3.2.0
17143 */
17144 /**
17145 * 计划在一段时间后尝试重新连接
17146 * @event IMClient#SCHEDULE
17147 * @param {Number} attempt 尝试重连的次数
17148 * @param {Number} delay 延迟的毫秒数
17149 * @since 3.2.0
17150 */
17151 /**
17152 * 正在尝试重新连接
17153 * @event IMClient#RETRY
17154 * @param {Number} attempt 尝试重连的次数
17155 * @since 3.2.0
17156 */
17157
17158 /**
17159 * 客户端进入离线状态。
17160 * 这通常意味着网络已断开,或者 {@link Realtime#pause} 被调用
17161 * @event Realtime#OFFLINE
17162 * @since 3.4.0
17163 */
17164 /**
17165 * 客户端恢复在线状态
17166 * 这通常意味着网络已恢复,或者 {@link Realtime#resume} 被调用
17167 * @event Realtime#ONLINE
17168 * @since 3.4.0
17169 */
17170 /**
17171 * 进入离线状态。
17172 * 这通常意味着网络已断开,或者 {@link Realtime#pause} 被调用
17173 * @event IMClient#OFFLINE
17174 * @since 3.4.0
17175 */
17176 /**
17177 * 恢复在线状态
17178 * 这通常意味着网络已恢复,或者 {@link Realtime#resume} 被调用
17179 * @event IMClient#ONLINE
17180 * @since 3.4.0
17181 */
17182
17183 // event proxy
17184 [DISCONNECT, RECONNECT, RETRY, SCHEDULE, OFFLINE, ONLINE].forEach(function (event) {
17185 return connection.on(event, function () {
17186 for (var _len = arguments.length, payload = new Array(_len), _key = 0; _key < _len; _key++) {
17187 payload[_key] = arguments[_key];
17188 }
17189 debug$6("".concat(event, " event emitted. %o"), payload);
17190 _this3.emit.apply(_this3, [event].concat(payload));
17191 if (event !== RECONNECT) {
17192 internal(_this3).clients.forEach(function (client) {
17193 client.emit.apply(client, [event].concat(payload));
17194 });
17195 }
17196 });
17197 });
17198 // override handleClose
17199 connection.handleClose = function handleClose(event) {
17200 var isFatal = [ErrorCode.APP_NOT_AVAILABLE, ErrorCode.INVALID_LOGIN, ErrorCode.INVALID_ORIGIN].some(function (errorCode) {
17201 return errorCode === event.code;
17202 });
17203 if (isFatal) {
17204 // in these cases, SDK should throw.
17205 this["throw"](createError(event));
17206 } else {
17207 // reconnect
17208 this.disconnect();
17209 }
17210 };
17211 internal(_this3).connection = connection;
17212 });
17213 return this._openPromise;
17214 };
17215 _proto._getRTMServers = /*#__PURE__*/function () {
17216 var _getRTMServers2 = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee3(options) {
17217 var info, cachedEndPoints, _info, server, secondary, ttl;
17218 return regenerator.wrap(function _callee3$(_context3) {
17219 while (1) switch (_context3.prev = _context3.next) {
17220 case 0:
17221 if (!options.RTMServers) {
17222 _context3.next = 2;
17223 break;
17224 }
17225 return _context3.abrupt("return", shuffle_1(ensureArray(options.RTMServers)));
17226 case 2:
17227 cachedEndPoints = this._cache.get('endpoints');
17228 if (!cachedEndPoints) {
17229 _context3.next = 7;
17230 break;
17231 }
17232 info = cachedEndPoints;
17233 _context3.next = 14;
17234 break;
17235 case 7:
17236 _context3.next = 9;
17237 return this.constructor._fetchRTMServers(options);
17238 case 9:
17239 info = _context3.sent;
17240 _info = info, server = _info.server, secondary = _info.secondary, ttl = _info.ttl;
17241 if (!(typeof server !== 'string' && typeof secondary !== 'string' && typeof ttl !== 'number')) {
17242 _context3.next = 13;
17243 break;
17244 }
17245 throw new Error("malformed RTM route response: ".concat(JSON.stringify(info)));
17246 case 13:
17247 this._cache.set('endpoints', info, info.ttl * 1000);
17248 case 14:
17249 debug$6('endpoint info: %O', info);
17250 return _context3.abrupt("return", [info.server, info.secondary]);
17251 case 16:
17252 case "end":
17253 return _context3.stop();
17254 }
17255 }, _callee3, this);
17256 }));
17257 function _getRTMServers(_x2) {
17258 return _getRTMServers2.apply(this, arguments);
17259 }
17260 return _getRTMServers;
17261 }();
17262 Realtime._getServerUrls = /*#__PURE__*/function () {
17263 var _getServerUrls2 = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee4(_ref4) {
17264 var appId, server, cachedRouter, defaultProtocol;
17265 return regenerator.wrap(function _callee4$(_context4) {
17266 while (1) switch (_context4.prev = _context4.next) {
17267 case 0:
17268 appId = _ref4.appId, server = _ref4.server;
17269 debug$6('fetch server urls');
17270 if (!server) {
17271 _context4.next = 6;
17272 break;
17273 }
17274 if (!(typeof server !== 'string')) {
17275 _context4.next = 5;
17276 break;
17277 }
17278 return _context4.abrupt("return", server);
17279 case 5:
17280 return _context4.abrupt("return", {
17281 RTMRouter: server,
17282 api: server
17283 });
17284 case 6:
17285 cachedRouter = routerCache.get(appId);
17286 if (!cachedRouter) {
17287 _context4.next = 9;
17288 break;
17289 }
17290 return _context4.abrupt("return", cachedRouter);
17291 case 9:
17292 defaultProtocol = 'https://';
17293 return _context4.abrupt("return", request({
17294 url: 'https://app-router.com/2/route',
17295 query: {
17296 appId: appId
17297 },
17298 timeout: 20000
17299 }).then(tap(debug$6)).then(function (_ref5) {
17300 var RTMRouterServer = _ref5.rtm_router_server,
17301 APIServer = _ref5.api_server,
17302 _ref5$ttl = _ref5.ttl,
17303 ttl = _ref5$ttl === void 0 ? 3600 : _ref5$ttl;
17304 if (!RTMRouterServer) {
17305 throw new Error('rtm router not exists');
17306 }
17307 var serverUrls = {
17308 RTMRouter: "".concat(defaultProtocol).concat(RTMRouterServer),
17309 api: "".concat(defaultProtocol).concat(APIServer)
17310 };
17311 routerCache.set(appId, serverUrls, ttl * 1000);
17312 return serverUrls;
17313 })["catch"](function () {
17314 var id = appId.slice(0, 8).toLowerCase();
17315 var domain = 'lncldglobal.com';
17316 return {
17317 RTMRouter: "".concat(defaultProtocol).concat(id, ".rtm.").concat(domain),
17318 api: "".concat(defaultProtocol).concat(id, ".api.").concat(domain)
17319 };
17320 }));
17321 case 11:
17322 case "end":
17323 return _context4.stop();
17324 }
17325 }, _callee4);
17326 }));
17327 function _getServerUrls(_x3) {
17328 return _getServerUrls2.apply(this, arguments);
17329 }
17330 return _getServerUrls;
17331 }();
17332 Realtime._fetchRTMServers = function _fetchRTMServers(_ref6) {
17333 var appId = _ref6.appId,
17334 ssl = _ref6.ssl,
17335 server = _ref6.server,
17336 RTMServerName = _ref6.RTMServerName;
17337 debug$6('fetch endpoint info');
17338 return this._getServerUrls({
17339 appId: appId,
17340 server: server
17341 }).then(tap(debug$6)).then(function (_ref7) {
17342 var RTMRouter = _ref7.RTMRouter;
17343 return request({
17344 url: "".concat(RTMRouter, "/v1/route"),
17345 query: {
17346 appId: appId,
17347 secure: ssl,
17348 features: isWeapp ? 'wechat' : undefined,
17349 server: RTMServerName,
17350 _t: Date.now()
17351 },
17352 timeout: 20000
17353 }).then(tap(debug$6));
17354 });
17355 };
17356 _proto._close = function _close() {
17357 if (this._openPromise) {
17358 this._openPromise.then(function (connection) {
17359 return connection.close();
17360 });
17361 }
17362 delete this._openPromise;
17363 }
17364
17365 /**
17366 * 手动进行重连。
17367 * SDK 在网络出现异常时会自动按照一定的时间间隔尝试重连,调用该方法会立即尝试重连并重置重连尝试计数器。
17368 * 只能在 `SCHEDULE` 事件之后,`RETRY` 事件之前调用,如果当前网络正常或者正在进行重连,调用该方法会抛异常。
17369 */;
17370 _proto.retry = function retry() {
17371 var _internal = internal(this),
17372 connection = _internal.connection;
17373 if (!connection) {
17374 throw new Error('no connection established');
17375 }
17376 if (connection.cannot('retry')) {
17377 throw new Error("retrying not allowed when not disconnected. the connection is now ".concat(connection.current));
17378 }
17379 return connection.retry();
17380 }
17381
17382 /**
17383 * 暂停,使 SDK 进入离线状态。
17384 * 你可以在网络断开、应用进入后台等时刻调用该方法让 SDK 进入离线状态,离线状态下不会尝试重连。
17385 * 在浏览器中 SDK 会自动监听网络变化,因此无需手动调用该方法。
17386 *
17387 * @since 3.4.0
17388 * @see Realtime#event:OFFLINE
17389 */;
17390 _proto.pause = function pause() {
17391 // 这个方法常常在网络断开、进入后台时被调用,此时 connection 可能没有建立或者已经 close。
17392 // 因此不像 retry,这个方法应该尽可能 loose
17393 var _internal2 = internal(this),
17394 connection = _internal2.connection;
17395 if (!connection) return;
17396 if (connection.can('pause')) connection.pause();
17397 }
17398
17399 /**
17400 * 恢复在线状态。
17401 * 你可以在网络恢复、应用回到前台等时刻调用该方法让 SDK 恢复在线状态,恢复在线状态后 SDK 会开始尝试重连。
17402 *
17403 * @since 3.4.0
17404 * @see Realtime#event:ONLINE
17405 */;
17406 _proto.resume = function resume() {
17407 // 与 pause 一样,这个方法应该尽可能 loose
17408 var _internal3 = internal(this),
17409 connection = _internal3.connection;
17410 if (!connection) return;
17411 if (connection.can('resume')) connection.resume();
17412 };
17413 _proto._registerPending = function _registerPending(value) {
17414 internal(this).pendingClients.add(value);
17415 };
17416 _proto._deregisterPending = function _deregisterPending(client) {
17417 internal(this).pendingClients["delete"](client);
17418 };
17419 _proto._register = function _register(client) {
17420 internal(this).clients.add(client);
17421 };
17422 _proto._deregister = function _deregister(client) {
17423 var _this = internal(this);
17424 _this.clients["delete"](client);
17425 if (_this.clients.size + _this.pendingClients.size === 0) {
17426 this._close();
17427 }
17428 };
17429 _proto._dispatchCommand = function _dispatchCommand(command) {
17430 return applyDispatcher(this._plugins.beforeCommandDispatch, [command, this]).then(function (shouldDispatch) {
17431 // no plugin handled this command
17432 if (shouldDispatch) return debug$6('[WARN] Unexpected message received: %O', trim(command));
17433 return false;
17434 });
17435 };
17436 return Realtime;
17437 }(eventemitter3); // For test purpose only
17438
17439 var polyfilledPromise = Promise;
17440
17441 var rngBrowser = createCommonjsModule(function (module) {
17442 // Unique ID creation requires a high quality random # generator. In the
17443 // browser this is a little complicated due to unknown quality of Math.random()
17444 // and inconsistent support for the `crypto` API. We do the best we can via
17445 // feature-detection
17446
17447 // getRandomValues needs to be invoked in a context where "this" is a Crypto
17448 // implementation. Also, find the complete implementation of crypto on IE11.
17449 var getRandomValues = (typeof(crypto) != 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto)) ||
17450 (typeof(msCrypto) != 'undefined' && typeof window.msCrypto.getRandomValues == 'function' && msCrypto.getRandomValues.bind(msCrypto));
17451
17452 if (getRandomValues) {
17453 // WHATWG crypto RNG - http://wiki.whatwg.org/wiki/Crypto
17454 var rnds8 = new Uint8Array(16); // eslint-disable-line no-undef
17455
17456 module.exports = function whatwgRNG() {
17457 getRandomValues(rnds8);
17458 return rnds8;
17459 };
17460 } else {
17461 // Math.random()-based (RNG)
17462 //
17463 // If all else fails, use Math.random(). It's fast, but is of unspecified
17464 // quality.
17465 var rnds = new Array(16);
17466
17467 module.exports = function mathRNG() {
17468 for (var i = 0, r; i < 16; i++) {
17469 if ((i & 0x03) === 0) r = Math.random() * 0x100000000;
17470 rnds[i] = r >>> ((i & 0x03) << 3) & 0xff;
17471 }
17472
17473 return rnds;
17474 };
17475 }
17476 });
17477
17478 /**
17479 * Convert array of 16 byte values to UUID string format of the form:
17480 * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
17481 */
17482 var byteToHex = [];
17483 for (var i = 0; i < 256; ++i) {
17484 byteToHex[i] = (i + 0x100).toString(16).substr(1);
17485 }
17486
17487 function bytesToUuid(buf, offset) {
17488 var i = offset || 0;
17489 var bth = byteToHex;
17490 // join used to fix memory issue caused by concatenation: https://bugs.chromium.org/p/v8/issues/detail?id=3175#c4
17491 return ([bth[buf[i++]], bth[buf[i++]],
17492 bth[buf[i++]], bth[buf[i++]], '-',
17493 bth[buf[i++]], bth[buf[i++]], '-',
17494 bth[buf[i++]], bth[buf[i++]], '-',
17495 bth[buf[i++]], bth[buf[i++]], '-',
17496 bth[buf[i++]], bth[buf[i++]],
17497 bth[buf[i++]], bth[buf[i++]],
17498 bth[buf[i++]], bth[buf[i++]]]).join('');
17499 }
17500
17501 var bytesToUuid_1 = bytesToUuid;
17502
17503 function v4(options, buf, offset) {
17504 var i = buf && offset || 0;
17505
17506 if (typeof(options) == 'string') {
17507 buf = options === 'binary' ? new Array(16) : null;
17508 options = null;
17509 }
17510 options = options || {};
17511
17512 var rnds = options.random || (options.rng || rngBrowser)();
17513
17514 // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
17515 rnds[6] = (rnds[6] & 0x0f) | 0x40;
17516 rnds[8] = (rnds[8] & 0x3f) | 0x80;
17517
17518 // Copy bytes to buffer, if provided
17519 if (buf) {
17520 for (var ii = 0; ii < 16; ++ii) {
17521 buf[i + ii] = rnds[ii];
17522 }
17523 }
17524
17525 return buf || bytesToUuid_1(rnds);
17526 }
17527
17528 var v4_1 = v4;
17529
17530 var iterableToArrayLimit = createCommonjsModule(function (module) {
17531 function _iterableToArrayLimit(arr, i) {
17532 var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"];
17533 if (null != _i) {
17534 var _s,
17535 _e,
17536 _x,
17537 _r,
17538 _arr = [],
17539 _n = !0,
17540 _d = !1;
17541 try {
17542 if (_x = (_i = _i.call(arr)).next, 0 === i) {
17543 if (Object(_i) !== _i) return;
17544 _n = !1;
17545 } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0);
17546 } catch (err) {
17547 _d = !0, _e = err;
17548 } finally {
17549 try {
17550 if (!_n && null != _i["return"] && (_r = _i["return"](), Object(_r) !== _r)) return;
17551 } finally {
17552 if (_d) throw _e;
17553 }
17554 }
17555 return _arr;
17556 }
17557 }
17558 module.exports = _iterableToArrayLimit, module.exports.__esModule = true, module.exports["default"] = module.exports;
17559 });
17560
17561 unwrapExports(iterableToArrayLimit);
17562
17563 var slicedToArray = createCommonjsModule(function (module) {
17564 function _slicedToArray(arr, i) {
17565 return arrayWithHoles(arr) || iterableToArrayLimit(arr, i) || unsupportedIterableToArray(arr, i) || nonIterableRest();
17566 }
17567 module.exports = _slicedToArray, module.exports.__esModule = true, module.exports["default"] = module.exports;
17568 });
17569
17570 var _slicedToArray = unwrapExports(slicedToArray);
17571
17572 var base64Arraybuffer = createCommonjsModule(function (module, exports) {
17573 /*
17574 * base64-arraybuffer
17575 * https://github.com/niklasvh/base64-arraybuffer
17576 *
17577 * Copyright (c) 2012 Niklas von Hertzen
17578 * Licensed under the MIT license.
17579 */
17580 (function(){
17581
17582 var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
17583
17584 // Use a lookup table to find the index.
17585 var lookup = new Uint8Array(256);
17586 for (var i = 0; i < chars.length; i++) {
17587 lookup[chars.charCodeAt(i)] = i;
17588 }
17589
17590 exports.encode = function(arraybuffer) {
17591 var bytes = new Uint8Array(arraybuffer),
17592 i, len = bytes.length, base64 = "";
17593
17594 for (i = 0; i < len; i+=3) {
17595 base64 += chars[bytes[i] >> 2];
17596 base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];
17597 base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];
17598 base64 += chars[bytes[i + 2] & 63];
17599 }
17600
17601 if ((len % 3) === 2) {
17602 base64 = base64.substring(0, base64.length - 1) + "=";
17603 } else if (len % 3 === 1) {
17604 base64 = base64.substring(0, base64.length - 2) + "==";
17605 }
17606
17607 return base64;
17608 };
17609
17610 exports.decode = function(base64) {
17611 var bufferLength = base64.length * 0.75,
17612 len = base64.length, i, p = 0,
17613 encoded1, encoded2, encoded3, encoded4;
17614
17615 if (base64[base64.length - 1] === "=") {
17616 bufferLength--;
17617 if (base64[base64.length - 2] === "=") {
17618 bufferLength--;
17619 }
17620 }
17621
17622 var arraybuffer = new ArrayBuffer(bufferLength),
17623 bytes = new Uint8Array(arraybuffer);
17624
17625 for (i = 0; i < len; i+=4) {
17626 encoded1 = lookup[base64.charCodeAt(i)];
17627 encoded2 = lookup[base64.charCodeAt(i+1)];
17628 encoded3 = lookup[base64.charCodeAt(i+2)];
17629 encoded4 = lookup[base64.charCodeAt(i+3)];
17630
17631 bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);
17632 bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);
17633 bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);
17634 }
17635
17636 return arraybuffer;
17637 };
17638 })();
17639 });
17640 var base64Arraybuffer_1 = base64Arraybuffer.encode;
17641 var base64Arraybuffer_2 = base64Arraybuffer.decode;
17642
17643 /**
17644 * Removes all key-value entries from the list cache.
17645 *
17646 * @private
17647 * @name clear
17648 * @memberOf ListCache
17649 */
17650 function listCacheClear() {
17651 this.__data__ = [];
17652 this.size = 0;
17653 }
17654
17655 var _listCacheClear = listCacheClear;
17656
17657 /**
17658 * Performs a
17659 * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
17660 * comparison between two values to determine if they are equivalent.
17661 *
17662 * @static
17663 * @memberOf _
17664 * @since 4.0.0
17665 * @category Lang
17666 * @param {*} value The value to compare.
17667 * @param {*} other The other value to compare.
17668 * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
17669 * @example
17670 *
17671 * var object = { 'a': 1 };
17672 * var other = { 'a': 1 };
17673 *
17674 * _.eq(object, object);
17675 * // => true
17676 *
17677 * _.eq(object, other);
17678 * // => false
17679 *
17680 * _.eq('a', 'a');
17681 * // => true
17682 *
17683 * _.eq('a', Object('a'));
17684 * // => false
17685 *
17686 * _.eq(NaN, NaN);
17687 * // => true
17688 */
17689 function eq(value, other) {
17690 return value === other || (value !== value && other !== other);
17691 }
17692
17693 var eq_1 = eq;
17694
17695 /**
17696 * Gets the index at which the `key` is found in `array` of key-value pairs.
17697 *
17698 * @private
17699 * @param {Array} array The array to inspect.
17700 * @param {*} key The key to search for.
17701 * @returns {number} Returns the index of the matched value, else `-1`.
17702 */
17703 function assocIndexOf(array, key) {
17704 var length = array.length;
17705 while (length--) {
17706 if (eq_1(array[length][0], key)) {
17707 return length;
17708 }
17709 }
17710 return -1;
17711 }
17712
17713 var _assocIndexOf = assocIndexOf;
17714
17715 /** Used for built-in method references. */
17716 var arrayProto = Array.prototype;
17717
17718 /** Built-in value references. */
17719 var splice = arrayProto.splice;
17720
17721 /**
17722 * Removes `key` and its value from the list cache.
17723 *
17724 * @private
17725 * @name delete
17726 * @memberOf ListCache
17727 * @param {string} key The key of the value to remove.
17728 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
17729 */
17730 function listCacheDelete(key) {
17731 var data = this.__data__,
17732 index = _assocIndexOf(data, key);
17733
17734 if (index < 0) {
17735 return false;
17736 }
17737 var lastIndex = data.length - 1;
17738 if (index == lastIndex) {
17739 data.pop();
17740 } else {
17741 splice.call(data, index, 1);
17742 }
17743 --this.size;
17744 return true;
17745 }
17746
17747 var _listCacheDelete = listCacheDelete;
17748
17749 /**
17750 * Gets the list cache value for `key`.
17751 *
17752 * @private
17753 * @name get
17754 * @memberOf ListCache
17755 * @param {string} key The key of the value to get.
17756 * @returns {*} Returns the entry value.
17757 */
17758 function listCacheGet(key) {
17759 var data = this.__data__,
17760 index = _assocIndexOf(data, key);
17761
17762 return index < 0 ? undefined : data[index][1];
17763 }
17764
17765 var _listCacheGet = listCacheGet;
17766
17767 /**
17768 * Checks if a list cache value for `key` exists.
17769 *
17770 * @private
17771 * @name has
17772 * @memberOf ListCache
17773 * @param {string} key The key of the entry to check.
17774 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
17775 */
17776 function listCacheHas(key) {
17777 return _assocIndexOf(this.__data__, key) > -1;
17778 }
17779
17780 var _listCacheHas = listCacheHas;
17781
17782 /**
17783 * Sets the list cache `key` to `value`.
17784 *
17785 * @private
17786 * @name set
17787 * @memberOf ListCache
17788 * @param {string} key The key of the value to set.
17789 * @param {*} value The value to set.
17790 * @returns {Object} Returns the list cache instance.
17791 */
17792 function listCacheSet(key, value) {
17793 var data = this.__data__,
17794 index = _assocIndexOf(data, key);
17795
17796 if (index < 0) {
17797 ++this.size;
17798 data.push([key, value]);
17799 } else {
17800 data[index][1] = value;
17801 }
17802 return this;
17803 }
17804
17805 var _listCacheSet = listCacheSet;
17806
17807 /**
17808 * Creates an list cache object.
17809 *
17810 * @private
17811 * @constructor
17812 * @param {Array} [entries] The key-value pairs to cache.
17813 */
17814 function ListCache(entries) {
17815 var index = -1,
17816 length = entries == null ? 0 : entries.length;
17817
17818 this.clear();
17819 while (++index < length) {
17820 var entry = entries[index];
17821 this.set(entry[0], entry[1]);
17822 }
17823 }
17824
17825 // Add methods to `ListCache`.
17826 ListCache.prototype.clear = _listCacheClear;
17827 ListCache.prototype['delete'] = _listCacheDelete;
17828 ListCache.prototype.get = _listCacheGet;
17829 ListCache.prototype.has = _listCacheHas;
17830 ListCache.prototype.set = _listCacheSet;
17831
17832 var _ListCache = ListCache;
17833
17834 /**
17835 * Removes all key-value entries from the stack.
17836 *
17837 * @private
17838 * @name clear
17839 * @memberOf Stack
17840 */
17841 function stackClear() {
17842 this.__data__ = new _ListCache;
17843 this.size = 0;
17844 }
17845
17846 var _stackClear = stackClear;
17847
17848 /**
17849 * Removes `key` and its value from the stack.
17850 *
17851 * @private
17852 * @name delete
17853 * @memberOf Stack
17854 * @param {string} key The key of the value to remove.
17855 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
17856 */
17857 function stackDelete(key) {
17858 var data = this.__data__,
17859 result = data['delete'](key);
17860
17861 this.size = data.size;
17862 return result;
17863 }
17864
17865 var _stackDelete = stackDelete;
17866
17867 /**
17868 * Gets the stack value for `key`.
17869 *
17870 * @private
17871 * @name get
17872 * @memberOf Stack
17873 * @param {string} key The key of the value to get.
17874 * @returns {*} Returns the entry value.
17875 */
17876 function stackGet(key) {
17877 return this.__data__.get(key);
17878 }
17879
17880 var _stackGet = stackGet;
17881
17882 /**
17883 * Checks if a stack value for `key` exists.
17884 *
17885 * @private
17886 * @name has
17887 * @memberOf Stack
17888 * @param {string} key The key of the entry to check.
17889 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
17890 */
17891 function stackHas(key) {
17892 return this.__data__.has(key);
17893 }
17894
17895 var _stackHas = stackHas;
17896
17897 /** Used to detect overreaching core-js shims. */
17898 var coreJsData = _root['__core-js_shared__'];
17899
17900 var _coreJsData = coreJsData;
17901
17902 /** Used to detect methods masquerading as native. */
17903 var maskSrcKey = (function() {
17904 var uid = /[^.]+$/.exec(_coreJsData && _coreJsData.keys && _coreJsData.keys.IE_PROTO || '');
17905 return uid ? ('Symbol(src)_1.' + uid) : '';
17906 }());
17907
17908 /**
17909 * Checks if `func` has its source masked.
17910 *
17911 * @private
17912 * @param {Function} func The function to check.
17913 * @returns {boolean} Returns `true` if `func` is masked, else `false`.
17914 */
17915 function isMasked(func) {
17916 return !!maskSrcKey && (maskSrcKey in func);
17917 }
17918
17919 var _isMasked = isMasked;
17920
17921 /** Used for built-in method references. */
17922 var funcProto$1 = Function.prototype;
17923
17924 /** Used to resolve the decompiled source of functions. */
17925 var funcToString$1 = funcProto$1.toString;
17926
17927 /**
17928 * Converts `func` to its source code.
17929 *
17930 * @private
17931 * @param {Function} func The function to convert.
17932 * @returns {string} Returns the source code.
17933 */
17934 function toSource(func) {
17935 if (func != null) {
17936 try {
17937 return funcToString$1.call(func);
17938 } catch (e) {}
17939 try {
17940 return (func + '');
17941 } catch (e) {}
17942 }
17943 return '';
17944 }
17945
17946 var _toSource = toSource;
17947
17948 /**
17949 * Used to match `RegExp`
17950 * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
17951 */
17952 var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
17953
17954 /** Used to detect host constructors (Safari). */
17955 var reIsHostCtor = /^\[object .+?Constructor\]$/;
17956
17957 /** Used for built-in method references. */
17958 var funcProto$2 = Function.prototype,
17959 objectProto$7 = Object.prototype;
17960
17961 /** Used to resolve the decompiled source of functions. */
17962 var funcToString$2 = funcProto$2.toString;
17963
17964 /** Used to check objects for own properties. */
17965 var hasOwnProperty$5 = objectProto$7.hasOwnProperty;
17966
17967 /** Used to detect if a method is native. */
17968 var reIsNative = RegExp('^' +
17969 funcToString$2.call(hasOwnProperty$5).replace(reRegExpChar, '\\$&')
17970 .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
17971 );
17972
17973 /**
17974 * The base implementation of `_.isNative` without bad shim checks.
17975 *
17976 * @private
17977 * @param {*} value The value to check.
17978 * @returns {boolean} Returns `true` if `value` is a native function,
17979 * else `false`.
17980 */
17981 function baseIsNative(value) {
17982 if (!isObject_1$1(value) || _isMasked(value)) {
17983 return false;
17984 }
17985 var pattern = isFunction_1(value) ? reIsNative : reIsHostCtor;
17986 return pattern.test(_toSource(value));
17987 }
17988
17989 var _baseIsNative = baseIsNative;
17990
17991 /**
17992 * Gets the value at `key` of `object`.
17993 *
17994 * @private
17995 * @param {Object} [object] The object to query.
17996 * @param {string} key The key of the property to get.
17997 * @returns {*} Returns the property value.
17998 */
17999 function getValue(object, key) {
18000 return object == null ? undefined : object[key];
18001 }
18002
18003 var _getValue = getValue;
18004
18005 /**
18006 * Gets the native function at `key` of `object`.
18007 *
18008 * @private
18009 * @param {Object} object The object to query.
18010 * @param {string} key The key of the method to get.
18011 * @returns {*} Returns the function if it's native, else `undefined`.
18012 */
18013 function getNative(object, key) {
18014 var value = _getValue(object, key);
18015 return _baseIsNative(value) ? value : undefined;
18016 }
18017
18018 var _getNative = getNative;
18019
18020 /* Built-in method references that are verified to be native. */
18021 var Map = _getNative(_root, 'Map');
18022
18023 var _Map = Map;
18024
18025 /* Built-in method references that are verified to be native. */
18026 var nativeCreate = _getNative(Object, 'create');
18027
18028 var _nativeCreate = nativeCreate;
18029
18030 /**
18031 * Removes all key-value entries from the hash.
18032 *
18033 * @private
18034 * @name clear
18035 * @memberOf Hash
18036 */
18037 function hashClear() {
18038 this.__data__ = _nativeCreate ? _nativeCreate(null) : {};
18039 this.size = 0;
18040 }
18041
18042 var _hashClear = hashClear;
18043
18044 /**
18045 * Removes `key` and its value from the hash.
18046 *
18047 * @private
18048 * @name delete
18049 * @memberOf Hash
18050 * @param {Object} hash The hash to modify.
18051 * @param {string} key The key of the value to remove.
18052 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
18053 */
18054 function hashDelete(key) {
18055 var result = this.has(key) && delete this.__data__[key];
18056 this.size -= result ? 1 : 0;
18057 return result;
18058 }
18059
18060 var _hashDelete = hashDelete;
18061
18062 /** Used to stand-in for `undefined` hash values. */
18063 var HASH_UNDEFINED = '__lodash_hash_undefined__';
18064
18065 /** Used for built-in method references. */
18066 var objectProto$8 = Object.prototype;
18067
18068 /** Used to check objects for own properties. */
18069 var hasOwnProperty$6 = objectProto$8.hasOwnProperty;
18070
18071 /**
18072 * Gets the hash value for `key`.
18073 *
18074 * @private
18075 * @name get
18076 * @memberOf Hash
18077 * @param {string} key The key of the value to get.
18078 * @returns {*} Returns the entry value.
18079 */
18080 function hashGet(key) {
18081 var data = this.__data__;
18082 if (_nativeCreate) {
18083 var result = data[key];
18084 return result === HASH_UNDEFINED ? undefined : result;
18085 }
18086 return hasOwnProperty$6.call(data, key) ? data[key] : undefined;
18087 }
18088
18089 var _hashGet = hashGet;
18090
18091 /** Used for built-in method references. */
18092 var objectProto$9 = Object.prototype;
18093
18094 /** Used to check objects for own properties. */
18095 var hasOwnProperty$7 = objectProto$9.hasOwnProperty;
18096
18097 /**
18098 * Checks if a hash value for `key` exists.
18099 *
18100 * @private
18101 * @name has
18102 * @memberOf Hash
18103 * @param {string} key The key of the entry to check.
18104 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
18105 */
18106 function hashHas(key) {
18107 var data = this.__data__;
18108 return _nativeCreate ? (data[key] !== undefined) : hasOwnProperty$7.call(data, key);
18109 }
18110
18111 var _hashHas = hashHas;
18112
18113 /** Used to stand-in for `undefined` hash values. */
18114 var HASH_UNDEFINED$1 = '__lodash_hash_undefined__';
18115
18116 /**
18117 * Sets the hash `key` to `value`.
18118 *
18119 * @private
18120 * @name set
18121 * @memberOf Hash
18122 * @param {string} key The key of the value to set.
18123 * @param {*} value The value to set.
18124 * @returns {Object} Returns the hash instance.
18125 */
18126 function hashSet(key, value) {
18127 var data = this.__data__;
18128 this.size += this.has(key) ? 0 : 1;
18129 data[key] = (_nativeCreate && value === undefined) ? HASH_UNDEFINED$1 : value;
18130 return this;
18131 }
18132
18133 var _hashSet = hashSet;
18134
18135 /**
18136 * Creates a hash object.
18137 *
18138 * @private
18139 * @constructor
18140 * @param {Array} [entries] The key-value pairs to cache.
18141 */
18142 function Hash(entries) {
18143 var index = -1,
18144 length = entries == null ? 0 : entries.length;
18145
18146 this.clear();
18147 while (++index < length) {
18148 var entry = entries[index];
18149 this.set(entry[0], entry[1]);
18150 }
18151 }
18152
18153 // Add methods to `Hash`.
18154 Hash.prototype.clear = _hashClear;
18155 Hash.prototype['delete'] = _hashDelete;
18156 Hash.prototype.get = _hashGet;
18157 Hash.prototype.has = _hashHas;
18158 Hash.prototype.set = _hashSet;
18159
18160 var _Hash = Hash;
18161
18162 /**
18163 * Removes all key-value entries from the map.
18164 *
18165 * @private
18166 * @name clear
18167 * @memberOf MapCache
18168 */
18169 function mapCacheClear() {
18170 this.size = 0;
18171 this.__data__ = {
18172 'hash': new _Hash,
18173 'map': new (_Map || _ListCache),
18174 'string': new _Hash
18175 };
18176 }
18177
18178 var _mapCacheClear = mapCacheClear;
18179
18180 /**
18181 * Checks if `value` is suitable for use as unique object key.
18182 *
18183 * @private
18184 * @param {*} value The value to check.
18185 * @returns {boolean} Returns `true` if `value` is suitable, else `false`.
18186 */
18187 function isKeyable(value) {
18188 var type = typeof value;
18189 return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')
18190 ? (value !== '__proto__')
18191 : (value === null);
18192 }
18193
18194 var _isKeyable = isKeyable;
18195
18196 /**
18197 * Gets the data for `map`.
18198 *
18199 * @private
18200 * @param {Object} map The map to query.
18201 * @param {string} key The reference key.
18202 * @returns {*} Returns the map data.
18203 */
18204 function getMapData(map, key) {
18205 var data = map.__data__;
18206 return _isKeyable(key)
18207 ? data[typeof key == 'string' ? 'string' : 'hash']
18208 : data.map;
18209 }
18210
18211 var _getMapData = getMapData;
18212
18213 /**
18214 * Removes `key` and its value from the map.
18215 *
18216 * @private
18217 * @name delete
18218 * @memberOf MapCache
18219 * @param {string} key The key of the value to remove.
18220 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
18221 */
18222 function mapCacheDelete(key) {
18223 var result = _getMapData(this, key)['delete'](key);
18224 this.size -= result ? 1 : 0;
18225 return result;
18226 }
18227
18228 var _mapCacheDelete = mapCacheDelete;
18229
18230 /**
18231 * Gets the map value for `key`.
18232 *
18233 * @private
18234 * @name get
18235 * @memberOf MapCache
18236 * @param {string} key The key of the value to get.
18237 * @returns {*} Returns the entry value.
18238 */
18239 function mapCacheGet(key) {
18240 return _getMapData(this, key).get(key);
18241 }
18242
18243 var _mapCacheGet = mapCacheGet;
18244
18245 /**
18246 * Checks if a map value for `key` exists.
18247 *
18248 * @private
18249 * @name has
18250 * @memberOf MapCache
18251 * @param {string} key The key of the entry to check.
18252 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
18253 */
18254 function mapCacheHas(key) {
18255 return _getMapData(this, key).has(key);
18256 }
18257
18258 var _mapCacheHas = mapCacheHas;
18259
18260 /**
18261 * Sets the map `key` to `value`.
18262 *
18263 * @private
18264 * @name set
18265 * @memberOf MapCache
18266 * @param {string} key The key of the value to set.
18267 * @param {*} value The value to set.
18268 * @returns {Object} Returns the map cache instance.
18269 */
18270 function mapCacheSet(key, value) {
18271 var data = _getMapData(this, key),
18272 size = data.size;
18273
18274 data.set(key, value);
18275 this.size += data.size == size ? 0 : 1;
18276 return this;
18277 }
18278
18279 var _mapCacheSet = mapCacheSet;
18280
18281 /**
18282 * Creates a map cache object to store key-value pairs.
18283 *
18284 * @private
18285 * @constructor
18286 * @param {Array} [entries] The key-value pairs to cache.
18287 */
18288 function MapCache(entries) {
18289 var index = -1,
18290 length = entries == null ? 0 : entries.length;
18291
18292 this.clear();
18293 while (++index < length) {
18294 var entry = entries[index];
18295 this.set(entry[0], entry[1]);
18296 }
18297 }
18298
18299 // Add methods to `MapCache`.
18300 MapCache.prototype.clear = _mapCacheClear;
18301 MapCache.prototype['delete'] = _mapCacheDelete;
18302 MapCache.prototype.get = _mapCacheGet;
18303 MapCache.prototype.has = _mapCacheHas;
18304 MapCache.prototype.set = _mapCacheSet;
18305
18306 var _MapCache = MapCache;
18307
18308 /** Used as the size to enable large array optimizations. */
18309 var LARGE_ARRAY_SIZE = 200;
18310
18311 /**
18312 * Sets the stack `key` to `value`.
18313 *
18314 * @private
18315 * @name set
18316 * @memberOf Stack
18317 * @param {string} key The key of the value to set.
18318 * @param {*} value The value to set.
18319 * @returns {Object} Returns the stack cache instance.
18320 */
18321 function stackSet(key, value) {
18322 var data = this.__data__;
18323 if (data instanceof _ListCache) {
18324 var pairs = data.__data__;
18325 if (!_Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) {
18326 pairs.push([key, value]);
18327 this.size = ++data.size;
18328 return this;
18329 }
18330 data = this.__data__ = new _MapCache(pairs);
18331 }
18332 data.set(key, value);
18333 this.size = data.size;
18334 return this;
18335 }
18336
18337 var _stackSet = stackSet;
18338
18339 /**
18340 * Creates a stack cache object to store key-value pairs.
18341 *
18342 * @private
18343 * @constructor
18344 * @param {Array} [entries] The key-value pairs to cache.
18345 */
18346 function Stack(entries) {
18347 var data = this.__data__ = new _ListCache(entries);
18348 this.size = data.size;
18349 }
18350
18351 // Add methods to `Stack`.
18352 Stack.prototype.clear = _stackClear;
18353 Stack.prototype['delete'] = _stackDelete;
18354 Stack.prototype.get = _stackGet;
18355 Stack.prototype.has = _stackHas;
18356 Stack.prototype.set = _stackSet;
18357
18358 var _Stack = Stack;
18359
18360 /** Used to stand-in for `undefined` hash values. */
18361 var HASH_UNDEFINED$2 = '__lodash_hash_undefined__';
18362
18363 /**
18364 * Adds `value` to the array cache.
18365 *
18366 * @private
18367 * @name add
18368 * @memberOf SetCache
18369 * @alias push
18370 * @param {*} value The value to cache.
18371 * @returns {Object} Returns the cache instance.
18372 */
18373 function setCacheAdd(value) {
18374 this.__data__.set(value, HASH_UNDEFINED$2);
18375 return this;
18376 }
18377
18378 var _setCacheAdd = setCacheAdd;
18379
18380 /**
18381 * Checks if `value` is in the array cache.
18382 *
18383 * @private
18384 * @name has
18385 * @memberOf SetCache
18386 * @param {*} value The value to search for.
18387 * @returns {number} Returns `true` if `value` is found, else `false`.
18388 */
18389 function setCacheHas(value) {
18390 return this.__data__.has(value);
18391 }
18392
18393 var _setCacheHas = setCacheHas;
18394
18395 /**
18396 *
18397 * Creates an array cache object to store unique values.
18398 *
18399 * @private
18400 * @constructor
18401 * @param {Array} [values] The values to cache.
18402 */
18403 function SetCache(values) {
18404 var index = -1,
18405 length = values == null ? 0 : values.length;
18406
18407 this.__data__ = new _MapCache;
18408 while (++index < length) {
18409 this.add(values[index]);
18410 }
18411 }
18412
18413 // Add methods to `SetCache`.
18414 SetCache.prototype.add = SetCache.prototype.push = _setCacheAdd;
18415 SetCache.prototype.has = _setCacheHas;
18416
18417 var _SetCache = SetCache;
18418
18419 /**
18420 * A specialized version of `_.some` for arrays without support for iteratee
18421 * shorthands.
18422 *
18423 * @private
18424 * @param {Array} [array] The array to iterate over.
18425 * @param {Function} predicate The function invoked per iteration.
18426 * @returns {boolean} Returns `true` if any element passes the predicate check,
18427 * else `false`.
18428 */
18429 function arraySome(array, predicate) {
18430 var index = -1,
18431 length = array == null ? 0 : array.length;
18432
18433 while (++index < length) {
18434 if (predicate(array[index], index, array)) {
18435 return true;
18436 }
18437 }
18438 return false;
18439 }
18440
18441 var _arraySome = arraySome;
18442
18443 /**
18444 * Checks if a `cache` value for `key` exists.
18445 *
18446 * @private
18447 * @param {Object} cache The cache to query.
18448 * @param {string} key The key of the entry to check.
18449 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
18450 */
18451 function cacheHas(cache, key) {
18452 return cache.has(key);
18453 }
18454
18455 var _cacheHas = cacheHas;
18456
18457 /** Used to compose bitmasks for value comparisons. */
18458 var COMPARE_PARTIAL_FLAG = 1,
18459 COMPARE_UNORDERED_FLAG = 2;
18460
18461 /**
18462 * A specialized version of `baseIsEqualDeep` for arrays with support for
18463 * partial deep comparisons.
18464 *
18465 * @private
18466 * @param {Array} array The array to compare.
18467 * @param {Array} other The other array to compare.
18468 * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
18469 * @param {Function} customizer The function to customize comparisons.
18470 * @param {Function} equalFunc The function to determine equivalents of values.
18471 * @param {Object} stack Tracks traversed `array` and `other` objects.
18472 * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.
18473 */
18474 function equalArrays(array, other, bitmask, customizer, equalFunc, stack) {
18475 var isPartial = bitmask & COMPARE_PARTIAL_FLAG,
18476 arrLength = array.length,
18477 othLength = other.length;
18478
18479 if (arrLength != othLength && !(isPartial && othLength > arrLength)) {
18480 return false;
18481 }
18482 // Check that cyclic values are equal.
18483 var arrStacked = stack.get(array);
18484 var othStacked = stack.get(other);
18485 if (arrStacked && othStacked) {
18486 return arrStacked == other && othStacked == array;
18487 }
18488 var index = -1,
18489 result = true,
18490 seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new _SetCache : undefined;
18491
18492 stack.set(array, other);
18493 stack.set(other, array);
18494
18495 // Ignore non-index properties.
18496 while (++index < arrLength) {
18497 var arrValue = array[index],
18498 othValue = other[index];
18499
18500 if (customizer) {
18501 var compared = isPartial
18502 ? customizer(othValue, arrValue, index, other, array, stack)
18503 : customizer(arrValue, othValue, index, array, other, stack);
18504 }
18505 if (compared !== undefined) {
18506 if (compared) {
18507 continue;
18508 }
18509 result = false;
18510 break;
18511 }
18512 // Recursively compare arrays (susceptible to call stack limits).
18513 if (seen) {
18514 if (!_arraySome(other, function(othValue, othIndex) {
18515 if (!_cacheHas(seen, othIndex) &&
18516 (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {
18517 return seen.push(othIndex);
18518 }
18519 })) {
18520 result = false;
18521 break;
18522 }
18523 } else if (!(
18524 arrValue === othValue ||
18525 equalFunc(arrValue, othValue, bitmask, customizer, stack)
18526 )) {
18527 result = false;
18528 break;
18529 }
18530 }
18531 stack['delete'](array);
18532 stack['delete'](other);
18533 return result;
18534 }
18535
18536 var _equalArrays = equalArrays;
18537
18538 /** Built-in value references. */
18539 var Uint8Array$1 = _root.Uint8Array;
18540
18541 var _Uint8Array = Uint8Array$1;
18542
18543 /**
18544 * Converts `map` to its key-value pairs.
18545 *
18546 * @private
18547 * @param {Object} map The map to convert.
18548 * @returns {Array} Returns the key-value pairs.
18549 */
18550 function mapToArray(map) {
18551 var index = -1,
18552 result = Array(map.size);
18553
18554 map.forEach(function(value, key) {
18555 result[++index] = [key, value];
18556 });
18557 return result;
18558 }
18559
18560 var _mapToArray = mapToArray;
18561
18562 /**
18563 * Converts `set` to an array of its values.
18564 *
18565 * @private
18566 * @param {Object} set The set to convert.
18567 * @returns {Array} Returns the values.
18568 */
18569 function setToArray(set) {
18570 var index = -1,
18571 result = Array(set.size);
18572
18573 set.forEach(function(value) {
18574 result[++index] = value;
18575 });
18576 return result;
18577 }
18578
18579 var _setToArray = setToArray;
18580
18581 /** Used to compose bitmasks for value comparisons. */
18582 var COMPARE_PARTIAL_FLAG$1 = 1,
18583 COMPARE_UNORDERED_FLAG$1 = 2;
18584
18585 /** `Object#toString` result references. */
18586 var boolTag$1 = '[object Boolean]',
18587 dateTag$1 = '[object Date]',
18588 errorTag$1 = '[object Error]',
18589 mapTag$1 = '[object Map]',
18590 numberTag$1 = '[object Number]',
18591 regexpTag$1 = '[object RegExp]',
18592 setTag$1 = '[object Set]',
18593 stringTag$1 = '[object String]',
18594 symbolTag = '[object Symbol]';
18595
18596 var arrayBufferTag$1 = '[object ArrayBuffer]',
18597 dataViewTag$1 = '[object DataView]';
18598
18599 /** Used to convert symbols to primitives and strings. */
18600 var symbolProto = _Symbol ? _Symbol.prototype : undefined,
18601 symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;
18602
18603 /**
18604 * A specialized version of `baseIsEqualDeep` for comparing objects of
18605 * the same `toStringTag`.
18606 *
18607 * **Note:** This function only supports comparing values with tags of
18608 * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
18609 *
18610 * @private
18611 * @param {Object} object The object to compare.
18612 * @param {Object} other The other object to compare.
18613 * @param {string} tag The `toStringTag` of the objects to compare.
18614 * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
18615 * @param {Function} customizer The function to customize comparisons.
18616 * @param {Function} equalFunc The function to determine equivalents of values.
18617 * @param {Object} stack Tracks traversed `object` and `other` objects.
18618 * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
18619 */
18620 function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {
18621 switch (tag) {
18622 case dataViewTag$1:
18623 if ((object.byteLength != other.byteLength) ||
18624 (object.byteOffset != other.byteOffset)) {
18625 return false;
18626 }
18627 object = object.buffer;
18628 other = other.buffer;
18629
18630 case arrayBufferTag$1:
18631 if ((object.byteLength != other.byteLength) ||
18632 !equalFunc(new _Uint8Array(object), new _Uint8Array(other))) {
18633 return false;
18634 }
18635 return true;
18636
18637 case boolTag$1:
18638 case dateTag$1:
18639 case numberTag$1:
18640 // Coerce booleans to `1` or `0` and dates to milliseconds.
18641 // Invalid dates are coerced to `NaN`.
18642 return eq_1(+object, +other);
18643
18644 case errorTag$1:
18645 return object.name == other.name && object.message == other.message;
18646
18647 case regexpTag$1:
18648 case stringTag$1:
18649 // Coerce regexes to strings and treat strings, primitives and objects,
18650 // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring
18651 // for more details.
18652 return object == (other + '');
18653
18654 case mapTag$1:
18655 var convert = _mapToArray;
18656
18657 case setTag$1:
18658 var isPartial = bitmask & COMPARE_PARTIAL_FLAG$1;
18659 convert || (convert = _setToArray);
18660
18661 if (object.size != other.size && !isPartial) {
18662 return false;
18663 }
18664 // Assume cyclic values are equal.
18665 var stacked = stack.get(object);
18666 if (stacked) {
18667 return stacked == other;
18668 }
18669 bitmask |= COMPARE_UNORDERED_FLAG$1;
18670
18671 // Recursively compare objects (susceptible to call stack limits).
18672 stack.set(object, other);
18673 var result = _equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack);
18674 stack['delete'](object);
18675 return result;
18676
18677 case symbolTag:
18678 if (symbolValueOf) {
18679 return symbolValueOf.call(object) == symbolValueOf.call(other);
18680 }
18681 }
18682 return false;
18683 }
18684
18685 var _equalByTag = equalByTag;
18686
18687 /**
18688 * Appends the elements of `values` to `array`.
18689 *
18690 * @private
18691 * @param {Array} array The array to modify.
18692 * @param {Array} values The values to append.
18693 * @returns {Array} Returns `array`.
18694 */
18695 function arrayPush(array, values) {
18696 var index = -1,
18697 length = values.length,
18698 offset = array.length;
18699
18700 while (++index < length) {
18701 array[offset + index] = values[index];
18702 }
18703 return array;
18704 }
18705
18706 var _arrayPush = arrayPush;
18707
18708 /**
18709 * The base implementation of `getAllKeys` and `getAllKeysIn` which uses
18710 * `keysFunc` and `symbolsFunc` to get the enumerable property names and
18711 * symbols of `object`.
18712 *
18713 * @private
18714 * @param {Object} object The object to query.
18715 * @param {Function} keysFunc The function to get the keys of `object`.
18716 * @param {Function} symbolsFunc The function to get the symbols of `object`.
18717 * @returns {Array} Returns the array of property names and symbols.
18718 */
18719 function baseGetAllKeys(object, keysFunc, symbolsFunc) {
18720 var result = keysFunc(object);
18721 return isArray_1(object) ? result : _arrayPush(result, symbolsFunc(object));
18722 }
18723
18724 var _baseGetAllKeys = baseGetAllKeys;
18725
18726 /**
18727 * A specialized version of `_.filter` for arrays without support for
18728 * iteratee shorthands.
18729 *
18730 * @private
18731 * @param {Array} [array] The array to iterate over.
18732 * @param {Function} predicate The function invoked per iteration.
18733 * @returns {Array} Returns the new filtered array.
18734 */
18735 function arrayFilter(array, predicate) {
18736 var index = -1,
18737 length = array == null ? 0 : array.length,
18738 resIndex = 0,
18739 result = [];
18740
18741 while (++index < length) {
18742 var value = array[index];
18743 if (predicate(value, index, array)) {
18744 result[resIndex++] = value;
18745 }
18746 }
18747 return result;
18748 }
18749
18750 var _arrayFilter = arrayFilter;
18751
18752 /**
18753 * This method returns a new empty array.
18754 *
18755 * @static
18756 * @memberOf _
18757 * @since 4.13.0
18758 * @category Util
18759 * @returns {Array} Returns the new empty array.
18760 * @example
18761 *
18762 * var arrays = _.times(2, _.stubArray);
18763 *
18764 * console.log(arrays);
18765 * // => [[], []]
18766 *
18767 * console.log(arrays[0] === arrays[1]);
18768 * // => false
18769 */
18770 function stubArray() {
18771 return [];
18772 }
18773
18774 var stubArray_1 = stubArray;
18775
18776 /** Used for built-in method references. */
18777 var objectProto$a = Object.prototype;
18778
18779 /** Built-in value references. */
18780 var propertyIsEnumerable$1 = objectProto$a.propertyIsEnumerable;
18781
18782 /* Built-in method references for those with the same name as other `lodash` methods. */
18783 var nativeGetSymbols = Object.getOwnPropertySymbols;
18784
18785 /**
18786 * Creates an array of the own enumerable symbols of `object`.
18787 *
18788 * @private
18789 * @param {Object} object The object to query.
18790 * @returns {Array} Returns the array of symbols.
18791 */
18792 var getSymbols = !nativeGetSymbols ? stubArray_1 : function(object) {
18793 if (object == null) {
18794 return [];
18795 }
18796 object = Object(object);
18797 return _arrayFilter(nativeGetSymbols(object), function(symbol) {
18798 return propertyIsEnumerable$1.call(object, symbol);
18799 });
18800 };
18801
18802 var _getSymbols = getSymbols;
18803
18804 /**
18805 * Creates an array of own enumerable property names and symbols of `object`.
18806 *
18807 * @private
18808 * @param {Object} object The object to query.
18809 * @returns {Array} Returns the array of property names and symbols.
18810 */
18811 function getAllKeys(object) {
18812 return _baseGetAllKeys(object, keys_1, _getSymbols);
18813 }
18814
18815 var _getAllKeys = getAllKeys;
18816
18817 /** Used to compose bitmasks for value comparisons. */
18818 var COMPARE_PARTIAL_FLAG$2 = 1;
18819
18820 /** Used for built-in method references. */
18821 var objectProto$b = Object.prototype;
18822
18823 /** Used to check objects for own properties. */
18824 var hasOwnProperty$8 = objectProto$b.hasOwnProperty;
18825
18826 /**
18827 * A specialized version of `baseIsEqualDeep` for objects with support for
18828 * partial deep comparisons.
18829 *
18830 * @private
18831 * @param {Object} object The object to compare.
18832 * @param {Object} other The other object to compare.
18833 * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
18834 * @param {Function} customizer The function to customize comparisons.
18835 * @param {Function} equalFunc The function to determine equivalents of values.
18836 * @param {Object} stack Tracks traversed `object` and `other` objects.
18837 * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
18838 */
18839 function equalObjects(object, other, bitmask, customizer, equalFunc, stack) {
18840 var isPartial = bitmask & COMPARE_PARTIAL_FLAG$2,
18841 objProps = _getAllKeys(object),
18842 objLength = objProps.length,
18843 othProps = _getAllKeys(other),
18844 othLength = othProps.length;
18845
18846 if (objLength != othLength && !isPartial) {
18847 return false;
18848 }
18849 var index = objLength;
18850 while (index--) {
18851 var key = objProps[index];
18852 if (!(isPartial ? key in other : hasOwnProperty$8.call(other, key))) {
18853 return false;
18854 }
18855 }
18856 // Check that cyclic values are equal.
18857 var objStacked = stack.get(object);
18858 var othStacked = stack.get(other);
18859 if (objStacked && othStacked) {
18860 return objStacked == other && othStacked == object;
18861 }
18862 var result = true;
18863 stack.set(object, other);
18864 stack.set(other, object);
18865
18866 var skipCtor = isPartial;
18867 while (++index < objLength) {
18868 key = objProps[index];
18869 var objValue = object[key],
18870 othValue = other[key];
18871
18872 if (customizer) {
18873 var compared = isPartial
18874 ? customizer(othValue, objValue, key, other, object, stack)
18875 : customizer(objValue, othValue, key, object, other, stack);
18876 }
18877 // Recursively compare objects (susceptible to call stack limits).
18878 if (!(compared === undefined
18879 ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack))
18880 : compared
18881 )) {
18882 result = false;
18883 break;
18884 }
18885 skipCtor || (skipCtor = key == 'constructor');
18886 }
18887 if (result && !skipCtor) {
18888 var objCtor = object.constructor,
18889 othCtor = other.constructor;
18890
18891 // Non `Object` object instances with different constructors are not equal.
18892 if (objCtor != othCtor &&
18893 ('constructor' in object && 'constructor' in other) &&
18894 !(typeof objCtor == 'function' && objCtor instanceof objCtor &&
18895 typeof othCtor == 'function' && othCtor instanceof othCtor)) {
18896 result = false;
18897 }
18898 }
18899 stack['delete'](object);
18900 stack['delete'](other);
18901 return result;
18902 }
18903
18904 var _equalObjects = equalObjects;
18905
18906 /* Built-in method references that are verified to be native. */
18907 var DataView = _getNative(_root, 'DataView');
18908
18909 var _DataView = DataView;
18910
18911 /* Built-in method references that are verified to be native. */
18912 var Promise$1 = _getNative(_root, 'Promise');
18913
18914 var _Promise = Promise$1;
18915
18916 /* Built-in method references that are verified to be native. */
18917 var Set$1 = _getNative(_root, 'Set');
18918
18919 var _Set = Set$1;
18920
18921 /* Built-in method references that are verified to be native. */
18922 var WeakMap$1 = _getNative(_root, 'WeakMap');
18923
18924 var _WeakMap = WeakMap$1;
18925
18926 /** `Object#toString` result references. */
18927 var mapTag$2 = '[object Map]',
18928 objectTag$2 = '[object Object]',
18929 promiseTag = '[object Promise]',
18930 setTag$2 = '[object Set]',
18931 weakMapTag$1 = '[object WeakMap]';
18932
18933 var dataViewTag$2 = '[object DataView]';
18934
18935 /** Used to detect maps, sets, and weakmaps. */
18936 var dataViewCtorString = _toSource(_DataView),
18937 mapCtorString = _toSource(_Map),
18938 promiseCtorString = _toSource(_Promise),
18939 setCtorString = _toSource(_Set),
18940 weakMapCtorString = _toSource(_WeakMap);
18941
18942 /**
18943 * Gets the `toStringTag` of `value`.
18944 *
18945 * @private
18946 * @param {*} value The value to query.
18947 * @returns {string} Returns the `toStringTag`.
18948 */
18949 var getTag = _baseGetTag;
18950
18951 // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.
18952 if ((_DataView && getTag(new _DataView(new ArrayBuffer(1))) != dataViewTag$2) ||
18953 (_Map && getTag(new _Map) != mapTag$2) ||
18954 (_Promise && getTag(_Promise.resolve()) != promiseTag) ||
18955 (_Set && getTag(new _Set) != setTag$2) ||
18956 (_WeakMap && getTag(new _WeakMap) != weakMapTag$1)) {
18957 getTag = function(value) {
18958 var result = _baseGetTag(value),
18959 Ctor = result == objectTag$2 ? value.constructor : undefined,
18960 ctorString = Ctor ? _toSource(Ctor) : '';
18961
18962 if (ctorString) {
18963 switch (ctorString) {
18964 case dataViewCtorString: return dataViewTag$2;
18965 case mapCtorString: return mapTag$2;
18966 case promiseCtorString: return promiseTag;
18967 case setCtorString: return setTag$2;
18968 case weakMapCtorString: return weakMapTag$1;
18969 }
18970 }
18971 return result;
18972 };
18973 }
18974
18975 var _getTag = getTag;
18976
18977 /** Used to compose bitmasks for value comparisons. */
18978 var COMPARE_PARTIAL_FLAG$3 = 1;
18979
18980 /** `Object#toString` result references. */
18981 var argsTag$2 = '[object Arguments]',
18982 arrayTag$1 = '[object Array]',
18983 objectTag$3 = '[object Object]';
18984
18985 /** Used for built-in method references. */
18986 var objectProto$c = Object.prototype;
18987
18988 /** Used to check objects for own properties. */
18989 var hasOwnProperty$9 = objectProto$c.hasOwnProperty;
18990
18991 /**
18992 * A specialized version of `baseIsEqual` for arrays and objects which performs
18993 * deep comparisons and tracks traversed objects enabling objects with circular
18994 * references to be compared.
18995 *
18996 * @private
18997 * @param {Object} object The object to compare.
18998 * @param {Object} other The other object to compare.
18999 * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
19000 * @param {Function} customizer The function to customize comparisons.
19001 * @param {Function} equalFunc The function to determine equivalents of values.
19002 * @param {Object} [stack] Tracks traversed `object` and `other` objects.
19003 * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
19004 */
19005 function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {
19006 var objIsArr = isArray_1(object),
19007 othIsArr = isArray_1(other),
19008 objTag = objIsArr ? arrayTag$1 : _getTag(object),
19009 othTag = othIsArr ? arrayTag$1 : _getTag(other);
19010
19011 objTag = objTag == argsTag$2 ? objectTag$3 : objTag;
19012 othTag = othTag == argsTag$2 ? objectTag$3 : othTag;
19013
19014 var objIsObj = objTag == objectTag$3,
19015 othIsObj = othTag == objectTag$3,
19016 isSameTag = objTag == othTag;
19017
19018 if (isSameTag && isBuffer_1(object)) {
19019 if (!isBuffer_1(other)) {
19020 return false;
19021 }
19022 objIsArr = true;
19023 objIsObj = false;
19024 }
19025 if (isSameTag && !objIsObj) {
19026 stack || (stack = new _Stack);
19027 return (objIsArr || isTypedArray_1(object))
19028 ? _equalArrays(object, other, bitmask, customizer, equalFunc, stack)
19029 : _equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);
19030 }
19031 if (!(bitmask & COMPARE_PARTIAL_FLAG$3)) {
19032 var objIsWrapped = objIsObj && hasOwnProperty$9.call(object, '__wrapped__'),
19033 othIsWrapped = othIsObj && hasOwnProperty$9.call(other, '__wrapped__');
19034
19035 if (objIsWrapped || othIsWrapped) {
19036 var objUnwrapped = objIsWrapped ? object.value() : object,
19037 othUnwrapped = othIsWrapped ? other.value() : other;
19038
19039 stack || (stack = new _Stack);
19040 return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);
19041 }
19042 }
19043 if (!isSameTag) {
19044 return false;
19045 }
19046 stack || (stack = new _Stack);
19047 return _equalObjects(object, other, bitmask, customizer, equalFunc, stack);
19048 }
19049
19050 var _baseIsEqualDeep = baseIsEqualDeep;
19051
19052 /**
19053 * The base implementation of `_.isEqual` which supports partial comparisons
19054 * and tracks traversed objects.
19055 *
19056 * @private
19057 * @param {*} value The value to compare.
19058 * @param {*} other The other value to compare.
19059 * @param {boolean} bitmask The bitmask flags.
19060 * 1 - Unordered comparison
19061 * 2 - Partial comparison
19062 * @param {Function} [customizer] The function to customize comparisons.
19063 * @param {Object} [stack] Tracks traversed `value` and `other` objects.
19064 * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
19065 */
19066 function baseIsEqual(value, other, bitmask, customizer, stack) {
19067 if (value === other) {
19068 return true;
19069 }
19070 if (value == null || other == null || (!isObjectLike_1(value) && !isObjectLike_1(other))) {
19071 return value !== value && other !== other;
19072 }
19073 return _baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);
19074 }
19075
19076 var _baseIsEqual = baseIsEqual;
19077
19078 /** Used to compose bitmasks for value comparisons. */
19079 var COMPARE_PARTIAL_FLAG$4 = 1,
19080 COMPARE_UNORDERED_FLAG$2 = 2;
19081
19082 /**
19083 * The base implementation of `_.isMatch` without support for iteratee shorthands.
19084 *
19085 * @private
19086 * @param {Object} object The object to inspect.
19087 * @param {Object} source The object of property values to match.
19088 * @param {Array} matchData The property names, values, and compare flags to match.
19089 * @param {Function} [customizer] The function to customize comparisons.
19090 * @returns {boolean} Returns `true` if `object` is a match, else `false`.
19091 */
19092 function baseIsMatch(object, source, matchData, customizer) {
19093 var index = matchData.length,
19094 length = index,
19095 noCustomizer = !customizer;
19096
19097 if (object == null) {
19098 return !length;
19099 }
19100 object = Object(object);
19101 while (index--) {
19102 var data = matchData[index];
19103 if ((noCustomizer && data[2])
19104 ? data[1] !== object[data[0]]
19105 : !(data[0] in object)
19106 ) {
19107 return false;
19108 }
19109 }
19110 while (++index < length) {
19111 data = matchData[index];
19112 var key = data[0],
19113 objValue = object[key],
19114 srcValue = data[1];
19115
19116 if (noCustomizer && data[2]) {
19117 if (objValue === undefined && !(key in object)) {
19118 return false;
19119 }
19120 } else {
19121 var stack = new _Stack;
19122 if (customizer) {
19123 var result = customizer(objValue, srcValue, key, object, source, stack);
19124 }
19125 if (!(result === undefined
19126 ? _baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG$4 | COMPARE_UNORDERED_FLAG$2, customizer, stack)
19127 : result
19128 )) {
19129 return false;
19130 }
19131 }
19132 }
19133 return true;
19134 }
19135
19136 var _baseIsMatch = baseIsMatch;
19137
19138 /**
19139 * Checks if `value` is suitable for strict equality comparisons, i.e. `===`.
19140 *
19141 * @private
19142 * @param {*} value The value to check.
19143 * @returns {boolean} Returns `true` if `value` if suitable for strict
19144 * equality comparisons, else `false`.
19145 */
19146 function isStrictComparable(value) {
19147 return value === value && !isObject_1$1(value);
19148 }
19149
19150 var _isStrictComparable = isStrictComparable;
19151
19152 /**
19153 * Gets the property names, values, and compare flags of `object`.
19154 *
19155 * @private
19156 * @param {Object} object The object to query.
19157 * @returns {Array} Returns the match data of `object`.
19158 */
19159 function getMatchData(object) {
19160 var result = keys_1(object),
19161 length = result.length;
19162
19163 while (length--) {
19164 var key = result[length],
19165 value = object[key];
19166
19167 result[length] = [key, value, _isStrictComparable(value)];
19168 }
19169 return result;
19170 }
19171
19172 var _getMatchData = getMatchData;
19173
19174 /**
19175 * A specialized version of `matchesProperty` for source values suitable
19176 * for strict equality comparisons, i.e. `===`.
19177 *
19178 * @private
19179 * @param {string} key The key of the property to get.
19180 * @param {*} srcValue The value to match.
19181 * @returns {Function} Returns the new spec function.
19182 */
19183 function matchesStrictComparable(key, srcValue) {
19184 return function(object) {
19185 if (object == null) {
19186 return false;
19187 }
19188 return object[key] === srcValue &&
19189 (srcValue !== undefined || (key in Object(object)));
19190 };
19191 }
19192
19193 var _matchesStrictComparable = matchesStrictComparable;
19194
19195 /**
19196 * The base implementation of `_.matches` which doesn't clone `source`.
19197 *
19198 * @private
19199 * @param {Object} source The object of property values to match.
19200 * @returns {Function} Returns the new spec function.
19201 */
19202 function baseMatches(source) {
19203 var matchData = _getMatchData(source);
19204 if (matchData.length == 1 && matchData[0][2]) {
19205 return _matchesStrictComparable(matchData[0][0], matchData[0][1]);
19206 }
19207 return function(object) {
19208 return object === source || _baseIsMatch(object, source, matchData);
19209 };
19210 }
19211
19212 var _baseMatches = baseMatches;
19213
19214 /** `Object#toString` result references. */
19215 var symbolTag$1 = '[object Symbol]';
19216
19217 /**
19218 * Checks if `value` is classified as a `Symbol` primitive or object.
19219 *
19220 * @static
19221 * @memberOf _
19222 * @since 4.0.0
19223 * @category Lang
19224 * @param {*} value The value to check.
19225 * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
19226 * @example
19227 *
19228 * _.isSymbol(Symbol.iterator);
19229 * // => true
19230 *
19231 * _.isSymbol('abc');
19232 * // => false
19233 */
19234 function isSymbol(value) {
19235 return typeof value == 'symbol' ||
19236 (isObjectLike_1(value) && _baseGetTag(value) == symbolTag$1);
19237 }
19238
19239 var isSymbol_1 = isSymbol;
19240
19241 /** Used to match property names within property paths. */
19242 var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,
19243 reIsPlainProp = /^\w*$/;
19244
19245 /**
19246 * Checks if `value` is a property name and not a property path.
19247 *
19248 * @private
19249 * @param {*} value The value to check.
19250 * @param {Object} [object] The object to query keys on.
19251 * @returns {boolean} Returns `true` if `value` is a property name, else `false`.
19252 */
19253 function isKey(value, object) {
19254 if (isArray_1(value)) {
19255 return false;
19256 }
19257 var type = typeof value;
19258 if (type == 'number' || type == 'symbol' || type == 'boolean' ||
19259 value == null || isSymbol_1(value)) {
19260 return true;
19261 }
19262 return reIsPlainProp.test(value) || !reIsDeepProp.test(value) ||
19263 (object != null && value in Object(object));
19264 }
19265
19266 var _isKey = isKey;
19267
19268 /** Error message constants. */
19269 var FUNC_ERROR_TEXT = 'Expected a function';
19270
19271 /**
19272 * Creates a function that memoizes the result of `func`. If `resolver` is
19273 * provided, it determines the cache key for storing the result based on the
19274 * arguments provided to the memoized function. By default, the first argument
19275 * provided to the memoized function is used as the map cache key. The `func`
19276 * is invoked with the `this` binding of the memoized function.
19277 *
19278 * **Note:** The cache is exposed as the `cache` property on the memoized
19279 * function. Its creation may be customized by replacing the `_.memoize.Cache`
19280 * constructor with one whose instances implement the
19281 * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)
19282 * method interface of `clear`, `delete`, `get`, `has`, and `set`.
19283 *
19284 * @static
19285 * @memberOf _
19286 * @since 0.1.0
19287 * @category Function
19288 * @param {Function} func The function to have its output memoized.
19289 * @param {Function} [resolver] The function to resolve the cache key.
19290 * @returns {Function} Returns the new memoized function.
19291 * @example
19292 *
19293 * var object = { 'a': 1, 'b': 2 };
19294 * var other = { 'c': 3, 'd': 4 };
19295 *
19296 * var values = _.memoize(_.values);
19297 * values(object);
19298 * // => [1, 2]
19299 *
19300 * values(other);
19301 * // => [3, 4]
19302 *
19303 * object.a = 2;
19304 * values(object);
19305 * // => [1, 2]
19306 *
19307 * // Modify the result cache.
19308 * values.cache.set(object, ['a', 'b']);
19309 * values(object);
19310 * // => ['a', 'b']
19311 *
19312 * // Replace `_.memoize.Cache`.
19313 * _.memoize.Cache = WeakMap;
19314 */
19315 function memoize(func, resolver) {
19316 if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) {
19317 throw new TypeError(FUNC_ERROR_TEXT);
19318 }
19319 var memoized = function() {
19320 var args = arguments,
19321 key = resolver ? resolver.apply(this, args) : args[0],
19322 cache = memoized.cache;
19323
19324 if (cache.has(key)) {
19325 return cache.get(key);
19326 }
19327 var result = func.apply(this, args);
19328 memoized.cache = cache.set(key, result) || cache;
19329 return result;
19330 };
19331 memoized.cache = new (memoize.Cache || _MapCache);
19332 return memoized;
19333 }
19334
19335 // Expose `MapCache`.
19336 memoize.Cache = _MapCache;
19337
19338 var memoize_1 = memoize;
19339
19340 /** Used as the maximum memoize cache size. */
19341 var MAX_MEMOIZE_SIZE = 500;
19342
19343 /**
19344 * A specialized version of `_.memoize` which clears the memoized function's
19345 * cache when it exceeds `MAX_MEMOIZE_SIZE`.
19346 *
19347 * @private
19348 * @param {Function} func The function to have its output memoized.
19349 * @returns {Function} Returns the new memoized function.
19350 */
19351 function memoizeCapped(func) {
19352 var result = memoize_1(func, function(key) {
19353 if (cache.size === MAX_MEMOIZE_SIZE) {
19354 cache.clear();
19355 }
19356 return key;
19357 });
19358
19359 var cache = result.cache;
19360 return result;
19361 }
19362
19363 var _memoizeCapped = memoizeCapped;
19364
19365 /** Used to match property names within property paths. */
19366 var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;
19367
19368 /** Used to match backslashes in property paths. */
19369 var reEscapeChar = /\\(\\)?/g;
19370
19371 /**
19372 * Converts `string` to a property path array.
19373 *
19374 * @private
19375 * @param {string} string The string to convert.
19376 * @returns {Array} Returns the property path array.
19377 */
19378 var stringToPath = _memoizeCapped(function(string) {
19379 var result = [];
19380 if (string.charCodeAt(0) === 46 /* . */) {
19381 result.push('');
19382 }
19383 string.replace(rePropName, function(match, number, quote, subString) {
19384 result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match));
19385 });
19386 return result;
19387 });
19388
19389 var _stringToPath = stringToPath;
19390
19391 /** Used as references for various `Number` constants. */
19392 var INFINITY = 1 / 0;
19393
19394 /** Used to convert symbols to primitives and strings. */
19395 var symbolProto$1 = _Symbol ? _Symbol.prototype : undefined,
19396 symbolToString = symbolProto$1 ? symbolProto$1.toString : undefined;
19397
19398 /**
19399 * The base implementation of `_.toString` which doesn't convert nullish
19400 * values to empty strings.
19401 *
19402 * @private
19403 * @param {*} value The value to process.
19404 * @returns {string} Returns the string.
19405 */
19406 function baseToString(value) {
19407 // Exit early for strings to avoid a performance hit in some environments.
19408 if (typeof value == 'string') {
19409 return value;
19410 }
19411 if (isArray_1(value)) {
19412 // Recursively convert values (susceptible to call stack limits).
19413 return _arrayMap(value, baseToString) + '';
19414 }
19415 if (isSymbol_1(value)) {
19416 return symbolToString ? symbolToString.call(value) : '';
19417 }
19418 var result = (value + '');
19419 return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;
19420 }
19421
19422 var _baseToString = baseToString;
19423
19424 /**
19425 * Converts `value` to a string. An empty string is returned for `null`
19426 * and `undefined` values. The sign of `-0` is preserved.
19427 *
19428 * @static
19429 * @memberOf _
19430 * @since 4.0.0
19431 * @category Lang
19432 * @param {*} value The value to convert.
19433 * @returns {string} Returns the converted string.
19434 * @example
19435 *
19436 * _.toString(null);
19437 * // => ''
19438 *
19439 * _.toString(-0);
19440 * // => '-0'
19441 *
19442 * _.toString([1, 2, 3]);
19443 * // => '1,2,3'
19444 */
19445 function toString(value) {
19446 return value == null ? '' : _baseToString(value);
19447 }
19448
19449 var toString_1 = toString;
19450
19451 /**
19452 * Casts `value` to a path array if it's not one.
19453 *
19454 * @private
19455 * @param {*} value The value to inspect.
19456 * @param {Object} [object] The object to query keys on.
19457 * @returns {Array} Returns the cast property path array.
19458 */
19459 function castPath(value, object) {
19460 if (isArray_1(value)) {
19461 return value;
19462 }
19463 return _isKey(value, object) ? [value] : _stringToPath(toString_1(value));
19464 }
19465
19466 var _castPath = castPath;
19467
19468 /** Used as references for various `Number` constants. */
19469 var INFINITY$1 = 1 / 0;
19470
19471 /**
19472 * Converts `value` to a string key if it's not a string or symbol.
19473 *
19474 * @private
19475 * @param {*} value The value to inspect.
19476 * @returns {string|symbol} Returns the key.
19477 */
19478 function toKey(value) {
19479 if (typeof value == 'string' || isSymbol_1(value)) {
19480 return value;
19481 }
19482 var result = (value + '');
19483 return (result == '0' && (1 / value) == -INFINITY$1) ? '-0' : result;
19484 }
19485
19486 var _toKey = toKey;
19487
19488 /**
19489 * The base implementation of `_.get` without support for default values.
19490 *
19491 * @private
19492 * @param {Object} object The object to query.
19493 * @param {Array|string} path The path of the property to get.
19494 * @returns {*} Returns the resolved value.
19495 */
19496 function baseGet(object, path) {
19497 path = _castPath(path, object);
19498
19499 var index = 0,
19500 length = path.length;
19501
19502 while (object != null && index < length) {
19503 object = object[_toKey(path[index++])];
19504 }
19505 return (index && index == length) ? object : undefined;
19506 }
19507
19508 var _baseGet = baseGet;
19509
19510 /**
19511 * Gets the value at `path` of `object`. If the resolved value is
19512 * `undefined`, the `defaultValue` is returned in its place.
19513 *
19514 * @static
19515 * @memberOf _
19516 * @since 3.7.0
19517 * @category Object
19518 * @param {Object} object The object to query.
19519 * @param {Array|string} path The path of the property to get.
19520 * @param {*} [defaultValue] The value returned for `undefined` resolved values.
19521 * @returns {*} Returns the resolved value.
19522 * @example
19523 *
19524 * var object = { 'a': [{ 'b': { 'c': 3 } }] };
19525 *
19526 * _.get(object, 'a[0].b.c');
19527 * // => 3
19528 *
19529 * _.get(object, ['a', '0', 'b', 'c']);
19530 * // => 3
19531 *
19532 * _.get(object, 'a.b.c', 'default');
19533 * // => 'default'
19534 */
19535 function get(object, path, defaultValue) {
19536 var result = object == null ? undefined : _baseGet(object, path);
19537 return result === undefined ? defaultValue : result;
19538 }
19539
19540 var get_1 = get;
19541
19542 /**
19543 * The base implementation of `_.hasIn` without support for deep paths.
19544 *
19545 * @private
19546 * @param {Object} [object] The object to query.
19547 * @param {Array|string} key The key to check.
19548 * @returns {boolean} Returns `true` if `key` exists, else `false`.
19549 */
19550 function baseHasIn(object, key) {
19551 return object != null && key in Object(object);
19552 }
19553
19554 var _baseHasIn = baseHasIn;
19555
19556 /**
19557 * Checks if `path` exists on `object`.
19558 *
19559 * @private
19560 * @param {Object} object The object to query.
19561 * @param {Array|string} path The path to check.
19562 * @param {Function} hasFunc The function to check properties.
19563 * @returns {boolean} Returns `true` if `path` exists, else `false`.
19564 */
19565 function hasPath(object, path, hasFunc) {
19566 path = _castPath(path, object);
19567
19568 var index = -1,
19569 length = path.length,
19570 result = false;
19571
19572 while (++index < length) {
19573 var key = _toKey(path[index]);
19574 if (!(result = object != null && hasFunc(object, key))) {
19575 break;
19576 }
19577 object = object[key];
19578 }
19579 if (result || ++index != length) {
19580 return result;
19581 }
19582 length = object == null ? 0 : object.length;
19583 return !!length && isLength_1(length) && _isIndex(key, length) &&
19584 (isArray_1(object) || isArguments_1(object));
19585 }
19586
19587 var _hasPath = hasPath;
19588
19589 /**
19590 * Checks if `path` is a direct or inherited property of `object`.
19591 *
19592 * @static
19593 * @memberOf _
19594 * @since 4.0.0
19595 * @category Object
19596 * @param {Object} object The object to query.
19597 * @param {Array|string} path The path to check.
19598 * @returns {boolean} Returns `true` if `path` exists, else `false`.
19599 * @example
19600 *
19601 * var object = _.create({ 'a': _.create({ 'b': 2 }) });
19602 *
19603 * _.hasIn(object, 'a');
19604 * // => true
19605 *
19606 * _.hasIn(object, 'a.b');
19607 * // => true
19608 *
19609 * _.hasIn(object, ['a', 'b']);
19610 * // => true
19611 *
19612 * _.hasIn(object, 'b');
19613 * // => false
19614 */
19615 function hasIn(object, path) {
19616 return object != null && _hasPath(object, path, _baseHasIn);
19617 }
19618
19619 var hasIn_1 = hasIn;
19620
19621 /** Used to compose bitmasks for value comparisons. */
19622 var COMPARE_PARTIAL_FLAG$5 = 1,
19623 COMPARE_UNORDERED_FLAG$3 = 2;
19624
19625 /**
19626 * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`.
19627 *
19628 * @private
19629 * @param {string} path The path of the property to get.
19630 * @param {*} srcValue The value to match.
19631 * @returns {Function} Returns the new spec function.
19632 */
19633 function baseMatchesProperty(path, srcValue) {
19634 if (_isKey(path) && _isStrictComparable(srcValue)) {
19635 return _matchesStrictComparable(_toKey(path), srcValue);
19636 }
19637 return function(object) {
19638 var objValue = get_1(object, path);
19639 return (objValue === undefined && objValue === srcValue)
19640 ? hasIn_1(object, path)
19641 : _baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG$5 | COMPARE_UNORDERED_FLAG$3);
19642 };
19643 }
19644
19645 var _baseMatchesProperty = baseMatchesProperty;
19646
19647 /**
19648 * This method returns the first argument it receives.
19649 *
19650 * @static
19651 * @since 0.1.0
19652 * @memberOf _
19653 * @category Util
19654 * @param {*} value Any value.
19655 * @returns {*} Returns `value`.
19656 * @example
19657 *
19658 * var object = { 'a': 1 };
19659 *
19660 * console.log(_.identity(object) === object);
19661 * // => true
19662 */
19663 function identity(value) {
19664 return value;
19665 }
19666
19667 var identity_1 = identity;
19668
19669 /**
19670 * The base implementation of `_.property` without support for deep paths.
19671 *
19672 * @private
19673 * @param {string} key The key of the property to get.
19674 * @returns {Function} Returns the new accessor function.
19675 */
19676 function baseProperty(key) {
19677 return function(object) {
19678 return object == null ? undefined : object[key];
19679 };
19680 }
19681
19682 var _baseProperty = baseProperty;
19683
19684 /**
19685 * A specialized version of `baseProperty` which supports deep paths.
19686 *
19687 * @private
19688 * @param {Array|string} path The path of the property to get.
19689 * @returns {Function} Returns the new accessor function.
19690 */
19691 function basePropertyDeep(path) {
19692 return function(object) {
19693 return _baseGet(object, path);
19694 };
19695 }
19696
19697 var _basePropertyDeep = basePropertyDeep;
19698
19699 /**
19700 * Creates a function that returns the value at `path` of a given object.
19701 *
19702 * @static
19703 * @memberOf _
19704 * @since 2.4.0
19705 * @category Util
19706 * @param {Array|string} path The path of the property to get.
19707 * @returns {Function} Returns the new accessor function.
19708 * @example
19709 *
19710 * var objects = [
19711 * { 'a': { 'b': 2 } },
19712 * { 'a': { 'b': 1 } }
19713 * ];
19714 *
19715 * _.map(objects, _.property('a.b'));
19716 * // => [2, 1]
19717 *
19718 * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b');
19719 * // => [1, 2]
19720 */
19721 function property(path) {
19722 return _isKey(path) ? _baseProperty(_toKey(path)) : _basePropertyDeep(path);
19723 }
19724
19725 var property_1 = property;
19726
19727 /**
19728 * The base implementation of `_.iteratee`.
19729 *
19730 * @private
19731 * @param {*} [value=_.identity] The value to convert to an iteratee.
19732 * @returns {Function} Returns the iteratee.
19733 */
19734 function baseIteratee(value) {
19735 // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9.
19736 // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details.
19737 if (typeof value == 'function') {
19738 return value;
19739 }
19740 if (value == null) {
19741 return identity_1;
19742 }
19743 if (typeof value == 'object') {
19744 return isArray_1(value)
19745 ? _baseMatchesProperty(value[0], value[1])
19746 : _baseMatches(value);
19747 }
19748 return property_1(value);
19749 }
19750
19751 var _baseIteratee = baseIteratee;
19752
19753 /**
19754 * Gets the last element of `array`.
19755 *
19756 * @static
19757 * @memberOf _
19758 * @since 0.1.0
19759 * @category Array
19760 * @param {Array} array The array to query.
19761 * @returns {*} Returns the last element of `array`.
19762 * @example
19763 *
19764 * _.last([1, 2, 3]);
19765 * // => 3
19766 */
19767 function last(array) {
19768 var length = array == null ? 0 : array.length;
19769 return length ? array[length - 1] : undefined;
19770 }
19771
19772 var last_1 = last;
19773
19774 /**
19775 * The base implementation of `_.slice` without an iteratee call guard.
19776 *
19777 * @private
19778 * @param {Array} array The array to slice.
19779 * @param {number} [start=0] The start position.
19780 * @param {number} [end=array.length] The end position.
19781 * @returns {Array} Returns the slice of `array`.
19782 */
19783 function baseSlice(array, start, end) {
19784 var index = -1,
19785 length = array.length;
19786
19787 if (start < 0) {
19788 start = -start > length ? 0 : (length + start);
19789 }
19790 end = end > length ? length : end;
19791 if (end < 0) {
19792 end += length;
19793 }
19794 length = start > end ? 0 : ((end - start) >>> 0);
19795 start >>>= 0;
19796
19797 var result = Array(length);
19798 while (++index < length) {
19799 result[index] = array[index + start];
19800 }
19801 return result;
19802 }
19803
19804 var _baseSlice = baseSlice;
19805
19806 /**
19807 * Gets the parent value at `path` of `object`.
19808 *
19809 * @private
19810 * @param {Object} object The object to query.
19811 * @param {Array} path The path to get the parent value of.
19812 * @returns {*} Returns the parent value.
19813 */
19814 function parent(object, path) {
19815 return path.length < 2 ? object : _baseGet(object, _baseSlice(path, 0, -1));
19816 }
19817
19818 var _parent = parent;
19819
19820 /**
19821 * The base implementation of `_.unset`.
19822 *
19823 * @private
19824 * @param {Object} object The object to modify.
19825 * @param {Array|string} path The property path to unset.
19826 * @returns {boolean} Returns `true` if the property is deleted, else `false`.
19827 */
19828 function baseUnset(object, path) {
19829 path = _castPath(path, object);
19830 object = _parent(object, path);
19831 return object == null || delete object[_toKey(last_1(path))];
19832 }
19833
19834 var _baseUnset = baseUnset;
19835
19836 /** Used for built-in method references. */
19837 var arrayProto$1 = Array.prototype;
19838
19839 /** Built-in value references. */
19840 var splice$1 = arrayProto$1.splice;
19841
19842 /**
19843 * The base implementation of `_.pullAt` without support for individual
19844 * indexes or capturing the removed elements.
19845 *
19846 * @private
19847 * @param {Array} array The array to modify.
19848 * @param {number[]} indexes The indexes of elements to remove.
19849 * @returns {Array} Returns `array`.
19850 */
19851 function basePullAt(array, indexes) {
19852 var length = array ? indexes.length : 0,
19853 lastIndex = length - 1;
19854
19855 while (length--) {
19856 var index = indexes[length];
19857 if (length == lastIndex || index !== previous) {
19858 var previous = index;
19859 if (_isIndex(index)) {
19860 splice$1.call(array, index, 1);
19861 } else {
19862 _baseUnset(array, index);
19863 }
19864 }
19865 }
19866 return array;
19867 }
19868
19869 var _basePullAt = basePullAt;
19870
19871 /**
19872 * Removes all elements from `array` that `predicate` returns truthy for
19873 * and returns an array of the removed elements. The predicate is invoked
19874 * with three arguments: (value, index, array).
19875 *
19876 * **Note:** Unlike `_.filter`, this method mutates `array`. Use `_.pull`
19877 * to pull elements from an array by value.
19878 *
19879 * @static
19880 * @memberOf _
19881 * @since 2.0.0
19882 * @category Array
19883 * @param {Array} array The array to modify.
19884 * @param {Function} [predicate=_.identity] The function invoked per iteration.
19885 * @returns {Array} Returns the new array of removed elements.
19886 * @example
19887 *
19888 * var array = [1, 2, 3, 4];
19889 * var evens = _.remove(array, function(n) {
19890 * return n % 2 == 0;
19891 * });
19892 *
19893 * console.log(array);
19894 * // => [1, 3]
19895 *
19896 * console.log(evens);
19897 * // => [2, 4]
19898 */
19899 function remove(array, predicate) {
19900 var result = [];
19901 if (!(array && array.length)) {
19902 return result;
19903 }
19904 var index = -1,
19905 indexes = [],
19906 length = array.length;
19907
19908 predicate = _baseIteratee(predicate);
19909 while (++index < length) {
19910 var value = array[index];
19911 if (predicate(value, index, array)) {
19912 result.push(value);
19913 indexes.push(index);
19914 }
19915 }
19916 _basePullAt(array, indexes);
19917 return result;
19918 }
19919
19920 var remove_1 = remove;
19921
19922 /** `Object#toString` result references. */
19923 var mapTag$3 = '[object Map]',
19924 setTag$3 = '[object Set]';
19925
19926 /** Used for built-in method references. */
19927 var objectProto$d = Object.prototype;
19928
19929 /** Used to check objects for own properties. */
19930 var hasOwnProperty$a = objectProto$d.hasOwnProperty;
19931
19932 /**
19933 * Checks if `value` is an empty object, collection, map, or set.
19934 *
19935 * Objects are considered empty if they have no own enumerable string keyed
19936 * properties.
19937 *
19938 * Array-like values such as `arguments` objects, arrays, buffers, strings, or
19939 * jQuery-like collections are considered empty if they have a `length` of `0`.
19940 * Similarly, maps and sets are considered empty if they have a `size` of `0`.
19941 *
19942 * @static
19943 * @memberOf _
19944 * @since 0.1.0
19945 * @category Lang
19946 * @param {*} value The value to check.
19947 * @returns {boolean} Returns `true` if `value` is empty, else `false`.
19948 * @example
19949 *
19950 * _.isEmpty(null);
19951 * // => true
19952 *
19953 * _.isEmpty(true);
19954 * // => true
19955 *
19956 * _.isEmpty(1);
19957 * // => true
19958 *
19959 * _.isEmpty([1, 2, 3]);
19960 * // => false
19961 *
19962 * _.isEmpty({ 'a': 1 });
19963 * // => false
19964 */
19965 function isEmpty(value) {
19966 if (value == null) {
19967 return true;
19968 }
19969 if (isArrayLike_1(value) &&
19970 (isArray_1(value) || typeof value == 'string' || typeof value.splice == 'function' ||
19971 isBuffer_1(value) || isTypedArray_1(value) || isArguments_1(value))) {
19972 return !value.length;
19973 }
19974 var tag = _getTag(value);
19975 if (tag == mapTag$3 || tag == setTag$3) {
19976 return !value.size;
19977 }
19978 if (_isPrototype(value)) {
19979 return !_baseKeys(value).length;
19980 }
19981 for (var key in value) {
19982 if (hasOwnProperty$a.call(value, key)) {
19983 return false;
19984 }
19985 }
19986 return true;
19987 }
19988
19989 var isEmpty_1 = isEmpty;
19990
19991 /**
19992 * A specialized version of `_.forEach` for arrays without support for
19993 * iteratee shorthands.
19994 *
19995 * @private
19996 * @param {Array} [array] The array to iterate over.
19997 * @param {Function} iteratee The function invoked per iteration.
19998 * @returns {Array} Returns `array`.
19999 */
20000 function arrayEach(array, iteratee) {
20001 var index = -1,
20002 length = array == null ? 0 : array.length;
20003
20004 while (++index < length) {
20005 if (iteratee(array[index], index, array) === false) {
20006 break;
20007 }
20008 }
20009 return array;
20010 }
20011
20012 var _arrayEach = arrayEach;
20013
20014 var defineProperty$1 = (function() {
20015 try {
20016 var func = _getNative(Object, 'defineProperty');
20017 func({}, '', {});
20018 return func;
20019 } catch (e) {}
20020 }());
20021
20022 var _defineProperty$1 = defineProperty$1;
20023
20024 /**
20025 * The base implementation of `assignValue` and `assignMergeValue` without
20026 * value checks.
20027 *
20028 * @private
20029 * @param {Object} object The object to modify.
20030 * @param {string} key The key of the property to assign.
20031 * @param {*} value The value to assign.
20032 */
20033 function baseAssignValue(object, key, value) {
20034 if (key == '__proto__' && _defineProperty$1) {
20035 _defineProperty$1(object, key, {
20036 'configurable': true,
20037 'enumerable': true,
20038 'value': value,
20039 'writable': true
20040 });
20041 } else {
20042 object[key] = value;
20043 }
20044 }
20045
20046 var _baseAssignValue = baseAssignValue;
20047
20048 /** Used for built-in method references. */
20049 var objectProto$e = Object.prototype;
20050
20051 /** Used to check objects for own properties. */
20052 var hasOwnProperty$b = objectProto$e.hasOwnProperty;
20053
20054 /**
20055 * Assigns `value` to `key` of `object` if the existing value is not equivalent
20056 * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
20057 * for equality comparisons.
20058 *
20059 * @private
20060 * @param {Object} object The object to modify.
20061 * @param {string} key The key of the property to assign.
20062 * @param {*} value The value to assign.
20063 */
20064 function assignValue(object, key, value) {
20065 var objValue = object[key];
20066 if (!(hasOwnProperty$b.call(object, key) && eq_1(objValue, value)) ||
20067 (value === undefined && !(key in object))) {
20068 _baseAssignValue(object, key, value);
20069 }
20070 }
20071
20072 var _assignValue = assignValue;
20073
20074 /**
20075 * Copies properties of `source` to `object`.
20076 *
20077 * @private
20078 * @param {Object} source The object to copy properties from.
20079 * @param {Array} props The property identifiers to copy.
20080 * @param {Object} [object={}] The object to copy properties to.
20081 * @param {Function} [customizer] The function to customize copied values.
20082 * @returns {Object} Returns `object`.
20083 */
20084 function copyObject(source, props, object, customizer) {
20085 var isNew = !object;
20086 object || (object = {});
20087
20088 var index = -1,
20089 length = props.length;
20090
20091 while (++index < length) {
20092 var key = props[index];
20093
20094 var newValue = customizer
20095 ? customizer(object[key], source[key], key, object, source)
20096 : undefined;
20097
20098 if (newValue === undefined) {
20099 newValue = source[key];
20100 }
20101 if (isNew) {
20102 _baseAssignValue(object, key, newValue);
20103 } else {
20104 _assignValue(object, key, newValue);
20105 }
20106 }
20107 return object;
20108 }
20109
20110 var _copyObject = copyObject;
20111
20112 /**
20113 * The base implementation of `_.assign` without support for multiple sources
20114 * or `customizer` functions.
20115 *
20116 * @private
20117 * @param {Object} object The destination object.
20118 * @param {Object} source The source object.
20119 * @returns {Object} Returns `object`.
20120 */
20121 function baseAssign(object, source) {
20122 return object && _copyObject(source, keys_1(source), object);
20123 }
20124
20125 var _baseAssign = baseAssign;
20126
20127 /**
20128 * This function is like
20129 * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
20130 * except that it includes inherited enumerable properties.
20131 *
20132 * @private
20133 * @param {Object} object The object to query.
20134 * @returns {Array} Returns the array of property names.
20135 */
20136 function nativeKeysIn(object) {
20137 var result = [];
20138 if (object != null) {
20139 for (var key in Object(object)) {
20140 result.push(key);
20141 }
20142 }
20143 return result;
20144 }
20145
20146 var _nativeKeysIn = nativeKeysIn;
20147
20148 /** Used for built-in method references. */
20149 var objectProto$f = Object.prototype;
20150
20151 /** Used to check objects for own properties. */
20152 var hasOwnProperty$c = objectProto$f.hasOwnProperty;
20153
20154 /**
20155 * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense.
20156 *
20157 * @private
20158 * @param {Object} object The object to query.
20159 * @returns {Array} Returns the array of property names.
20160 */
20161 function baseKeysIn(object) {
20162 if (!isObject_1$1(object)) {
20163 return _nativeKeysIn(object);
20164 }
20165 var isProto = _isPrototype(object),
20166 result = [];
20167
20168 for (var key in object) {
20169 if (!(key == 'constructor' && (isProto || !hasOwnProperty$c.call(object, key)))) {
20170 result.push(key);
20171 }
20172 }
20173 return result;
20174 }
20175
20176 var _baseKeysIn = baseKeysIn;
20177
20178 /**
20179 * Creates an array of the own and inherited enumerable property names of `object`.
20180 *
20181 * **Note:** Non-object values are coerced to objects.
20182 *
20183 * @static
20184 * @memberOf _
20185 * @since 3.0.0
20186 * @category Object
20187 * @param {Object} object The object to query.
20188 * @returns {Array} Returns the array of property names.
20189 * @example
20190 *
20191 * function Foo() {
20192 * this.a = 1;
20193 * this.b = 2;
20194 * }
20195 *
20196 * Foo.prototype.c = 3;
20197 *
20198 * _.keysIn(new Foo);
20199 * // => ['a', 'b', 'c'] (iteration order is not guaranteed)
20200 */
20201 function keysIn(object) {
20202 return isArrayLike_1(object) ? _arrayLikeKeys(object, true) : _baseKeysIn(object);
20203 }
20204
20205 var keysIn_1 = keysIn;
20206
20207 /**
20208 * The base implementation of `_.assignIn` without support for multiple sources
20209 * or `customizer` functions.
20210 *
20211 * @private
20212 * @param {Object} object The destination object.
20213 * @param {Object} source The source object.
20214 * @returns {Object} Returns `object`.
20215 */
20216 function baseAssignIn(object, source) {
20217 return object && _copyObject(source, keysIn_1(source), object);
20218 }
20219
20220 var _baseAssignIn = baseAssignIn;
20221
20222 var _cloneBuffer = createCommonjsModule(function (module, exports) {
20223 /** Detect free variable `exports`. */
20224 var freeExports = exports && !exports.nodeType && exports;
20225
20226 /** Detect free variable `module`. */
20227 var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module;
20228
20229 /** Detect the popular CommonJS extension `module.exports`. */
20230 var moduleExports = freeModule && freeModule.exports === freeExports;
20231
20232 /** Built-in value references. */
20233 var Buffer = moduleExports ? _root.Buffer : undefined,
20234 allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined;
20235
20236 /**
20237 * Creates a clone of `buffer`.
20238 *
20239 * @private
20240 * @param {Buffer} buffer The buffer to clone.
20241 * @param {boolean} [isDeep] Specify a deep clone.
20242 * @returns {Buffer} Returns the cloned buffer.
20243 */
20244 function cloneBuffer(buffer, isDeep) {
20245 if (isDeep) {
20246 return buffer.slice();
20247 }
20248 var length = buffer.length,
20249 result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length);
20250
20251 buffer.copy(result);
20252 return result;
20253 }
20254
20255 module.exports = cloneBuffer;
20256 });
20257
20258 /**
20259 * Copies own symbols of `source` to `object`.
20260 *
20261 * @private
20262 * @param {Object} source The object to copy symbols from.
20263 * @param {Object} [object={}] The object to copy symbols to.
20264 * @returns {Object} Returns `object`.
20265 */
20266 function copySymbols(source, object) {
20267 return _copyObject(source, _getSymbols(source), object);
20268 }
20269
20270 var _copySymbols = copySymbols;
20271
20272 /* Built-in method references for those with the same name as other `lodash` methods. */
20273 var nativeGetSymbols$1 = Object.getOwnPropertySymbols;
20274
20275 /**
20276 * Creates an array of the own and inherited enumerable symbols of `object`.
20277 *
20278 * @private
20279 * @param {Object} object The object to query.
20280 * @returns {Array} Returns the array of symbols.
20281 */
20282 var getSymbolsIn = !nativeGetSymbols$1 ? stubArray_1 : function(object) {
20283 var result = [];
20284 while (object) {
20285 _arrayPush(result, _getSymbols(object));
20286 object = _getPrototype(object);
20287 }
20288 return result;
20289 };
20290
20291 var _getSymbolsIn = getSymbolsIn;
20292
20293 /**
20294 * Copies own and inherited symbols of `source` to `object`.
20295 *
20296 * @private
20297 * @param {Object} source The object to copy symbols from.
20298 * @param {Object} [object={}] The object to copy symbols to.
20299 * @returns {Object} Returns `object`.
20300 */
20301 function copySymbolsIn(source, object) {
20302 return _copyObject(source, _getSymbolsIn(source), object);
20303 }
20304
20305 var _copySymbolsIn = copySymbolsIn;
20306
20307 /**
20308 * Creates an array of own and inherited enumerable property names and
20309 * symbols of `object`.
20310 *
20311 * @private
20312 * @param {Object} object The object to query.
20313 * @returns {Array} Returns the array of property names and symbols.
20314 */
20315 function getAllKeysIn(object) {
20316 return _baseGetAllKeys(object, keysIn_1, _getSymbolsIn);
20317 }
20318
20319 var _getAllKeysIn = getAllKeysIn;
20320
20321 /** Used for built-in method references. */
20322 var objectProto$g = Object.prototype;
20323
20324 /** Used to check objects for own properties. */
20325 var hasOwnProperty$d = objectProto$g.hasOwnProperty;
20326
20327 /**
20328 * Initializes an array clone.
20329 *
20330 * @private
20331 * @param {Array} array The array to clone.
20332 * @returns {Array} Returns the initialized clone.
20333 */
20334 function initCloneArray(array) {
20335 var length = array.length,
20336 result = new array.constructor(length);
20337
20338 // Add properties assigned by `RegExp#exec`.
20339 if (length && typeof array[0] == 'string' && hasOwnProperty$d.call(array, 'index')) {
20340 result.index = array.index;
20341 result.input = array.input;
20342 }
20343 return result;
20344 }
20345
20346 var _initCloneArray = initCloneArray;
20347
20348 /**
20349 * Creates a clone of `arrayBuffer`.
20350 *
20351 * @private
20352 * @param {ArrayBuffer} arrayBuffer The array buffer to clone.
20353 * @returns {ArrayBuffer} Returns the cloned array buffer.
20354 */
20355 function cloneArrayBuffer(arrayBuffer) {
20356 var result = new arrayBuffer.constructor(arrayBuffer.byteLength);
20357 new _Uint8Array(result).set(new _Uint8Array(arrayBuffer));
20358 return result;
20359 }
20360
20361 var _cloneArrayBuffer = cloneArrayBuffer;
20362
20363 /**
20364 * Creates a clone of `dataView`.
20365 *
20366 * @private
20367 * @param {Object} dataView The data view to clone.
20368 * @param {boolean} [isDeep] Specify a deep clone.
20369 * @returns {Object} Returns the cloned data view.
20370 */
20371 function cloneDataView(dataView, isDeep) {
20372 var buffer = isDeep ? _cloneArrayBuffer(dataView.buffer) : dataView.buffer;
20373 return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength);
20374 }
20375
20376 var _cloneDataView = cloneDataView;
20377
20378 /** Used to match `RegExp` flags from their coerced string values. */
20379 var reFlags = /\w*$/;
20380
20381 /**
20382 * Creates a clone of `regexp`.
20383 *
20384 * @private
20385 * @param {Object} regexp The regexp to clone.
20386 * @returns {Object} Returns the cloned regexp.
20387 */
20388 function cloneRegExp(regexp) {
20389 var result = new regexp.constructor(regexp.source, reFlags.exec(regexp));
20390 result.lastIndex = regexp.lastIndex;
20391 return result;
20392 }
20393
20394 var _cloneRegExp = cloneRegExp;
20395
20396 /** Used to convert symbols to primitives and strings. */
20397 var symbolProto$2 = _Symbol ? _Symbol.prototype : undefined,
20398 symbolValueOf$1 = symbolProto$2 ? symbolProto$2.valueOf : undefined;
20399
20400 /**
20401 * Creates a clone of the `symbol` object.
20402 *
20403 * @private
20404 * @param {Object} symbol The symbol object to clone.
20405 * @returns {Object} Returns the cloned symbol object.
20406 */
20407 function cloneSymbol(symbol) {
20408 return symbolValueOf$1 ? Object(symbolValueOf$1.call(symbol)) : {};
20409 }
20410
20411 var _cloneSymbol = cloneSymbol;
20412
20413 /**
20414 * Creates a clone of `typedArray`.
20415 *
20416 * @private
20417 * @param {Object} typedArray The typed array to clone.
20418 * @param {boolean} [isDeep] Specify a deep clone.
20419 * @returns {Object} Returns the cloned typed array.
20420 */
20421 function cloneTypedArray(typedArray, isDeep) {
20422 var buffer = isDeep ? _cloneArrayBuffer(typedArray.buffer) : typedArray.buffer;
20423 return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);
20424 }
20425
20426 var _cloneTypedArray = cloneTypedArray;
20427
20428 /** `Object#toString` result references. */
20429 var boolTag$2 = '[object Boolean]',
20430 dateTag$2 = '[object Date]',
20431 mapTag$4 = '[object Map]',
20432 numberTag$2 = '[object Number]',
20433 regexpTag$2 = '[object RegExp]',
20434 setTag$4 = '[object Set]',
20435 stringTag$2 = '[object String]',
20436 symbolTag$2 = '[object Symbol]';
20437
20438 var arrayBufferTag$2 = '[object ArrayBuffer]',
20439 dataViewTag$3 = '[object DataView]',
20440 float32Tag$1 = '[object Float32Array]',
20441 float64Tag$1 = '[object Float64Array]',
20442 int8Tag$1 = '[object Int8Array]',
20443 int16Tag$1 = '[object Int16Array]',
20444 int32Tag$1 = '[object Int32Array]',
20445 uint8Tag$1 = '[object Uint8Array]',
20446 uint8ClampedTag$1 = '[object Uint8ClampedArray]',
20447 uint16Tag$1 = '[object Uint16Array]',
20448 uint32Tag$1 = '[object Uint32Array]';
20449
20450 /**
20451 * Initializes an object clone based on its `toStringTag`.
20452 *
20453 * **Note:** This function only supports cloning values with tags of
20454 * `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`.
20455 *
20456 * @private
20457 * @param {Object} object The object to clone.
20458 * @param {string} tag The `toStringTag` of the object to clone.
20459 * @param {boolean} [isDeep] Specify a deep clone.
20460 * @returns {Object} Returns the initialized clone.
20461 */
20462 function initCloneByTag(object, tag, isDeep) {
20463 var Ctor = object.constructor;
20464 switch (tag) {
20465 case arrayBufferTag$2:
20466 return _cloneArrayBuffer(object);
20467
20468 case boolTag$2:
20469 case dateTag$2:
20470 return new Ctor(+object);
20471
20472 case dataViewTag$3:
20473 return _cloneDataView(object, isDeep);
20474
20475 case float32Tag$1: case float64Tag$1:
20476 case int8Tag$1: case int16Tag$1: case int32Tag$1:
20477 case uint8Tag$1: case uint8ClampedTag$1: case uint16Tag$1: case uint32Tag$1:
20478 return _cloneTypedArray(object, isDeep);
20479
20480 case mapTag$4:
20481 return new Ctor;
20482
20483 case numberTag$2:
20484 case stringTag$2:
20485 return new Ctor(object);
20486
20487 case regexpTag$2:
20488 return _cloneRegExp(object);
20489
20490 case setTag$4:
20491 return new Ctor;
20492
20493 case symbolTag$2:
20494 return _cloneSymbol(object);
20495 }
20496 }
20497
20498 var _initCloneByTag = initCloneByTag;
20499
20500 /** Built-in value references. */
20501 var objectCreate = Object.create;
20502
20503 /**
20504 * The base implementation of `_.create` without support for assigning
20505 * properties to the created object.
20506 *
20507 * @private
20508 * @param {Object} proto The object to inherit from.
20509 * @returns {Object} Returns the new object.
20510 */
20511 var baseCreate = (function() {
20512 function object() {}
20513 return function(proto) {
20514 if (!isObject_1$1(proto)) {
20515 return {};
20516 }
20517 if (objectCreate) {
20518 return objectCreate(proto);
20519 }
20520 object.prototype = proto;
20521 var result = new object;
20522 object.prototype = undefined;
20523 return result;
20524 };
20525 }());
20526
20527 var _baseCreate = baseCreate;
20528
20529 /**
20530 * Initializes an object clone.
20531 *
20532 * @private
20533 * @param {Object} object The object to clone.
20534 * @returns {Object} Returns the initialized clone.
20535 */
20536 function initCloneObject(object) {
20537 return (typeof object.constructor == 'function' && !_isPrototype(object))
20538 ? _baseCreate(_getPrototype(object))
20539 : {};
20540 }
20541
20542 var _initCloneObject = initCloneObject;
20543
20544 /** `Object#toString` result references. */
20545 var mapTag$5 = '[object Map]';
20546
20547 /**
20548 * The base implementation of `_.isMap` without Node.js optimizations.
20549 *
20550 * @private
20551 * @param {*} value The value to check.
20552 * @returns {boolean} Returns `true` if `value` is a map, else `false`.
20553 */
20554 function baseIsMap(value) {
20555 return isObjectLike_1(value) && _getTag(value) == mapTag$5;
20556 }
20557
20558 var _baseIsMap = baseIsMap;
20559
20560 /* Node.js helper references. */
20561 var nodeIsMap = _nodeUtil && _nodeUtil.isMap;
20562
20563 /**
20564 * Checks if `value` is classified as a `Map` object.
20565 *
20566 * @static
20567 * @memberOf _
20568 * @since 4.3.0
20569 * @category Lang
20570 * @param {*} value The value to check.
20571 * @returns {boolean} Returns `true` if `value` is a map, else `false`.
20572 * @example
20573 *
20574 * _.isMap(new Map);
20575 * // => true
20576 *
20577 * _.isMap(new WeakMap);
20578 * // => false
20579 */
20580 var isMap = nodeIsMap ? _baseUnary(nodeIsMap) : _baseIsMap;
20581
20582 var isMap_1 = isMap;
20583
20584 /** `Object#toString` result references. */
20585 var setTag$5 = '[object Set]';
20586
20587 /**
20588 * The base implementation of `_.isSet` without Node.js optimizations.
20589 *
20590 * @private
20591 * @param {*} value The value to check.
20592 * @returns {boolean} Returns `true` if `value` is a set, else `false`.
20593 */
20594 function baseIsSet(value) {
20595 return isObjectLike_1(value) && _getTag(value) == setTag$5;
20596 }
20597
20598 var _baseIsSet = baseIsSet;
20599
20600 /* Node.js helper references. */
20601 var nodeIsSet = _nodeUtil && _nodeUtil.isSet;
20602
20603 /**
20604 * Checks if `value` is classified as a `Set` object.
20605 *
20606 * @static
20607 * @memberOf _
20608 * @since 4.3.0
20609 * @category Lang
20610 * @param {*} value The value to check.
20611 * @returns {boolean} Returns `true` if `value` is a set, else `false`.
20612 * @example
20613 *
20614 * _.isSet(new Set);
20615 * // => true
20616 *
20617 * _.isSet(new WeakSet);
20618 * // => false
20619 */
20620 var isSet = nodeIsSet ? _baseUnary(nodeIsSet) : _baseIsSet;
20621
20622 var isSet_1 = isSet;
20623
20624 /** Used to compose bitmasks for cloning. */
20625 var CLONE_DEEP_FLAG = 1,
20626 CLONE_FLAT_FLAG = 2,
20627 CLONE_SYMBOLS_FLAG = 4;
20628
20629 /** `Object#toString` result references. */
20630 var argsTag$3 = '[object Arguments]',
20631 arrayTag$2 = '[object Array]',
20632 boolTag$3 = '[object Boolean]',
20633 dateTag$3 = '[object Date]',
20634 errorTag$2 = '[object Error]',
20635 funcTag$2 = '[object Function]',
20636 genTag$1 = '[object GeneratorFunction]',
20637 mapTag$6 = '[object Map]',
20638 numberTag$3 = '[object Number]',
20639 objectTag$4 = '[object Object]',
20640 regexpTag$3 = '[object RegExp]',
20641 setTag$6 = '[object Set]',
20642 stringTag$3 = '[object String]',
20643 symbolTag$3 = '[object Symbol]',
20644 weakMapTag$2 = '[object WeakMap]';
20645
20646 var arrayBufferTag$3 = '[object ArrayBuffer]',
20647 dataViewTag$4 = '[object DataView]',
20648 float32Tag$2 = '[object Float32Array]',
20649 float64Tag$2 = '[object Float64Array]',
20650 int8Tag$2 = '[object Int8Array]',
20651 int16Tag$2 = '[object Int16Array]',
20652 int32Tag$2 = '[object Int32Array]',
20653 uint8Tag$2 = '[object Uint8Array]',
20654 uint8ClampedTag$2 = '[object Uint8ClampedArray]',
20655 uint16Tag$2 = '[object Uint16Array]',
20656 uint32Tag$2 = '[object Uint32Array]';
20657
20658 /** Used to identify `toStringTag` values supported by `_.clone`. */
20659 var cloneableTags = {};
20660 cloneableTags[argsTag$3] = cloneableTags[arrayTag$2] =
20661 cloneableTags[arrayBufferTag$3] = cloneableTags[dataViewTag$4] =
20662 cloneableTags[boolTag$3] = cloneableTags[dateTag$3] =
20663 cloneableTags[float32Tag$2] = cloneableTags[float64Tag$2] =
20664 cloneableTags[int8Tag$2] = cloneableTags[int16Tag$2] =
20665 cloneableTags[int32Tag$2] = cloneableTags[mapTag$6] =
20666 cloneableTags[numberTag$3] = cloneableTags[objectTag$4] =
20667 cloneableTags[regexpTag$3] = cloneableTags[setTag$6] =
20668 cloneableTags[stringTag$3] = cloneableTags[symbolTag$3] =
20669 cloneableTags[uint8Tag$2] = cloneableTags[uint8ClampedTag$2] =
20670 cloneableTags[uint16Tag$2] = cloneableTags[uint32Tag$2] = true;
20671 cloneableTags[errorTag$2] = cloneableTags[funcTag$2] =
20672 cloneableTags[weakMapTag$2] = false;
20673
20674 /**
20675 * The base implementation of `_.clone` and `_.cloneDeep` which tracks
20676 * traversed objects.
20677 *
20678 * @private
20679 * @param {*} value The value to clone.
20680 * @param {boolean} bitmask The bitmask flags.
20681 * 1 - Deep clone
20682 * 2 - Flatten inherited properties
20683 * 4 - Clone symbols
20684 * @param {Function} [customizer] The function to customize cloning.
20685 * @param {string} [key] The key of `value`.
20686 * @param {Object} [object] The parent object of `value`.
20687 * @param {Object} [stack] Tracks traversed objects and their clone counterparts.
20688 * @returns {*} Returns the cloned value.
20689 */
20690 function baseClone(value, bitmask, customizer, key, object, stack) {
20691 var result,
20692 isDeep = bitmask & CLONE_DEEP_FLAG,
20693 isFlat = bitmask & CLONE_FLAT_FLAG,
20694 isFull = bitmask & CLONE_SYMBOLS_FLAG;
20695
20696 if (customizer) {
20697 result = object ? customizer(value, key, object, stack) : customizer(value);
20698 }
20699 if (result !== undefined) {
20700 return result;
20701 }
20702 if (!isObject_1$1(value)) {
20703 return value;
20704 }
20705 var isArr = isArray_1(value);
20706 if (isArr) {
20707 result = _initCloneArray(value);
20708 if (!isDeep) {
20709 return _copyArray(value, result);
20710 }
20711 } else {
20712 var tag = _getTag(value),
20713 isFunc = tag == funcTag$2 || tag == genTag$1;
20714
20715 if (isBuffer_1(value)) {
20716 return _cloneBuffer(value, isDeep);
20717 }
20718 if (tag == objectTag$4 || tag == argsTag$3 || (isFunc && !object)) {
20719 result = (isFlat || isFunc) ? {} : _initCloneObject(value);
20720 if (!isDeep) {
20721 return isFlat
20722 ? _copySymbolsIn(value, _baseAssignIn(result, value))
20723 : _copySymbols(value, _baseAssign(result, value));
20724 }
20725 } else {
20726 if (!cloneableTags[tag]) {
20727 return object ? value : {};
20728 }
20729 result = _initCloneByTag(value, tag, isDeep);
20730 }
20731 }
20732 // Check for circular references and return its corresponding clone.
20733 stack || (stack = new _Stack);
20734 var stacked = stack.get(value);
20735 if (stacked) {
20736 return stacked;
20737 }
20738 stack.set(value, result);
20739
20740 if (isSet_1(value)) {
20741 value.forEach(function(subValue) {
20742 result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack));
20743 });
20744 } else if (isMap_1(value)) {
20745 value.forEach(function(subValue, key) {
20746 result.set(key, baseClone(subValue, bitmask, customizer, key, value, stack));
20747 });
20748 }
20749
20750 var keysFunc = isFull
20751 ? (isFlat ? _getAllKeysIn : _getAllKeys)
20752 : (isFlat ? keysIn_1 : keys_1);
20753
20754 var props = isArr ? undefined : keysFunc(value);
20755 _arrayEach(props || value, function(subValue, key) {
20756 if (props) {
20757 key = subValue;
20758 subValue = value[key];
20759 }
20760 // Recursively populate clone (susceptible to call stack limits).
20761 _assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack));
20762 });
20763 return result;
20764 }
20765
20766 var _baseClone = baseClone;
20767
20768 /** Used to compose bitmasks for cloning. */
20769 var CLONE_DEEP_FLAG$1 = 1,
20770 CLONE_SYMBOLS_FLAG$1 = 4;
20771
20772 /**
20773 * This method is like `_.clone` except that it recursively clones `value`.
20774 *
20775 * @static
20776 * @memberOf _
20777 * @since 1.0.0
20778 * @category Lang
20779 * @param {*} value The value to recursively clone.
20780 * @returns {*} Returns the deep cloned value.
20781 * @see _.clone
20782 * @example
20783 *
20784 * var objects = [{ 'a': 1 }, { 'b': 2 }];
20785 *
20786 * var deep = _.cloneDeep(objects);
20787 * console.log(deep[0] === objects[0]);
20788 * // => false
20789 */
20790 function cloneDeep(value) {
20791 return _baseClone(value, CLONE_DEEP_FLAG$1 | CLONE_SYMBOLS_FLAG$1);
20792 }
20793
20794 var cloneDeep_1 = cloneDeep;
20795
20796 /**
20797 * Creates a `_.find` or `_.findLast` function.
20798 *
20799 * @private
20800 * @param {Function} findIndexFunc The function to find the collection index.
20801 * @returns {Function} Returns the new find function.
20802 */
20803 function createFind(findIndexFunc) {
20804 return function(collection, predicate, fromIndex) {
20805 var iterable = Object(collection);
20806 if (!isArrayLike_1(collection)) {
20807 var iteratee = _baseIteratee(predicate);
20808 collection = keys_1(collection);
20809 predicate = function(key) { return iteratee(iterable[key], key, iterable); };
20810 }
20811 var index = findIndexFunc(collection, predicate, fromIndex);
20812 return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined;
20813 };
20814 }
20815
20816 var _createFind = createFind;
20817
20818 /**
20819 * The base implementation of `_.findIndex` and `_.findLastIndex` without
20820 * support for iteratee shorthands.
20821 *
20822 * @private
20823 * @param {Array} array The array to inspect.
20824 * @param {Function} predicate The function invoked per iteration.
20825 * @param {number} fromIndex The index to search from.
20826 * @param {boolean} [fromRight] Specify iterating from right to left.
20827 * @returns {number} Returns the index of the matched value, else `-1`.
20828 */
20829 function baseFindIndex(array, predicate, fromIndex, fromRight) {
20830 var length = array.length,
20831 index = fromIndex + (fromRight ? 1 : -1);
20832
20833 while ((fromRight ? index-- : ++index < length)) {
20834 if (predicate(array[index], index, array)) {
20835 return index;
20836 }
20837 }
20838 return -1;
20839 }
20840
20841 var _baseFindIndex = baseFindIndex;
20842
20843 /** Used to match a single whitespace character. */
20844 var reWhitespace = /\s/;
20845
20846 /**
20847 * Used by `_.trim` and `_.trimEnd` to get the index of the last non-whitespace
20848 * character of `string`.
20849 *
20850 * @private
20851 * @param {string} string The string to inspect.
20852 * @returns {number} Returns the index of the last non-whitespace character.
20853 */
20854 function trimmedEndIndex(string) {
20855 var index = string.length;
20856
20857 while (index-- && reWhitespace.test(string.charAt(index))) {}
20858 return index;
20859 }
20860
20861 var _trimmedEndIndex = trimmedEndIndex;
20862
20863 /** Used to match leading whitespace. */
20864 var reTrimStart = /^\s+/;
20865
20866 /**
20867 * The base implementation of `_.trim`.
20868 *
20869 * @private
20870 * @param {string} string The string to trim.
20871 * @returns {string} Returns the trimmed string.
20872 */
20873 function baseTrim(string) {
20874 return string
20875 ? string.slice(0, _trimmedEndIndex(string) + 1).replace(reTrimStart, '')
20876 : string;
20877 }
20878
20879 var _baseTrim = baseTrim;
20880
20881 /** Used as references for various `Number` constants. */
20882 var NAN = 0 / 0;
20883
20884 /** Used to detect bad signed hexadecimal string values. */
20885 var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
20886
20887 /** Used to detect binary string values. */
20888 var reIsBinary = /^0b[01]+$/i;
20889
20890 /** Used to detect octal string values. */
20891 var reIsOctal = /^0o[0-7]+$/i;
20892
20893 /** Built-in method references without a dependency on `root`. */
20894 var freeParseInt = parseInt;
20895
20896 /**
20897 * Converts `value` to a number.
20898 *
20899 * @static
20900 * @memberOf _
20901 * @since 4.0.0
20902 * @category Lang
20903 * @param {*} value The value to process.
20904 * @returns {number} Returns the number.
20905 * @example
20906 *
20907 * _.toNumber(3.2);
20908 * // => 3.2
20909 *
20910 * _.toNumber(Number.MIN_VALUE);
20911 * // => 5e-324
20912 *
20913 * _.toNumber(Infinity);
20914 * // => Infinity
20915 *
20916 * _.toNumber('3.2');
20917 * // => 3.2
20918 */
20919 function toNumber(value) {
20920 if (typeof value == 'number') {
20921 return value;
20922 }
20923 if (isSymbol_1(value)) {
20924 return NAN;
20925 }
20926 if (isObject_1$1(value)) {
20927 var other = typeof value.valueOf == 'function' ? value.valueOf() : value;
20928 value = isObject_1$1(other) ? (other + '') : other;
20929 }
20930 if (typeof value != 'string') {
20931 return value === 0 ? value : +value;
20932 }
20933 value = _baseTrim(value);
20934 var isBinary = reIsBinary.test(value);
20935 return (isBinary || reIsOctal.test(value))
20936 ? freeParseInt(value.slice(2), isBinary ? 2 : 8)
20937 : (reIsBadHex.test(value) ? NAN : +value);
20938 }
20939
20940 var toNumber_1 = toNumber;
20941
20942 /** Used as references for various `Number` constants. */
20943 var INFINITY$2 = 1 / 0,
20944 MAX_INTEGER = 1.7976931348623157e+308;
20945
20946 /**
20947 * Converts `value` to a finite number.
20948 *
20949 * @static
20950 * @memberOf _
20951 * @since 4.12.0
20952 * @category Lang
20953 * @param {*} value The value to convert.
20954 * @returns {number} Returns the converted number.
20955 * @example
20956 *
20957 * _.toFinite(3.2);
20958 * // => 3.2
20959 *
20960 * _.toFinite(Number.MIN_VALUE);
20961 * // => 5e-324
20962 *
20963 * _.toFinite(Infinity);
20964 * // => 1.7976931348623157e+308
20965 *
20966 * _.toFinite('3.2');
20967 * // => 3.2
20968 */
20969 function toFinite(value) {
20970 if (!value) {
20971 return value === 0 ? value : 0;
20972 }
20973 value = toNumber_1(value);
20974 if (value === INFINITY$2 || value === -INFINITY$2) {
20975 var sign = (value < 0 ? -1 : 1);
20976 return sign * MAX_INTEGER;
20977 }
20978 return value === value ? value : 0;
20979 }
20980
20981 var toFinite_1 = toFinite;
20982
20983 /**
20984 * Converts `value` to an integer.
20985 *
20986 * **Note:** This method is loosely based on
20987 * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger).
20988 *
20989 * @static
20990 * @memberOf _
20991 * @since 4.0.0
20992 * @category Lang
20993 * @param {*} value The value to convert.
20994 * @returns {number} Returns the converted integer.
20995 * @example
20996 *
20997 * _.toInteger(3.2);
20998 * // => 3
20999 *
21000 * _.toInteger(Number.MIN_VALUE);
21001 * // => 0
21002 *
21003 * _.toInteger(Infinity);
21004 * // => 1.7976931348623157e+308
21005 *
21006 * _.toInteger('3.2');
21007 * // => 3
21008 */
21009 function toInteger(value) {
21010 var result = toFinite_1(value),
21011 remainder = result % 1;
21012
21013 return result === result ? (remainder ? result - remainder : result) : 0;
21014 }
21015
21016 var toInteger_1 = toInteger;
21017
21018 /* Built-in method references for those with the same name as other `lodash` methods. */
21019 var nativeMax = Math.max;
21020
21021 /**
21022 * This method is like `_.find` except that it returns the index of the first
21023 * element `predicate` returns truthy for instead of the element itself.
21024 *
21025 * @static
21026 * @memberOf _
21027 * @since 1.1.0
21028 * @category Array
21029 * @param {Array} array The array to inspect.
21030 * @param {Function} [predicate=_.identity] The function invoked per iteration.
21031 * @param {number} [fromIndex=0] The index to search from.
21032 * @returns {number} Returns the index of the found element, else `-1`.
21033 * @example
21034 *
21035 * var users = [
21036 * { 'user': 'barney', 'active': false },
21037 * { 'user': 'fred', 'active': false },
21038 * { 'user': 'pebbles', 'active': true }
21039 * ];
21040 *
21041 * _.findIndex(users, function(o) { return o.user == 'barney'; });
21042 * // => 0
21043 *
21044 * // The `_.matches` iteratee shorthand.
21045 * _.findIndex(users, { 'user': 'fred', 'active': false });
21046 * // => 1
21047 *
21048 * // The `_.matchesProperty` iteratee shorthand.
21049 * _.findIndex(users, ['active', false]);
21050 * // => 0
21051 *
21052 * // The `_.property` iteratee shorthand.
21053 * _.findIndex(users, 'active');
21054 * // => 2
21055 */
21056 function findIndex(array, predicate, fromIndex) {
21057 var length = array == null ? 0 : array.length;
21058 if (!length) {
21059 return -1;
21060 }
21061 var index = fromIndex == null ? 0 : toInteger_1(fromIndex);
21062 if (index < 0) {
21063 index = nativeMax(length + index, 0);
21064 }
21065 return _baseFindIndex(array, _baseIteratee(predicate), index);
21066 }
21067
21068 var findIndex_1 = findIndex;
21069
21070 /**
21071 * Iterates over elements of `collection`, returning the first element
21072 * `predicate` returns truthy for. The predicate is invoked with three
21073 * arguments: (value, index|key, collection).
21074 *
21075 * @static
21076 * @memberOf _
21077 * @since 0.1.0
21078 * @category Collection
21079 * @param {Array|Object} collection The collection to inspect.
21080 * @param {Function} [predicate=_.identity] The function invoked per iteration.
21081 * @param {number} [fromIndex=0] The index to search from.
21082 * @returns {*} Returns the matched element, else `undefined`.
21083 * @example
21084 *
21085 * var users = [
21086 * { 'user': 'barney', 'age': 36, 'active': true },
21087 * { 'user': 'fred', 'age': 40, 'active': false },
21088 * { 'user': 'pebbles', 'age': 1, 'active': true }
21089 * ];
21090 *
21091 * _.find(users, function(o) { return o.age < 40; });
21092 * // => object for 'barney'
21093 *
21094 * // The `_.matches` iteratee shorthand.
21095 * _.find(users, { 'age': 1, 'active': true });
21096 * // => object for 'pebbles'
21097 *
21098 * // The `_.matchesProperty` iteratee shorthand.
21099 * _.find(users, ['active', false]);
21100 * // => object for 'fred'
21101 *
21102 * // The `_.property` iteratee shorthand.
21103 * _.find(users, 'active');
21104 * // => object for 'barney'
21105 */
21106 var find = _createFind(findIndex_1);
21107
21108 var find_1 = find;
21109
21110 // IMClient
21111 var UNREAD_MESSAGES_COUNT_UPDATE = 'unreadmessagescountupdate';
21112 var CLOSE = 'close';
21113 var CONFLICT = 'conflict';
21114 var CONVERSATION_INFO_UPDATED = 'conversationinfoupdated';
21115 var UNHANDLED_MESSAGE = 'unhandledmessage';
21116
21117 // shared
21118 var INVITED = 'invited';
21119 var KICKED = 'kicked';
21120 var MEMBERS_JOINED = 'membersjoined';
21121 var MEMBERS_LEFT = 'membersleft';
21122 var MEMBER_INFO_UPDATED = 'memberinfoupdated';
21123 var BLOCKED = 'blocked';
21124 var UNBLOCKED = 'unblocked';
21125 var MEMBERS_BLOCKED = 'membersblocked';
21126 var MEMBERS_UNBLOCKED = 'membersunblocked';
21127 var MUTED = 'muted';
21128 var UNMUTED = 'unmuted';
21129 var MEMBERS_MUTED = 'membersmuted';
21130 var MEMBERS_UNMUTED = 'membersunmuted';
21131 var MESSAGE$1 = 'message';
21132 var MESSAGE_RECALL = 'messagerecall';
21133 var MESSAGE_UPDATE = 'messageupdate';
21134
21135 // Conversation
21136 var LAST_DELIVERED_AT_UPDATE = 'lastdeliveredatupdate';
21137 var LAST_READ_AT_UPDATE = 'lastreadatupdate';
21138 var INFO_UPDATED = 'infoupdated';
21139
21140 var IMEvent = /*#__PURE__*/Object.freeze({
21141 __proto__: null,
21142 UNREAD_MESSAGES_COUNT_UPDATE: UNREAD_MESSAGES_COUNT_UPDATE,
21143 CLOSE: CLOSE,
21144 CONFLICT: CONFLICT,
21145 CONVERSATION_INFO_UPDATED: CONVERSATION_INFO_UPDATED,
21146 UNHANDLED_MESSAGE: UNHANDLED_MESSAGE,
21147 INVITED: INVITED,
21148 KICKED: KICKED,
21149 MEMBERS_JOINED: MEMBERS_JOINED,
21150 MEMBERS_LEFT: MEMBERS_LEFT,
21151 MEMBER_INFO_UPDATED: MEMBER_INFO_UPDATED,
21152 BLOCKED: BLOCKED,
21153 UNBLOCKED: UNBLOCKED,
21154 MEMBERS_BLOCKED: MEMBERS_BLOCKED,
21155 MEMBERS_UNBLOCKED: MEMBERS_UNBLOCKED,
21156 MUTED: MUTED,
21157 UNMUTED: UNMUTED,
21158 MEMBERS_MUTED: MEMBERS_MUTED,
21159 MEMBERS_UNMUTED: MEMBERS_UNMUTED,
21160 MESSAGE: MESSAGE$1,
21161 MESSAGE_RECALL: MESSAGE_RECALL,
21162 MESSAGE_UPDATE: MESSAGE_UPDATE,
21163 LAST_DELIVERED_AT_UPDATE: LAST_DELIVERED_AT_UPDATE,
21164 LAST_READ_AT_UPDATE: LAST_READ_AT_UPDATE,
21165 INFO_UPDATED: INFO_UPDATED
21166 });
21167
21168 var _rMessageStatus;
21169 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; }
21170 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; }
21171
21172 /**
21173 * 消息状态枚举
21174 * @enum {Symbol}
21175 * @since 3.2.0
21176 * @memberof module:leancloud-realtime
21177 */
21178 var MessageStatus = {
21179 /** 初始状态、未知状态 */
21180 NONE: Symbol('none'),
21181 /** 正在发送 */
21182 SENDING: Symbol('sending'),
21183 /** 已发送 */
21184 SENT: Symbol('sent'),
21185 /** 已送达 */
21186 DELIVERED: Symbol('delivered'),
21187 /** 发送失败 */
21188 FAILED: Symbol('failed')
21189 };
21190 Object.freeze(MessageStatus);
21191 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);
21192 var Message = /*#__PURE__*/function () {
21193 /**
21194 * @implements AVMessage
21195 * @param {Object|String|ArrayBuffer} content 消息内容
21196 */
21197 function Message(content) {
21198 Object.assign(this, {
21199 content: content
21200 }, {
21201 /**
21202 * @type {String}
21203 * @memberof Message#
21204 */
21205 id: v4_1(),
21206 /**
21207 * 消息所在的 conversation id
21208 * @memberof Message#
21209 * @type {String?}
21210 */
21211 cid: null,
21212 /**
21213 * 消息发送时间
21214 * @memberof Message#
21215 * @type {Date}
21216 */
21217 timestamp: new Date(),
21218 /**
21219 * 消息发送者
21220 * @memberof Message#
21221 * @type {String}
21222 */
21223 from: undefined,
21224 /**
21225 * 消息提及的用户
21226 * @since 4.0.0
21227 * @memberof Message#
21228 * @type {String[]}
21229 */
21230 mentionList: [],
21231 /**
21232 * 消息是否提及了所有人
21233 * @since 4.0.0
21234 * @memberof Message#
21235 * @type {Boolean}
21236 */
21237 mentionedAll: false,
21238 _mentioned: false
21239 });
21240 this._setStatus(MessageStatus.NONE);
21241 }
21242
21243 /**
21244 * 将当前消息的内容序列化为 JSON 对象
21245 * @private
21246 * @return {Object}
21247 */
21248 var _proto = Message.prototype;
21249 _proto.getPayload = function getPayload() {
21250 return this.content;
21251 };
21252 _proto._toJSON = function _toJSON() {
21253 var id = this.id,
21254 cid = this.cid,
21255 from = this.from,
21256 timestamp = this.timestamp,
21257 deliveredAt = this.deliveredAt,
21258 updatedAt = this.updatedAt,
21259 mentionList = this.mentionList,
21260 mentionedAll = this.mentionedAll,
21261 mentioned = this.mentioned;
21262 return {
21263 id: id,
21264 cid: cid,
21265 from: from,
21266 timestamp: timestamp,
21267 deliveredAt: deliveredAt,
21268 updatedAt: updatedAt,
21269 mentionList: mentionList,
21270 mentionedAll: mentionedAll,
21271 mentioned: mentioned
21272 };
21273 }
21274
21275 /**
21276 * 返回 JSON 格式的消息
21277 * @return {Object} 返回值是一个 plain Object
21278 */;
21279 _proto.toJSON = function toJSON() {
21280 return _objectSpread$3(_objectSpread$3({}, this._toJSON()), {}, {
21281 data: this.content
21282 });
21283 }
21284
21285 /**
21286 * 返回 JSON 格式的消息,与 toJSON 不同的是,该对象包含了完整的信息,可以通过 {@link IMClient#parseMessage} 反序列化。
21287 * @return {Object} 返回值是一个 plain Object
21288 * @since 4.0.0
21289 */;
21290 _proto.toFullJSON = function toFullJSON() {
21291 var content = this.content,
21292 id = this.id,
21293 cid = this.cid,
21294 from = this.from,
21295 timestamp = this.timestamp,
21296 deliveredAt = this.deliveredAt,
21297 _updatedAt = this._updatedAt,
21298 mentionList = this.mentionList,
21299 mentionedAll = this.mentionedAll;
21300 return {
21301 data: content,
21302 id: id,
21303 cid: cid,
21304 from: from,
21305 timestamp: getTime(timestamp),
21306 deliveredAt: getTime(deliveredAt),
21307 updatedAt: getTime(_updatedAt),
21308 mentionList: mentionList,
21309 mentionedAll: mentionedAll
21310 };
21311 }
21312
21313 /**
21314 * 消息状态,值为 {@link module:leancloud-realtime.MessageStatus} 之一
21315 * @type {Symbol}
21316 * @readonly
21317 * @since 3.2.0
21318 */;
21319 _proto._setStatus = function _setStatus(status) {
21320 if (!rMessageStatus[status]) {
21321 throw new Error('Invalid message status');
21322 }
21323 this._status = status;
21324 };
21325 _proto._updateMentioned = function _updateMentioned(client) {
21326 this._mentioned = this.from !== client && (this.mentionedAll || this.mentionList.indexOf(client) > -1);
21327 }
21328
21329 /**
21330 * 获取提及用户列表
21331 * @since 4.0.0
21332 * @return {String[]} 提及用户的 id 列表
21333 */;
21334 _proto.getMentionList = function getMentionList() {
21335 return this.mentionList;
21336 }
21337
21338 /**
21339 * 设置提及用户列表
21340 * @since 4.0.0
21341 * @param {String[]} clients 提及用户的 id 列表
21342 * @return {this} self
21343 */;
21344 _proto.setMentionList = function setMentionList(clients) {
21345 this.mentionList = ensureArray(clients);
21346 return this;
21347 }
21348
21349 /**
21350 * 设置是否提及所有人
21351 * @since 4.0.0
21352 * @param {Boolean} [value=true]
21353 * @return {this} self
21354 */;
21355 _proto.mentionAll = function mentionAll() {
21356 var value = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
21357 this.mentionedAll = Boolean(value);
21358 return this;
21359 }
21360
21361 /**
21362 * 判断给定的内容是否是有效的 Message,
21363 * 该方法始终返回 true
21364 * @private
21365 * @returns {Boolean}
21366 * @implements AVMessage.validate
21367 */;
21368 Message.validate = function validate() {
21369 return true;
21370 }
21371
21372 /**
21373 * 解析处理消息内容
21374 * <pre>
21375 * 如果子类提供了 message,返回该 message
21376 * 如果没有提供,将 json 作为 content 实例化一个 Message
21377 * @private
21378 * @param {Object} json json 格式的消息内容
21379 * @param {Message} message 子类提供的 message
21380 * @return {Message}
21381 * @implements AVMessage.parse
21382 */;
21383 Message.parse = function parse(json, message) {
21384 return message || new this(json);
21385 };
21386 _createClass(Message, [{
21387 key: "status",
21388 get: function get() {
21389 return this._status;
21390 }
21391 }, {
21392 key: "timestamp",
21393 get: function get() {
21394 return this._timestamp;
21395 },
21396 set: function set(value) {
21397 this._timestamp = decodeDate(value);
21398 }
21399
21400 /**
21401 * 消息送达时间
21402 * @type {?Date}
21403 */
21404 }, {
21405 key: "deliveredAt",
21406 get: function get() {
21407 return this._deliveredAt;
21408 },
21409 set: function set(value) {
21410 this._deliveredAt = decodeDate(value);
21411 }
21412
21413 /**
21414 * 消息修改或撤回时间,可以通过比较其与消息的 timestamp 是否相等判断消息是否被修改过或撤回过。
21415 * @type {Date}
21416 * @since 3.5.0
21417 */
21418 }, {
21419 key: "updatedAt",
21420 get: function get() {
21421 return this._updatedAt || this.timestamp;
21422 },
21423 set: function set(value) {
21424 this._updatedAt = decodeDate(value);
21425 }
21426
21427 /**
21428 * 当前用户是否在该消息中被提及
21429 * @type {Boolean}
21430 * @readonly
21431 * @since 4.0.0
21432 */
21433 }, {
21434 key: "mentioned",
21435 get: function get() {
21436 return this._mentioned;
21437 }
21438 }]);
21439 return Message;
21440 }();
21441
21442 /* eslint-disable no-param-reassign */
21443
21444 // documented in ../index.js
21445 var messageType = function messageType(type) {
21446 if (typeof type !== 'number') {
21447 throw new TypeError("".concat(type, " is not a Number"));
21448 }
21449 return function (target) {
21450 target.TYPE = type;
21451 target.validate = function (json) {
21452 return json._lctype === type;
21453 };
21454 target.prototype._getType = function () {
21455 return {
21456 _lctype: type
21457 };
21458 };
21459 };
21460 };
21461
21462 // documented in ../plugin-im.js
21463 var messageField = function messageField(fields) {
21464 if (typeof fields !== 'string') {
21465 if (!Array.isArray(fields)) {
21466 throw new TypeError("".concat(fields, " is not an Array"));
21467 } else if (fields.some(function (value) {
21468 return typeof value !== 'string';
21469 })) {
21470 throw new TypeError('fields contains non-string typed member');
21471 }
21472 }
21473 return function (target) {
21474 // IE10 Hack:
21475 // static properties in IE10 will not be inherited from super
21476 // search for parse method and assign it manually
21477 var originalCustomFields = isIE10 ? getStaticProperty(target, '_customFields') : target._customFields;
21478 originalCustomFields = Array.isArray(originalCustomFields) ? originalCustomFields : [];
21479 target._customFields = originalCustomFields.concat(fields);
21480 };
21481 };
21482
21483 // IE10 Hack:
21484 // static properties in IE10 will not be inherited from super
21485 // search for parse method and assign it manually
21486
21487 var IE10Compatible = function IE10Compatible(target) {
21488 if (isIE10) {
21489 target.parse = getStaticProperty(target, 'parse');
21490 }
21491 };
21492
21493 var _dec, _class$1;
21494 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; }
21495 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; }
21496
21497 // jsdoc-ignore-start
21498 var TypedMessage = (_dec = messageField(['_lctext', '_lcattrs']), _dec(_class$1 = /*#__PURE__*/function (_Message) {
21499 _inheritsLoose(TypedMessage, _Message);
21500 function TypedMessage() {
21501 return _Message.apply(this, arguments) || this;
21502 }
21503 var _proto = TypedMessage.prototype;
21504 /**
21505 * @param {String} text
21506 * @return {this} self
21507 */
21508 _proto.setText = function setText(text) {
21509 this._lctext = text;
21510 return this;
21511 }
21512
21513 /**
21514 * @return {String}
21515 */;
21516 _proto.getText = function getText() {
21517 return this._lctext;
21518 }
21519
21520 /**
21521 * @param {Object} attributes
21522 * @return {this} self
21523 */;
21524 _proto.setAttributes = function setAttributes(attributes) {
21525 this._lcattrs = attributes;
21526 return this;
21527 }
21528
21529 /**
21530 * @return {Object}
21531 */;
21532 _proto.getAttributes = function getAttributes() {
21533 return this._lcattrs;
21534 };
21535 _proto._getCustomFields = function _getCustomFields() {
21536 var _this = this;
21537 var fields = Array.isArray(this.constructor._customFields) ? this.constructor._customFields : [];
21538 return fields.reduce(function (result, field) {
21539 if (typeof field !== 'string') return result;
21540 result[field] = _this[field]; // eslint-disable-line no-param-reassign
21541 return result;
21542 }, {});
21543 }
21544
21545 /* eslint-disable class-methods-use-this */;
21546 _proto._getType = function _getType() {
21547 throw new Error('not implemented');
21548 }
21549 /* eslint-enable class-methods-use-this */;
21550 _proto.getPayload = function getPayload() {
21551 return compact(_objectSpread$4(_objectSpread$4({
21552 _lctext: this.getText(),
21553 _lcattrs: this.getAttributes()
21554 }, this._getCustomFields()), this._getType()));
21555 };
21556 _proto.toJSON = function toJSON() {
21557 var type = this.type,
21558 text = this.text,
21559 attributes = this.attributes,
21560 summary = this.summary;
21561 return _objectSpread$4(_objectSpread$4({}, _Message.prototype._toJSON.call(this)), {}, {
21562 type: type,
21563 text: text,
21564 attributes: attributes,
21565 summary: summary
21566 });
21567 };
21568 _proto.toFullJSON = function toFullJSON() {
21569 return _objectSpread$4(_objectSpread$4({}, _Message.prototype.toFullJSON.call(this)), {}, {
21570 data: this.getPayload()
21571 });
21572 }
21573
21574 /**
21575 * 解析处理消息内容
21576 * <pre>
21577 * 为给定的 message 设置 text 与 attributes 属性,返回该 message
21578 * 如果子类没有提供 message,new this()
21579 * @protected
21580 * @param {Object} json json 格式的消息内容
21581 * @param {TypedMessage} message 子类提供的 message
21582 * @return {TypedMessage}
21583 * @implements AVMessage.parse
21584 */;
21585 TypedMessage.parse = function parse(json) {
21586 var message = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : new this();
21587 message.content = json; // eslint-disable-line no-param-reassign
21588 var customFields = isIE10 ? getStaticProperty(message.constructor, '_customFields') : message.constructor._customFields;
21589 var fields = Array.isArray(customFields) ? customFields : [];
21590 fields = fields.reduce(function (result, field) {
21591 if (typeof field !== 'string') return result;
21592 result[field] = json[field]; // eslint-disable-line no-param-reassign
21593 return result;
21594 }, {});
21595 Object.assign(message, fields);
21596 return _Message.parse.call(this, json, message);
21597 };
21598 _createClass(TypedMessage, [{
21599 key: "type",
21600 get:
21601 /**
21602 * @type {Number}
21603 * @readonly
21604 */
21605 function get() {
21606 return this.constructor.TYPE;
21607 }
21608
21609 /** @type {String} */
21610 }, {
21611 key: "text",
21612 get: function get() {
21613 return this.getText();
21614 }
21615
21616 /** @type {Object} */,
21617 set: function set(text) {
21618 return this.setText(text);
21619 }
21620 }, {
21621 key: "attributes",
21622 get: function get() {
21623 return this.getAttributes();
21624 }
21625
21626 /**
21627 * 在客户端需要以文本形式展示该消息时显示的文案,
21628 * 如 <code>[红包] 新春快乐</code>。
21629 * 默认值为消息的 text。
21630 * @type {String}
21631 * @readonly
21632 */,
21633 set: function set(attributes) {
21634 return this.setAttributes(attributes);
21635 }
21636 }, {
21637 key: "summary",
21638 get: function get() {
21639 return this.text;
21640 }
21641 }]);
21642 return TypedMessage;
21643 }(Message)) || _class$1);
21644
21645 var _dec$1, _class$2;
21646
21647 // jsdoc-ignore-start
21648 var RecalledMessage = (_dec$1 = messageType(-127), _dec$1(_class$2 = IE10Compatible(_class$2 = /*#__PURE__*/function (_TypedMessage) {
21649 _inheritsLoose(RecalledMessage, _TypedMessage);
21650 function RecalledMessage() {
21651 return _TypedMessage.apply(this, arguments) || this;
21652 }
21653 _createClass(RecalledMessage, [{
21654 key: "summary",
21655 get:
21656 /**
21657 * 在客户端需要以文本形式展示该消息时显示的文案,值为 <code>[该消息已撤回]</code>
21658 * @type {String}
21659 * @readonly
21660 */
21661 // eslint-disable-next-line class-methods-use-this
21662 function get() {
21663 return '[该消息已撤回]';
21664 }
21665 }]);
21666 return RecalledMessage;
21667 }(TypedMessage)) || _class$2) || _class$2);
21668
21669 var _excluded$1 = ["id", "lastMessageAt", "lastMessage", "lastDeliveredAt", "lastReadAt", "unreadMessagesCount", "members", "mentioned"];
21670 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; }
21671 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; }
21672 var debug$7 = browser('LC:Conversation');
21673 var serializeMessage = function serializeMessage(message) {
21674 var content = message.getPayload();
21675 var msg;
21676 var binaryMsg;
21677 if (content instanceof ArrayBuffer) {
21678 binaryMsg = content;
21679 } else if (typeof content !== 'string') {
21680 msg = JSON.stringify(content);
21681 } else {
21682 msg = content;
21683 }
21684 return {
21685 msg: msg,
21686 binaryMsg: binaryMsg
21687 };
21688 };
21689 var _LogsCommand$QueryDir = LogsCommand.QueryDirection,
21690 NEW = _LogsCommand$QueryDir.NEW,
21691 OLD = _LogsCommand$QueryDir.OLD;
21692
21693 /**
21694 * 历史消息查询方向枚举
21695 * @enum {Number}
21696 * @since 4.0.0
21697 * @memberof module:leancloud-realtime
21698 */
21699 var MessageQueryDirection = {
21700 /** 从后向前 */
21701 NEW_TO_OLD: OLD,
21702 /** 从前向后 */
21703 OLD_TO_NEW: NEW
21704 };
21705 Object.freeze(MessageQueryDirection);
21706 var ConversationBase = /*#__PURE__*/function (_EventEmitter) {
21707 _inheritsLoose(ConversationBase, _EventEmitter);
21708 /**
21709 * @extends EventEmitter
21710 * @private
21711 * @abstract
21712 */
21713 function ConversationBase(_ref, client) {
21714 var _this;
21715 var id = _ref.id,
21716 lastMessageAt = _ref.lastMessageAt,
21717 lastMessage = _ref.lastMessage,
21718 lastDeliveredAt = _ref.lastDeliveredAt,
21719 lastReadAt = _ref.lastReadAt,
21720 _ref$unreadMessagesCo = _ref.unreadMessagesCount,
21721 unreadMessagesCount = _ref$unreadMessagesCo === void 0 ? 0 : _ref$unreadMessagesCo,
21722 _ref$members = _ref.members,
21723 members = _ref$members === void 0 ? [] : _ref$members,
21724 _ref$mentioned = _ref.mentioned,
21725 mentioned = _ref$mentioned === void 0 ? false : _ref$mentioned,
21726 properties = _objectWithoutProperties(_ref, _excluded$1);
21727 _this = _EventEmitter.call(this) || this;
21728 Object.assign(_assertThisInitialized(_this), _objectSpread$5({
21729 /**
21730 * 对话 id,对应 _Conversation 表中的 objectId
21731 * @memberof ConversationBase#
21732 * @type {String}
21733 */
21734 id: id,
21735 /**
21736 * 最后一条消息时间
21737 * @memberof ConversationBase#
21738 * @type {?Date}
21739 */
21740 lastMessageAt: lastMessageAt,
21741 /**
21742 * 最后一条消息
21743 * @memberof ConversationBase#
21744 * @type {?Message}
21745 */
21746 lastMessage: lastMessage,
21747 /**
21748 * 参与该对话的用户列表
21749 * @memberof ConversationBase#
21750 * @type {String[]}
21751 */
21752 members: members
21753 }, properties));
21754 _this.members = Array.from(new Set(_this.members));
21755 Object.assign(internal(_assertThisInitialized(_this)), {
21756 messagesWaitingForReceipt: {},
21757 lastDeliveredAt: lastDeliveredAt,
21758 lastReadAt: lastReadAt,
21759 unreadMessagesCount: unreadMessagesCount,
21760 mentioned: mentioned
21761 });
21762 _this._client = client;
21763 if (debug$7.enabled) {
21764 values_1(IMEvent).forEach(function (event) {
21765 return _this.on(event, function () {
21766 for (var _len = arguments.length, payload = new Array(_len), _key = 0; _key < _len; _key++) {
21767 payload[_key] = arguments[_key];
21768 }
21769 return _this._debug("".concat(event, " event emitted. %o"), payload);
21770 });
21771 });
21772 }
21773 // onConversationCreate hook
21774 applyDecorators(_this._client._plugins.onConversationCreate, _assertThisInitialized(_this));
21775 return _this;
21776 }
21777
21778 /**
21779 * 当前用户是否在该对话的未读消息中被提及
21780 * @type {Boolean}
21781 * @since 4.0.0
21782 */
21783 var _proto = ConversationBase.prototype;
21784 _proto._setUnreadMessagesMentioned = function _setUnreadMessagesMentioned(value) {
21785 internal(this).unreadMessagesMentioned = Boolean(value);
21786 };
21787 _proto._setLastDeliveredAt = function _setLastDeliveredAt(value) {
21788 var date = decodeDate(value);
21789 if (!(date < internal(this).lastDeliveredAt)) {
21790 internal(this).lastDeliveredAt = date;
21791 /**
21792 * 最后消息送达时间更新
21793 * @event ConversationBase#LAST_DELIVERED_AT_UPDATE
21794 * @since 3.4.0
21795 */
21796 this.emit(LAST_DELIVERED_AT_UPDATE);
21797 }
21798 }
21799
21800 /**
21801 * 最后消息被阅读时间,常用来实现发送消息的「已读」标记,可通过 {@link Conversation#fetchReceiptTimestamps} 获取或更新该属性
21802 * @type {?Date}
21803 * @since 3.4.0
21804 */;
21805 _proto._setLastReadAt = function _setLastReadAt(value) {
21806 var date = decodeDate(value);
21807 if (!(date < internal(this).lastReadAt)) {
21808 internal(this).lastReadAt = date;
21809 /**
21810 * 最后消息被阅读时间更新
21811 * @event ConversationBase#LAST_READ_AT_UPDATE
21812 * @since 3.4.0
21813 */
21814 this.emit(LAST_READ_AT_UPDATE);
21815 }
21816 }
21817
21818 /**
21819 * 返回 JSON 格式的对话,与 toJSON 不同的是,该对象包含了完整的信息,可以通过 {@link IMClient#parseConversation} 反序列化。
21820 * @return {Object} 返回值是一个 plain Object
21821 * @since 4.0.0
21822 */;
21823 _proto.toFullJSON = function toFullJSON() {
21824 var id = this.id,
21825 members = this.members,
21826 lastMessageAt = this.lastMessageAt,
21827 lastDeliveredAt = this.lastDeliveredAt,
21828 lastReadAt = this.lastReadAt,
21829 lastMessage = this.lastMessage,
21830 unreadMessagesCount = this.unreadMessagesCount;
21831 return {
21832 id: id,
21833 members: members,
21834 lastMessageAt: getTime(lastMessageAt),
21835 lastDeliveredAt: getTime(lastDeliveredAt),
21836 lastReadAt: getTime(lastReadAt),
21837 lastMessage: lastMessage ? lastMessage.toFullJSON() : undefined,
21838 unreadMessagesCount: unreadMessagesCount
21839 };
21840 }
21841
21842 /**
21843 * 返回 JSON 格式的对话
21844 * @return {Object} 返回值是一个 plain Object
21845 * @since 4.0.0
21846 */;
21847 _proto.toJSON = function toJSON() {
21848 var id = this.id,
21849 members = this.members,
21850 lastMessageAt = this.lastMessageAt,
21851 lastDeliveredAt = this.lastDeliveredAt,
21852 lastReadAt = this.lastReadAt,
21853 lastMessage = this.lastMessage,
21854 unreadMessagesCount = this.unreadMessagesCount,
21855 unreadMessagesMentioned = this.unreadMessagesMentioned;
21856 return {
21857 id: id,
21858 members: members,
21859 lastMessageAt: lastMessageAt,
21860 lastDeliveredAt: lastDeliveredAt,
21861 lastReadAt: lastReadAt,
21862 lastMessage: lastMessage ? lastMessage.toJSON() : undefined,
21863 unreadMessagesCount: unreadMessagesCount,
21864 unreadMessagesMentioned: unreadMessagesMentioned
21865 };
21866 };
21867 _proto._debug = function _debug() {
21868 for (var _len2 = arguments.length, params = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
21869 params[_key2] = arguments[_key2];
21870 }
21871 debug$7.apply(void 0, params.concat(["[".concat(this.id, "]")]));
21872 };
21873 _proto._send = function _send(command) {
21874 var _this$_client;
21875 /* eslint-disable no-param-reassign */
21876 if (command.cmd === null) {
21877 command.cmd = 'conv';
21878 }
21879 if (command.cmd === 'conv' && command.convMessage === null) {
21880 command.convMessage = new ConvCommand();
21881 }
21882 if (command.convMessage && command.convMessage.cid === null) {
21883 command.convMessage.cid = this.id;
21884 }
21885 /* eslint-enable no-param-reassign */
21886 for (var _len3 = arguments.length, args = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {
21887 args[_key3 - 1] = arguments[_key3];
21888 }
21889 return (_this$_client = this._client)._send.apply(_this$_client, [command].concat(args));
21890 }
21891
21892 /**
21893 * 发送消息
21894 * @param {Message} message 消息,Message 及其子类的实例
21895 * @param {Object} [options] since v3.3.0,发送选项
21896 * @param {Boolean} [options.transient] since v3.3.1,是否作为暂态消息发送
21897 * @param {Boolean} [options.receipt] 是否需要回执,仅在普通对话中有效
21898 * @param {Boolean} [options.will] since v3.4.0,是否指定该消息作为「掉线消息」发送,
21899 * 「掉线消息」会延迟到当前用户掉线后发送,常用来实现「下线通知」功能
21900 * @param {MessagePriority} [options.priority] 消息优先级,仅在暂态对话中有效,
21901 * see: {@link module:leancloud-realtime.MessagePriority MessagePriority}
21902 * @param {Object} [options.pushData] 消息对应的离线推送内容,如果消息接收方不在线,会推送指定的内容。其结构说明参见: {@link https://url.leanapp.cn/pushData 推送消息内容}
21903 * @return {Promise.<Message>} 发送的消息
21904 */;
21905 _proto.send =
21906 /*#__PURE__*/
21907 function () {
21908 var _send2 = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee(message, options) {
21909 var _message$constructor$, _transient, receipt, priority, pushData, will, _serializeMessage, msg, binaryMsg, command, resCommand, _resCommand$ackMessag, uid, t, code, reason, appCode;
21910 return regenerator.wrap(function _callee$(_context) {
21911 while (1) switch (_context.prev = _context.next) {
21912 case 0:
21913 this._debug(message, 'send');
21914 if (message instanceof Message) {
21915 _context.next = 3;
21916 break;
21917 }
21918 throw new TypeError("".concat(message, " is not a Message"));
21919 case 3:
21920 _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;
21921 if (receipt) {
21922 if (this["transient"]) {
21923 console.warn('receipt option is ignored as the conversation is transient.');
21924 } else if (_transient) {
21925 console.warn('receipt option is ignored as the message is sent transiently.');
21926 } else if (this.members.length > 2) {
21927 console.warn('receipt option is recommended to be used in one-on-one conversation.'); // eslint-disable-line max-len
21928 }
21929 }
21930
21931 if (priority && !this["transient"]) {
21932 console.warn('priority option is ignored as the conversation is not transient.');
21933 }
21934 Object.assign(message, {
21935 cid: this.id,
21936 from: this._client.id
21937 });
21938 message._setStatus(MessageStatus.SENDING);
21939 _serializeMessage = serializeMessage(message), msg = _serializeMessage.msg, binaryMsg = _serializeMessage.binaryMsg;
21940 command = new GenericCommand({
21941 cmd: 'direct',
21942 directMessage: new DirectCommand({
21943 msg: msg,
21944 binaryMsg: binaryMsg,
21945 cid: this.id,
21946 r: receipt,
21947 "transient": _transient,
21948 dt: message.id,
21949 pushData: JSON.stringify(pushData),
21950 will: will,
21951 mentionPids: message.mentionList,
21952 mentionAll: message.mentionedAll
21953 }),
21954 priority: priority
21955 });
21956 _context.prev = 10;
21957 _context.next = 13;
21958 return this._send(command);
21959 case 13:
21960 resCommand = _context.sent;
21961 _resCommand$ackMessag = resCommand.ackMessage, uid = _resCommand$ackMessag.uid, t = _resCommand$ackMessag.t, code = _resCommand$ackMessag.code, reason = _resCommand$ackMessag.reason, appCode = _resCommand$ackMessag.appCode;
21962 if (!(code !== null)) {
21963 _context.next = 17;
21964 break;
21965 }
21966 throw createError({
21967 code: code,
21968 reason: reason,
21969 appCode: appCode
21970 });
21971 case 17:
21972 Object.assign(message, {
21973 id: uid,
21974 timestamp: t
21975 });
21976 if (!_transient) {
21977 this.lastMessage = message;
21978 this.lastMessageAt = message.timestamp;
21979 }
21980 message._setStatus(MessageStatus.SENT);
21981 if (receipt) {
21982 internal(this).messagesWaitingForReceipt[message.id] = message;
21983 }
21984 return _context.abrupt("return", message);
21985 case 24:
21986 _context.prev = 24;
21987 _context.t0 = _context["catch"](10);
21988 message._setStatus(MessageStatus.FAILED);
21989 throw _context.t0;
21990 case 28:
21991 case "end":
21992 return _context.stop();
21993 }
21994 }, _callee, this, [[10, 24]]);
21995 }));
21996 function send(_x, _x2) {
21997 return _send2.apply(this, arguments);
21998 }
21999 return send;
22000 }();
22001 _proto._update = /*#__PURE__*/function () {
22002 var _update2 = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee2(message, newMessage, recall) {
22003 var msg, binaryMsg, content, id, cid, timestamp, from, _status;
22004 return regenerator.wrap(function _callee2$(_context2) {
22005 while (1) switch (_context2.prev = _context2.next) {
22006 case 0:
22007 this._debug('patch %O %O %O', message, newMessage, recall);
22008 if (!(message instanceof Message)) {
22009 _context2.next = 8;
22010 break;
22011 }
22012 if (!(message.from !== this._client.id)) {
22013 _context2.next = 4;
22014 break;
22015 }
22016 throw new Error('Updating message from others is not allowed');
22017 case 4:
22018 if (!(message.status !== MessageStatus.SENT && message.status !== MessageStatus.DELIVERED)) {
22019 _context2.next = 6;
22020 break;
22021 }
22022 throw new Error('Message is not sent');
22023 case 6:
22024 _context2.next = 10;
22025 break;
22026 case 8:
22027 if (message.id && message.timestamp) {
22028 _context2.next = 10;
22029 break;
22030 }
22031 throw new TypeError("".concat(message, " is not a Message"));
22032 case 10:
22033 if (!recall) {
22034 content = serializeMessage(newMessage);
22035 msg = content.msg;
22036 binaryMsg = content.binaryMsg;
22037 }
22038 _context2.next = 13;
22039 return this._send(new GenericCommand({
22040 cmd: CommandType.patch,
22041 op: OpType.modify,
22042 patchMessage: new PatchCommand({
22043 patches: [new PatchItem({
22044 cid: this.id,
22045 mid: message.id,
22046 timestamp: Number(message.timestamp),
22047 recall: recall,
22048 data: msg,
22049 binaryMsg: binaryMsg,
22050 mentionPids: newMessage.mentionList,
22051 mentionAll: newMessage.mentionedAll
22052 })],
22053 lastPatchTime: this._client._lastPatchTime
22054 })
22055 }));
22056 case 13:
22057 id = message.id, cid = message.cid, timestamp = message.timestamp, from = message.from, _status = message._status;
22058 Object.assign(newMessage, {
22059 id: id,
22060 cid: cid,
22061 timestamp: timestamp,
22062 from: from,
22063 _status: _status
22064 });
22065 if (this.lastMessage && this.lastMessage.id === newMessage.id) {
22066 this.lastMessage = newMessage;
22067 }
22068 return _context2.abrupt("return", newMessage);
22069 case 17:
22070 case "end":
22071 return _context2.stop();
22072 }
22073 }, _callee2, this);
22074 }));
22075 function _update(_x3, _x4, _x5) {
22076 return _update2.apply(this, arguments);
22077 }
22078 return _update;
22079 }()
22080 /**
22081 * 获取对话人数,或暂态对话的在线人数
22082 * @return {Promise.<Number>}
22083 */
22084 ;
22085 _proto.count =
22086 /*#__PURE__*/
22087 function () {
22088 var _count = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee3() {
22089 var resCommand;
22090 return regenerator.wrap(function _callee3$(_context3) {
22091 while (1) switch (_context3.prev = _context3.next) {
22092 case 0:
22093 this._debug('count');
22094 _context3.next = 3;
22095 return this._send(new GenericCommand({
22096 op: 'count'
22097 }));
22098 case 3:
22099 resCommand = _context3.sent;
22100 return _context3.abrupt("return", resCommand.convMessage.count);
22101 case 5:
22102 case "end":
22103 return _context3.stop();
22104 }
22105 }, _callee3, this);
22106 }));
22107 function count() {
22108 return _count.apply(this, arguments);
22109 }
22110 return count;
22111 }()
22112 /**
22113 * 应用增加成员的操作,产生副作用
22114 * @param {string[]} members
22115 * @abstract
22116 * @private
22117 */
22118 ;
22119 _proto._addMembers = function _addMembers() {}
22120
22121 /**
22122 * 应用减少成员的操作,产生副作用
22123 * @param {string[]} members
22124 * @abstract
22125 * @private
22126 */;
22127 _proto._removeMembers = function _removeMembers() {}
22128
22129 /**
22130 * 修改已发送的消息
22131 * @param {AVMessage} message 要修改的消息,该消息必须是由当前用户发送的。也可以提供一个包含消息 {id, timestamp} 的对象
22132 * @param {AVMessage} newMessage 新的消息
22133 * @return {Promise.<AVMessage>} 更新后的消息
22134 */;
22135 _proto.update =
22136 /*#__PURE__*/
22137 function () {
22138 var _update3 = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee4(message, newMessage) {
22139 return regenerator.wrap(function _callee4$(_context4) {
22140 while (1) switch (_context4.prev = _context4.next) {
22141 case 0:
22142 if (newMessage instanceof Message) {
22143 _context4.next = 2;
22144 break;
22145 }
22146 throw new TypeError("".concat(newMessage, " is not a Message"));
22147 case 2:
22148 return _context4.abrupt("return", this._update(message, newMessage, false));
22149 case 3:
22150 case "end":
22151 return _context4.stop();
22152 }
22153 }, _callee4, this);
22154 }));
22155 function update(_x6, _x7) {
22156 return _update3.apply(this, arguments);
22157 }
22158 return update;
22159 }()
22160 /**
22161 * 撤回已发送的消息
22162 * @param {AVMessage} message 要撤回的消息,该消息必须是由当前用户发送的。也可以提供一个包含消息 {id, timestamp} 的对象
22163 * @return {Promise.<RecalledMessage>} 一条已撤回的消息
22164 */
22165 ;
22166 _proto.recall =
22167 /*#__PURE__*/
22168 function () {
22169 var _recall = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee5(message) {
22170 return regenerator.wrap(function _callee5$(_context5) {
22171 while (1) switch (_context5.prev = _context5.next) {
22172 case 0:
22173 return _context5.abrupt("return", this._update(message, new RecalledMessage(), true));
22174 case 1:
22175 case "end":
22176 return _context5.stop();
22177 }
22178 }, _callee5, this);
22179 }));
22180 function recall(_x8) {
22181 return _recall.apply(this, arguments);
22182 }
22183 return recall;
22184 }()
22185 /**
22186 * 查询消息记录
22187 * 如果仅需实现消息向前记录翻页查询需求,建议使用 {@link Conversation#createMessagesIterator}。
22188 * 不论何种方向,获得的消息都是按照时间升序排列的。
22189 * startClosed 与 endClosed 用于指定查询区间的开闭。
22190 *
22191 * @param {Object} [options]
22192 * @param {Number} [options.limit] 限制查询结果的数量,目前服务端默认为 20
22193 * @param {Number} [options.type] 指定查询的富媒体消息类型,不指定则查询所有消息。
22194 * @param {MessageQueryDirection} [options.direction] 查询的方向。
22195 * 在不指定的情况下如果 startTime 大于 endTime,则为从新到旧查询,可以实现加载聊天记录等场景。
22196 * 如果 startTime 小于 endTime,则为从旧到新查询,可以实现弹幕等场景。
22197 * @param {Date} [options.startTime] 从该时间开始查询,不传则从当前时间开始查询
22198 * @param {String} [options.startMessageId] 从该消息之前开始查询,需要与 startTime 同时使用,为防止某时刻有重复消息
22199 * @param {Boolean}[options.startClosed] 指定查询范围是否包括开始的时间点,默认不包括
22200 * @param {Date} [options.endTime] 查询到该时间为止,不传则查询最早消息为止
22201 * @param {String} [options.endMessageId] 查询到该消息为止,需要与 endTime 同时使用,为防止某时刻有重复消息
22202 * @param {Boolean}[options.endClosed] 指定查询范围是否包括结束的时间点,默认不包括
22203 *
22204 * @param {Date} [options.beforeTime] DEPRECATED: 使用 startTime 代替。限制查询结果为小于该时间之前的消息,不传则为当前时间
22205 * @param {String} [options.beforeMessageId] DEPRECATED: 使用 startMessageId 代替。
22206 * 限制查询结果为该消息之前的消息,需要与 beforeTime 同时使用,为防止某时刻有重复消息
22207 * @param {Date} [options.afterTime] DEPRECATED: 使用 endTime 代替。限制查询结果为大于该时间之前的消息
22208 * @param {String} [options.afterMessageId] DEPRECATED: 使用 endMessageId 代替。
22209 * 限制查询结果为该消息之后的消息,需要与 afterTime 同时使用,为防止某时刻有重复消息
22210 * @return {Promise.<Message[]>} 消息列表
22211 */
22212 ;
22213 _proto.queryMessages =
22214 /*#__PURE__*/
22215 function () {
22216 var _queryMessages = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee7() {
22217 var _this2 = this;
22218 var options,
22219 beforeTime,
22220 beforeMessageId,
22221 afterTime,
22222 afterMessageId,
22223 limit,
22224 direction,
22225 type,
22226 startTime,
22227 startMessageId,
22228 startClosed,
22229 endTime,
22230 endMessageId,
22231 endClosed,
22232 conditions,
22233 resCommand,
22234 _args7 = arguments;
22235 return regenerator.wrap(function _callee7$(_context7) {
22236 while (1) switch (_context7.prev = _context7.next) {
22237 case 0:
22238 options = _args7.length > 0 && _args7[0] !== undefined ? _args7[0] : {};
22239 this._debug('query messages %O', options);
22240 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;
22241 if (!(beforeMessageId || beforeTime || afterMessageId || afterTime)) {
22242 _context7.next = 6;
22243 break;
22244 }
22245 console.warn('DEPRECATION: queryMessages options beforeTime, beforeMessageId, afterTime and afterMessageId are deprecated in favor of startTime, startMessageId, endTime and endMessageId.');
22246 return _context7.abrupt("return", this.queryMessages({
22247 startTime: beforeTime,
22248 startMessageId: beforeMessageId,
22249 endTime: afterTime,
22250 endMessageId: afterMessageId,
22251 limit: limit
22252 }));
22253 case 6:
22254 if (!(startMessageId && !startTime)) {
22255 _context7.next = 8;
22256 break;
22257 }
22258 throw new Error('query option startMessageId must be used with option startTime');
22259 case 8:
22260 if (!(endMessageId && !endTime)) {
22261 _context7.next = 10;
22262 break;
22263 }
22264 throw new Error('query option endMessageId must be used with option endTime');
22265 case 10:
22266 conditions = {
22267 t: startTime,
22268 mid: startMessageId,
22269 tIncluded: startClosed,
22270 tt: endTime,
22271 tmid: endMessageId,
22272 ttIncluded: endClosed,
22273 l: limit,
22274 lctype: type
22275 };
22276 if (conditions.t instanceof Date) {
22277 conditions.t = conditions.t.getTime();
22278 }
22279 if (conditions.tt instanceof Date) {
22280 conditions.tt = conditions.tt.getTime();
22281 }
22282 if (direction !== undefined) {
22283 conditions.direction = direction;
22284 } else if (conditions.tt > conditions.t) {
22285 conditions.direction = MessageQueryDirection.OLD_TO_NEW;
22286 }
22287 _context7.next = 16;
22288 return this._send(new GenericCommand({
22289 cmd: 'logs',
22290 logsMessage: new LogsCommand(Object.assign(conditions, {
22291 cid: this.id
22292 }))
22293 }));
22294 case 16:
22295 resCommand = _context7.sent;
22296 return _context7.abrupt("return", Promise.all(resCommand.logsMessage.logs.map( /*#__PURE__*/function () {
22297 var _ref3 = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee6(_ref2) {
22298 var msgId, timestamp, patchTimestamp, from, ackAt, readAt, data, mentionAll, mentionPids, bin, messageData, message, status;
22299 return regenerator.wrap(function _callee6$(_context6) {
22300 while (1) switch (_context6.prev = _context6.next) {
22301 case 0:
22302 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;
22303 messageData = {
22304 data: data,
22305 bin: bin,
22306 id: msgId,
22307 cid: _this2.id,
22308 timestamp: timestamp,
22309 from: from,
22310 deliveredAt: ackAt,
22311 updatedAt: patchTimestamp,
22312 mentionList: mentionPids,
22313 mentionedAll: mentionAll
22314 };
22315 _context6.next = 4;
22316 return _this2._client.parseMessage(messageData);
22317 case 4:
22318 message = _context6.sent;
22319 status = MessageStatus.SENT;
22320 if (_this2.members.length === 2) {
22321 if (ackAt) status = MessageStatus.DELIVERED;
22322 if (ackAt) _this2._setLastDeliveredAt(ackAt);
22323 if (readAt) _this2._setLastReadAt(readAt);
22324 }
22325 message._setStatus(status);
22326 return _context6.abrupt("return", message);
22327 case 9:
22328 case "end":
22329 return _context6.stop();
22330 }
22331 }, _callee6);
22332 }));
22333 return function (_x9) {
22334 return _ref3.apply(this, arguments);
22335 };
22336 }())));
22337 case 18:
22338 case "end":
22339 return _context7.stop();
22340 }
22341 }, _callee7, this);
22342 }));
22343 function queryMessages() {
22344 return _queryMessages.apply(this, arguments);
22345 }
22346 return queryMessages;
22347 }()
22348 /**
22349 * 获取消息翻页迭代器
22350 * @param {Object} [options]
22351 * @param {Date} [options.beforeTime] 限制起始查询结果为小于该时间之前的消息,不传则为当前时间
22352 * @param {String} [options.beforeMessageId] 限制起始查询结果为该消息之前的消息,需要与 beforeTime 同时使用,为防止某时刻有重复消息
22353 * @param {Number} [options.limit] 限制每页查询结果的数量,目前服务端默认为 20
22354 * @return {AsyncIterater.<Promise.<IteratorResult<Message[]>>>} [AsyncIterator]{@link https://github.com/tc39/proposal-async-iteration},调用其 next 方法返回获取下一页消息的 Promise
22355 * @example
22356 * var messageIterator = conversation.createMessagesIterator({ limit: 10 });
22357 * messageIterator.next().then(function(result) {
22358 * // result: {
22359 * // value: [message1, ..., message10],
22360 * // done: false,
22361 * // }
22362 * });
22363 * messageIterator.next().then(function(result) {
22364 * // result: {
22365 * // value: [message11, ..., message20],
22366 * // done: false,
22367 * // }
22368 * });
22369 * messageIterator.next().then(function(result) {
22370 * // No more messages
22371 * // result: { value: [], done: true }
22372 * });
22373 */
22374 ;
22375 _proto.createMessagesIterator = function createMessagesIterator() {
22376 var _this3 = this;
22377 var _ref4 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
22378 beforeTime = _ref4.beforeTime,
22379 beforeMessageId = _ref4.beforeMessageId,
22380 limit = _ref4.limit;
22381 var promise;
22382 return {
22383 next: function next() {
22384 if (promise === undefined) {
22385 // first call
22386 promise = _this3.queryMessages({
22387 limit: limit,
22388 startTime: beforeTime,
22389 startMessageId: beforeMessageId
22390 });
22391 } else {
22392 promise = promise.then(function (prevMessages) {
22393 if (prevMessages.length === 0 || prevMessages.length < limit) {
22394 // no more messages
22395 return [];
22396 }
22397 return _this3.queryMessages({
22398 startTime: prevMessages[0].timestamp,
22399 startMessageId: prevMessages[0].id,
22400 limit: limit
22401 });
22402 });
22403 }
22404 return promise.then(function (value) {
22405 return {
22406 value: Array.from(value),
22407 done: value.length === 0 || value.length < limit
22408 };
22409 });
22410 }
22411 };
22412 }
22413
22414 /**
22415 * 将该会话标记为已读
22416 * @return {Promise.<this>} self
22417 */;
22418 _proto.read =
22419 /*#__PURE__*/
22420 function () {
22421 var _read = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee8() {
22422 var client;
22423 return regenerator.wrap(function _callee8$(_context8) {
22424 while (1) switch (_context8.prev = _context8.next) {
22425 case 0:
22426 this.unreadMessagesCount = 0;
22427 this._setUnreadMessagesMentioned(false);
22428 // 跳过暂态会话
22429 if (!this["transient"]) {
22430 _context8.next = 4;
22431 break;
22432 }
22433 return _context8.abrupt("return", this);
22434 case 4:
22435 client = this._client;
22436 if (!internal(client).readConversationsBuffer) {
22437 internal(client).readConversationsBuffer = new Set();
22438 }
22439 internal(client).readConversationsBuffer.add(this);
22440 client._doSendRead();
22441 return _context8.abrupt("return", this);
22442 case 9:
22443 case "end":
22444 return _context8.stop();
22445 }
22446 }, _callee8, this);
22447 }));
22448 function read() {
22449 return _read.apply(this, arguments);
22450 }
22451 return read;
22452 }();
22453 _proto._handleReceipt = function _handleReceipt(_ref5) {
22454 var messageId = _ref5.messageId,
22455 timestamp = _ref5.timestamp,
22456 read = _ref5.read;
22457 if (read) {
22458 this._setLastReadAt(timestamp);
22459 } else {
22460 this._setLastDeliveredAt(timestamp);
22461 }
22462 var _internal = internal(this),
22463 messagesWaitingForReceipt = _internal.messagesWaitingForReceipt;
22464 var message = messagesWaitingForReceipt[messageId];
22465 if (!message) return;
22466 message._setStatus(MessageStatus.DELIVERED);
22467 message.deliveredAt = timestamp;
22468 delete messagesWaitingForReceipt[messageId];
22469 }
22470
22471 /**
22472 * 更新对话的最新回执时间戳(lastDeliveredAt、lastReadAt)
22473 * @since 3.4.0
22474 * @return {Promise.<this>} this
22475 */;
22476 _proto.fetchReceiptTimestamps =
22477 /*#__PURE__*/
22478 function () {
22479 var _fetchReceiptTimestamps = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee9() {
22480 var _yield$this$_send, _yield$this$_send$con, maxReadTimestamp, maxAckTimestamp;
22481 return regenerator.wrap(function _callee9$(_context9) {
22482 while (1) switch (_context9.prev = _context9.next) {
22483 case 0:
22484 if (!(this["transient"] || this.system)) {
22485 _context9.next = 2;
22486 break;
22487 }
22488 return _context9.abrupt("return", this);
22489 case 2:
22490 _context9.next = 4;
22491 return this._send(new GenericCommand({
22492 op: 'max_read'
22493 }));
22494 case 4:
22495 _yield$this$_send = _context9.sent;
22496 _yield$this$_send$con = _yield$this$_send.convMessage;
22497 maxReadTimestamp = _yield$this$_send$con.maxReadTimestamp;
22498 maxAckTimestamp = _yield$this$_send$con.maxAckTimestamp;
22499 this._setLastDeliveredAt(maxAckTimestamp);
22500 this._setLastReadAt(maxReadTimestamp);
22501 return _context9.abrupt("return", this);
22502 case 11:
22503 case "end":
22504 return _context9.stop();
22505 }
22506 }, _callee9, this);
22507 }));
22508 function fetchReceiptTimestamps() {
22509 return _fetchReceiptTimestamps.apply(this, arguments);
22510 }
22511 return fetchReceiptTimestamps;
22512 }();
22513 _proto._fetchAllReceiptTimestamps = function _fetchAllReceiptTimestamps() {
22514 // 暂态/系统会话不支持回执
22515 if (this["transient"] || this.system) return this;
22516 var convMessage = new ConvCommand({
22517 queryAllMembers: true
22518 });
22519 return this._send(new GenericCommand({
22520 op: 'max_read',
22521 convMessage: convMessage
22522 })).then(function (_ref6) {
22523 var maxReadTuples = _ref6.convMessage.maxReadTuples;
22524 return maxReadTuples.filter(function (maxReadTuple) {
22525 return maxReadTuple.maxAckTimestamp || maxReadTuple.maxReadTimestamp;
22526 }).map(function (_ref7) {
22527 var pid = _ref7.pid,
22528 maxAckTimestamp = _ref7.maxAckTimestamp,
22529 maxReadTimestamp = _ref7.maxReadTimestamp;
22530 return {
22531 pid: pid,
22532 lastDeliveredAt: decodeDate(maxAckTimestamp),
22533 lastReadAt: decodeDate(maxReadTimestamp)
22534 };
22535 });
22536 });
22537 };
22538 _createClass(ConversationBase, [{
22539 key: "unreadMessagesMentioned",
22540 get: function get() {
22541 return internal(this).unreadMessagesMentioned;
22542 }
22543 }, {
22544 key: "unreadMessagesCount",
22545 get:
22546 /**
22547 * 当前用户在该对话的未读消息数
22548 * @type {Number}
22549 */
22550 function get() {
22551 return internal(this).unreadMessagesCount;
22552 },
22553 set: function set(value) {
22554 if (value !== this.unreadMessagesCount) {
22555 internal(this).unreadMessagesCount = value;
22556 this._client.emit(UNREAD_MESSAGES_COUNT_UPDATE, [this]);
22557 }
22558 }
22559 }, {
22560 key: "lastMessageAt",
22561 get: function get() {
22562 return this._lastMessageAt;
22563 }
22564
22565 /**
22566 * 最后消息送达时间,常用来实现消息的「已送达」标记,可通过 {@link Conversation#fetchReceiptTimestamps} 获取或更新该属性
22567 * @type {?Date}
22568 * @since 3.4.0
22569 */,
22570 set: function set(value) {
22571 var time = decodeDate(value);
22572 if (time <= this._lastMessageAt) return;
22573 this._lastMessageAt = time;
22574 }
22575 }, {
22576 key: "lastDeliveredAt",
22577 get: function get() {
22578 if (this.members.length !== 2) return null;
22579 return internal(this).lastDeliveredAt;
22580 }
22581 }, {
22582 key: "lastReadAt",
22583 get: function get() {
22584 if (this.members.length !== 2) return null;
22585 return internal(this).lastReadAt;
22586 }
22587 }]);
22588 return ConversationBase;
22589 }(eventemitter3);
22590
22591 var debug$8 = browser('LC:SignatureFactoryRunner');
22592 function _validateSignature() {
22593 var signatureResult = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
22594 var signature = signatureResult.signature,
22595 timestamp = signatureResult.timestamp,
22596 nonce = signatureResult.nonce;
22597 if (typeof signature !== 'string' || typeof timestamp !== 'number' || typeof nonce !== 'string') {
22598 throw new Error('malformed signature');
22599 }
22600 return {
22601 signature: signature,
22602 timestamp: timestamp,
22603 nonce: nonce
22604 };
22605 }
22606 var runSignatureFactory = (function (signatureFactory, params) {
22607 return Promise.resolve().then(function () {
22608 debug$8('call signatureFactory with %O', params);
22609 return signatureFactory.apply(void 0, _toConsumableArray$1(params));
22610 }).then(tap(function (signatureResult) {
22611 return debug$8('sign result %O', signatureResult);
22612 }), function (error) {
22613 // eslint-disable-next-line no-param-reassign
22614 error.message = "sign error: ".concat(error.message);
22615 debug$8(error);
22616 throw error;
22617 }).then(_validateSignature);
22618 });
22619
22620 var _excluded$2 = ["pids"],
22621 _excluded2 = ["creator", "createdAt", "updatedAt", "transient", "system", "muted", "mutedMembers"];
22622 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; }
22623 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; }
22624
22625 /**
22626 * 部分失败异常
22627 * @typedef OperationFailureError
22628 * @type {Error}
22629 * @property {string} message 异常信息
22630 * @property {string[]} clientIds 因为该原因失败的 client id 列表
22631 * @property {number} [code] 错误码
22632 * @property {string} [detail] 详细信息
22633 */
22634
22635 /**
22636 * 部分成功的结果
22637 * @typedef PartiallySuccess
22638 * @type {Object}
22639 * @property {string[]} successfulClientIds 成功的 client id 列表
22640 * @property {OperationFailureError[]} failures 失败的异常列表
22641 */
22642
22643 /**
22644 * 分页查询结果
22645 * @typedef PagedResults
22646 * @type {Object}
22647 * @property {T[]} results 查询结果
22648 * @property {string} [next] 存在表示还有更多结果,在下次查询中带上可实现翻页。
22649 */
22650
22651 var createPartiallySuccess = function createPartiallySuccess(_ref) {
22652 var allowedPids = _ref.allowedPids,
22653 failedPids = _ref.failedPids;
22654 return {
22655 successfulClientIds: allowedPids,
22656 failures: failedPids.map(function (_ref2) {
22657 var pids = _ref2.pids,
22658 error = _objectWithoutProperties(_ref2, _excluded$2);
22659 return Object.assign(createError(error), {
22660 clientIds: pids
22661 });
22662 })
22663 };
22664 };
22665
22666 /**
22667 * @extends ConversationBase
22668 * @private
22669 * @abstract
22670 */
22671 var PersistentConversation = /*#__PURE__*/function (_ConversationBase) {
22672 _inheritsLoose(PersistentConversation, _ConversationBase);
22673 function PersistentConversation(data, _ref3, client) {
22674 var _this;
22675 var creator = _ref3.creator,
22676 createdAt = _ref3.createdAt,
22677 updatedAt = _ref3.updatedAt,
22678 _ref3$transient = _ref3["transient"],
22679 _transient = _ref3$transient === void 0 ? false : _ref3$transient,
22680 _ref3$system = _ref3.system,
22681 system = _ref3$system === void 0 ? false : _ref3$system,
22682 _ref3$muted = _ref3.muted,
22683 muted = _ref3$muted === void 0 ? false : _ref3$muted,
22684 _ref3$mutedMembers = _ref3.mutedMembers,
22685 mutedMembers = _ref3$mutedMembers === void 0 ? [] : _ref3$mutedMembers,
22686 attributes = _objectWithoutProperties(_ref3, _excluded2);
22687 _this = _ConversationBase.call(this, _objectSpread$6(_objectSpread$6({}, data), {}, {
22688 /**
22689 * 对话创建者
22690 * @memberof PersistentConversation#
22691 * @type {String}
22692 */
22693 creator: creator,
22694 /**
22695 * 对话创建时间
22696 * @memberof PersistentConversation#
22697 * @type {Date}
22698 */
22699 createdAt: createdAt,
22700 /**
22701 * 对话更新时间
22702 * @memberof PersistentConversation#
22703 * @type {Date}
22704 */
22705 updatedAt: updatedAt,
22706 /**
22707 * 对该对话设置了静音的用户列表
22708 * @memberof PersistentConversation#
22709 * @type {?String[]}
22710 */
22711 mutedMembers: mutedMembers,
22712 /**
22713 * 暂态对话标记
22714 * @memberof PersistentConversation#
22715 * @type {Boolean}
22716 */
22717 "transient": _transient,
22718 /**
22719 * 系统对话标记
22720 * @memberof PersistentConversation#
22721 * @type {Boolean}
22722 * @since 3.3.0
22723 */
22724 system: system,
22725 /**
22726 * 当前用户静音该对话标记
22727 * @memberof PersistentConversation#
22728 * @type {Boolean}
22729 */
22730 muted: muted,
22731 _attributes: attributes
22732 }), client) || this;
22733 _this._reset();
22734 return _this;
22735 }
22736 var _proto = PersistentConversation.prototype;
22737 /**
22738 * 获取对话的自定义属性
22739 * @since 3.2.0
22740 * @param {String} key key 属性的键名,'x' 对应 Conversation 表中的 x 列
22741 * @return {Any} 属性的值
22742 */
22743 _proto.get = function get(key) {
22744 return get_1(internal(this).currentAttributes, key);
22745 }
22746
22747 /**
22748 * 设置对话的自定义属性
22749 * @since 3.2.0
22750 * @param {String} key 属性的键名,'x' 对应 Conversation 表中的 x 列,支持使用 'x.y.z' 来修改对象的部分字段。
22751 * @param {Any} value 属性的值
22752 * @return {this} self
22753 * @example
22754 *
22755 * // 设置对话的 color 属性
22756 * conversation.set('color', {
22757 * text: '#000',
22758 * background: '#DDD',
22759 * });
22760 * // 设置对话的 color.text 属性
22761 * conversation.set('color.text', '#333');
22762 */;
22763 _proto.set = function set(key, value) {
22764 this._debug("set [".concat(key, "]: ").concat(value));
22765 var _internal = internal(this),
22766 pendingAttributes = _internal.pendingAttributes;
22767 var pendingKeys = Object.keys(pendingAttributes);
22768 // suppose pendingAttributes = { 'a.b': {} }
22769 // set 'a' or 'a.b': delete 'a.b'
22770 var re = new RegExp("^".concat(key));
22771 var childKeys = pendingKeys.filter(re.test.bind(re));
22772 childKeys.forEach(function (k) {
22773 delete pendingAttributes[k];
22774 });
22775 if (childKeys.length) {
22776 pendingAttributes[key] = value;
22777 } else {
22778 // set 'a.c': nothing to do
22779 // set 'a.b.c.d': assign c: { d: {} } to 'a.b'
22780 var parentKey = find_1(pendingKeys, function (k) {
22781 return key.indexOf(k) === 0;
22782 }); // 'a.b'
22783 if (parentKey) {
22784 setValue(pendingAttributes[parentKey], key.slice(parentKey.length + 1), value);
22785 } else {
22786 pendingAttributes[key] = value;
22787 }
22788 }
22789 this._buildCurrentAttributes();
22790 return this;
22791 };
22792 _proto._buildCurrentAttributes = function _buildCurrentAttributes() {
22793 var _internal2 = internal(this),
22794 pendingAttributes = _internal2.pendingAttributes;
22795 internal(this).currentAttributes = Object.keys(pendingAttributes).reduce(function (target, k) {
22796 return setValue(target, k, pendingAttributes[k]);
22797 }, cloneDeep_1(this._attributes));
22798 };
22799 _proto._updateServerAttributes = function _updateServerAttributes(attributes) {
22800 var _this2 = this;
22801 Object.keys(attributes).forEach(function (key) {
22802 return setValue(_this2._attributes, key, attributes[key]);
22803 });
22804 this._buildCurrentAttributes();
22805 };
22806 _proto._reset = function _reset() {
22807 Object.assign(internal(this), {
22808 pendingAttributes: {},
22809 currentAttributes: this._attributes
22810 });
22811 }
22812
22813 /**
22814 * 保存当前对话的属性至服务器
22815 * @return {Promise.<this>} self
22816 */;
22817 _proto.save =
22818 /*#__PURE__*/
22819 function () {
22820 var _save = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee() {
22821 var attr, convMessage, resCommand;
22822 return regenerator.wrap(function _callee$(_context) {
22823 while (1) switch (_context.prev = _context.next) {
22824 case 0:
22825 this._debug('save');
22826 attr = internal(this).pendingAttributes;
22827 if (!isEmpty_1(attr)) {
22828 _context.next = 5;
22829 break;
22830 }
22831 this._debug('nothing touched, resolve with self');
22832 return _context.abrupt("return", this);
22833 case 5:
22834 this._debug('attr: %O', attr);
22835 convMessage = new ConvCommand({
22836 attr: new JsonObjectMessage({
22837 data: JSON.stringify(encode(attr))
22838 })
22839 });
22840 _context.next = 9;
22841 return this._send(new GenericCommand({
22842 op: 'update',
22843 convMessage: convMessage
22844 }));
22845 case 9:
22846 resCommand = _context.sent;
22847 this.updatedAt = resCommand.convMessage.udate;
22848 this._attributes = internal(this).currentAttributes;
22849 internal(this).pendingAttributes = {};
22850 return _context.abrupt("return", this);
22851 case 14:
22852 case "end":
22853 return _context.stop();
22854 }
22855 }, _callee, this);
22856 }));
22857 function save() {
22858 return _save.apply(this, arguments);
22859 }
22860 return save;
22861 }()
22862 /**
22863 * 从服务器更新对话的属性
22864 * @return {Promise.<this>} self
22865 */
22866 ;
22867 _proto.fetch =
22868 /*#__PURE__*/
22869 function () {
22870 var _fetch = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee2() {
22871 var query;
22872 return regenerator.wrap(function _callee2$(_context2) {
22873 while (1) switch (_context2.prev = _context2.next) {
22874 case 0:
22875 query = this._client.getQuery().equalTo('objectId', this.id);
22876 _context2.next = 3;
22877 return query.find();
22878 case 3:
22879 return _context2.abrupt("return", this);
22880 case 4:
22881 case "end":
22882 return _context2.stop();
22883 }
22884 }, _callee2, this);
22885 }));
22886 function fetch() {
22887 return _fetch.apply(this, arguments);
22888 }
22889 return fetch;
22890 }()
22891 /**
22892 * 静音,客户端拒绝收到服务器端的离线推送通知
22893 * @return {Promise.<this>} self
22894 */
22895 ;
22896 _proto.mute =
22897 /*#__PURE__*/
22898 function () {
22899 var _mute = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee3() {
22900 return regenerator.wrap(function _callee3$(_context3) {
22901 while (1) switch (_context3.prev = _context3.next) {
22902 case 0:
22903 this._debug('mute');
22904 _context3.next = 3;
22905 return this._send(new GenericCommand({
22906 op: 'mute'
22907 }));
22908 case 3:
22909 if (!this["transient"]) {
22910 this.muted = true;
22911 this.mutedMembers = union(this.mutedMembers, [this._client.id]);
22912 }
22913 return _context3.abrupt("return", this);
22914 case 5:
22915 case "end":
22916 return _context3.stop();
22917 }
22918 }, _callee3, this);
22919 }));
22920 function mute() {
22921 return _mute.apply(this, arguments);
22922 }
22923 return mute;
22924 }()
22925 /**
22926 * 取消静音
22927 * @return {Promise.<this>} self
22928 */
22929 ;
22930 _proto.unmute =
22931 /*#__PURE__*/
22932 function () {
22933 var _unmute = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee4() {
22934 return regenerator.wrap(function _callee4$(_context4) {
22935 while (1) switch (_context4.prev = _context4.next) {
22936 case 0:
22937 this._debug('unmute');
22938 _context4.next = 3;
22939 return this._send(new GenericCommand({
22940 op: 'unmute'
22941 }));
22942 case 3:
22943 if (!this["transient"]) {
22944 this.muted = false;
22945 this.mutedMembers = difference(this.mutedMembers, [this._client.id]);
22946 }
22947 return _context4.abrupt("return", this);
22948 case 5:
22949 case "end":
22950 return _context4.stop();
22951 }
22952 }, _callee4, this);
22953 }));
22954 function unmute() {
22955 return _unmute.apply(this, arguments);
22956 }
22957 return unmute;
22958 }();
22959 _proto._appendConversationSignature = /*#__PURE__*/function () {
22960 var _appendConversationSignature2 = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee5(command, action, clientIds) {
22961 var params, signatureResult;
22962 return regenerator.wrap(function _callee5$(_context5) {
22963 while (1) switch (_context5.prev = _context5.next) {
22964 case 0:
22965 if (!this._client.options.conversationSignatureFactory) {
22966 _context5.next = 6;
22967 break;
22968 }
22969 params = [this.id, this._client.id, clientIds.sort(), action];
22970 _context5.next = 4;
22971 return runSignatureFactory(this._client.options.conversationSignatureFactory, params);
22972 case 4:
22973 signatureResult = _context5.sent;
22974 Object.assign(command.convMessage, keyRemap({
22975 signature: 's',
22976 timestamp: 't',
22977 nonce: 'n'
22978 }, signatureResult));
22979 case 6:
22980 case "end":
22981 return _context5.stop();
22982 }
22983 }, _callee5, this);
22984 }));
22985 function _appendConversationSignature(_x, _x2, _x3) {
22986 return _appendConversationSignature2.apply(this, arguments);
22987 }
22988 return _appendConversationSignature;
22989 }();
22990 _proto._appendBlacklistSignature = /*#__PURE__*/function () {
22991 var _appendBlacklistSignature2 = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee6(command, action, clientIds) {
22992 var params, signatureResult;
22993 return regenerator.wrap(function _callee6$(_context6) {
22994 while (1) switch (_context6.prev = _context6.next) {
22995 case 0:
22996 if (!this._client.options.blacklistSignatureFactory) {
22997 _context6.next = 6;
22998 break;
22999 }
23000 params = [this.id, this._client.id, clientIds.sort(), action];
23001 _context6.next = 4;
23002 return runSignatureFactory(this._client.options.blacklistSignatureFactory, params);
23003 case 4:
23004 signatureResult = _context6.sent;
23005 Object.assign(command.blacklistMessage, keyRemap({
23006 signature: 's',
23007 timestamp: 't',
23008 nonce: 'n'
23009 }, signatureResult));
23010 case 6:
23011 case "end":
23012 return _context6.stop();
23013 }
23014 }, _callee6, this);
23015 }));
23016 function _appendBlacklistSignature(_x4, _x5, _x6) {
23017 return _appendBlacklistSignature2.apply(this, arguments);
23018 }
23019 return _appendBlacklistSignature;
23020 }()
23021 /**
23022 * 增加成员
23023 * @param {String|String[]} clientIds 新增成员 client id
23024 * @return {Promise.<PartiallySuccess>} 部分成功结果,包含了成功的 id 列表、失败原因与对应的 id 列表
23025 */
23026 ;
23027 _proto.add =
23028 /*#__PURE__*/
23029 function () {
23030 var _add = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee7(clientIds) {
23031 var command, _yield$this$_send, convMessage, allowedPids;
23032 return regenerator.wrap(function _callee7$(_context7) {
23033 while (1) switch (_context7.prev = _context7.next) {
23034 case 0:
23035 this._debug('add', clientIds);
23036 if (typeof clientIds === 'string') {
23037 clientIds = [clientIds]; // eslint-disable-line no-param-reassign
23038 }
23039 command = new GenericCommand({
23040 op: 'add',
23041 convMessage: new ConvCommand({
23042 m: clientIds
23043 })
23044 });
23045 _context7.next = 5;
23046 return this._appendConversationSignature(command, 'invite', clientIds);
23047 case 5:
23048 _context7.next = 7;
23049 return this._send(command);
23050 case 7:
23051 _yield$this$_send = _context7.sent;
23052 convMessage = _yield$this$_send.convMessage;
23053 allowedPids = _yield$this$_send.convMessage.allowedPids;
23054 this._addMembers(allowedPids);
23055 return _context7.abrupt("return", createPartiallySuccess(convMessage));
23056 case 12:
23057 case "end":
23058 return _context7.stop();
23059 }
23060 }, _callee7, this);
23061 }));
23062 function add(_x7) {
23063 return _add.apply(this, arguments);
23064 }
23065 return add;
23066 }()
23067 /**
23068 * 剔除成员
23069 * @param {String|String[]} clientIds 成员 client id
23070 * @return {Promise.<PartiallySuccess>} 部分成功结果,包含了成功的 id 列表、失败原因与对应的 id 列表
23071 */
23072 ;
23073 _proto.remove =
23074 /*#__PURE__*/
23075 function () {
23076 var _remove = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee8(clientIds) {
23077 var command, _yield$this$_send2, convMessage, allowedPids;
23078 return regenerator.wrap(function _callee8$(_context8) {
23079 while (1) switch (_context8.prev = _context8.next) {
23080 case 0:
23081 this._debug('remove', clientIds);
23082 if (typeof clientIds === 'string') {
23083 clientIds = [clientIds]; // eslint-disable-line no-param-reassign
23084 }
23085 command = new GenericCommand({
23086 op: 'remove',
23087 convMessage: new ConvCommand({
23088 m: clientIds
23089 })
23090 });
23091 _context8.next = 5;
23092 return this._appendConversationSignature(command, 'kick', clientIds);
23093 case 5:
23094 _context8.next = 7;
23095 return this._send(command);
23096 case 7:
23097 _yield$this$_send2 = _context8.sent;
23098 convMessage = _yield$this$_send2.convMessage;
23099 allowedPids = _yield$this$_send2.convMessage.allowedPids;
23100 this._removeMembers(allowedPids);
23101 return _context8.abrupt("return", createPartiallySuccess(convMessage));
23102 case 12:
23103 case "end":
23104 return _context8.stop();
23105 }
23106 }, _callee8, this);
23107 }));
23108 function remove(_x8) {
23109 return _remove.apply(this, arguments);
23110 }
23111 return remove;
23112 }()
23113 /**
23114 * (当前用户)加入该对话
23115 * @return {Promise.<this>} self
23116 */
23117 ;
23118 _proto.join =
23119 /*#__PURE__*/
23120 function () {
23121 var _join = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee9() {
23122 var _this3 = this;
23123 return regenerator.wrap(function _callee9$(_context9) {
23124 while (1) switch (_context9.prev = _context9.next) {
23125 case 0:
23126 this._debug('join');
23127 return _context9.abrupt("return", this.add(this._client.id).then(function (_ref4) {
23128 var failures = _ref4.failures;
23129 if (failures[0]) throw failures[0];
23130 return _this3;
23131 }));
23132 case 2:
23133 case "end":
23134 return _context9.stop();
23135 }
23136 }, _callee9, this);
23137 }));
23138 function join() {
23139 return _join.apply(this, arguments);
23140 }
23141 return join;
23142 }()
23143 /**
23144 * (当前用户)退出该对话
23145 * @return {Promise.<this>} self
23146 */
23147 ;
23148 _proto.quit =
23149 /*#__PURE__*/
23150 function () {
23151 var _quit = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee10() {
23152 var _this4 = this;
23153 return regenerator.wrap(function _callee10$(_context10) {
23154 while (1) switch (_context10.prev = _context10.next) {
23155 case 0:
23156 this._debug('quit');
23157 return _context10.abrupt("return", this.remove(this._client.id).then(function (_ref5) {
23158 var failures = _ref5.failures;
23159 if (failures[0]) throw failures[0];
23160 return _this4;
23161 }));
23162 case 2:
23163 case "end":
23164 return _context10.stop();
23165 }
23166 }, _callee10, this);
23167 }));
23168 function quit() {
23169 return _quit.apply(this, arguments);
23170 }
23171 return quit;
23172 }()
23173 /**
23174 * 在该对话中禁言成员
23175 * @param {String|String[]} clientIds 成员 client id
23176 * @return {Promise.<PartiallySuccess>} 部分成功结果,包含了成功的 id 列表、失败原因与对应的 id 列表
23177 */
23178 ;
23179 _proto.muteMembers =
23180 /*#__PURE__*/
23181 function () {
23182 var _muteMembers = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee11(clientIds) {
23183 var command, _yield$this$_send3, convMessage;
23184 return regenerator.wrap(function _callee11$(_context11) {
23185 while (1) switch (_context11.prev = _context11.next) {
23186 case 0:
23187 this._debug('mute', clientIds);
23188 clientIds = ensureArray(clientIds); // eslint-disable-line no-param-reassign
23189 command = new GenericCommand({
23190 op: OpType.add_shutup,
23191 convMessage: new ConvCommand({
23192 m: clientIds
23193 })
23194 });
23195 _context11.next = 5;
23196 return this._send(command);
23197 case 5:
23198 _yield$this$_send3 = _context11.sent;
23199 convMessage = _yield$this$_send3.convMessage;
23200 return _context11.abrupt("return", createPartiallySuccess(convMessage));
23201 case 8:
23202 case "end":
23203 return _context11.stop();
23204 }
23205 }, _callee11, this);
23206 }));
23207 function muteMembers(_x9) {
23208 return _muteMembers.apply(this, arguments);
23209 }
23210 return muteMembers;
23211 }()
23212 /**
23213 * 在该对话中解除成员禁言
23214 * @param {String|String[]} clientIds 成员 client id
23215 * @return {Promise.<PartiallySuccess>} 部分成功结果,包含了成功的 id 列表、失败原因与对应的 id 列表
23216 */
23217 ;
23218 _proto.unmuteMembers =
23219 /*#__PURE__*/
23220 function () {
23221 var _unmuteMembers = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee12(clientIds) {
23222 var command, _yield$this$_send4, convMessage;
23223 return regenerator.wrap(function _callee12$(_context12) {
23224 while (1) switch (_context12.prev = _context12.next) {
23225 case 0:
23226 this._debug('unmute', clientIds);
23227 clientIds = ensureArray(clientIds); // eslint-disable-line no-param-reassign
23228 command = new GenericCommand({
23229 op: OpType.remove_shutup,
23230 convMessage: new ConvCommand({
23231 m: clientIds
23232 })
23233 });
23234 _context12.next = 5;
23235 return this._send(command);
23236 case 5:
23237 _yield$this$_send4 = _context12.sent;
23238 convMessage = _yield$this$_send4.convMessage;
23239 return _context12.abrupt("return", createPartiallySuccess(convMessage));
23240 case 8:
23241 case "end":
23242 return _context12.stop();
23243 }
23244 }, _callee12, this);
23245 }));
23246 function unmuteMembers(_x10) {
23247 return _unmuteMembers.apply(this, arguments);
23248 }
23249 return unmuteMembers;
23250 }()
23251 /**
23252 * 查询该对话禁言成员列表
23253 * @param {Object} [options]
23254 * @param {Number} [options.limit] 返回的成员数量,服务器默认值 10
23255 * @param {String} [options.next] 从指定 next 开始查询,与 limit 一起使用可以完成翻页。
23256 * @return {PagedResults.<string>} 查询结果。其中的 cureser 存在表示还有更多结果。
23257 */
23258 ;
23259 _proto.queryMutedMembers =
23260 /*#__PURE__*/
23261 function () {
23262 var _queryMutedMembers = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee13() {
23263 var _ref6,
23264 limit,
23265 next,
23266 command,
23267 _yield$this$_send5,
23268 _yield$this$_send5$co,
23269 m,
23270 newNext,
23271 _args13 = arguments;
23272 return regenerator.wrap(function _callee13$(_context13) {
23273 while (1) switch (_context13.prev = _context13.next) {
23274 case 0:
23275 _ref6 = _args13.length > 0 && _args13[0] !== undefined ? _args13[0] : {}, limit = _ref6.limit, next = _ref6.next;
23276 this._debug('query muted: limit %O, next: %O', limit, next);
23277 command = new GenericCommand({
23278 op: OpType.query_shutup,
23279 convMessage: new ConvCommand({
23280 limit: limit,
23281 next: next
23282 })
23283 });
23284 _context13.next = 5;
23285 return this._send(command);
23286 case 5:
23287 _yield$this$_send5 = _context13.sent;
23288 _yield$this$_send5$co = _yield$this$_send5.convMessage;
23289 m = _yield$this$_send5$co.m;
23290 newNext = _yield$this$_send5$co.next;
23291 return _context13.abrupt("return", {
23292 results: m,
23293 next: newNext
23294 });
23295 case 10:
23296 case "end":
23297 return _context13.stop();
23298 }
23299 }, _callee13, this);
23300 }));
23301 function queryMutedMembers() {
23302 return _queryMutedMembers.apply(this, arguments);
23303 }
23304 return queryMutedMembers;
23305 }()
23306 /**
23307 * 将用户加入该对话黑名单
23308 * @param {String|String[]} clientIds 成员 client id
23309 * @return {Promise.<PartiallySuccess>} 部分成功结果,包含了成功的 id 列表、失败原因与对应的 id 列表
23310 */
23311 ;
23312 _proto.blockMembers =
23313 /*#__PURE__*/
23314 function () {
23315 var _blockMembers = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee14(clientIds) {
23316 var command, _yield$this$_send6, blacklistMessage;
23317 return regenerator.wrap(function _callee14$(_context14) {
23318 while (1) switch (_context14.prev = _context14.next) {
23319 case 0:
23320 this._debug('block', clientIds);
23321 clientIds = ensureArray(clientIds); // eslint-disable-line no-param-reassign
23322 command = new GenericCommand({
23323 cmd: 'blacklist',
23324 op: OpType.block,
23325 blacklistMessage: new BlacklistCommand({
23326 srcCid: this.id,
23327 toPids: clientIds
23328 })
23329 });
23330 _context14.next = 5;
23331 return this._appendBlacklistSignature(command, 'conversation-block-clients', clientIds);
23332 case 5:
23333 _context14.next = 7;
23334 return this._send(command);
23335 case 7:
23336 _yield$this$_send6 = _context14.sent;
23337 blacklistMessage = _yield$this$_send6.blacklistMessage;
23338 return _context14.abrupt("return", createPartiallySuccess(blacklistMessage));
23339 case 10:
23340 case "end":
23341 return _context14.stop();
23342 }
23343 }, _callee14, this);
23344 }));
23345 function blockMembers(_x11) {
23346 return _blockMembers.apply(this, arguments);
23347 }
23348 return blockMembers;
23349 }()
23350 /**
23351 * 将用户移出该对话黑名单
23352 * @param {String|String[]} clientIds 成员 client id
23353 * @return {Promise.<PartiallySuccess>} 部分成功结果,包含了成功的 id 列表、失败原因与对应的 id 列表
23354 */
23355 ;
23356 _proto.unblockMembers =
23357 /*#__PURE__*/
23358 function () {
23359 var _unblockMembers = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee15(clientIds) {
23360 var command, _yield$this$_send7, blacklistMessage;
23361 return regenerator.wrap(function _callee15$(_context15) {
23362 while (1) switch (_context15.prev = _context15.next) {
23363 case 0:
23364 this._debug('unblock', clientIds);
23365 clientIds = ensureArray(clientIds); // eslint-disable-line no-param-reassign
23366 command = new GenericCommand({
23367 cmd: 'blacklist',
23368 op: OpType.unblock,
23369 blacklistMessage: new BlacklistCommand({
23370 srcCid: this.id,
23371 toPids: clientIds
23372 })
23373 });
23374 _context15.next = 5;
23375 return this._appendBlacklistSignature(command, 'conversation-unblock-clients', clientIds);
23376 case 5:
23377 _context15.next = 7;
23378 return this._send(command);
23379 case 7:
23380 _yield$this$_send7 = _context15.sent;
23381 blacklistMessage = _yield$this$_send7.blacklistMessage;
23382 return _context15.abrupt("return", createPartiallySuccess(blacklistMessage));
23383 case 10:
23384 case "end":
23385 return _context15.stop();
23386 }
23387 }, _callee15, this);
23388 }));
23389 function unblockMembers(_x12) {
23390 return _unblockMembers.apply(this, arguments);
23391 }
23392 return unblockMembers;
23393 }()
23394 /**
23395 * 查询该对话黑名单
23396 * @param {Object} [options]
23397 * @param {Number} [options.limit] 返回的成员数量,服务器默认值 10
23398 * @param {String} [options.next] 从指定 next 开始查询,与 limit 一起使用可以完成翻页
23399 * @return {PagedResults.<string>} 查询结果。其中的 cureser 存在表示还有更多结果。
23400 */
23401 ;
23402 _proto.queryBlockedMembers =
23403 /*#__PURE__*/
23404 function () {
23405 var _queryBlockedMembers = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee16() {
23406 var _ref7,
23407 limit,
23408 next,
23409 command,
23410 _yield$this$_send8,
23411 _yield$this$_send8$bl,
23412 blockedPids,
23413 newNext,
23414 _args16 = arguments;
23415 return regenerator.wrap(function _callee16$(_context16) {
23416 while (1) switch (_context16.prev = _context16.next) {
23417 case 0:
23418 _ref7 = _args16.length > 0 && _args16[0] !== undefined ? _args16[0] : {}, limit = _ref7.limit, next = _ref7.next;
23419 this._debug('query blocked: limit %O, next: %O', limit, next);
23420 command = new GenericCommand({
23421 cmd: 'blacklist',
23422 op: OpType.query,
23423 blacklistMessage: new BlacklistCommand({
23424 srcCid: this.id,
23425 limit: limit,
23426 next: next
23427 })
23428 });
23429 _context16.next = 5;
23430 return this._send(command);
23431 case 5:
23432 _yield$this$_send8 = _context16.sent;
23433 _yield$this$_send8$bl = _yield$this$_send8.blacklistMessage;
23434 blockedPids = _yield$this$_send8$bl.blockedPids;
23435 newNext = _yield$this$_send8$bl.next;
23436 return _context16.abrupt("return", {
23437 results: blockedPids,
23438 next: newNext
23439 });
23440 case 10:
23441 case "end":
23442 return _context16.stop();
23443 }
23444 }, _callee16, this);
23445 }));
23446 function queryBlockedMembers() {
23447 return _queryBlockedMembers.apply(this, arguments);
23448 }
23449 return queryBlockedMembers;
23450 }();
23451 _proto.toFullJSON = function toFullJSON() {
23452 var creator = this.creator,
23453 system = this.system,
23454 _transient2 = this["transient"],
23455 createdAt = this.createdAt,
23456 updatedAt = this.updatedAt,
23457 _attributes = this._attributes;
23458 return _objectSpread$6(_objectSpread$6({}, _ConversationBase.prototype.toFullJSON.call(this)), {}, {
23459 creator: creator,
23460 system: system,
23461 "transient": _transient2,
23462 createdAt: getTime(createdAt),
23463 updatedAt: getTime(updatedAt)
23464 }, _attributes);
23465 };
23466 _proto.toJSON = function toJSON() {
23467 var creator = this.creator,
23468 system = this.system,
23469 _transient3 = this["transient"],
23470 muted = this.muted,
23471 mutedMembers = this.mutedMembers,
23472 createdAt = this.createdAt,
23473 updatedAt = this.updatedAt,
23474 _attributes = this._attributes;
23475 return _objectSpread$6(_objectSpread$6({}, _ConversationBase.prototype.toJSON.call(this)), {}, {
23476 creator: creator,
23477 system: system,
23478 "transient": _transient3,
23479 muted: muted,
23480 mutedMembers: mutedMembers,
23481 createdAt: createdAt,
23482 updatedAt: updatedAt
23483 }, _attributes);
23484 };
23485 _createClass(PersistentConversation, [{
23486 key: "createdAt",
23487 get: function get() {
23488 return this._createdAt;
23489 },
23490 set: function set(value) {
23491 this._createdAt = decodeDate(value);
23492 }
23493 }, {
23494 key: "updatedAt",
23495 get: function get() {
23496 return this._updatedAt;
23497 }
23498
23499 /**
23500 * 对话名字,对应 _Conversation 表中的 name
23501 * @type {String}
23502 */,
23503 set: function set(value) {
23504 this._updatedAt = decodeDate(value);
23505 }
23506 }, {
23507 key: "name",
23508 get: function get() {
23509 return this.get('name');
23510 },
23511 set: function set(value) {
23512 this.set('name', value);
23513 }
23514 }]);
23515 return PersistentConversation;
23516 }(ConversationBase);
23517
23518 /**
23519 * 对话成员角色枚举
23520 * @enum {String}
23521 * @since 4.0.0
23522 * @memberof module:leancloud-realtime
23523 */
23524 var ConversationMemberRole = {
23525 /** 所有者 */
23526 OWNER: 'Owner',
23527 /** 管理员 */
23528 MANAGER: 'Manager',
23529 /** 成员 */
23530 MEMBER: 'Member'
23531 };
23532 Object.freeze(ConversationMemberRole);
23533 var ConversationMemberInfo = /*#__PURE__*/function () {
23534 /**
23535 * 对话成员属性,保存了成员与某个对话相关的属性,对应 _ConversationMemberInfo 表
23536 * @since 4.0.0
23537 */
23538 function ConversationMemberInfo(_ref) {
23539 var conversation = _ref.conversation,
23540 memberId = _ref.memberId,
23541 role = _ref.role;
23542 if (!conversation) throw new Error('conversation requried');
23543 if (!memberId) throw new Error('memberId requried');
23544 Object.assign(internal(this), {
23545 conversation: conversation,
23546 memberId: memberId,
23547 role: role
23548 });
23549 }
23550
23551 /**
23552 * 对话 Id
23553 * @type {String}
23554 * @readonly
23555 */
23556 var _proto = ConversationMemberInfo.prototype;
23557 _proto.toJSON = function toJSON() {
23558 var conversationId = this.conversationId,
23559 memberId = this.memberId,
23560 role = this.role,
23561 isOwner = this.isOwner;
23562 return {
23563 conversationId: conversationId,
23564 memberId: memberId,
23565 role: role,
23566 isOwner: isOwner
23567 };
23568 };
23569 _createClass(ConversationMemberInfo, [{
23570 key: "conversationId",
23571 get: function get() {
23572 return internal(this).conversation.id;
23573 }
23574
23575 /**
23576 * 成员 Id
23577 * @type {String}
23578 * @readonly
23579 */
23580 }, {
23581 key: "memberId",
23582 get: function get() {
23583 return internal(this).memberId;
23584 }
23585
23586 /**
23587 * 角色
23588 * @type {module:leancloud-realtime.ConversationMemberRole | String}
23589 * @readonly
23590 */
23591 }, {
23592 key: "role",
23593 get: function get() {
23594 if (this.isOwner) return ConversationMemberRole.OWNER;
23595 return internal(this).role;
23596 }
23597
23598 /**
23599 * 是否是管理员
23600 * @type {Boolean}
23601 * @readonly
23602 */
23603 }, {
23604 key: "isOwner",
23605 get: function get() {
23606 return this.memberId === internal(this).conversation.creator;
23607 }
23608 }]);
23609 return ConversationMemberInfo;
23610 }();
23611
23612 /**
23613 * 普通对话
23614 *
23615 * 无法直接实例化,请使用 {@link IMClient#createConversation} 创建新的普通对话。
23616 * @extends PersistentConversation
23617 * @public
23618 */
23619 var Conversation = /*#__PURE__*/function (_PersistentConversati) {
23620 _inheritsLoose(Conversation, _PersistentConversati);
23621 function Conversation() {
23622 return _PersistentConversati.apply(this, arguments) || this;
23623 }
23624 var _proto = Conversation.prototype;
23625 _proto._addMembers = function _addMembers(members) {
23626 var _this = this;
23627 _PersistentConversati.prototype._addMembers.call(this, members);
23628 this.members = union(this.members, members);
23629 var _internal = internal(this),
23630 memberInfoMap = _internal.memberInfoMap;
23631 if (!memberInfoMap) return;
23632 members.forEach(function (memberId) {
23633 memberInfoMap[memberId] = memberInfoMap[memberId] || new ConversationMemberInfo({
23634 conversation: _this,
23635 memberId: memberId,
23636 role: ConversationMemberRole.MEMBER
23637 });
23638 });
23639 };
23640 _proto._removeMembers = function _removeMembers(members) {
23641 _PersistentConversati.prototype._removeMembers.call(this, members);
23642 this.members = difference(this.members, members);
23643 var _internal2 = internal(this),
23644 memberInfoMap = _internal2.memberInfoMap;
23645 if (!memberInfoMap) return;
23646 members.forEach(function (memberId) {
23647 delete memberInfoMap[memberId];
23648 });
23649 };
23650 _proto._fetchAllMemberInfo = /*#__PURE__*/function () {
23651 var _fetchAllMemberInfo2 = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee() {
23652 var _this2 = this;
23653 var response, memberInfos, memberInfoMap;
23654 return regenerator.wrap(function _callee$(_context) {
23655 while (1) switch (_context.prev = _context.next) {
23656 case 0:
23657 _context.next = 2;
23658 return this._client._requestWithSessionToken({
23659 method: 'GET',
23660 path: '/classes/_ConversationMemberInfo',
23661 query: {
23662 where: {
23663 cid: this.id
23664 }
23665 }
23666 });
23667 case 2:
23668 response = _context.sent;
23669 memberInfos = response.results.map(function (info) {
23670 return new ConversationMemberInfo({
23671 conversation: _this2,
23672 memberId: info.clientId,
23673 role: info.role
23674 });
23675 });
23676 memberInfoMap = {};
23677 memberInfos.forEach(function (memberInfo) {
23678 memberInfoMap[memberInfo.memberId] = memberInfo;
23679 });
23680 this.members.forEach(function (memberId) {
23681 memberInfoMap[memberId] = memberInfoMap[memberId] || new ConversationMemberInfo({
23682 conversation: _this2,
23683 memberId: memberId,
23684 role: ConversationMemberRole.MEMBER
23685 });
23686 });
23687 internal(this).memberInfoMap = memberInfoMap;
23688 return _context.abrupt("return", memberInfoMap);
23689 case 9:
23690 case "end":
23691 return _context.stop();
23692 }
23693 }, _callee, this);
23694 }));
23695 function _fetchAllMemberInfo() {
23696 return _fetchAllMemberInfo2.apply(this, arguments);
23697 }
23698 return _fetchAllMemberInfo;
23699 }()
23700 /**
23701 * 获取所有成员的对话属性
23702 * @since 4.0.0
23703 * @return {Promise.<ConversationMemberInfo[]>} 所有成员的对话属性列表
23704 */
23705 ;
23706 _proto.getAllMemberInfo =
23707 /*#__PURE__*/
23708 function () {
23709 var _getAllMemberInfo = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee2() {
23710 var _ref,
23711 _ref$noCache,
23712 noCache,
23713 _internal3,
23714 memberInfoMap,
23715 _args2 = arguments;
23716 return regenerator.wrap(function _callee2$(_context2) {
23717 while (1) switch (_context2.prev = _context2.next) {
23718 case 0:
23719 _ref = _args2.length > 0 && _args2[0] !== undefined ? _args2[0] : {}, _ref$noCache = _ref.noCache, noCache = _ref$noCache === void 0 ? false : _ref$noCache;
23720 _internal3 = internal(this), memberInfoMap = _internal3.memberInfoMap;
23721 if (!(!memberInfoMap || noCache)) {
23722 _context2.next = 6;
23723 break;
23724 }
23725 _context2.next = 5;
23726 return this._fetchAllMemberInfo();
23727 case 5:
23728 memberInfoMap = _context2.sent;
23729 case 6:
23730 return _context2.abrupt("return", this.members.map(function (memberId) {
23731 return memberInfoMap[memberId];
23732 }));
23733 case 7:
23734 case "end":
23735 return _context2.stop();
23736 }
23737 }, _callee2, this);
23738 }));
23739 function getAllMemberInfo() {
23740 return _getAllMemberInfo.apply(this, arguments);
23741 }
23742 return getAllMemberInfo;
23743 }()
23744 /**
23745 * 获取指定成员的对话属性
23746 * @since 4.0.0
23747 * @param {String} memberId 成员 Id
23748 * @return {Promise.<ConversationMemberInfo>} 指定成员的对话属性
23749 */
23750 ;
23751 _proto.getMemberInfo =
23752 /*#__PURE__*/
23753 function () {
23754 var _getMemberInfo = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee3(memberId) {
23755 var _internal4, memberInfoMap;
23756 return regenerator.wrap(function _callee3$(_context3) {
23757 while (1) switch (_context3.prev = _context3.next) {
23758 case 0:
23759 if (!(this.members.indexOf(memberId) === -1)) {
23760 _context3.next = 2;
23761 break;
23762 }
23763 throw new Error("".concat(memberId, " is not the mumber of conversation[").concat(this.id, "]"));
23764 case 2:
23765 _internal4 = internal(this), memberInfoMap = _internal4.memberInfoMap;
23766 if (memberInfoMap && memberInfoMap[memberId]) {
23767 _context3.next = 6;
23768 break;
23769 }
23770 _context3.next = 6;
23771 return this.getAllMemberInfo();
23772 case 6:
23773 return _context3.abrupt("return", internal(this).memberInfoMap[memberId]);
23774 case 7:
23775 case "end":
23776 return _context3.stop();
23777 }
23778 }, _callee3, this);
23779 }));
23780 function getMemberInfo(_x) {
23781 return _getMemberInfo.apply(this, arguments);
23782 }
23783 return getMemberInfo;
23784 }()
23785 /**
23786 * 更新指定用户的角色
23787 * @since 4.0.0
23788 * @param {String} memberId 成员 Id
23789 * @param {module:leancloud-realtime.ConversationMemberRole | String} role 角色
23790 * @return {Promise.<this>} self
23791 */
23792 ;
23793 _proto.updateMemberRole =
23794 /*#__PURE__*/
23795 function () {
23796 var _updateMemberRole = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee4(memberId, role) {
23797 var _internal5, memberInfos;
23798 return regenerator.wrap(function _callee4$(_context4) {
23799 while (1) switch (_context4.prev = _context4.next) {
23800 case 0:
23801 this._debug('update member role');
23802 if (!(role === ConversationMemberRole.OWNER)) {
23803 _context4.next = 3;
23804 break;
23805 }
23806 throw createError({
23807 code: ErrorCode.OWNER_PROMOTION_NOT_ALLOWED
23808 });
23809 case 3:
23810 _context4.next = 5;
23811 return this._send(new GenericCommand({
23812 op: OpType.member_info_update,
23813 convMessage: new ConvCommand({
23814 targetClientId: memberId,
23815 info: new ConvMemberInfo({
23816 pid: memberId,
23817 role: role
23818 })
23819 })
23820 }));
23821 case 5:
23822 _internal5 = internal(this), memberInfos = _internal5.memberInfos;
23823 if (memberInfos && memberInfos[memberId]) {
23824 internal(memberInfos[memberId]).role = role;
23825 }
23826 return _context4.abrupt("return", this);
23827 case 8:
23828 case "end":
23829 return _context4.stop();
23830 }
23831 }, _callee4, this);
23832 }));
23833 function updateMemberRole(_x2, _x3) {
23834 return _updateMemberRole.apply(this, arguments);
23835 }
23836 return updateMemberRole;
23837 }();
23838 return Conversation;
23839 }(PersistentConversation);
23840
23841 /**
23842 * 聊天室。
23843 *
23844 * 无法直接实例化,请使用 {@link IMClient#createChatRoom} 创建新的聊天室。
23845 * @since 4.0.0
23846 * @extends PersistentConversation
23847 * @public
23848 */
23849 var ChatRoom = /*#__PURE__*/function (_PersistentConversati) {
23850 _inheritsLoose(ChatRoom, _PersistentConversati);
23851 function ChatRoom() {
23852 return _PersistentConversati.apply(this, arguments) || this;
23853 }
23854 return ChatRoom;
23855 }(PersistentConversation);
23856
23857 /**
23858 * 服务号。
23859 *
23860 * 服务号不支持在客户端创建。
23861 * @since 4.0.0
23862 * @extends PersistentConversation
23863 * @public
23864 */
23865 var ServiceConversation = /*#__PURE__*/function (_PersistentConversati) {
23866 _inheritsLoose(ServiceConversation, _PersistentConversati);
23867 function ServiceConversation() {
23868 return _PersistentConversati.apply(this, arguments) || this;
23869 }
23870 var _proto = ServiceConversation.prototype;
23871 /**
23872 * 订阅该服务号
23873 * @return {Promise.<this>} self
23874 */
23875 _proto.subscribe =
23876 /*#__PURE__*/
23877 function () {
23878 var _subscribe = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee() {
23879 return regenerator.wrap(function _callee$(_context) {
23880 while (1) switch (_context.prev = _context.next) {
23881 case 0:
23882 return _context.abrupt("return", this.join());
23883 case 1:
23884 case "end":
23885 return _context.stop();
23886 }
23887 }, _callee, this);
23888 }));
23889 function subscribe() {
23890 return _subscribe.apply(this, arguments);
23891 }
23892 return subscribe;
23893 }()
23894 /**
23895 * 退订该服务号
23896 * @return {Promise.<this>} self
23897 */
23898 ;
23899 _proto.unsubscribe =
23900 /*#__PURE__*/
23901 function () {
23902 var _unsubscribe = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee2() {
23903 return regenerator.wrap(function _callee2$(_context2) {
23904 while (1) switch (_context2.prev = _context2.next) {
23905 case 0:
23906 return _context2.abrupt("return", this.quit());
23907 case 1:
23908 case "end":
23909 return _context2.stop();
23910 }
23911 }, _callee2, this);
23912 }));
23913 function unsubscribe() {
23914 return _unsubscribe.apply(this, arguments);
23915 }
23916 return unsubscribe;
23917 }();
23918 return ServiceConversation;
23919 }(PersistentConversation);
23920
23921 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; }
23922 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; }
23923 var transformNotFoundError = function transformNotFoundError(error) {
23924 return error.code === ErrorCode.CONVERSATION_NOT_FOUND ? createError({
23925 code: ErrorCode.TEMPORARY_CONVERSATION_EXPIRED
23926 }) : error;
23927 };
23928
23929 /**
23930 * 临时对话
23931 * @since 4.0.0
23932 * @extends ConversationBase
23933 * @public
23934 */
23935 var TemporaryConversation = /*#__PURE__*/function (_ConversationBase) {
23936 _inheritsLoose(TemporaryConversation, _ConversationBase);
23937 /**
23938 * 无法直接实例化,请使用 {@link IMClient#createTemporaryConversation} 创建新的临时对话。
23939 */
23940 function TemporaryConversation(data, _ref, client) {
23941 var expiredAt = _ref.expiredAt;
23942 return _ConversationBase.call(this, _objectSpread$7(_objectSpread$7({}, data), {}, {
23943 expiredAt: expiredAt
23944 }), client) || this;
23945 }
23946
23947 /**
23948 * 对话失效时间
23949 * @type {Date}
23950 */
23951 var _proto = TemporaryConversation.prototype;
23952 _proto._send = /*#__PURE__*/function () {
23953 var _send2 = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee() {
23954 var _ConversationBase$pro,
23955 _len,
23956 args,
23957 _key,
23958 _args = arguments;
23959 return regenerator.wrap(function _callee$(_context) {
23960 while (1) switch (_context.prev = _context.next) {
23961 case 0:
23962 if (!this.expired) {
23963 _context.next = 2;
23964 break;
23965 }
23966 throw createError({
23967 code: ErrorCode.TEMPORARY_CONVERSATION_EXPIRED
23968 });
23969 case 2:
23970 _context.prev = 2;
23971 for (_len = _args.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
23972 args[_key] = _args[_key];
23973 }
23974 _context.next = 6;
23975 return (_ConversationBase$pro = _ConversationBase.prototype._send).call.apply(_ConversationBase$pro, [this].concat(args));
23976 case 6:
23977 return _context.abrupt("return", _context.sent);
23978 case 9:
23979 _context.prev = 9;
23980 _context.t0 = _context["catch"](2);
23981 throw transformNotFoundError(_context.t0);
23982 case 12:
23983 case "end":
23984 return _context.stop();
23985 }
23986 }, _callee, this, [[2, 9]]);
23987 }));
23988 function _send() {
23989 return _send2.apply(this, arguments);
23990 }
23991 return _send;
23992 }();
23993 _proto.send = /*#__PURE__*/function () {
23994 var _send3 = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee2() {
23995 var _ConversationBase$pro2,
23996 _len2,
23997 args,
23998 _key2,
23999 _args2 = arguments;
24000 return regenerator.wrap(function _callee2$(_context2) {
24001 while (1) switch (_context2.prev = _context2.next) {
24002 case 0:
24003 _context2.prev = 0;
24004 for (_len2 = _args2.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
24005 args[_key2] = _args2[_key2];
24006 }
24007 _context2.next = 4;
24008 return (_ConversationBase$pro2 = _ConversationBase.prototype.send).call.apply(_ConversationBase$pro2, [this].concat(args));
24009 case 4:
24010 return _context2.abrupt("return", _context2.sent);
24011 case 7:
24012 _context2.prev = 7;
24013 _context2.t0 = _context2["catch"](0);
24014 throw transformNotFoundError(_context2.t0);
24015 case 10:
24016 case "end":
24017 return _context2.stop();
24018 }
24019 }, _callee2, this, [[0, 7]]);
24020 }));
24021 function send() {
24022 return _send3.apply(this, arguments);
24023 }
24024 return send;
24025 }();
24026 _proto.toFullJSON = function toFullJSON() {
24027 var expiredAt = this.expiredAt;
24028 return _objectSpread$7(_objectSpread$7({}, _ConversationBase.prototype.toFullJSON.call(this)), {}, {
24029 expiredAt: getTime(expiredAt)
24030 });
24031 };
24032 _proto.toJSON = function toJSON() {
24033 var expiredAt = this.expiredAt,
24034 expired = this.expired;
24035 return _objectSpread$7(_objectSpread$7({}, _ConversationBase.prototype.toJSON.call(this)), {}, {
24036 expiredAt: expiredAt,
24037 expired: expired
24038 });
24039 };
24040 _createClass(TemporaryConversation, [{
24041 key: "expiredAt",
24042 get: function get() {
24043 return this._expiredAt;
24044 }
24045
24046 /**
24047 * 对话是否已失效
24048 * @type {Boolean}
24049 */,
24050 set: function set(value) {
24051 this._expiredAt = decodeDate(value);
24052 }
24053 }, {
24054 key: "expired",
24055 get: function get() {
24056 return this.expiredAt < new Date();
24057 }
24058 }]);
24059 return TemporaryConversation;
24060 }(ConversationBase);
24061
24062 var debug$9 = browser('LC:ConversationQuery');
24063 var ConversationQuery = /*#__PURE__*/function () {
24064 ConversationQuery._encode = function _encode(value) {
24065 if (value instanceof Date) {
24066 return {
24067 __type: 'Date',
24068 iso: value.toJSON()
24069 };
24070 }
24071 if (value instanceof RegExp) {
24072 return value.source;
24073 }
24074 return value;
24075 };
24076 ConversationQuery._quote = function _quote(s) {
24077 return "\\Q".concat(s.replace('\\E', '\\E\\\\E\\Q'), "\\E");
24078 };
24079 ConversationQuery._calculateFlag = function _calculateFlag(options) {
24080 return ['withLastMessagesRefreshed', 'compact'].reduce(
24081 // eslint-disable-next-line no-bitwise
24082 function (prev, key) {
24083 return (prev << 1) + Boolean(options[key]);
24084 }, 0);
24085 }
24086
24087 /**
24088 * 构造一个用 AND 连接所有查询的 ConversationQuery
24089 * @param {...ConversationQuery} queries
24090 * @return {ConversationQuery}
24091 */;
24092 ConversationQuery.and = function and() {
24093 for (var _len = arguments.length, queries = new Array(_len), _key = 0; _key < _len; _key++) {
24094 queries[_key] = arguments[_key];
24095 }
24096 if (queries.length < 2) {
24097 throw new Error('The queries must contain at least two elements');
24098 }
24099 if (!queries.every(function (q) {
24100 return q instanceof ConversationQuery;
24101 })) {
24102 throw new Error('The element of queries must be an instance of ConversationQuery');
24103 }
24104 var combined = new ConversationQuery(queries[0]._client);
24105 combined._where.$and = queries.map(function (q) {
24106 return q._where;
24107 });
24108 return combined;
24109 }
24110
24111 /**
24112 * 构造一个用 OR 连接所有查询的 ConversationQuery
24113 * @param {...ConversationQuery} queries
24114 * @return {ConversationQuery}
24115 */;
24116 ConversationQuery.or = function or() {
24117 var combined = ConversationQuery.and.apply(ConversationQuery, arguments);
24118 combined._where.$or = combined._where.$and;
24119 delete combined._where.$and;
24120 return combined;
24121 }
24122
24123 /**
24124 * Create a ConversationQuery
24125 * @param {IMClient} client
24126 */;
24127 function ConversationQuery(client) {
24128 this._client = client;
24129 this._where = {};
24130 this._extraOptions = {};
24131 }
24132 var _proto = ConversationQuery.prototype;
24133 _proto._addCondition = function _addCondition(key, condition, value) {
24134 // Check if we already have a condition
24135 if (!this._where[key]) {
24136 this._where[key] = {};
24137 }
24138 this._where[key][condition] = this.constructor._encode(value);
24139 return this;
24140 };
24141 _proto.toJSON = function toJSON() {
24142 var json = {
24143 where: this._where,
24144 flag: this.constructor._calculateFlag(this._extraOptions)
24145 };
24146 if (typeof this._skip !== 'undefined') json.skip = this._skip;
24147 if (typeof this._limit !== 'undefined') json.limit = this._limit;
24148 if (typeof this._order !== 'undefined') json.sort = this._order;
24149 debug$9(json);
24150 return json;
24151 }
24152
24153 /**
24154 * 增加查询条件,指定聊天室的组员包含某些成员即可返回
24155 * @param {string[]} peerIds - 成员 ID 列表
24156 * @return {ConversationQuery} self
24157 */;
24158 _proto.containsMembers = function containsMembers(peerIds) {
24159 return this.containsAll('m', peerIds);
24160 }
24161
24162 /**
24163 * 增加查询条件,指定聊天室的组员条件满足条件的才返回
24164 *
24165 * @param {string[]} - 成员 ID 列表
24166 * @param {Boolean} includeSelf - 是否包含自己
24167 * @return {ConversationQuery} self
24168 */;
24169 _proto.withMembers = function withMembers(peerIds, includeSelf) {
24170 var peerIdsSet = new Set(peerIds);
24171 if (includeSelf) {
24172 peerIdsSet.add(this._client.id);
24173 }
24174 this.sizeEqualTo('m', peerIdsSet.size);
24175 return this.containsMembers(Array.from(peerIdsSet));
24176 }
24177
24178 /**
24179 * 增加查询条件,当 conversation 的属性中对应的字段满足等于条件时即可返回
24180 *
24181 * @param {string} key
24182 * @param value
24183 * @return {ConversationQuery} self
24184 */;
24185 _proto.equalTo = function equalTo(key, value) {
24186 this._where[key] = this.constructor._encode(value);
24187 return this;
24188 }
24189
24190 /**
24191 * 增加查询条件,当 conversation 的属性中对应的字段满足小于条件时即可返回
24192 * @param {string} key
24193 * @param value
24194 * @return {ConversationQuery} self
24195 */;
24196 _proto.lessThan = function lessThan(key, value) {
24197 return this._addCondition(key, '$lt', value);
24198 }
24199
24200 /**
24201 * 增加查询条件,当 conversation 的属性中对应的字段满足小于等于条件时即可返回
24202 * @param {string} key
24203 * @param value
24204 * @return {ConversationQuery} self
24205 */;
24206 _proto.lessThanOrEqualTo = function lessThanOrEqualTo(key, value) {
24207 return this._addCondition(key, '$lte', value);
24208 }
24209
24210 /**
24211 * 增加查询条件,当 conversation 的属性中对应的字段满足大于条件时即可返回
24212 *
24213 * @param {string} key
24214 * @param value
24215 * @return {ConversationQuery} self
24216 */;
24217 _proto.greaterThan = function greaterThan(key, value) {
24218 return this._addCondition(key, '$gt', value);
24219 }
24220
24221 /**
24222 * 增加查询条件,当 conversation 的属性中对应的字段满足大于等于条件时即可返回
24223 *
24224 * @param {string} key
24225 * @param value
24226 * @return {ConversationQuery} self
24227 */;
24228 _proto.greaterThanOrEqualTo = function greaterThanOrEqualTo(key, value) {
24229 return this._addCondition(key, '$gte', value);
24230 }
24231
24232 /**
24233 * 增加查询条件,当 conversation 的属性中对应的字段满足不等于条件时即可返回
24234 *
24235 * @param {string} key
24236 * @param value
24237 * @return {ConversationQuery} self
24238 */;
24239 _proto.notEqualTo = function notEqualTo(key, value) {
24240 return this._addCondition(key, '$ne', value);
24241 }
24242
24243 /**
24244 * 增加查询条件,当 conversation 存在指定的字段时即可返回
24245 *
24246 * @since 3.5.0
24247 * @param {string} key
24248 * @return {ConversationQuery} self
24249 */;
24250 _proto.exists = function exists(key) {
24251 return this._addCondition(key, '$exists', true);
24252 }
24253
24254 /**
24255 * 增加查询条件,当 conversation 不存在指定的字段时即可返回
24256 *
24257 * @since 3.5.0
24258 * @param {string} key
24259 * @return {ConversationQuery} self
24260 */;
24261 _proto.doesNotExist = function doesNotExist(key) {
24262 return this._addCondition(key, '$exists', false);
24263 }
24264
24265 /**
24266 * 增加查询条件,当 conversation 的属性中对应的字段对应的值包含在指定值中时即可返回
24267 *
24268 * @param {string} key
24269 * @param values
24270 * @return {ConversationQuery} self
24271 */;
24272 _proto.containedIn = function containedIn(key, values) {
24273 return this._addCondition(key, '$in', values);
24274 }
24275
24276 /**
24277 * 增加查询条件,当 conversation 的属性中对应的字段对应的值不包含在指定值中时即可返回
24278 *
24279 * @param {string} key
24280 * @param values
24281 * @return {ConversationQuery} self
24282 */;
24283 _proto.notContainsIn = function notContainsIn(key, values) {
24284 return this._addCondition(key, '$nin', values);
24285 }
24286
24287 /**
24288 * 增加查询条件,当conversation的属性中对应的字段中的元素包含所有的值才可返回
24289 *
24290 * @param {string} key
24291 * @param values
24292 * @return {ConversationQuery} self
24293 */;
24294 _proto.containsAll = function containsAll(key, values) {
24295 return this._addCondition(key, '$all', values);
24296 }
24297
24298 /**
24299 * 增加查询条件,当 conversation 的属性中对应的字段对应的值包含此字符串即可返回
24300 *
24301 * @param {string} key
24302 * @param {string} subString
24303 * @return {ConversationQuery} self
24304 */;
24305 _proto.contains = function contains(key, subString) {
24306 return this._addCondition(key, '$regex', ConversationQuery._quote(subString));
24307 }
24308
24309 /**
24310 * 增加查询条件,当 conversation 的属性中对应的字段对应的值以此字符串起始即可返回
24311 *
24312 * @param {string} key
24313 * @param {string} prefix
24314 * @return {ConversationQuery} self
24315 */;
24316 _proto.startsWith = function startsWith(key, prefix) {
24317 return this._addCondition(key, '$regex', "^".concat(ConversationQuery._quote(prefix)));
24318 }
24319
24320 /**
24321 * 增加查询条件,当 conversation 的属性中对应的字段对应的值以此字符串结束即可返回
24322 *
24323 * @param {string} key
24324 * @param {string} suffix
24325 * @return {ConversationQuery} self
24326 */;
24327 _proto.endsWith = function endsWith(key, suffix) {
24328 return this._addCondition(key, '$regex', "".concat(ConversationQuery._quote(suffix), "$"));
24329 }
24330
24331 /**
24332 * 增加查询条件,当 conversation 的属性中对应的字段对应的值满足提供的正则表达式即可返回
24333 *
24334 * @param {string} key
24335 * @param {RegExp} regex
24336 * @return {ConversationQuery} self
24337 */;
24338 _proto.matches = function matches(key, regex) {
24339 this._addCondition(key, '$regex', regex);
24340 // Javascript regex options support mig as inline options but store them
24341 // as properties of the object. We support mi & should migrate them to
24342 // modifiers
24343 var _modifiers = '';
24344 if (regex.ignoreCase) {
24345 _modifiers += 'i';
24346 }
24347 if (regex.multiline) {
24348 _modifiers += 'm';
24349 }
24350 if (_modifiers && _modifiers.length) {
24351 this._addCondition(key, '$options', _modifiers);
24352 }
24353 return this;
24354 }
24355
24356 /**
24357 * 添加查询约束条件,查找 key 类型是数组,该数组的长度匹配提供的数值
24358 *
24359 * @param {string} key
24360 * @param {Number} length
24361 * @return {ConversationQuery} self
24362 */;
24363 _proto.sizeEqualTo = function sizeEqualTo(key, length) {
24364 return this._addCondition(key, '$size', length);
24365 }
24366
24367 /**
24368 * 设置返回集合的大小上限
24369 *
24370 * @param {Number} limit - 上限
24371 * @return {ConversationQuery} self
24372 */;
24373 _proto.limit = function limit(_limit) {
24374 this._limit = _limit;
24375 return this;
24376 }
24377
24378 /**
24379 * 设置返回集合的起始位置,一般用于分页
24380 *
24381 * @param {Number} skip - 起始位置跳过几个对象
24382 * @return {ConversationQuery} self
24383 */;
24384 _proto.skip = function skip(_skip) {
24385 this._skip = _skip;
24386 return this;
24387 }
24388
24389 /**
24390 * 设置返回集合按照指定key进行增序排列
24391 *
24392 * @param {string} key
24393 * @return {ConversationQuery} self
24394 */;
24395 _proto.ascending = function ascending(key) {
24396 this._order = key;
24397 return this;
24398 }
24399
24400 /**
24401 * 设置返回集合按照指定key进行增序排列,如果已设置其他排序,原排序的优先级较高
24402 *
24403 * @param {string} key
24404 * @return {ConversationQuery} self
24405 */;
24406 _proto.addAscending = function addAscending(key) {
24407 if (this._order) {
24408 this._order += ",".concat(key);
24409 } else {
24410 this._order = key;
24411 }
24412 return this;
24413 }
24414
24415 /**
24416 * 设置返回集合按照指定 key 进行降序排列
24417 *
24418 * @param {string} key
24419 * @return {ConversationQuery} self
24420 */;
24421 _proto.descending = function descending(key) {
24422 this._order = "-".concat(key);
24423 return this;
24424 }
24425
24426 /**
24427 * 设置返回集合按照指定 key 进行降序排列,如果已设置其他排序,原排序的优先级较高
24428 *
24429 * @param {string} key
24430 * @return {ConversationQuery} self
24431 */;
24432 _proto.addDescending = function addDescending(key) {
24433 if (this._order) {
24434 this._order += ",-".concat(key);
24435 } else {
24436 this._order = "-".concat(key);
24437 }
24438 return this;
24439 }
24440
24441 /**
24442 * 设置返回的 conversations 刷新最后一条消息
24443 * @param {Boolean} [enabled=true]
24444 * @return {ConversationQuery} self
24445 */;
24446 _proto.withLastMessagesRefreshed = function withLastMessagesRefreshed() {
24447 var enabled = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
24448 this._extraOptions.withLastMessagesRefreshed = enabled;
24449 return this;
24450 }
24451
24452 /**
24453 * 设置返回的 conversations 为精简模式,即不含成员列表
24454 * @param {Boolean} [enabled=true]
24455 * @return {ConversationQuery} self
24456 */;
24457 _proto.compact = function compact() {
24458 var enabled = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
24459 this._extraOptions.compact = enabled;
24460 return this;
24461 }
24462
24463 /**
24464 * 执行查询
24465 * @return {Promise.<ConversationBase[]>}
24466 */;
24467 _proto.find =
24468 /*#__PURE__*/
24469 function () {
24470 var _find = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee() {
24471 return regenerator.wrap(function _callee$(_context) {
24472 while (1) switch (_context.prev = _context.next) {
24473 case 0:
24474 return _context.abrupt("return", this._client._executeQuery(this));
24475 case 1:
24476 case "end":
24477 return _context.stop();
24478 }
24479 }, _callee, this);
24480 }));
24481 function find() {
24482 return _find.apply(this, arguments);
24483 }
24484 return find;
24485 }()
24486 /**
24487 * 返回符合条件的第一个结果
24488 * @return {Promise.<ConversationBase>}
24489 */
24490 ;
24491 _proto.first =
24492 /*#__PURE__*/
24493 function () {
24494 var _first = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee2() {
24495 return regenerator.wrap(function _callee2$(_context2) {
24496 while (1) switch (_context2.prev = _context2.next) {
24497 case 0:
24498 _context2.next = 2;
24499 return this.limit(1).find();
24500 case 2:
24501 return _context2.abrupt("return", _context2.sent[0]);
24502 case 3:
24503 case "end":
24504 return _context2.stop();
24505 }
24506 }, _callee2, this);
24507 }));
24508 function first() {
24509 return _first.apply(this, arguments);
24510 }
24511 return first;
24512 }();
24513 return ConversationQuery;
24514 }();
24515
24516 var debug$a = browser('LC:SessionManager');
24517 var SessionManager = /*#__PURE__*/function () {
24518 function SessionManager() {
24519 var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
24520 refresh = _ref.refresh,
24521 onBeforeGetSessionToken = _ref.onBeforeGetSessionToken;
24522 this.refresh = refresh;
24523 this._onBeforeGetSessionToken = onBeforeGetSessionToken;
24524 this.setSessionToken(null, 0);
24525 }
24526 var _proto = SessionManager.prototype;
24527 _proto.setSessionToken = function setSessionToken(token, ttl) {
24528 debug$a('set session token', token, ttl);
24529 var sessionToken = new Expirable(token, ttl * 1000);
24530 this._sessionToken = sessionToken;
24531 delete this._pendingSessionTokenPromise;
24532 return sessionToken;
24533 };
24534 _proto.setSessionTokenAsync = /*#__PURE__*/function () {
24535 var _setSessionTokenAsync = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee(promise) {
24536 var _this = this;
24537 var currentSessionToken;
24538 return regenerator.wrap(function _callee$(_context) {
24539 while (1) switch (_context.prev = _context.next) {
24540 case 0:
24541 currentSessionToken = this._sessionToken;
24542 this._pendingSessionTokenPromise = promise["catch"](function (error) {
24543 // revert, otherwise the following getSessionToken calls
24544 // will all be rejected
24545 _this._sessionToken = currentSessionToken;
24546 throw error;
24547 });
24548 _context.t0 = this.setSessionToken;
24549 _context.t1 = this;
24550 _context.t2 = _toConsumableArray$1;
24551 _context.next = 7;
24552 return this._pendingSessionTokenPromise;
24553 case 7:
24554 _context.t3 = _context.sent;
24555 _context.t4 = (0, _context.t2)(_context.t3);
24556 return _context.abrupt("return", _context.t0.apply.call(_context.t0, _context.t1, _context.t4));
24557 case 10:
24558 case "end":
24559 return _context.stop();
24560 }
24561 }, _callee, this);
24562 }));
24563 function setSessionTokenAsync(_x) {
24564 return _setSessionTokenAsync.apply(this, arguments);
24565 }
24566 return setSessionTokenAsync;
24567 }();
24568 _proto.getSessionToken = /*#__PURE__*/function () {
24569 var _getSessionToken = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee2() {
24570 var _ref2,
24571 _ref2$autoRefresh,
24572 autoRefresh,
24573 _ref3,
24574 value,
24575 originalValue,
24576 _yield$this$setSessio,
24577 newValue,
24578 _args2 = arguments;
24579 return regenerator.wrap(function _callee2$(_context2) {
24580 while (1) switch (_context2.prev = _context2.next) {
24581 case 0:
24582 _ref2 = _args2.length > 0 && _args2[0] !== undefined ? _args2[0] : {}, _ref2$autoRefresh = _ref2.autoRefresh, autoRefresh = _ref2$autoRefresh === void 0 ? true : _ref2$autoRefresh;
24583 debug$a('get session token');
24584 if (this._onBeforeGetSessionToken) {
24585 this._onBeforeGetSessionToken(this);
24586 }
24587 _context2.t0 = this._sessionToken;
24588 if (_context2.t0) {
24589 _context2.next = 8;
24590 break;
24591 }
24592 _context2.next = 7;
24593 return this._pendingSessionTokenPromise;
24594 case 7:
24595 _context2.t0 = _context2.sent;
24596 case 8:
24597 _ref3 = _context2.t0;
24598 value = _ref3.value;
24599 originalValue = _ref3.originalValue;
24600 if (!(value === Expirable.EXPIRED && autoRefresh && this.refresh)) {
24601 _context2.next = 19;
24602 break;
24603 }
24604 debug$a('refresh expired session token');
24605 _context2.next = 15;
24606 return this.setSessionTokenAsync(this.refresh(this, originalValue));
24607 case 15:
24608 _yield$this$setSessio = _context2.sent;
24609 newValue = _yield$this$setSessio.value;
24610 debug$a('session token', newValue);
24611 return _context2.abrupt("return", newValue);
24612 case 19:
24613 debug$a('session token', value);
24614 return _context2.abrupt("return", value);
24615 case 21:
24616 case "end":
24617 return _context2.stop();
24618 }
24619 }, _callee2, this);
24620 }));
24621 function getSessionToken() {
24622 return _getSessionToken.apply(this, arguments);
24623 }
24624 return getSessionToken;
24625 }();
24626 _proto.revoke = function revoke() {
24627 if (this._sessionToken) this._sessionToken.expiredAt = -1;
24628 };
24629 return SessionManager;
24630 }();
24631
24632 var _excluded$3 = ["cmd", "op", "serverTs", "notificationType"],
24633 _excluded2$1 = ["headers", "query"],
24634 _excluded3 = ["data", "bin"],
24635 _excluded4 = ["id", "lastMessageAt", "lastMessage", "lastDeliveredAt", "lastReadAt", "unreadMessagesCount", "members", "mentioned"],
24636 _excluded5 = ["members", "name", "transient", "unique", "_tempConv", "_tempConvTTL"],
24637 _excluded6 = ["ttl"];
24638 var _dec$2, _dec2, _class$3;
24639 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; }
24640 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; }
24641 var debug$b = browser('LC:IMClient');
24642 var INVITED$1 = INVITED,
24643 KICKED$1 = KICKED,
24644 MEMBERS_JOINED$1 = MEMBERS_JOINED,
24645 MEMBERS_LEFT$1 = MEMBERS_LEFT,
24646 MEMBER_INFO_UPDATED$1 = MEMBER_INFO_UPDATED,
24647 BLOCKED$1 = BLOCKED,
24648 UNBLOCKED$1 = UNBLOCKED,
24649 MEMBERS_BLOCKED$1 = MEMBERS_BLOCKED,
24650 MEMBERS_UNBLOCKED$1 = MEMBERS_UNBLOCKED,
24651 MUTED$1 = MUTED,
24652 UNMUTED$1 = UNMUTED,
24653 MEMBERS_MUTED$1 = MEMBERS_MUTED,
24654 MEMBERS_UNMUTED$1 = MEMBERS_UNMUTED,
24655 MESSAGE$2 = MESSAGE$1,
24656 UNREAD_MESSAGES_COUNT_UPDATE$1 = UNREAD_MESSAGES_COUNT_UPDATE,
24657 CLOSE$1 = CLOSE,
24658 CONFLICT$1 = CONFLICT,
24659 UNHANDLED_MESSAGE$1 = UNHANDLED_MESSAGE,
24660 CONVERSATION_INFO_UPDATED$1 = CONVERSATION_INFO_UPDATED,
24661 MESSAGE_RECALL$1 = MESSAGE_RECALL,
24662 MESSAGE_UPDATE$1 = MESSAGE_UPDATE,
24663 INFO_UPDATED$1 = INFO_UPDATED;
24664 var isTemporaryConversatrionId = function isTemporaryConversatrionId(id) {
24665 return /^_tmp:/.test(id);
24666 };
24667
24668 /**
24669 * 1 patch-msg
24670 * 1 temp-conv-msg
24671 * 0 auto-bind-deviceid-and-installation
24672 * 1 transient-msg-ack
24673 * 1 keep-notification
24674 * 1 partial-failed-msg
24675 * 0 group-chat-rcp
24676 * 1 omit-peer-id
24677 * @ignore
24678 */
24679 var configBitmap = 187;
24680 var IMClient = (_dec$2 = throttle(1000), _dec2 = throttle(1000), (_class$3 = /*#__PURE__*/function (_EventEmitter) {
24681 _inheritsLoose(IMClient, _EventEmitter);
24682 /**
24683 * 无法直接实例化,请使用 {@link Realtime#createIMClient} 创建新的 IMClient。
24684 *
24685 * @extends EventEmitter
24686 */
24687 function IMClient(id) {
24688 var _this;
24689 var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
24690 var props = arguments.length > 2 ? arguments[2] : undefined;
24691 if (!(id === undefined || typeof id === 'string')) {
24692 throw new TypeError("Client id [".concat(id, "] is not a String"));
24693 }
24694 _this = _EventEmitter.call(this) || this;
24695 Object.assign(_assertThisInitialized(_this), {
24696 /**
24697 * @var id {String} 客户端 id
24698 * @memberof IMClient#
24699 */
24700 id: id,
24701 options: options
24702 }, props);
24703 if (!_this._messageParser) {
24704 throw new Error('IMClient must be initialized with a MessageParser');
24705 }
24706 _this._conversationCache = new Cache("client:".concat(_this.id));
24707 _this._ackMessageBuffer = {};
24708 internal(_assertThisInitialized(_this)).lastPatchTime = Date.now();
24709 internal(_assertThisInitialized(_this)).lastNotificationTime = undefined;
24710 internal(_assertThisInitialized(_this))._eventemitter = new eventemitter3();
24711 if (debug$b.enabled) {
24712 values_1(IMEvent).forEach(function (event) {
24713 return _this.on(event, function () {
24714 for (var _len = arguments.length, payload = new Array(_len), _key = 0; _key < _len; _key++) {
24715 payload[_key] = arguments[_key];
24716 }
24717 return _this._debug("".concat(event, " event emitted. %o"), payload);
24718 });
24719 });
24720 }
24721 // onIMClientCreate hook
24722 applyDecorators(_this._plugins.onIMClientCreate, _assertThisInitialized(_this));
24723 return _this;
24724 }
24725 var _proto = IMClient.prototype;
24726 _proto._debug = function _debug() {
24727 for (var _len2 = arguments.length, params = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
24728 params[_key2] = arguments[_key2];
24729 }
24730 debug$b.apply(void 0, params.concat(["[".concat(this.id, "]")]));
24731 }
24732
24733 /**
24734 * @override
24735 * @private
24736 */;
24737 _proto._dispatchCommand =
24738 /*#__PURE__*/
24739 function () {
24740 var _dispatchCommand2 = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee(command) {
24741 return regenerator.wrap(function _callee$(_context) {
24742 while (1) switch (_context.prev = _context.next) {
24743 case 0:
24744 this._debug(trim(command), 'received');
24745 if (command.serverTs && command.notificationType === 1) {
24746 internal(this).lastNotificationTime = getTime(decodeDate(command.serverTs));
24747 }
24748 _context.t0 = command.cmd;
24749 _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;
24750 break;
24751 case 5:
24752 return _context.abrupt("return", this._dispatchConvMessage(command));
24753 case 6:
24754 return _context.abrupt("return", this._dispatchDirectMessage(command));
24755 case 7:
24756 return _context.abrupt("return", this._dispatchSessionMessage(command));
24757 case 8:
24758 return _context.abrupt("return", this._dispatchUnreadMessage(command));
24759 case 9:
24760 return _context.abrupt("return", this._dispatchRcpMessage(command));
24761 case 10:
24762 return _context.abrupt("return", this._dispatchPatchMessage(command));
24763 case 11:
24764 return _context.abrupt("return", this.emit(UNHANDLED_MESSAGE$1, command));
24765 case 12:
24766 case "end":
24767 return _context.stop();
24768 }
24769 }, _callee, this);
24770 }));
24771 function _dispatchCommand(_x) {
24772 return _dispatchCommand2.apply(this, arguments);
24773 }
24774 return _dispatchCommand;
24775 }();
24776 _proto._dispatchSessionMessage = /*#__PURE__*/function () {
24777 var _dispatchSessionMessage2 = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee2(message) {
24778 var _message$sessionMessa, code, reason;
24779 return regenerator.wrap(function _callee2$(_context2) {
24780 while (1) switch (_context2.prev = _context2.next) {
24781 case 0:
24782 _message$sessionMessa = message.sessionMessage, code = _message$sessionMessa.code, reason = _message$sessionMessa.reason;
24783 _context2.t0 = message.op;
24784 _context2.next = _context2.t0 === OpType.closed ? 4 : 8;
24785 break;
24786 case 4:
24787 internal(this)._eventemitter.emit('close');
24788 if (!(code === ErrorCode.SESSION_CONFLICT)) {
24789 _context2.next = 7;
24790 break;
24791 }
24792 return _context2.abrupt("return", this.emit(CONFLICT$1, {
24793 reason: reason
24794 }));
24795 case 7:
24796 return _context2.abrupt("return", this.emit(CLOSE$1, {
24797 code: code,
24798 reason: reason
24799 }));
24800 case 8:
24801 this.emit(UNHANDLED_MESSAGE$1, message);
24802 throw new Error('Unrecognized session command');
24803 case 10:
24804 case "end":
24805 return _context2.stop();
24806 }
24807 }, _callee2, this);
24808 }));
24809 function _dispatchSessionMessage(_x2) {
24810 return _dispatchSessionMessage2.apply(this, arguments);
24811 }
24812 return _dispatchSessionMessage;
24813 }();
24814 _proto._dispatchUnreadMessage = function _dispatchUnreadMessage(_ref) {
24815 var _this2 = this;
24816 var _ref$unreadMessage = _ref.unreadMessage,
24817 convs = _ref$unreadMessage.convs,
24818 notifTime = _ref$unreadMessage.notifTime;
24819 internal(this).lastUnreadNotifTime = notifTime;
24820 // ensure all converstions are cached
24821 return this.getConversations(convs.map(function (conv) {
24822 return conv.cid;
24823 })).then(function () {
24824 return (
24825 // update conversations data
24826 Promise.all(convs.map(function (_ref2) {
24827 var cid = _ref2.cid,
24828 unread = _ref2.unread,
24829 mid = _ref2.mid,
24830 ts = _ref2.timestamp,
24831 from = _ref2.from,
24832 data = _ref2.data,
24833 binaryMsg = _ref2.binaryMsg,
24834 patchTimestamp = _ref2.patchTimestamp,
24835 mentioned = _ref2.mentioned;
24836 var conversation = _this2._conversationCache.get(cid);
24837 // deleted conversation
24838 if (!conversation) return null;
24839 var timestamp;
24840 if (ts) {
24841 timestamp = decodeDate(ts);
24842 conversation.lastMessageAt = timestamp; // eslint-disable-line no-param-reassign
24843 }
24844
24845 return (mid ? _this2._messageParser.parse(binaryMsg || data).then(function (message) {
24846 var messageProps = {
24847 id: mid,
24848 cid: cid,
24849 timestamp: timestamp,
24850 updatedAt: patchTimestamp,
24851 from: from
24852 };
24853 Object.assign(message, messageProps);
24854 conversation.lastMessage = message; // eslint-disable-line no-param-reassign
24855 }) : Promise.resolve()).then(function () {
24856 conversation._setUnreadMessagesMentioned(mentioned);
24857 var countNotUpdated = unread === internal(conversation).unreadMessagesCount;
24858 if (countNotUpdated) return null; // to be filtered
24859 // manipulate internal property directly to skip unreadmessagescountupdate event
24860 internal(conversation).unreadMessagesCount = unread;
24861 return conversation;
24862 });
24863 // filter conversations without unread count update
24864 })).then(function (conversations) {
24865 return conversations.filter(function (conversation) {
24866 return conversation;
24867 });
24868 })
24869 );
24870 }).then(function (conversations) {
24871 if (conversations.length) {
24872 /**
24873 * 未读消息数目更新
24874 * @event IMClient#UNREAD_MESSAGES_COUNT_UPDATE
24875 * @since 3.4.0
24876 * @param {Conversation[]} conversations 未读消息数目有更新的对话列表
24877 */
24878 _this2.emit(UNREAD_MESSAGES_COUNT_UPDATE$1, conversations);
24879 }
24880 });
24881 };
24882 _proto._dispatchRcpMessage = /*#__PURE__*/function () {
24883 var _dispatchRcpMessage2 = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee3(message) {
24884 var rcpMessage, read, conversationId, messageId, timestamp, conversation;
24885 return regenerator.wrap(function _callee3$(_context3) {
24886 while (1) switch (_context3.prev = _context3.next) {
24887 case 0:
24888 rcpMessage = message.rcpMessage, read = message.rcpMessage.read;
24889 conversationId = rcpMessage.cid;
24890 messageId = rcpMessage.id;
24891 timestamp = decodeDate(rcpMessage.t);
24892 conversation = this._conversationCache.get(conversationId); // conversation not cached means the client does not send the message
24893 // during this session
24894 if (conversation) {
24895 _context3.next = 7;
24896 break;
24897 }
24898 return _context3.abrupt("return");
24899 case 7:
24900 conversation._handleReceipt({
24901 messageId: messageId,
24902 timestamp: timestamp,
24903 read: read
24904 });
24905 case 8:
24906 case "end":
24907 return _context3.stop();
24908 }
24909 }, _callee3, this);
24910 }));
24911 function _dispatchRcpMessage(_x3) {
24912 return _dispatchRcpMessage2.apply(this, arguments);
24913 }
24914 return _dispatchRcpMessage;
24915 }();
24916 _proto._dispatchPatchMessage = function _dispatchPatchMessage(_ref3) {
24917 var _this3 = this;
24918 var patches = _ref3.patchMessage.patches;
24919 // ensure all converstions are cached
24920 return this.getConversations(patches.map(function (patch) {
24921 return patch.cid;
24922 })).then(function () {
24923 return Promise.all(patches.map(function (_ref4) {
24924 var cid = _ref4.cid,
24925 mid = _ref4.mid,
24926 timestamp = _ref4.timestamp,
24927 recall = _ref4.recall,
24928 data = _ref4.data,
24929 patchTimestamp = _ref4.patchTimestamp,
24930 from = _ref4.from,
24931 binaryMsg = _ref4.binaryMsg,
24932 mentionAll = _ref4.mentionAll,
24933 mentionPids = _ref4.mentionPids,
24934 patchCode = _ref4.patchCode,
24935 patchReason = _ref4.patchReason;
24936 var conversation = _this3._conversationCache.get(cid);
24937 // deleted conversation
24938 if (!conversation) return null;
24939 return _this3._messageParser.parse(binaryMsg || data).then(function (message) {
24940 var patchTime = getTime(decodeDate(patchTimestamp));
24941 var messageProps = {
24942 id: mid,
24943 cid: cid,
24944 timestamp: timestamp,
24945 updatedAt: patchTime,
24946 from: from,
24947 mentionList: mentionPids,
24948 mentionedAll: mentionAll
24949 };
24950 Object.assign(message, messageProps);
24951 message._setStatus(MessageStatus.SENT);
24952 message._updateMentioned(_this3.id);
24953 if (internal(_this3).lastPatchTime < patchTime) {
24954 internal(_this3).lastPatchTime = patchTime;
24955 }
24956 // update conversation lastMessage
24957 if (conversation.lastMessage && conversation.lastMessage.id === mid) {
24958 conversation.lastMessage = message; // eslint-disable-line no-param-reassign
24959 }
24960
24961 var reason;
24962 if (patchCode) {
24963 reason = {
24964 code: patchCode.toNumber(),
24965 detail: patchReason
24966 };
24967 }
24968 if (recall) {
24969 /**
24970 * 消息被撤回
24971 * @event IMClient#MESSAGE_RECALL
24972 * @param {AVMessage} message 被撤回的消息
24973 * @param {ConversationBase} conversation 消息所在的会话
24974 * @param {PatchReason} [reason] 撤回的原因,不存在代表是发送者主动撤回
24975 */
24976 _this3.emit(MESSAGE_RECALL$1, message, conversation, reason);
24977 /**
24978 * 消息被撤回
24979 * @event ConversationBase#MESSAGE_RECALL
24980 * @param {AVMessage} message 被撤回的消息
24981 * @param {PatchReason} [reason] 撤回的原因,不存在代表是发送者主动撤回
24982 */
24983 conversation.emit(MESSAGE_RECALL$1, message, reason);
24984 } else {
24985 /**
24986 * 消息被修改
24987 * @event IMClient#MESSAGE_UPDATE
24988 * @param {AVMessage} message 被修改的消息
24989 * @param {ConversationBase} conversation 消息所在的会话
24990 * @param {PatchReason} [reason] 修改的原因,不存在代表是发送者主动修改
24991 */
24992 _this3.emit(MESSAGE_UPDATE$1, message, conversation, reason);
24993 /**
24994 * 消息被修改
24995 * @event ConversationBase#MESSAGE_UPDATE
24996 * @param {AVMessage} message 被修改的消息
24997 * @param {PatchReason} [reason] 修改的原因,不存在代表是发送者主动修改
24998 */
24999 conversation.emit(MESSAGE_UPDATE$1, message, reason);
25000 }
25001 });
25002 }));
25003 });
25004 };
25005 _proto._dispatchConvMessage = /*#__PURE__*/function () {
25006 var _dispatchConvMessage2 = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee4(message) {
25007 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;
25008 return regenerator.wrap(function _callee4$(_context4) {
25009 while (1) switch (_context4.prev = _context4.next) {
25010 case 0:
25011 convMessage = message.convMessage, _message$convMessage = message.convMessage, initBy = _message$convMessage.initBy, m = _message$convMessage.m, info = _message$convMessage.info, attr = _message$convMessage.attr;
25012 _context4.next = 3;
25013 return this.getConversation(convMessage.cid);
25014 case 3:
25015 conversation = _context4.sent;
25016 _context4.t0 = message.op;
25017 _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;
25018 break;
25019 case 7:
25020 conversation._addMembers([this.id]);
25021 payload = {
25022 invitedBy: initBy
25023 };
25024 /**
25025 * 当前用户被添加至某个对话
25026 * @event IMClient#INVITED
25027 * @param {Object} payload
25028 * @param {String} payload.invitedBy 邀请者 id
25029 * @param {ConversationBase} conversation
25030 */
25031 this.emit(INVITED$1, payload, conversation);
25032 /**
25033 * 当前用户被添加至当前对话
25034 * @event ConversationBase#INVITED
25035 * @param {Object} payload
25036 * @param {String} payload.invitedBy 该移除操作的发起者 id
25037 */
25038 conversation.emit(INVITED$1, payload);
25039 return _context4.abrupt("return");
25040 case 12:
25041 conversation._removeMembers([this.id]);
25042 _payload = {
25043 kickedBy: initBy
25044 };
25045 /**
25046 * 当前用户被从某个对话中移除
25047 * @event IMClient#KICKED
25048 * @param {Object} payload
25049 * @param {String} payload.kickedBy 该移除操作的发起者 id
25050 * @param {ConversationBase} conversation
25051 */
25052 this.emit(KICKED$1, _payload, conversation);
25053 /**
25054 * 当前用户被从当前对话中移除
25055 * @event ConversationBase#KICKED
25056 * @param {Object} payload
25057 * @param {String} payload.kickedBy 该移除操作的发起者 id
25058 */
25059 conversation.emit(KICKED$1, _payload);
25060 return _context4.abrupt("return");
25061 case 17:
25062 conversation._addMembers(m);
25063 _payload2 = {
25064 invitedBy: initBy,
25065 members: m
25066 };
25067 /**
25068 * 有用户被添加至某个对话
25069 * @event IMClient#MEMBERS_JOINED
25070 * @param {Object} payload
25071 * @param {String[]} payload.members 被添加的用户 id 列表
25072 * @param {String} payload.invitedBy 邀请者 id
25073 * @param {ConversationBase} conversation
25074 */
25075 this.emit(MEMBERS_JOINED$1, _payload2, conversation);
25076 /**
25077 * 有成员被添加至当前对话
25078 * @event ConversationBase#MEMBERS_JOINED
25079 * @param {Object} payload
25080 * @param {String[]} payload.members 被添加的成员 id 列表
25081 * @param {String} payload.invitedBy 邀请者 id
25082 */
25083 conversation.emit(MEMBERS_JOINED$1, _payload2);
25084 return _context4.abrupt("return");
25085 case 22:
25086 conversation._removeMembers(m);
25087 _payload3 = {
25088 kickedBy: initBy,
25089 members: m
25090 };
25091 /**
25092 * 有成员被从某个对话中移除
25093 * @event IMClient#MEMBERS_LEFT
25094 * @param {Object} payload
25095 * @param {String[]} payload.members 被移除的成员 id 列表
25096 * @param {String} payload.kickedBy 该移除操作的发起者 id
25097 * @param {ConversationBase} conversation
25098 */
25099 this.emit(MEMBERS_LEFT$1, _payload3, conversation);
25100 /**
25101 * 有成员被从当前对话中移除
25102 * @event ConversationBase#MEMBERS_LEFT
25103 * @param {Object} payload
25104 * @param {String[]} payload.members 被移除的成员 id 列表
25105 * @param {String} payload.kickedBy 该移除操作的发起者 id
25106 */
25107 conversation.emit(MEMBERS_LEFT$1, _payload3);
25108 return _context4.abrupt("return");
25109 case 27:
25110 _payload4 = {
25111 blockedBy: initBy,
25112 members: m
25113 };
25114 /**
25115 * 有成员被加入某个对话的黑名单
25116 * @event IMClient#MEMBERS_BLOCKED
25117 * @param {Object} payload
25118 * @param {String[]} payload.members 成员 id 列表
25119 * @param {String} payload.blockedBy 该操作的发起者 id
25120 * @param {ConversationBase} conversation
25121 */
25122 this.emit(MEMBERS_BLOCKED$1, _payload4, conversation);
25123 /**
25124 * 有成员被加入当前对话的黑名单
25125 * @event ConversationBase#MEMBERS_BLOCKED
25126 * @param {Object} payload
25127 * @param {String[]} payload.members 成员 id 列表
25128 * @param {String} payload.blockedBy 该操作的发起者 id
25129 */
25130 conversation.emit(MEMBERS_BLOCKED$1, _payload4);
25131 return _context4.abrupt("return");
25132 case 31:
25133 _payload5 = {
25134 unblockedBy: initBy,
25135 members: m
25136 };
25137 /**
25138 * 有成员被移出某个对话的黑名单
25139 * @event IMClient#MEMBERS_UNBLOCKED
25140 * @param {Object} payload
25141 * @param {String[]} payload.members 成员 id 列表
25142 * @param {String} payload.unblockedBy 该操作的发起者 id
25143 * @param {ConversationBase} conversation
25144 */
25145 this.emit(MEMBERS_UNBLOCKED$1, _payload5, conversation);
25146 /**
25147 * 有成员被移出当前对话的黑名单
25148 * @event ConversationBase#MEMBERS_UNBLOCKED
25149 * @param {Object} payload
25150 * @param {String[]} payload.members 成员 id 列表
25151 * @param {String} payload.unblockedBy 该操作的发起者 id
25152 */
25153 conversation.emit(MEMBERS_UNBLOCKED$1, _payload5);
25154 return _context4.abrupt("return");
25155 case 35:
25156 _payload6 = {
25157 blockedBy: initBy
25158 };
25159 /**
25160 * 当前用户被加入某个对话的黑名单
25161 * @event IMClient#BLOCKED
25162 * @param {Object} payload
25163 * @param {String} payload.blockedBy 该操作的发起者 id
25164 * @param {ConversationBase} conversation
25165 */
25166 this.emit(BLOCKED$1, _payload6, conversation);
25167 /**
25168 * 当前用户被加入当前对话的黑名单
25169 * @event ConversationBase#BLOCKED
25170 * @param {Object} payload
25171 * @param {String} payload.blockedBy 该操作的发起者 id
25172 */
25173 conversation.emit(BLOCKED$1, _payload6);
25174 return _context4.abrupt("return");
25175 case 39:
25176 _payload7 = {
25177 unblockedBy: initBy
25178 };
25179 /**
25180 * 当前用户被移出某个对话的黑名单
25181 * @event IMClient#UNBLOCKED
25182 * @param {Object} payload
25183 * @param {String} payload.unblockedBy 该操作的发起者 id
25184 * @param {ConversationBase} conversation
25185 */
25186 this.emit(UNBLOCKED$1, _payload7, conversation);
25187 /**
25188 * 当前用户被移出当前对话的黑名单
25189 * @event ConversationBase#UNBLOCKED
25190 * @param {Object} payload
25191 * @param {String} payload.unblockedBy 该操作的发起者 id
25192 */
25193 conversation.emit(UNBLOCKED$1, _payload7);
25194 return _context4.abrupt("return");
25195 case 43:
25196 _payload8 = {
25197 mutedBy: initBy,
25198 members: m
25199 };
25200 /**
25201 * 有成员在某个对话中被禁言
25202 * @event IMClient#MEMBERS_MUTED
25203 * @param {Object} payload
25204 * @param {String[]} payload.members 成员 id 列表
25205 * @param {String} payload.mutedBy 该操作的发起者 id
25206 * @param {ConversationBase} conversation
25207 */
25208 this.emit(MEMBERS_MUTED$1, _payload8, conversation);
25209 /**
25210 * 有成员在当前对话中被禁言
25211 * @event ConversationBase#MEMBERS_MUTED
25212 * @param {Object} payload
25213 * @param {String[]} payload.members 成员 id 列表
25214 * @param {String} payload.mutedBy 该操作的发起者 id
25215 */
25216 conversation.emit(MEMBERS_MUTED$1, _payload8);
25217 return _context4.abrupt("return");
25218 case 47:
25219 _payload9 = {
25220 unmutedBy: initBy,
25221 members: m
25222 };
25223 /**
25224 * 有成员在某个对话中被解除禁言
25225 * @event IMClient#MEMBERS_UNMUTED
25226 * @param {Object} payload
25227 * @param {String[]} payload.members 成员 id 列表
25228 * @param {String} payload.unmutedBy 该操作的发起者 id
25229 * @param {ConversationBase} conversation
25230 */
25231 this.emit(MEMBERS_UNMUTED$1, _payload9, conversation);
25232 /**
25233 * 有成员在当前对话中被解除禁言
25234 * @event ConversationBase#MEMBERS_UNMUTED
25235 * @param {Object} payload
25236 * @param {String[]} payload.members 成员 id 列表
25237 * @param {String} payload.unmutedBy 该操作的发起者 id
25238 */
25239 conversation.emit(MEMBERS_UNMUTED$1, _payload9);
25240 return _context4.abrupt("return");
25241 case 51:
25242 _payload10 = {
25243 mutedBy: initBy
25244 };
25245 /**
25246 * 有成员在某个对话中被禁言
25247 * @event IMClient#MUTED
25248 * @param {Object} payload
25249 * @param {String} payload.mutedBy 该操作的发起者 id
25250 * @param {ConversationBase} conversation
25251 */
25252 this.emit(MUTED$1, _payload10, conversation);
25253 /**
25254 * 有成员在当前对话中被禁言
25255 * @event ConversationBase#MUTED
25256 * @param {Object} payload
25257 * @param {String} payload.mutedBy 该操作的发起者 id
25258 */
25259 conversation.emit(MUTED$1, _payload10);
25260 return _context4.abrupt("return");
25261 case 55:
25262 _payload11 = {
25263 unmutedBy: initBy
25264 };
25265 /**
25266 * 有成员在某个对话中被解除禁言
25267 * @event IMClient#UNMUTED
25268 * @param {Object} payload
25269 * @param {String} payload.unmutedBy 该操作的发起者 id
25270 * @param {ConversationBase} conversation
25271 */
25272 this.emit(UNMUTED$1, _payload11, conversation);
25273 /**
25274 * 有成员在当前对话中被解除禁言
25275 * @event ConversationBase#UNMUTED
25276 * @param {Object} payload
25277 * @param {String} payload.unmutedBy 该操作的发起者 id
25278 */
25279 conversation.emit(UNMUTED$1, _payload11);
25280 return _context4.abrupt("return");
25281 case 59:
25282 pid = info.pid, role = info.role;
25283 _internal = internal(conversation), memberInfoMap = _internal.memberInfoMap; // 如果不存在缓存,且不是 role 的更新,则不通知
25284 if (!(!memberInfoMap && !role)) {
25285 _context4.next = 63;
25286 break;
25287 }
25288 return _context4.abrupt("return");
25289 case 63:
25290 _context4.next = 65;
25291 return conversation.getMemberInfo(pid);
25292 case 65:
25293 memberInfo = _context4.sent;
25294 internal(memberInfo).role = role;
25295 _payload12 = {
25296 member: pid,
25297 memberInfo: memberInfo,
25298 updatedBy: initBy
25299 };
25300 /**
25301 * 有成员的对话信息被更新
25302 * @event IMClient#MEMBER_INFO_UPDATED
25303 * @param {Object} payload
25304 * @param {String} payload.member 被更新对话信息的成员 id
25305 * @param {ConversationMumberInfo} payload.memberInfo 被更新的成员对话信息
25306 * @param {String} payload.updatedBy 该操作的发起者 id
25307 * @param {ConversationBase} conversation
25308 */
25309 this.emit(MEMBER_INFO_UPDATED$1, _payload12, conversation);
25310 /**
25311 * 有成员的对话信息被更新
25312 * @event ConversationBase#MEMBER_INFO_UPDATED
25313 * @param {Object} payload
25314 * @param {String} payload.member 被更新对话信息的成员 id
25315 * @param {ConversationMumberInfo} payload.memberInfo 被更新的成员对话信息
25316 * @param {String} payload.updatedBy 该操作的发起者 id
25317 */
25318 conversation.emit(MEMBER_INFO_UPDATED$1, _payload12);
25319 return _context4.abrupt("return");
25320 case 71:
25321 attributes = decode(JSON.parse(attr.data));
25322 conversation._updateServerAttributes(attributes);
25323 _payload13 = {
25324 attributes: attributes,
25325 updatedBy: initBy
25326 };
25327 /**
25328 * 该对话信息被更新
25329 * @event IMClient#CONVERSATION_INFO_UPDATED
25330 * @param {Object} payload
25331 * @param {Object} payload.attributes 被更新的属性
25332 * @param {String} payload.updatedBy 该操作的发起者 id
25333 * @param {ConversationBase} conversation
25334 */
25335 this.emit(CONVERSATION_INFO_UPDATED$1, _payload13, conversation);
25336 /**
25337 * 有对话信息被更新
25338 * @event ConversationBase#INFO_UPDATED
25339 * @param {Object} payload
25340 * @param {Object} payload.attributes 被更新的属性
25341 * @param {String} payload.updatedBy 该操作的发起者 id
25342 */
25343 conversation.emit(INFO_UPDATED$1, _payload13);
25344 return _context4.abrupt("return");
25345 case 77:
25346 this.emit(UNHANDLED_MESSAGE$1, message);
25347 throw new Error('Unrecognized conversation command');
25348 case 79:
25349 case "end":
25350 return _context4.stop();
25351 }
25352 }, _callee4, this);
25353 }));
25354 function _dispatchConvMessage(_x4) {
25355 return _dispatchConvMessage2.apply(this, arguments);
25356 }
25357 return _dispatchConvMessage;
25358 }();
25359 _proto._dispatchDirectMessage = function _dispatchDirectMessage(originalMessage) {
25360 var _this4 = this;
25361 var directMessage = originalMessage.directMessage,
25362 _originalMessage$dire = originalMessage.directMessage,
25363 id = _originalMessage$dire.id,
25364 cid = _originalMessage$dire.cid,
25365 fromPeerId = _originalMessage$dire.fromPeerId,
25366 timestamp = _originalMessage$dire.timestamp,
25367 _transient = _originalMessage$dire["transient"],
25368 patchTimestamp = _originalMessage$dire.patchTimestamp,
25369 mentionPids = _originalMessage$dire.mentionPids,
25370 mentionAll = _originalMessage$dire.mentionAll,
25371 binaryMsg = _originalMessage$dire.binaryMsg,
25372 msg = _originalMessage$dire.msg;
25373 var content = binaryMsg ? binaryMsg.toArrayBuffer() : msg;
25374 return Promise.all([this.getConversation(directMessage.cid), this._messageParser.parse(content)]).then(function (_ref5) {
25375 var _ref6 = _slicedToArray(_ref5, 2),
25376 conversation = _ref6[0],
25377 message = _ref6[1];
25378 // deleted conversation
25379 if (!conversation) return undefined;
25380 var messageProps = {
25381 id: id,
25382 cid: cid,
25383 timestamp: timestamp,
25384 updatedAt: patchTimestamp,
25385 from: fromPeerId,
25386 mentionList: mentionPids,
25387 mentionedAll: mentionAll
25388 };
25389 Object.assign(message, messageProps);
25390 message._updateMentioned(_this4.id);
25391 message._setStatus(MessageStatus.SENT);
25392 // filter outgoing message sent from another device
25393 if (message.from !== _this4.id) {
25394 if (!(_transient || conversation["transient"])) {
25395 _this4._sendAck(message);
25396 }
25397 }
25398 return _this4._dispatchParsedMessage(message, conversation);
25399 });
25400 };
25401 _proto._dispatchParsedMessage = function _dispatchParsedMessage(message, conversation) {
25402 var _this5 = this;
25403 // beforeMessageDispatch hook
25404 return applyDispatcher(this._plugins.beforeMessageDispatch, [message, conversation]).then(function (shouldDispatch) {
25405 if (shouldDispatch === false) return;
25406 conversation.lastMessage = message; // eslint-disable-line no-param-reassign
25407 conversation.lastMessageAt = message.timestamp; // eslint-disable-line no-param-reassign
25408 // filter outgoing message sent from another device
25409 if (message.from !== _this5.id) {
25410 conversation.unreadMessagesCount += 1; // eslint-disable-line no-param-reassign
25411 if (message.mentioned) conversation._setUnreadMessagesMentioned(true);
25412 }
25413 /**
25414 * 当前用户收到消息
25415 * @event IMClient#MESSAGE
25416 * @param {Message} message
25417 * @param {ConversationBase} conversation 收到消息的对话
25418 */
25419 _this5.emit(MESSAGE$2, message, conversation);
25420 /**
25421 * 当前对话收到消息
25422 * @event ConversationBase#MESSAGE
25423 * @param {Message} message
25424 */
25425 conversation.emit(MESSAGE$2, message);
25426 });
25427 };
25428 _proto._sendAck = function _sendAck(message) {
25429 this._debug('send ack for %O', message);
25430 var cid = message.cid;
25431 if (!cid) {
25432 throw new Error('missing cid');
25433 }
25434 if (!this._ackMessageBuffer[cid]) {
25435 this._ackMessageBuffer[cid] = [];
25436 }
25437 this._ackMessageBuffer[cid].push(message);
25438 return this._doSendAck();
25439 }
25440
25441 // jsdoc-ignore-start
25442 ;
25443 _proto.
25444 // jsdoc-ignore-end
25445 _doSendAck = function _doSendAck() {
25446 var _this6 = this;
25447 // if not connected, just skip everything
25448 if (!this._connection.is('connected')) return;
25449 this._debug('do send ack %O', this._ackMessageBuffer);
25450 Promise.all(Object.keys(this._ackMessageBuffer).map(function (cid) {
25451 var convAckMessages = _this6._ackMessageBuffer[cid];
25452 var timestamps = convAckMessages.map(function (message) {
25453 return message.timestamp;
25454 });
25455 var command = new GenericCommand({
25456 cmd: 'ack',
25457 ackMessage: new AckCommand({
25458 cid: cid,
25459 fromts: Math.min.apply(null, timestamps),
25460 tots: Math.max.apply(null, timestamps)
25461 })
25462 });
25463 delete _this6._ackMessageBuffer[cid];
25464 return _this6._send(command, false)["catch"](function (error) {
25465 _this6._debug('send ack failed: %O', error);
25466 _this6._ackMessageBuffer[cid] = convAckMessages;
25467 });
25468 }));
25469 };
25470 _proto._omitPeerId = function _omitPeerId(value) {
25471 internal(this).peerIdOmittable = value;
25472 };
25473 _proto._send = function _send(cmd) {
25474 var _this$_connection;
25475 var command = cmd;
25476 if (!internal(this).peerIdOmittable && this.id) {
25477 command.peerId = this.id;
25478 }
25479 for (var _len3 = arguments.length, args = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {
25480 args[_key3 - 1] = arguments[_key3];
25481 }
25482 return (_this$_connection = this._connection).send.apply(_this$_connection, [command].concat(args));
25483 };
25484 _proto._open = /*#__PURE__*/function () {
25485 var _open2 = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee5(appId, tag, deviceId) {
25486 var isReconnect,
25487 _internal2,
25488 lastUnreadNotifTime,
25489 lastPatchTime,
25490 lastNotificationTime,
25491 command,
25492 signatureResult,
25493 sessionToken,
25494 resCommand,
25495 _resCommand,
25496 peerId,
25497 sessionMessage,
25498 _resCommand$sessionMe,
25499 token,
25500 tokenTTL,
25501 code,
25502 serverTs,
25503 serverTime,
25504 _args5 = arguments;
25505 return regenerator.wrap(function _callee5$(_context5) {
25506 while (1) switch (_context5.prev = _context5.next) {
25507 case 0:
25508 isReconnect = _args5.length > 3 && _args5[3] !== undefined ? _args5[3] : false;
25509 this._debug('open session');
25510 _internal2 = internal(this), lastUnreadNotifTime = _internal2.lastUnreadNotifTime, lastPatchTime = _internal2.lastPatchTime, lastNotificationTime = _internal2.lastNotificationTime;
25511 command = new GenericCommand({
25512 cmd: 'session',
25513 op: 'open',
25514 appId: appId,
25515 peerId: this.id,
25516 sessionMessage: new SessionCommand({
25517 ua: "js/".concat(version),
25518 r: isReconnect,
25519 lastUnreadNotifTime: lastUnreadNotifTime,
25520 lastPatchTime: lastPatchTime,
25521 configBitmap: configBitmap
25522 })
25523 });
25524 if (isReconnect) {
25525 _context5.next = 13;
25526 break;
25527 }
25528 Object.assign(command.sessionMessage, trim({
25529 tag: tag,
25530 deviceId: deviceId
25531 }));
25532 if (!this.options.signatureFactory) {
25533 _context5.next = 11;
25534 break;
25535 }
25536 _context5.next = 9;
25537 return runSignatureFactory(this.options.signatureFactory, [this._identity]);
25538 case 9:
25539 signatureResult = _context5.sent;
25540 Object.assign(command.sessionMessage, keyRemap({
25541 signature: 's',
25542 timestamp: 't',
25543 nonce: 'n'
25544 }, signatureResult));
25545 case 11:
25546 _context5.next = 17;
25547 break;
25548 case 13:
25549 _context5.next = 15;
25550 return this._sessionManager.getSessionToken({
25551 autoRefresh: false
25552 });
25553 case 15:
25554 sessionToken = _context5.sent;
25555 if (sessionToken && sessionToken !== Expirable.EXPIRED) {
25556 Object.assign(command.sessionMessage, {
25557 st: sessionToken
25558 });
25559 }
25560 case 17:
25561 _context5.prev = 17;
25562 _context5.next = 20;
25563 return this._send(command);
25564 case 20:
25565 resCommand = _context5.sent;
25566 _context5.next = 32;
25567 break;
25568 case 23:
25569 _context5.prev = 23;
25570 _context5.t0 = _context5["catch"](17);
25571 if (!(_context5.t0.code === ErrorCode.SESSION_TOKEN_EXPIRED)) {
25572 _context5.next = 31;
25573 break;
25574 }
25575 if (this._sessionManager) {
25576 _context5.next = 28;
25577 break;
25578 }
25579 throw new Error('Unexpected session expiration');
25580 case 28:
25581 debug$b('Session token expired, reopening');
25582 this._sessionManager.revoke();
25583 return _context5.abrupt("return", this._open(appId, tag, deviceId, isReconnect));
25584 case 31:
25585 throw _context5.t0;
25586 case 32:
25587 _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;
25588 if (!code) {
25589 _context5.next = 35;
25590 break;
25591 }
25592 throw createError(sessionMessage);
25593 case 35:
25594 if (peerId) {
25595 this.id = peerId;
25596 if (!this._identity) this._identity = peerId;
25597 if (token) {
25598 this._sessionManager = this._sessionManager || this._createSessionManager();
25599 this._sessionManager.setSessionToken(token, tokenTTL);
25600 }
25601 serverTime = getTime(decodeDate(serverTs));
25602 if (serverTs) {
25603 internal(this).lastPatchTime = serverTime;
25604 }
25605 if (lastNotificationTime) {
25606 // Do not await for it as this is failable
25607 this._syncNotifications(lastNotificationTime)["catch"](function (error) {
25608 return console.warn('Syncing notifications failed:', error);
25609 });
25610 } else {
25611 // Set timestamp to now for next reconnection
25612 internal(this).lastNotificationTime = serverTime;
25613 }
25614 } else {
25615 console.warn('Unexpected session opened without peerId.');
25616 }
25617 return _context5.abrupt("return", undefined);
25618 case 37:
25619 case "end":
25620 return _context5.stop();
25621 }
25622 }, _callee5, this, [[17, 23]]);
25623 }));
25624 function _open(_x5, _x6, _x7) {
25625 return _open2.apply(this, arguments);
25626 }
25627 return _open;
25628 }();
25629 _proto._syncNotifications = /*#__PURE__*/function () {
25630 var _syncNotifications2 = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee6(timestamp) {
25631 var _this7 = this;
25632 var _yield$this$_fetchNot, hasMore, notifications;
25633 return regenerator.wrap(function _callee6$(_context6) {
25634 while (1) switch (_context6.prev = _context6.next) {
25635 case 0:
25636 _context6.next = 2;
25637 return this._fetchNotifications(timestamp);
25638 case 2:
25639 _yield$this$_fetchNot = _context6.sent;
25640 hasMore = _yield$this$_fetchNot.hasMore;
25641 notifications = _yield$this$_fetchNot.notifications;
25642 notifications.forEach(function (notification) {
25643 var cmd = notification.cmd,
25644 op = notification.op,
25645 serverTs = notification.serverTs,
25646 notificationType = notification.notificationType,
25647 payload = _objectWithoutProperties(notification, _excluded$3);
25648 _this7._dispatchCommand(_defineProperty({
25649 cmd: CommandType[cmd],
25650 op: OpType[op],
25651 serverTs: serverTs,
25652 notificationType: notificationType
25653 }, "".concat(cmd, "Message"), payload));
25654 });
25655 if (!hasMore) {
25656 _context6.next = 8;
25657 break;
25658 }
25659 return _context6.abrupt("return", this._syncNotifications(internal(this).lastNotificationTime));
25660 case 8:
25661 return _context6.abrupt("return", undefined);
25662 case 9:
25663 case "end":
25664 return _context6.stop();
25665 }
25666 }, _callee6, this);
25667 }));
25668 function _syncNotifications(_x8) {
25669 return _syncNotifications2.apply(this, arguments);
25670 }
25671 return _syncNotifications;
25672 }();
25673 _proto._fetchNotifications = /*#__PURE__*/function () {
25674 var _fetchNotifications2 = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee7(timestamp) {
25675 return regenerator.wrap(function _callee7$(_context7) {
25676 while (1) switch (_context7.prev = _context7.next) {
25677 case 0:
25678 return _context7.abrupt("return", this._requestWithSessionToken({
25679 method: 'GET',
25680 path: '/rtm/notifications',
25681 query: {
25682 start_ts: timestamp,
25683 notification_type: 'permanent'
25684 }
25685 }));
25686 case 1:
25687 case "end":
25688 return _context7.stop();
25689 }
25690 }, _callee7, this);
25691 }));
25692 function _fetchNotifications(_x9) {
25693 return _fetchNotifications2.apply(this, arguments);
25694 }
25695 return _fetchNotifications;
25696 }();
25697 _proto._createSessionManager = function _createSessionManager() {
25698 var _this8 = this;
25699 debug$b('create SessionManager');
25700 return new SessionManager({
25701 onBeforeGetSessionToken: this._connection.checkConnectionAvailability.bind(this._connection),
25702 refresh: function refresh(manager, expiredSessionToken) {
25703 return manager.setSessionTokenAsync(Promise.resolve(new GenericCommand({
25704 cmd: 'session',
25705 op: 'refresh',
25706 sessionMessage: new SessionCommand({
25707 ua: "js/".concat(version),
25708 st: expiredSessionToken
25709 })
25710 })).then( /*#__PURE__*/function () {
25711 var _ref7 = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee8(command) {
25712 var signatureResult;
25713 return regenerator.wrap(function _callee8$(_context8) {
25714 while (1) switch (_context8.prev = _context8.next) {
25715 case 0:
25716 if (!_this8.options.signatureFactory) {
25717 _context8.next = 5;
25718 break;
25719 }
25720 _context8.next = 3;
25721 return runSignatureFactory(_this8.options.signatureFactory, [_this8._identity]);
25722 case 3:
25723 signatureResult = _context8.sent;
25724 Object.assign(command.sessionMessage, keyRemap({
25725 signature: 's',
25726 timestamp: 't',
25727 nonce: 'n'
25728 }, signatureResult));
25729 case 5:
25730 return _context8.abrupt("return", command);
25731 case 6:
25732 case "end":
25733 return _context8.stop();
25734 }
25735 }, _callee8);
25736 }));
25737 return function (_x10) {
25738 return _ref7.apply(this, arguments);
25739 };
25740 }()).then(_this8._send.bind(_this8)).then(function (_ref8) {
25741 var _ref8$sessionMessage = _ref8.sessionMessage,
25742 token = _ref8$sessionMessage.st,
25743 ttl = _ref8$sessionMessage.stTtl;
25744 return [token, ttl];
25745 }));
25746 }
25747 });
25748 };
25749 _proto._requestWithSessionToken = /*#__PURE__*/function () {
25750 var _requestWithSessionToken2 = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee9(_ref9) {
25751 var headers, query, params, sessionToken;
25752 return regenerator.wrap(function _callee9$(_context9) {
25753 while (1) switch (_context9.prev = _context9.next) {
25754 case 0:
25755 headers = _ref9.headers, query = _ref9.query, params = _objectWithoutProperties(_ref9, _excluded2$1);
25756 _context9.next = 3;
25757 return this._sessionManager.getSessionToken();
25758 case 3:
25759 sessionToken = _context9.sent;
25760 return _context9.abrupt("return", this._request(_objectSpread$8({
25761 headers: _objectSpread$8({
25762 'X-LC-IM-Session-Token': sessionToken
25763 }, headers),
25764 query: _objectSpread$8({
25765 client_id: this.id
25766 }, query)
25767 }, params)));
25768 case 5:
25769 case "end":
25770 return _context9.stop();
25771 }
25772 }, _callee9, this);
25773 }));
25774 function _requestWithSessionToken(_x11) {
25775 return _requestWithSessionToken2.apply(this, arguments);
25776 }
25777 return _requestWithSessionToken;
25778 }()
25779 /**
25780 * 关闭客户端
25781 * @return {Promise}
25782 */
25783 ;
25784 _proto.close =
25785 /*#__PURE__*/
25786 function () {
25787 var _close = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee10() {
25788 var _ee, command;
25789 return regenerator.wrap(function _callee10$(_context10) {
25790 while (1) switch (_context10.prev = _context10.next) {
25791 case 0:
25792 this._debug('close session');
25793 _ee = internal(this)._eventemitter;
25794 _ee.emit('beforeclose');
25795 if (!this._connection.is('connected')) {
25796 _context10.next = 7;
25797 break;
25798 }
25799 command = new GenericCommand({
25800 cmd: 'session',
25801 op: 'close'
25802 });
25803 _context10.next = 7;
25804 return this._send(command);
25805 case 7:
25806 _ee.emit('close');
25807 this.emit(CLOSE$1, {
25808 code: 0
25809 });
25810 case 9:
25811 case "end":
25812 return _context10.stop();
25813 }
25814 }, _callee10, this);
25815 }));
25816 function close() {
25817 return _close.apply(this, arguments);
25818 }
25819 return close;
25820 }()
25821 /**
25822 * 获取 client 列表中在线的 client,每次查询最多 20 个 clientId,超出部分会被忽略
25823 * @param {String[]} clientIds 要查询的 client ids
25824 * @return {Primse.<String[]>} 在线的 client ids
25825 */
25826 ;
25827 _proto.ping =
25828 /*#__PURE__*/
25829 function () {
25830 var _ping = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee11(clientIds) {
25831 var command, resCommand;
25832 return regenerator.wrap(function _callee11$(_context11) {
25833 while (1) switch (_context11.prev = _context11.next) {
25834 case 0:
25835 this._debug('ping');
25836 if (clientIds instanceof Array) {
25837 _context11.next = 3;
25838 break;
25839 }
25840 throw new TypeError("clientIds ".concat(clientIds, " is not an Array"));
25841 case 3:
25842 if (clientIds.length) {
25843 _context11.next = 5;
25844 break;
25845 }
25846 return _context11.abrupt("return", Promise.resolve([]));
25847 case 5:
25848 command = new GenericCommand({
25849 cmd: 'session',
25850 op: 'query',
25851 sessionMessage: new SessionCommand({
25852 sessionPeerIds: clientIds
25853 })
25854 });
25855 _context11.next = 8;
25856 return this._send(command);
25857 case 8:
25858 resCommand = _context11.sent;
25859 return _context11.abrupt("return", resCommand.sessionMessage.onlineSessionPeerIds);
25860 case 10:
25861 case "end":
25862 return _context11.stop();
25863 }
25864 }, _callee11, this);
25865 }));
25866 function ping(_x12) {
25867 return _ping.apply(this, arguments);
25868 }
25869 return ping;
25870 }()
25871 /**
25872 * 获取某个特定的对话
25873 * @param {String} id 对话 id,对应 _Conversation 表中的 objectId
25874 * @param {Boolean} [noCache=false] 强制不从缓存中获取
25875 * @return {Promise.<ConversationBase>} 如果 id 对应的对话不存在则返回 null
25876 */
25877 ;
25878 _proto.getConversation =
25879 /*#__PURE__*/
25880 function () {
25881 var _getConversation = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee12(id) {
25882 var noCache,
25883 cachedConversation,
25884 _args12 = arguments;
25885 return regenerator.wrap(function _callee12$(_context12) {
25886 while (1) switch (_context12.prev = _context12.next) {
25887 case 0:
25888 noCache = _args12.length > 1 && _args12[1] !== undefined ? _args12[1] : false;
25889 if (!(typeof id !== 'string')) {
25890 _context12.next = 3;
25891 break;
25892 }
25893 throw new TypeError("".concat(id, " is not a String"));
25894 case 3:
25895 if (noCache) {
25896 _context12.next = 7;
25897 break;
25898 }
25899 cachedConversation = this._conversationCache.get(id);
25900 if (!cachedConversation) {
25901 _context12.next = 7;
25902 break;
25903 }
25904 return _context12.abrupt("return", cachedConversation);
25905 case 7:
25906 if (!isTemporaryConversatrionId(id)) {
25907 _context12.next = 14;
25908 break;
25909 }
25910 _context12.next = 10;
25911 return this._getTemporaryConversations([id]);
25912 case 10:
25913 _context12.t0 = _context12.sent[0];
25914 if (_context12.t0) {
25915 _context12.next = 13;
25916 break;
25917 }
25918 _context12.t0 = null;
25919 case 13:
25920 return _context12.abrupt("return", _context12.t0);
25921 case 14:
25922 return _context12.abrupt("return", this.getQuery().equalTo('objectId', id).find().then(function (conversations) {
25923 return conversations[0] || null;
25924 }));
25925 case 15:
25926 case "end":
25927 return _context12.stop();
25928 }
25929 }, _callee12, this);
25930 }));
25931 function getConversation(_x13) {
25932 return _getConversation.apply(this, arguments);
25933 }
25934 return getConversation;
25935 }()
25936 /**
25937 * 通过 id 批量获取某个特定的对话
25938 * @since 3.4.0
25939 * @param {String[]} ids 对话 id 列表,对应 _Conversation 表中的 objectId
25940 * @param {Boolean} [noCache=false] 强制不从缓存中获取
25941 * @return {Promise.<ConversationBase[]>} 如果 id 对应的对话不存在则返回 null
25942 */
25943 ;
25944 _proto.getConversations =
25945 /*#__PURE__*/
25946 function () {
25947 var _getConversations = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee13(ids) {
25948 var _this9 = this;
25949 var noCache,
25950 remoteConversationIds,
25951 remoteTemporaryConversationIds,
25952 query,
25953 remoteTemporaryConversationsPromise,
25954 _args13 = arguments;
25955 return regenerator.wrap(function _callee13$(_context13) {
25956 while (1) switch (_context13.prev = _context13.next) {
25957 case 0:
25958 noCache = _args13.length > 1 && _args13[1] !== undefined ? _args13[1] : false;
25959 remoteConversationIds = noCache ? ids : ids.filter(function (id) {
25960 return _this9._conversationCache.get(id) === null;
25961 });
25962 if (!remoteConversationIds.length) {
25963 _context13.next = 9;
25964 break;
25965 }
25966 remoteTemporaryConversationIds = remove_1(remoteConversationIds, isTemporaryConversatrionId);
25967 query = [];
25968 if (remoteConversationIds.length) {
25969 query.push(this.getQuery().containedIn('objectId', remoteConversationIds).limit(999).find());
25970 }
25971 if (remoteTemporaryConversationIds.length) {
25972 remoteTemporaryConversationsPromise = remoteTemporaryConversationIds.map(this._getTemporaryConversations.bind(this));
25973 query.push.apply(query, _toConsumableArray$1(remoteTemporaryConversationsPromise));
25974 }
25975 _context13.next = 9;
25976 return Promise.all(query);
25977 case 9:
25978 return _context13.abrupt("return", ids.map(function (id) {
25979 return _this9._conversationCache.get(id);
25980 }));
25981 case 10:
25982 case "end":
25983 return _context13.stop();
25984 }
25985 }, _callee13, this);
25986 }));
25987 function getConversations(_x14) {
25988 return _getConversations.apply(this, arguments);
25989 }
25990 return getConversations;
25991 }();
25992 _proto._getTemporaryConversations = /*#__PURE__*/function () {
25993 var _getTemporaryConversations2 = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee14(ids) {
25994 var command, resCommand;
25995 return regenerator.wrap(function _callee14$(_context14) {
25996 while (1) switch (_context14.prev = _context14.next) {
25997 case 0:
25998 command = new GenericCommand({
25999 cmd: 'conv',
26000 op: 'query',
26001 convMessage: new ConvCommand({
26002 tempConvIds: ids
26003 })
26004 });
26005 _context14.next = 3;
26006 return this._send(command);
26007 case 3:
26008 resCommand = _context14.sent;
26009 return _context14.abrupt("return", this._handleQueryResults(resCommand));
26010 case 5:
26011 case "end":
26012 return _context14.stop();
26013 }
26014 }, _callee14, this);
26015 }));
26016 function _getTemporaryConversations(_x15) {
26017 return _getTemporaryConversations2.apply(this, arguments);
26018 }
26019 return _getTemporaryConversations;
26020 }()
26021 /**
26022 * 构造一个 ConversationQuery 来查询对话
26023 * @return {ConversationQuery.<PersistentConversation>}
26024 */
26025 ;
26026 _proto.getQuery = function getQuery() {
26027 return new ConversationQuery(this);
26028 }
26029
26030 /**
26031 * 构造一个 ConversationQuery 来查询聊天室
26032 * @return {ConversationQuery.<ChatRoom>}
26033 */;
26034 _proto.getChatRoomQuery = function getChatRoomQuery() {
26035 return this.getQuery().equalTo('tr', true);
26036 }
26037
26038 /**
26039 * 构造一个 ConversationQuery 来查询服务号
26040 * @return {ConversationQuery.<ServiceConversation>}
26041 */;
26042 _proto.getServiceConversationQuery = function getServiceConversationQuery() {
26043 return this.getQuery().equalTo('sys', true);
26044 };
26045 _proto._executeQuery = /*#__PURE__*/function () {
26046 var _executeQuery2 = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee15(query) {
26047 var queryJSON, command, resCommand;
26048 return regenerator.wrap(function _callee15$(_context15) {
26049 while (1) switch (_context15.prev = _context15.next) {
26050 case 0:
26051 queryJSON = query.toJSON();
26052 queryJSON.where = new JsonObjectMessage({
26053 data: JSON.stringify(encode(queryJSON.where))
26054 });
26055 command = new GenericCommand({
26056 cmd: 'conv',
26057 op: 'query',
26058 convMessage: new ConvCommand(queryJSON)
26059 });
26060 _context15.next = 5;
26061 return this._send(command);
26062 case 5:
26063 resCommand = _context15.sent;
26064 return _context15.abrupt("return", this._handleQueryResults(resCommand));
26065 case 7:
26066 case "end":
26067 return _context15.stop();
26068 }
26069 }, _callee15, this);
26070 }));
26071 function _executeQuery(_x16) {
26072 return _executeQuery2.apply(this, arguments);
26073 }
26074 return _executeQuery;
26075 }();
26076 _proto._handleQueryResults = /*#__PURE__*/function () {
26077 var _handleQueryResults2 = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee16(resCommand) {
26078 var conversations, commandString;
26079 return regenerator.wrap(function _callee16$(_context16) {
26080 while (1) switch (_context16.prev = _context16.next) {
26081 case 0:
26082 _context16.prev = 0;
26083 conversations = decode(JSON.parse(resCommand.convMessage.results.data));
26084 _context16.next = 8;
26085 break;
26086 case 4:
26087 _context16.prev = 4;
26088 _context16.t0 = _context16["catch"](0);
26089 commandString = JSON.stringify(trim(resCommand));
26090 throw new Error("Parse query result failed: ".concat(_context16.t0.message, ". Command: ").concat(commandString));
26091 case 8:
26092 _context16.next = 10;
26093 return Promise.all(conversations.map(this._parseConversationFromRawData.bind(this)));
26094 case 10:
26095 conversations = _context16.sent;
26096 return _context16.abrupt("return", conversations.map(this._upsertConversationToCache.bind(this)));
26097 case 12:
26098 case "end":
26099 return _context16.stop();
26100 }
26101 }, _callee16, this, [[0, 4]]);
26102 }));
26103 function _handleQueryResults(_x17) {
26104 return _handleQueryResults2.apply(this, arguments);
26105 }
26106 return _handleQueryResults;
26107 }();
26108 _proto._upsertConversationToCache = function _upsertConversationToCache(fetchedConversation) {
26109 var conversation = this._conversationCache.get(fetchedConversation.id);
26110 if (!conversation) {
26111 conversation = fetchedConversation;
26112 this._debug('no match, set cache');
26113 this._conversationCache.set(fetchedConversation.id, fetchedConversation);
26114 } else {
26115 this._debug('update cached conversation');
26116 ['creator', 'createdAt', 'updatedAt', 'lastMessageAt', 'lastMessage', 'mutedMembers', 'members', '_attributes', 'transient', 'muted'].forEach(function (key) {
26117 var value = fetchedConversation[key];
26118 if (value !== undefined) conversation[key] = value;
26119 });
26120 if (conversation._reset) conversation._reset();
26121 }
26122 return conversation;
26123 }
26124
26125 /**
26126 * 反序列化消息,与 {@link Message#toFullJSON} 相对。
26127 * @param {Object}
26128 * @return {AVMessage} 解析后的消息
26129 * @since 4.0.0
26130 */;
26131 _proto.parseMessage =
26132 /*#__PURE__*/
26133 function () {
26134 var _parseMessage = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee17(_ref10) {
26135 var data, _ref10$bin, bin, properties, content, message;
26136 return regenerator.wrap(function _callee17$(_context17) {
26137 while (1) switch (_context17.prev = _context17.next) {
26138 case 0:
26139 data = _ref10.data, _ref10$bin = _ref10.bin, bin = _ref10$bin === void 0 ? false : _ref10$bin, properties = _objectWithoutProperties(_ref10, _excluded3);
26140 content = bin ? base64Arraybuffer_2(data) : data;
26141 _context17.next = 4;
26142 return this._messageParser.parse(content);
26143 case 4:
26144 message = _context17.sent;
26145 Object.assign(message, properties);
26146 message._updateMentioned(this.id);
26147 return _context17.abrupt("return", message);
26148 case 8:
26149 case "end":
26150 return _context17.stop();
26151 }
26152 }, _callee17, this);
26153 }));
26154 function parseMessage(_x18) {
26155 return _parseMessage.apply(this, arguments);
26156 }
26157 return parseMessage;
26158 }()
26159 /**
26160 * 反序列化对话,与 {@link Conversation#toFullJSON} 相对。
26161 * @param {Object}
26162 * @return {ConversationBase} 解析后的对话
26163 * @since 4.0.0
26164 */
26165 ;
26166 _proto.parseConversation =
26167 /*#__PURE__*/
26168 function () {
26169 var _parseConversation = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee18(_ref11) {
26170 var id, lastMessageAt, lastMessage, lastDeliveredAt, lastReadAt, unreadMessagesCount, members, mentioned, properties, conversationData, _transient2, system, expiredAt;
26171 return regenerator.wrap(function _callee18$(_context18) {
26172 while (1) switch (_context18.prev = _context18.next) {
26173 case 0:
26174 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);
26175 conversationData = {
26176 id: id,
26177 lastMessageAt: lastMessageAt,
26178 lastMessage: lastMessage,
26179 lastDeliveredAt: lastDeliveredAt,
26180 lastReadAt: lastReadAt,
26181 unreadMessagesCount: unreadMessagesCount,
26182 members: members,
26183 mentioned: mentioned
26184 };
26185 if (!lastMessage) {
26186 _context18.next = 7;
26187 break;
26188 }
26189 _context18.next = 5;
26190 return this.parseMessage(lastMessage);
26191 case 5:
26192 conversationData.lastMessage = _context18.sent;
26193 conversationData.lastMessage._setStatus(MessageStatus.SENT);
26194 case 7:
26195 _transient2 = properties["transient"], system = properties.system, expiredAt = properties.expiredAt;
26196 if (!_transient2) {
26197 _context18.next = 10;
26198 break;
26199 }
26200 return _context18.abrupt("return", new ChatRoom(conversationData, properties, this));
26201 case 10:
26202 if (!system) {
26203 _context18.next = 12;
26204 break;
26205 }
26206 return _context18.abrupt("return", new ServiceConversation(conversationData, properties, this));
26207 case 12:
26208 if (!(expiredAt || isTemporaryConversatrionId(id))) {
26209 _context18.next = 14;
26210 break;
26211 }
26212 return _context18.abrupt("return", new TemporaryConversation(conversationData, {
26213 expiredAt: expiredAt
26214 }, this));
26215 case 14:
26216 return _context18.abrupt("return", new Conversation(conversationData, properties, this));
26217 case 15:
26218 case "end":
26219 return _context18.stop();
26220 }
26221 }, _callee18, this);
26222 }));
26223 function parseConversation(_x19) {
26224 return _parseConversation.apply(this, arguments);
26225 }
26226 return parseConversation;
26227 }();
26228 _proto._parseConversationFromRawData = /*#__PURE__*/function () {
26229 var _parseConversationFromRawData2 = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee19(rawData) {
26230 var data, ttl;
26231 return regenerator.wrap(function _callee19$(_context19) {
26232 while (1) switch (_context19.prev = _context19.next) {
26233 case 0:
26234 data = keyRemap({
26235 objectId: 'id',
26236 lm: 'lastMessageAt',
26237 m: 'members',
26238 tr: 'transient',
26239 sys: 'system',
26240 c: 'creator',
26241 mu: 'mutedMembers'
26242 }, rawData);
26243 if (data.msg) {
26244 data.lastMessage = {
26245 data: data.msg,
26246 bin: data.bin,
26247 from: data.msg_from,
26248 id: data.msg_mid,
26249 timestamp: data.msg_timestamp,
26250 updatedAt: data.patch_timestamp
26251 };
26252 delete data.lastMessageFrom;
26253 delete data.lastMessageId;
26254 delete data.lastMessageTimestamp;
26255 delete data.lastMessagePatchTimestamp;
26256 }
26257 ttl = data.ttl;
26258 if (ttl) data.expiredAt = Date.now() + ttl * 1000;
26259 return _context19.abrupt("return", this.parseConversation(data));
26260 case 5:
26261 case "end":
26262 return _context19.stop();
26263 }
26264 }, _callee19, this);
26265 }));
26266 function _parseConversationFromRawData(_x20) {
26267 return _parseConversationFromRawData2.apply(this, arguments);
26268 }
26269 return _parseConversationFromRawData;
26270 }()
26271 /**
26272 * 创建一个对话
26273 * @param {Object} options 除了下列字段外的其他字段将被视为对话的自定义属性
26274 * @param {String[]} options.members 对话的初始成员列表,默认包含当前 client
26275 * @param {String} [options.name] 对话的名字
26276 * @param {Boolean} [options.unique=true] 唯一对话,当其为 true 时,如果当前已经有相同成员的对话存在则返回该对话,否则会创建新的对话
26277 * @return {Promise.<Conversation>}
26278 */
26279 ;
26280 _proto.createConversation =
26281 /*#__PURE__*/
26282 function () {
26283 var _createConversation = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee20() {
26284 var _ref12,
26285 m,
26286 name,
26287 _transient3,
26288 _ref12$unique,
26289 unique,
26290 tempConv,
26291 tempConvTTL,
26292 properties,
26293 members,
26294 attr,
26295 startCommandJson,
26296 command,
26297 params,
26298 signatureResult,
26299 _yield$this$_send,
26300 _yield$this$_send$con,
26301 cid,
26302 cdate,
26303 ttl,
26304 data,
26305 conversation,
26306 _args20 = arguments;
26307 return regenerator.wrap(function _callee20$(_context20) {
26308 while (1) switch (_context20.prev = _context20.next) {
26309 case 0:
26310 _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);
26311 if (_transient3 || Array.isArray(m)) {
26312 _context20.next = 3;
26313 break;
26314 }
26315 throw new TypeError("conversation members ".concat(m, " is not an array"));
26316 case 3:
26317 members = new Set(m);
26318 members.add(this.id);
26319 members = Array.from(members).sort();
26320 attr = properties || {};
26321 if (!name) {
26322 _context20.next = 11;
26323 break;
26324 }
26325 if (!(typeof name !== 'string')) {
26326 _context20.next = 10;
26327 break;
26328 }
26329 throw new TypeError("conversation name ".concat(name, " is not a string"));
26330 case 10:
26331 attr.name = name;
26332 case 11:
26333 attr = new JsonObjectMessage({
26334 data: JSON.stringify(encode(attr))
26335 });
26336 startCommandJson = {
26337 m: members,
26338 attr: attr,
26339 "transient": _transient3,
26340 unique: unique,
26341 tempConv: tempConv,
26342 tempConvTTL: tempConvTTL
26343 };
26344 command = new GenericCommand({
26345 cmd: 'conv',
26346 op: 'start',
26347 convMessage: new ConvCommand(startCommandJson)
26348 });
26349 if (!this.options.conversationSignatureFactory) {
26350 _context20.next = 20;
26351 break;
26352 }
26353 params = [null, this._identity, members, 'create'];
26354 _context20.next = 18;
26355 return runSignatureFactory(this.options.conversationSignatureFactory, params);
26356 case 18:
26357 signatureResult = _context20.sent;
26358 Object.assign(command.convMessage, keyRemap({
26359 signature: 's',
26360 timestamp: 't',
26361 nonce: 'n'
26362 }, signatureResult));
26363 case 20:
26364 _context20.next = 22;
26365 return this._send(command);
26366 case 22:
26367 _yield$this$_send = _context20.sent;
26368 _yield$this$_send$con = _yield$this$_send.convMessage;
26369 cid = _yield$this$_send$con.cid;
26370 cdate = _yield$this$_send$con.cdate;
26371 ttl = _yield$this$_send$con.tempConvTTL;
26372 data = _objectSpread$8({
26373 name: name,
26374 "transient": _transient3,
26375 unique: unique,
26376 id: cid,
26377 createdAt: cdate,
26378 updatedAt: cdate,
26379 lastMessageAt: null,
26380 creator: this.id,
26381 members: _transient3 ? [] : members
26382 }, properties);
26383 if (ttl) data.expiredAt = Date.now() + ttl * 1000;
26384 _context20.next = 31;
26385 return this.parseConversation(data);
26386 case 31:
26387 conversation = _context20.sent;
26388 return _context20.abrupt("return", this._upsertConversationToCache(conversation));
26389 case 33:
26390 case "end":
26391 return _context20.stop();
26392 }
26393 }, _callee20, this);
26394 }));
26395 function createConversation() {
26396 return _createConversation.apply(this, arguments);
26397 }
26398 return createConversation;
26399 }()
26400 /**
26401 * 创建一个聊天室
26402 * @since 4.0.0
26403 * @param {Object} options 除了下列字段外的其他字段将被视为对话的自定义属性
26404 * @param {String} [options.name] 对话的名字
26405 * @return {Promise.<ChatRoom>}
26406 */
26407 ;
26408 _proto.createChatRoom =
26409 /*#__PURE__*/
26410 function () {
26411 var _createChatRoom = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee21(param) {
26412 return regenerator.wrap(function _callee21$(_context21) {
26413 while (1) switch (_context21.prev = _context21.next) {
26414 case 0:
26415 return _context21.abrupt("return", this.createConversation(_objectSpread$8(_objectSpread$8({}, param), {}, {
26416 "transient": true,
26417 members: null,
26418 unique: false,
26419 _tempConv: false
26420 })));
26421 case 1:
26422 case "end":
26423 return _context21.stop();
26424 }
26425 }, _callee21, this);
26426 }));
26427 function createChatRoom(_x21) {
26428 return _createChatRoom.apply(this, arguments);
26429 }
26430 return createChatRoom;
26431 }()
26432 /**
26433 * 创建一个临时对话
26434 * @since 4.0.0
26435 * @param {Object} options
26436 * @param {String[]} options.members 对话的初始成员列表,默认包含当前 client
26437 * @param {String} [options.ttl] 对话存在时间,单位为秒,最大值与默认值均为 86400(一天),过期后该对话不再可用。
26438 * @return {Promise.<TemporaryConversation>}
26439 */
26440 ;
26441 _proto.createTemporaryConversation =
26442 /*#__PURE__*/
26443 function () {
26444 var _createTemporaryConversation = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee22(_ref13) {
26445 var _tempConvTTL, param;
26446 return regenerator.wrap(function _callee22$(_context22) {
26447 while (1) switch (_context22.prev = _context22.next) {
26448 case 0:
26449 _tempConvTTL = _ref13.ttl, param = _objectWithoutProperties(_ref13, _excluded6);
26450 return _context22.abrupt("return", this.createConversation(_objectSpread$8(_objectSpread$8({}, param), {}, {
26451 _tempConv: true,
26452 _tempConvTTL: _tempConvTTL
26453 })));
26454 case 2:
26455 case "end":
26456 return _context22.stop();
26457 }
26458 }, _callee22, this);
26459 }));
26460 function createTemporaryConversation(_x22) {
26461 return _createTemporaryConversation.apply(this, arguments);
26462 }
26463 return createTemporaryConversation;
26464 }() // jsdoc-ignore-start
26465 ;
26466 _proto.
26467 // jsdoc-ignore-end
26468 _doSendRead = function _doSendRead() {
26469 var _this10 = this;
26470 // if not connected, just skip everything
26471 if (!this._connection.is('connected')) return;
26472 var buffer = internal(this).readConversationsBuffer;
26473 var conversations = Array.from(buffer);
26474 if (!conversations.length) return;
26475 var ids = conversations.map(function (conversation) {
26476 if (!(conversation instanceof ConversationBase)) {
26477 throw new TypeError("".concat(conversation, " is not a Conversation"));
26478 }
26479 return conversation.id;
26480 });
26481 this._debug("mark [".concat(ids, "] as read"));
26482 buffer.clear();
26483 this._sendReadCommand(conversations)["catch"](function (error) {
26484 _this10._debug('send read failed: %O', error);
26485 conversations.forEach(buffer.add.bind(buffer));
26486 });
26487 };
26488 _proto._sendReadCommand = function _sendReadCommand(conversations) {
26489 var _this11 = this;
26490 return this._send(new GenericCommand({
26491 cmd: 'read',
26492 readMessage: new ReadCommand({
26493 convs: conversations.map(function (conversation) {
26494 return new ReadTuple({
26495 cid: conversation.id,
26496 mid: conversation.lastMessage && conversation.lastMessage.from !== _this11.id ? conversation.lastMessage.id : undefined,
26497 timestamp: (conversation.lastMessageAt || new Date()).getTime()
26498 });
26499 })
26500 })
26501 }), false);
26502 };
26503 return IMClient;
26504 }(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));
26505 /**
26506 * 修改、撤回消息的原因
26507 * @typedef PatchReason
26508 * @type {Object}
26509 * @property {number} code 负数为内置 code,正数为开发者在 hook 中自定义的 code。比如因为敏感词过滤被修改的 code 为 -4408。
26510 * @property {string} [detail] 具体的原因说明。
26511 */
26512
26513 var RECONNECT_ERROR = 'reconnecterror';
26514
26515 var CoreEvent = /*#__PURE__*/Object.freeze({
26516 __proto__: null,
26517 RECONNECT_ERROR: RECONNECT_ERROR,
26518 DISCONNECT: DISCONNECT,
26519 RECONNECT: RECONNECT,
26520 RETRY: RETRY,
26521 SCHEDULE: SCHEDULE,
26522 OFFLINE: OFFLINE,
26523 ONLINE: ONLINE
26524 });
26525
26526 var _class$4;
26527 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; }
26528 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; }
26529 // jsdoc-ignore-start
26530 var BinaryMessage = IE10Compatible(_class$4 = /*#__PURE__*/function (_Message) {
26531 _inheritsLoose(BinaryMessage, _Message);
26532 /**
26533 * 二进制消息
26534 * @extends Message
26535 * @param {ArrayBuffer} buffer
26536 * @since 4.0.0
26537 */
26538 function BinaryMessage(buffer) {
26539 if (!(buffer instanceof ArrayBuffer)) {
26540 throw new TypeError("".concat(buffer, " is not an ArrayBuffer"));
26541 }
26542 return _Message.call(this, buffer) || this;
26543 }
26544
26545 /**
26546 * @type ArrayBuffer
26547 */
26548 BinaryMessage.validate = function validate(target) {
26549 return target instanceof ArrayBuffer;
26550 };
26551 var _proto = BinaryMessage.prototype;
26552 _proto.toJSON = function toJSON() {
26553 return _objectSpread$9(_objectSpread$9({}, _Message.prototype._toJSON.call(this)), {}, {
26554 data: base64Arraybuffer_1(this.content)
26555 });
26556 };
26557 _proto.toFullJSON = function toFullJSON() {
26558 return _objectSpread$9(_objectSpread$9({}, _Message.prototype.toFullJSON.call(this)), {}, {
26559 bin: true,
26560 data: base64Arraybuffer_1(this.content)
26561 });
26562 };
26563 _createClass(BinaryMessage, [{
26564 key: "buffer",
26565 get: function get() {
26566 return this.content;
26567 },
26568 set: function set(buffer) {
26569 this.content = buffer;
26570 }
26571 }]);
26572 return BinaryMessage;
26573 }(Message)) || _class$4;
26574
26575 var _dec$3, _class$5;
26576
26577 // jsdoc-ignore-start
26578 var TextMessage = (_dec$3 = messageType(-1), _dec$3(_class$5 = IE10Compatible(_class$5 = /*#__PURE__*/function (_TypedMessage) {
26579 _inheritsLoose(TextMessage, _TypedMessage);
26580 /**
26581 * 文类类型消息
26582 * @extends TypedMessage
26583 * @param {String} [text='']
26584 * @throws {TypeError} text 不是 String 类型
26585 */
26586 function TextMessage() {
26587 var _this;
26588 var text = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
26589 if (typeof text !== 'string') {
26590 throw new TypeError("".concat(text, " is not a string"));
26591 }
26592 _this = _TypedMessage.call(this) || this;
26593 _this.setText(text);
26594 return _this;
26595 }
26596 return TextMessage;
26597 }(TypedMessage)) || _class$5) || _class$5);
26598 /**
26599 * @name TYPE
26600 * @memberof TextMessage
26601 * @type Number
26602 * @static
26603 * @const
26604 */
26605
26606 var _class$6;
26607 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; }
26608 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; }
26609 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; } } }; }
26610 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); }
26611 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; }
26612 var debug$c = browser('LC:MessageParser');
26613 var tryParseJson = function tryParseJson(target, key, descriptor) {
26614 var fn = descriptor.value;
26615 // eslint-disable-next-line no-param-reassign
26616 descriptor.value = function wrapper(param) {
26617 var content;
26618 if (typeof param !== 'string') {
26619 content = param;
26620 } else {
26621 try {
26622 content = JSON.parse(param);
26623 } catch (error) {
26624 content = param;
26625 }
26626 }
26627 return fn.call(this, content);
26628 };
26629 };
26630 var applyPlugins = function applyPlugins(target, key, descriptor) {
26631 var fn = descriptor.value;
26632 // eslint-disable-next-line no-param-reassign
26633 descriptor.value = function wrapper(json) {
26634 var _this = this;
26635 return Promise.resolve(json).then(applyMiddlewares(this._plugins.beforeMessageParse)).then(function (decoratedJson) {
26636 return fn.call(_this, decoratedJson);
26637 }).then(applyMiddlewares(this._plugins.afterMessageParse));
26638 };
26639 };
26640 var MessageParser = (_class$6 = /*#__PURE__*/function () {
26641 /**
26642 * 消息解析器
26643 * @param {Object} plugins 插件,插件的 messageClasses 会自动被注册,在解析时 beforeMessageParse 与 afterMessageParse Middleware 会被应用。
26644 */
26645 function MessageParser() {
26646 var plugins = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
26647 this._plugins = plugins;
26648 this._messageClasses = [];
26649 this.register(plugins.messageClasses);
26650 }
26651
26652 /**
26653 * 注册消息类
26654 *
26655 * @param {Function | Function[]} messageClass 消息类,需要实现 {@link AVMessage} 接口,
26656 * 建议继承自 {@link TypedMessage},也可以传入一个消息类数组。
26657 * @throws {TypeError} 如果 messageClass 没有实现 {@link AVMessage} 接口则抛出异常
26658 */
26659 var _proto = MessageParser.prototype;
26660 _proto.register = function register(messageClasses) {
26661 var _this2 = this;
26662 ensureArray(messageClasses).map(function (klass) {
26663 return _this2._register(klass);
26664 });
26665 };
26666 _proto._register = function _register(messageClass) {
26667 if (messageClass && messageClass.parse && messageClass.prototype && messageClass.prototype.getPayload) {
26668 this._messageClasses.unshift(messageClass);
26669 } else {
26670 throw new TypeError('Invalid messageClass');
26671 }
26672 }
26673
26674 // jsdoc-ignore-start
26675 ;
26676 _proto.
26677 // jsdoc-ignore-end
26678 /**
26679 * 解析消息内容
26680 * @param {Object | string | any} target 消息内容,如果是字符串会尝试 parse 为 JSON。
26681 * @return {AVMessage} 解析后的消息
26682 * @throws {Error} 如果不匹配任何注册的消息则抛出异常
26683 */
26684 parse = function parse(content) {
26685 debug$c('parsing message: %O', content);
26686 // eslint-disable-next-line
26687 var _iterator = _createForOfIteratorHelper(this._messageClasses),
26688 _step;
26689 try {
26690 for (_iterator.s(); !(_step = _iterator.n()).done;) {
26691 var Klass = _step.value;
26692 var contentCopy = isPlainObject_1(content) ? _objectSpread$a({}, content) : content;
26693 var valid = void 0;
26694 var result = void 0;
26695 try {
26696 valid = Klass.validate(contentCopy);
26697 } catch (error) {
26698 // eslint-disable-line no-empty
26699 }
26700 if (valid) {
26701 try {
26702 result = Klass.parse(contentCopy);
26703 } catch (error) {
26704 console.warn('parsing a valid message content error', {
26705 error: error,
26706 Klass: Klass,
26707 content: contentCopy
26708 });
26709 }
26710 if (result !== undefined) {
26711 debug$c('parse result: %O', result);
26712 return result;
26713 }
26714 }
26715 }
26716 } catch (err) {
26717 _iterator.e(err);
26718 } finally {
26719 _iterator.f();
26720 }
26721 throw new Error('No Message Class matched');
26722 };
26723 return MessageParser;
26724 }(), (_applyDecoratedDescriptor(_class$6.prototype, "parse", [tryParseJson, applyPlugins], Object.getOwnPropertyDescriptor(_class$6.prototype, "parse"), _class$6.prototype)), _class$6);
26725
26726 var _excluded$4 = ["tag", "isReconnect"];
26727 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; }
26728 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; }
26729 var debug$d = browser('LC:IMPlugin');
26730
26731 /**
26732 * 消息优先级枚举
26733 * @enum {Number}
26734 * @since 3.3.0
26735 */
26736 var MessagePriority = {
26737 /** 高 */
26738 HIGH: 1,
26739 /** 普通 */
26740 NORMAL: 2,
26741 /** 低 */
26742 LOW: 3
26743 };
26744 Object.freeze(MessagePriority);
26745
26746 /**
26747 * 为 Conversation 定义一个新属性
26748 * @param {String} prop 属性名
26749 * @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
26750 * @returns void
26751 * @example
26752 *
26753 * conversation.get('type');
26754 * conversation.set('type', 1);
26755 *
26756 * // equals to
26757 * defineConversationProperty('type');
26758 * conversation.type;
26759 * conversation.type = 1;
26760 */
26761 var defineConversationProperty = function defineConversationProperty(prop) {
26762 var descriptor = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {
26763 get: function get() {
26764 return this.get(prop);
26765 },
26766 set: function set(value) {
26767 this.set(prop, value);
26768 }
26769 };
26770 Object.defineProperty(Conversation.prototype, prop, descriptor);
26771 };
26772 var onRealtimeCreate = function onRealtimeCreate(realtime) {
26773 /* eslint-disable no-param-reassign */
26774 var deviceId = v4_1();
26775 realtime._IMClients = {};
26776 realtime._IMClientsCreationCount = 0;
26777 var messageParser = new MessageParser(realtime._plugins);
26778 realtime._messageParser = messageParser;
26779 var signAVUser = /*#__PURE__*/function () {
26780 var _ref = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee(user) {
26781 return regenerator.wrap(function _callee$(_context) {
26782 while (1) switch (_context.prev = _context.next) {
26783 case 0:
26784 return _context.abrupt("return", realtime._request({
26785 method: 'POST',
26786 path: '/rtm/sign',
26787 data: {
26788 session_token: user.getSessionToken()
26789 }
26790 }));
26791 case 1:
26792 case "end":
26793 return _context.stop();
26794 }
26795 }, _callee);
26796 }));
26797 return function signAVUser(_x) {
26798 return _ref.apply(this, arguments);
26799 };
26800 }();
26801
26802 /**
26803 * 注册消息类
26804 *
26805 * 在接收消息、查询消息时,会按照消息类注册顺序的逆序依次尝试解析消息内容
26806 *
26807 * @memberof Realtime
26808 * @instance
26809 * @param {Function | Function[]} messageClass 消息类,需要实现 {@link AVMessage} 接口,
26810 * 建议继承自 {@link TypedMessage}
26811 * @throws {TypeError} 如果 messageClass 没有实现 {@link AVMessage} 接口则抛出异常
26812 */
26813 var register = messageParser.register.bind(messageParser);
26814 /**
26815 * 创建一个即时通讯客户端,多次创建相同 id 的客户端会返回同一个实例
26816 * @memberof Realtime
26817 * @instance
26818 * @param {String|AV.User} [identity] 客户端 identity,如果不指定该参数,服务端会随机生成一个字符串作为 identity,
26819 * 如果传入一个已登录的 AV.User,则会使用该用户的 id 作为客户端 identity 登录。
26820 * @param {Object} [options]
26821 * @param {Function} [options.signatureFactory] open session 时的签名方法 // TODO need details
26822 * @param {Function} [options.conversationSignatureFactory] 对话创建、增减成员操作时的签名方法
26823 * @param {Function} [options.blacklistSignatureFactory] 黑名单操作时的签名方法
26824 * @param {String} [options.tag] 客户端类型标记,以支持单点登录功能
26825 * @param {String} [options.isReconnect=false] 单点登录时标记该次登录是不是应用启动时自动重新登录
26826 * @return {Promise.<IMClient>}
26827 */
26828 var createIMClient = /*#__PURE__*/function () {
26829 var _ref2 = _asyncToGenerator( /*#__PURE__*/regenerator.mark(function _callee2(identity) {
26830 var _realtime$_open$then;
26831 var _ref3,
26832 tag,
26833 isReconnect,
26834 clientOptions,
26835 lagecyTag,
26836 id,
26837 buildinOptions,
26838 sessionToken,
26839 _tag,
26840 promise,
26841 _args2 = arguments;
26842 return regenerator.wrap(function _callee2$(_context2) {
26843 while (1) switch (_context2.prev = _context2.next) {
26844 case 0:
26845 _ref3 = _args2.length > 1 && _args2[1] !== undefined ? _args2[1] : {}, tag = _ref3.tag, isReconnect = _ref3.isReconnect, clientOptions = _objectWithoutProperties(_ref3, _excluded$4);
26846 lagecyTag = _args2.length > 2 ? _args2[2] : undefined;
26847 buildinOptions = {};
26848 if (!identity) {
26849 _context2.next = 19;
26850 break;
26851 }
26852 if (!(typeof identity === 'string')) {
26853 _context2.next = 8;
26854 break;
26855 }
26856 id = identity;
26857 _context2.next = 17;
26858 break;
26859 case 8:
26860 if (!(identity.id && identity.getSessionToken)) {
26861 _context2.next = 16;
26862 break;
26863 }
26864 id = identity.id;
26865 sessionToken = identity.getSessionToken();
26866 if (sessionToken) {
26867 _context2.next = 13;
26868 break;
26869 }
26870 throw new Error('User must be authenticated');
26871 case 13:
26872 buildinOptions.signatureFactory = signAVUser;
26873 _context2.next = 17;
26874 break;
26875 case 16:
26876 throw new TypeError('Identity must be a String or an AV.User');
26877 case 17:
26878 if (!(realtime._IMClients[id] !== undefined)) {
26879 _context2.next = 19;
26880 break;
26881 }
26882 return _context2.abrupt("return", realtime._IMClients[id]);
26883 case 19:
26884 if (lagecyTag) {
26885 console.warn('DEPRECATION createIMClient tag param: Use options.tag instead.');
26886 }
26887 _tag = tag || lagecyTag;
26888 promise = (_realtime$_open$then = realtime._open().then(function (connection) {
26889 var client = new IMClient(id, _objectSpread$b(_objectSpread$b({}, buildinOptions), clientOptions), {
26890 _connection: connection,
26891 _request: realtime._request.bind(realtime),
26892 _messageParser: messageParser,
26893 _plugins: realtime._plugins,
26894 _identity: identity
26895 });
26896 connection.on(RECONNECT, function () {
26897 return client._open(realtime._options.appId, _tag, deviceId, true)
26898 /**
26899 * 客户端连接恢复正常,该事件通常在 {@link Realtime#event:RECONNECT} 之后发生
26900 * @event IMClient#RECONNECT
26901 * @see Realtime#event:RECONNECT
26902 * @since 3.2.0
26903 */
26904 /**
26905 * 客户端重新登录发生错误(网络连接已恢复,但重新登录错误)
26906 * @event IMClient#RECONNECT_ERROR
26907 * @since 3.2.0
26908 */.then(function () {
26909 return client.emit(RECONNECT);
26910 }, function (error) {
26911 return client.emit(RECONNECT_ERROR, error);
26912 });
26913 });
26914 internal(client)._eventemitter.on('beforeclose', function () {
26915 delete realtime._IMClients[client.id];
26916 if (realtime._firstIMClient === client) {
26917 delete realtime._firstIMClient;
26918 }
26919 }, realtime);
26920 internal(client)._eventemitter.on('close', function () {
26921 realtime._deregister(client);
26922 }, realtime);
26923 return client._open(realtime._options.appId, _tag, deviceId, isReconnect).then(function () {
26924 realtime._IMClients[client.id] = client;
26925 realtime._IMClientsCreationCount += 1;
26926 if (realtime._IMClientsCreationCount === 1) {
26927 client._omitPeerId(true);
26928 realtime._firstIMClient = client;
26929 } else if (realtime._IMClientsCreationCount > 1 && realtime._firstIMClient) {
26930 realtime._firstIMClient._omitPeerId(false);
26931 }
26932 realtime._register(client);
26933 return client;
26934 })["catch"](function (error) {
26935 delete realtime._IMClients[client.id];
26936 throw error;
26937 });
26938 })).then.apply(_realtime$_open$then, _toConsumableArray$1(finalize(function () {
26939 realtime._deregisterPending(promise);
26940 })))["catch"](function (error) {
26941 delete realtime._IMClients[id];
26942 throw error;
26943 });
26944 if (identity) {
26945 realtime._IMClients[id] = promise;
26946 }
26947 realtime._registerPending(promise);
26948 return _context2.abrupt("return", promise);
26949 case 25:
26950 case "end":
26951 return _context2.stop();
26952 }
26953 }, _callee2);
26954 }));
26955 return function createIMClient(_x2) {
26956 return _ref2.apply(this, arguments);
26957 };
26958 }();
26959 Object.assign(realtime, {
26960 register: register,
26961 createIMClient: createIMClient
26962 });
26963 /* eslint-enable no-param-reassign */
26964 };
26965
26966 var beforeCommandDispatch = function beforeCommandDispatch(command, realtime) {
26967 var isIMCommand = command.service === null || command.service === 2;
26968 if (!isIMCommand) return true;
26969 var targetClient = command.peerId ? realtime._IMClients[command.peerId] : realtime._firstIMClient;
26970 if (targetClient) {
26971 Promise.resolve(targetClient).then(function (client) {
26972 return client._dispatchCommand(command);
26973 })["catch"](debug$d);
26974 } else {
26975 debug$d('[WARN] Unexpected message received without any live client match: %O', trim(command));
26976 }
26977 return false;
26978 };
26979 var IMPlugin = {
26980 name: 'leancloud-realtime-plugin-im',
26981 onRealtimeCreate: onRealtimeCreate,
26982 beforeCommandDispatch: beforeCommandDispatch,
26983 messageClasses: [Message, BinaryMessage, RecalledMessage, TextMessage]
26984 };
26985
26986 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; }
26987 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; }
26988 Realtime.defineConversationProperty = defineConversationProperty;
26989 Realtime.__preRegisteredPlugins = [IMPlugin];
26990 var Event = _objectSpread$c(_objectSpread$c({}, CoreEvent), IMEvent);
26991
26992 /** core + plugins + platform adapters */
26993 setAdapters({
26994 WebSocket: lib_4,
26995 request: lib_1$1
26996 });
26997
26998 exports.BinaryMessage = BinaryMessage;
26999 exports.ChatRoom = ChatRoom;
27000 exports.Conversation = Conversation;
27001 exports.ConversationMemberRole = ConversationMemberRole;
27002 exports.ConversationQuery = ConversationQuery;
27003 exports.ErrorCode = ErrorCode;
27004 exports.Event = Event;
27005 exports.EventEmitter = eventemitter3;
27006 exports.IE10Compatible = IE10Compatible;
27007 exports.IMPlugin = IMPlugin;
27008 exports.Message = Message;
27009 exports.MessageParser = MessageParser;
27010 exports.MessagePriority = MessagePriority;
27011 exports.MessageQueryDirection = MessageQueryDirection;
27012 exports.MessageStatus = MessageStatus;
27013 exports.Promise = polyfilledPromise;
27014 exports.Protocals = message;
27015 exports.Protocols = message;
27016 exports.Realtime = Realtime;
27017 exports.RecalledMessage = RecalledMessage;
27018 exports.ServiceConversation = ServiceConversation;
27019 exports.TemporaryConversation = TemporaryConversation;
27020 exports.TextMessage = TextMessage;
27021 exports.TypedMessage = TypedMessage;
27022 exports.debug = debug$2;
27023 exports.defineConversationProperty = defineConversationProperty;
27024 exports.getAdapter = getAdapter;
27025 exports.messageField = messageField;
27026 exports.messageType = messageType;
27027 exports.setAdapters = setAdapters;
27028
27029 Object.defineProperty(exports, '__esModule', { value: true });
27030
27031})));
27032//# sourceMappingURL=im-browser.js.map