UNPKG

612 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 window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
16
17 function commonjsRequire () {
18 throw new Error('Dynamic requires are not currently supported by rollup-plugin-commonjs');
19 }
20
21 function createCommonjsModule(fn, module) {
22 return module = { exports: {} }, fn(module, module.exports), module.exports;
23 }
24
25 var long_1 = createCommonjsModule(function (module) {
26 /*
27 Copyright 2013 Daniel Wirtz <dcode@dcode.io>
28 Copyright 2009 The Closure Library Authors. All Rights Reserved.
29
30 Licensed under the Apache License, Version 2.0 (the "License");
31 you may not use this file except in compliance with the License.
32 You may obtain a copy of the License at
33
34 http://www.apache.org/licenses/LICENSE-2.0
35
36 Unless required by applicable law or agreed to in writing, software
37 distributed under the License is distributed on an "AS-IS" BASIS,
38 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
39 See the License for the specific language governing permissions and
40 limitations under the License.
41 */
42
43 /**
44 * @license long.js (c) 2013 Daniel Wirtz <dcode@dcode.io>
45 * Released under the Apache License, Version 2.0
46 * see: https://github.com/dcodeIO/long.js for details
47 */
48 (function(global, factory) {
49
50 /* AMD */ if (typeof commonjsRequire === 'function' && 'object' === "object" && module && module["exports"])
51 module["exports"] = factory();
52 /* Global */ else
53 (global["dcodeIO"] = global["dcodeIO"] || {})["Long"] = factory();
54
55 })(commonjsGlobal, function() {
56
57 /**
58 * Constructs a 64 bit two's-complement integer, given its low and high 32 bit values as *signed* integers.
59 * See the from* functions below for more convenient ways of constructing Longs.
60 * @exports Long
61 * @class A Long class for representing a 64 bit two's-complement integer value.
62 * @param {number} low The low (signed) 32 bits of the long
63 * @param {number} high The high (signed) 32 bits of the long
64 * @param {boolean=} unsigned Whether unsigned or not, defaults to `false` for signed
65 * @constructor
66 */
67 function Long(low, high, unsigned) {
68
69 /**
70 * The low 32 bits as a signed value.
71 * @type {number}
72 */
73 this.low = low | 0;
74
75 /**
76 * The high 32 bits as a signed value.
77 * @type {number}
78 */
79 this.high = high | 0;
80
81 /**
82 * Whether unsigned or not.
83 * @type {boolean}
84 */
85 this.unsigned = !!unsigned;
86 }
87
88 // The internal representation of a long is the two given signed, 32-bit values.
89 // We use 32-bit pieces because these are the size of integers on which
90 // Javascript performs bit-operations. For operations like addition and
91 // multiplication, we split each number into 16 bit pieces, which can easily be
92 // multiplied within Javascript's floating-point representation without overflow
93 // or change in sign.
94 //
95 // In the algorithms below, we frequently reduce the negative case to the
96 // positive case by negating the input(s) and then post-processing the result.
97 // Note that we must ALWAYS check specially whether those values are MIN_VALUE
98 // (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as
99 // a positive number, it overflows back into a negative). Not handling this
100 // case would often result in infinite recursion.
101 //
102 // Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the from*
103 // methods on which they depend.
104
105 /**
106 * An indicator used to reliably determine if an object is a Long or not.
107 * @type {boolean}
108 * @const
109 * @private
110 */
111 Long.prototype.__isLong__;
112
113 Object.defineProperty(Long.prototype, "__isLong__", {
114 value: true,
115 enumerable: false,
116 configurable: false
117 });
118
119 /**
120 * @function
121 * @param {*} obj Object
122 * @returns {boolean}
123 * @inner
124 */
125 function isLong(obj) {
126 return (obj && obj["__isLong__"]) === true;
127 }
128
129 /**
130 * Tests if the specified object is a Long.
131 * @function
132 * @param {*} obj Object
133 * @returns {boolean}
134 */
135 Long.isLong = isLong;
136
137 /**
138 * A cache of the Long representations of small integer values.
139 * @type {!Object}
140 * @inner
141 */
142 var INT_CACHE = {};
143
144 /**
145 * A cache of the Long representations of small unsigned integer values.
146 * @type {!Object}
147 * @inner
148 */
149 var UINT_CACHE = {};
150
151 /**
152 * @param {number} value
153 * @param {boolean=} unsigned
154 * @returns {!Long}
155 * @inner
156 */
157 function fromInt(value, unsigned) {
158 var obj, cachedObj, cache;
159 if (unsigned) {
160 value >>>= 0;
161 if (cache = (0 <= value && value < 256)) {
162 cachedObj = UINT_CACHE[value];
163 if (cachedObj)
164 return cachedObj;
165 }
166 obj = fromBits(value, (value | 0) < 0 ? -1 : 0, true);
167 if (cache)
168 UINT_CACHE[value] = obj;
169 return obj;
170 } else {
171 value |= 0;
172 if (cache = (-128 <= value && value < 128)) {
173 cachedObj = INT_CACHE[value];
174 if (cachedObj)
175 return cachedObj;
176 }
177 obj = fromBits(value, value < 0 ? -1 : 0, false);
178 if (cache)
179 INT_CACHE[value] = obj;
180 return obj;
181 }
182 }
183
184 /**
185 * Returns a Long representing the given 32 bit integer value.
186 * @function
187 * @param {number} value The 32 bit integer in question
188 * @param {boolean=} unsigned Whether unsigned or not, defaults to `false` for signed
189 * @returns {!Long} The corresponding Long value
190 */
191 Long.fromInt = fromInt;
192
193 /**
194 * @param {number} value
195 * @param {boolean=} unsigned
196 * @returns {!Long}
197 * @inner
198 */
199 function fromNumber(value, unsigned) {
200 if (isNaN(value) || !isFinite(value))
201 return unsigned ? UZERO : ZERO;
202 if (unsigned) {
203 if (value < 0)
204 return UZERO;
205 if (value >= TWO_PWR_64_DBL)
206 return MAX_UNSIGNED_VALUE;
207 } else {
208 if (value <= -TWO_PWR_63_DBL)
209 return MIN_VALUE;
210 if (value + 1 >= TWO_PWR_63_DBL)
211 return MAX_VALUE;
212 }
213 if (value < 0)
214 return fromNumber(-value, unsigned).neg();
215 return fromBits((value % TWO_PWR_32_DBL) | 0, (value / TWO_PWR_32_DBL) | 0, unsigned);
216 }
217
218 /**
219 * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned.
220 * @function
221 * @param {number} value The number in question
222 * @param {boolean=} unsigned Whether unsigned or not, defaults to `false` for signed
223 * @returns {!Long} The corresponding Long value
224 */
225 Long.fromNumber = fromNumber;
226
227 /**
228 * @param {number} lowBits
229 * @param {number} highBits
230 * @param {boolean=} unsigned
231 * @returns {!Long}
232 * @inner
233 */
234 function fromBits(lowBits, highBits, unsigned) {
235 return new Long(lowBits, highBits, unsigned);
236 }
237
238 /**
239 * Returns a Long representing the 64 bit integer that comes by concatenating the given low and high bits. Each is
240 * assumed to use 32 bits.
241 * @function
242 * @param {number} lowBits The low 32 bits
243 * @param {number} highBits The high 32 bits
244 * @param {boolean=} unsigned Whether unsigned or not, defaults to `false` for signed
245 * @returns {!Long} The corresponding Long value
246 */
247 Long.fromBits = fromBits;
248
249 /**
250 * @function
251 * @param {number} base
252 * @param {number} exponent
253 * @returns {number}
254 * @inner
255 */
256 var pow_dbl = Math.pow; // Used 4 times (4*8 to 15+4)
257
258 /**
259 * @param {string} str
260 * @param {(boolean|number)=} unsigned
261 * @param {number=} radix
262 * @returns {!Long}
263 * @inner
264 */
265 function fromString(str, unsigned, radix) {
266 if (str.length === 0)
267 throw Error('empty string');
268 if (str === "NaN" || str === "Infinity" || str === "+Infinity" || str === "-Infinity")
269 return ZERO;
270 if (typeof unsigned === 'number') {
271 // For goog.math.long compatibility
272 radix = unsigned,
273 unsigned = false;
274 } else {
275 unsigned = !! unsigned;
276 }
277 radix = radix || 10;
278 if (radix < 2 || 36 < radix)
279 throw RangeError('radix');
280
281 var p;
282 if ((p = str.indexOf('-')) > 0)
283 throw Error('interior hyphen');
284 else if (p === 0) {
285 return fromString(str.substring(1), unsigned, radix).neg();
286 }
287
288 // Do several (8) digits each time through the loop, so as to
289 // minimize the calls to the very expensive emulated div.
290 var radixToPower = fromNumber(pow_dbl(radix, 8));
291
292 var result = ZERO;
293 for (var i = 0; i < str.length; i += 8) {
294 var size = Math.min(8, str.length - i),
295 value = parseInt(str.substring(i, i + size), radix);
296 if (size < 8) {
297 var power = fromNumber(pow_dbl(radix, size));
298 result = result.mul(power).add(fromNumber(value));
299 } else {
300 result = result.mul(radixToPower);
301 result = result.add(fromNumber(value));
302 }
303 }
304 result.unsigned = unsigned;
305 return result;
306 }
307
308 /**
309 * Returns a Long representation of the given string, written using the specified radix.
310 * @function
311 * @param {string} str The textual representation of the Long
312 * @param {(boolean|number)=} unsigned Whether unsigned or not, defaults to `false` for signed
313 * @param {number=} radix The radix in which the text is written (2-36), defaults to 10
314 * @returns {!Long} The corresponding Long value
315 */
316 Long.fromString = fromString;
317
318 /**
319 * @function
320 * @param {!Long|number|string|!{low: number, high: number, unsigned: boolean}} val
321 * @returns {!Long}
322 * @inner
323 */
324 function fromValue(val) {
325 if (val /* is compatible */ instanceof Long)
326 return val;
327 if (typeof val === 'number')
328 return fromNumber(val);
329 if (typeof val === 'string')
330 return fromString(val);
331 // Throws for non-objects, converts non-instanceof Long:
332 return fromBits(val.low, val.high, val.unsigned);
333 }
334
335 /**
336 * Converts the specified value to a Long.
337 * @function
338 * @param {!Long|number|string|!{low: number, high: number, unsigned: boolean}} val Value
339 * @returns {!Long}
340 */
341 Long.fromValue = fromValue;
342
343 // NOTE: the compiler should inline these constant values below and then remove these variables, so there should be
344 // no runtime penalty for these.
345
346 /**
347 * @type {number}
348 * @const
349 * @inner
350 */
351 var TWO_PWR_16_DBL = 1 << 16;
352
353 /**
354 * @type {number}
355 * @const
356 * @inner
357 */
358 var TWO_PWR_24_DBL = 1 << 24;
359
360 /**
361 * @type {number}
362 * @const
363 * @inner
364 */
365 var TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL;
366
367 /**
368 * @type {number}
369 * @const
370 * @inner
371 */
372 var TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL;
373
374 /**
375 * @type {number}
376 * @const
377 * @inner
378 */
379 var TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2;
380
381 /**
382 * @type {!Long}
383 * @const
384 * @inner
385 */
386 var TWO_PWR_24 = fromInt(TWO_PWR_24_DBL);
387
388 /**
389 * @type {!Long}
390 * @inner
391 */
392 var ZERO = fromInt(0);
393
394 /**
395 * Signed zero.
396 * @type {!Long}
397 */
398 Long.ZERO = ZERO;
399
400 /**
401 * @type {!Long}
402 * @inner
403 */
404 var UZERO = fromInt(0, true);
405
406 /**
407 * Unsigned zero.
408 * @type {!Long}
409 */
410 Long.UZERO = UZERO;
411
412 /**
413 * @type {!Long}
414 * @inner
415 */
416 var ONE = fromInt(1);
417
418 /**
419 * Signed one.
420 * @type {!Long}
421 */
422 Long.ONE = ONE;
423
424 /**
425 * @type {!Long}
426 * @inner
427 */
428 var UONE = fromInt(1, true);
429
430 /**
431 * Unsigned one.
432 * @type {!Long}
433 */
434 Long.UONE = UONE;
435
436 /**
437 * @type {!Long}
438 * @inner
439 */
440 var NEG_ONE = fromInt(-1);
441
442 /**
443 * Signed negative one.
444 * @type {!Long}
445 */
446 Long.NEG_ONE = NEG_ONE;
447
448 /**
449 * @type {!Long}
450 * @inner
451 */
452 var MAX_VALUE = fromBits(0xFFFFFFFF|0, 0x7FFFFFFF|0, false);
453
454 /**
455 * Maximum signed value.
456 * @type {!Long}
457 */
458 Long.MAX_VALUE = MAX_VALUE;
459
460 /**
461 * @type {!Long}
462 * @inner
463 */
464 var MAX_UNSIGNED_VALUE = fromBits(0xFFFFFFFF|0, 0xFFFFFFFF|0, true);
465
466 /**
467 * Maximum unsigned value.
468 * @type {!Long}
469 */
470 Long.MAX_UNSIGNED_VALUE = MAX_UNSIGNED_VALUE;
471
472 /**
473 * @type {!Long}
474 * @inner
475 */
476 var MIN_VALUE = fromBits(0, 0x80000000|0, false);
477
478 /**
479 * Minimum signed value.
480 * @type {!Long}
481 */
482 Long.MIN_VALUE = MIN_VALUE;
483
484 /**
485 * @alias Long.prototype
486 * @inner
487 */
488 var LongPrototype = Long.prototype;
489
490 /**
491 * Converts the Long to a 32 bit integer, assuming it is a 32 bit integer.
492 * @returns {number}
493 */
494 LongPrototype.toInt = function toInt() {
495 return this.unsigned ? this.low >>> 0 : this.low;
496 };
497
498 /**
499 * Converts the Long to a the nearest floating-point representation of this value (double, 53 bit mantissa).
500 * @returns {number}
501 */
502 LongPrototype.toNumber = function toNumber() {
503 if (this.unsigned)
504 return ((this.high >>> 0) * TWO_PWR_32_DBL) + (this.low >>> 0);
505 return this.high * TWO_PWR_32_DBL + (this.low >>> 0);
506 };
507
508 /**
509 * Converts the Long to a string written in the specified radix.
510 * @param {number=} radix Radix (2-36), defaults to 10
511 * @returns {string}
512 * @override
513 * @throws {RangeError} If `radix` is out of range
514 */
515 LongPrototype.toString = function toString(radix) {
516 radix = radix || 10;
517 if (radix < 2 || 36 < radix)
518 throw RangeError('radix');
519 if (this.isZero())
520 return '0';
521 if (this.isNegative()) { // Unsigned Longs are never negative
522 if (this.eq(MIN_VALUE)) {
523 // We need to change the Long value before it can be negated, so we remove
524 // the bottom-most digit in this base and then recurse to do the rest.
525 var radixLong = fromNumber(radix),
526 div = this.div(radixLong),
527 rem1 = div.mul(radixLong).sub(this);
528 return div.toString(radix) + rem1.toInt().toString(radix);
529 } else
530 return '-' + this.neg().toString(radix);
531 }
532
533 // Do several (6) digits each time through the loop, so as to
534 // minimize the calls to the very expensive emulated div.
535 var radixToPower = fromNumber(pow_dbl(radix, 6), this.unsigned),
536 rem = this;
537 var result = '';
538 while (true) {
539 var remDiv = rem.div(radixToPower),
540 intval = rem.sub(remDiv.mul(radixToPower)).toInt() >>> 0,
541 digits = intval.toString(radix);
542 rem = remDiv;
543 if (rem.isZero())
544 return digits + result;
545 else {
546 while (digits.length < 6)
547 digits = '0' + digits;
548 result = '' + digits + result;
549 }
550 }
551 };
552
553 /**
554 * Gets the high 32 bits as a signed integer.
555 * @returns {number} Signed high bits
556 */
557 LongPrototype.getHighBits = function getHighBits() {
558 return this.high;
559 };
560
561 /**
562 * Gets the high 32 bits as an unsigned integer.
563 * @returns {number} Unsigned high bits
564 */
565 LongPrototype.getHighBitsUnsigned = function getHighBitsUnsigned() {
566 return this.high >>> 0;
567 };
568
569 /**
570 * Gets the low 32 bits as a signed integer.
571 * @returns {number} Signed low bits
572 */
573 LongPrototype.getLowBits = function getLowBits() {
574 return this.low;
575 };
576
577 /**
578 * Gets the low 32 bits as an unsigned integer.
579 * @returns {number} Unsigned low bits
580 */
581 LongPrototype.getLowBitsUnsigned = function getLowBitsUnsigned() {
582 return this.low >>> 0;
583 };
584
585 /**
586 * Gets the number of bits needed to represent the absolute value of this Long.
587 * @returns {number}
588 */
589 LongPrototype.getNumBitsAbs = function getNumBitsAbs() {
590 if (this.isNegative()) // Unsigned Longs are never negative
591 return this.eq(MIN_VALUE) ? 64 : this.neg().getNumBitsAbs();
592 var val = this.high != 0 ? this.high : this.low;
593 for (var bit = 31; bit > 0; bit--)
594 if ((val & (1 << bit)) != 0)
595 break;
596 return this.high != 0 ? bit + 33 : bit + 1;
597 };
598
599 /**
600 * Tests if this Long's value equals zero.
601 * @returns {boolean}
602 */
603 LongPrototype.isZero = function isZero() {
604 return this.high === 0 && this.low === 0;
605 };
606
607 /**
608 * Tests if this Long's value is negative.
609 * @returns {boolean}
610 */
611 LongPrototype.isNegative = function isNegative() {
612 return !this.unsigned && this.high < 0;
613 };
614
615 /**
616 * Tests if this Long's value is positive.
617 * @returns {boolean}
618 */
619 LongPrototype.isPositive = function isPositive() {
620 return this.unsigned || this.high >= 0;
621 };
622
623 /**
624 * Tests if this Long's value is odd.
625 * @returns {boolean}
626 */
627 LongPrototype.isOdd = function isOdd() {
628 return (this.low & 1) === 1;
629 };
630
631 /**
632 * Tests if this Long's value is even.
633 * @returns {boolean}
634 */
635 LongPrototype.isEven = function isEven() {
636 return (this.low & 1) === 0;
637 };
638
639 /**
640 * Tests if this Long's value equals the specified's.
641 * @param {!Long|number|string} other Other value
642 * @returns {boolean}
643 */
644 LongPrototype.equals = function equals(other) {
645 if (!isLong(other))
646 other = fromValue(other);
647 if (this.unsigned !== other.unsigned && (this.high >>> 31) === 1 && (other.high >>> 31) === 1)
648 return false;
649 return this.high === other.high && this.low === other.low;
650 };
651
652 /**
653 * Tests if this Long's value equals the specified's. This is an alias of {@link Long#equals}.
654 * @function
655 * @param {!Long|number|string} other Other value
656 * @returns {boolean}
657 */
658 LongPrototype.eq = LongPrototype.equals;
659
660 /**
661 * Tests if this Long's value differs from the specified's.
662 * @param {!Long|number|string} other Other value
663 * @returns {boolean}
664 */
665 LongPrototype.notEquals = function notEquals(other) {
666 return !this.eq(/* validates */ other);
667 };
668
669 /**
670 * Tests if this Long's value differs from the specified's. This is an alias of {@link Long#notEquals}.
671 * @function
672 * @param {!Long|number|string} other Other value
673 * @returns {boolean}
674 */
675 LongPrototype.neq = LongPrototype.notEquals;
676
677 /**
678 * Tests if this Long's value is less than the specified's.
679 * @param {!Long|number|string} other Other value
680 * @returns {boolean}
681 */
682 LongPrototype.lessThan = function lessThan(other) {
683 return this.comp(/* validates */ other) < 0;
684 };
685
686 /**
687 * Tests if this Long's value is less than the specified's. This is an alias of {@link Long#lessThan}.
688 * @function
689 * @param {!Long|number|string} other Other value
690 * @returns {boolean}
691 */
692 LongPrototype.lt = LongPrototype.lessThan;
693
694 /**
695 * Tests if this Long's value is less than or equal the specified's.
696 * @param {!Long|number|string} other Other value
697 * @returns {boolean}
698 */
699 LongPrototype.lessThanOrEqual = function lessThanOrEqual(other) {
700 return this.comp(/* validates */ other) <= 0;
701 };
702
703 /**
704 * Tests if this Long's value is less than or equal the specified's. This is an alias of {@link Long#lessThanOrEqual}.
705 * @function
706 * @param {!Long|number|string} other Other value
707 * @returns {boolean}
708 */
709 LongPrototype.lte = LongPrototype.lessThanOrEqual;
710
711 /**
712 * Tests if this Long's value is greater than the specified's.
713 * @param {!Long|number|string} other Other value
714 * @returns {boolean}
715 */
716 LongPrototype.greaterThan = function greaterThan(other) {
717 return this.comp(/* validates */ other) > 0;
718 };
719
720 /**
721 * Tests if this Long's value is greater than the specified's. This is an alias of {@link Long#greaterThan}.
722 * @function
723 * @param {!Long|number|string} other Other value
724 * @returns {boolean}
725 */
726 LongPrototype.gt = LongPrototype.greaterThan;
727
728 /**
729 * Tests if this Long's value is greater than or equal the specified's.
730 * @param {!Long|number|string} other Other value
731 * @returns {boolean}
732 */
733 LongPrototype.greaterThanOrEqual = function greaterThanOrEqual(other) {
734 return this.comp(/* validates */ other) >= 0;
735 };
736
737 /**
738 * Tests if this Long's value is greater than or equal the specified's. This is an alias of {@link Long#greaterThanOrEqual}.
739 * @function
740 * @param {!Long|number|string} other Other value
741 * @returns {boolean}
742 */
743 LongPrototype.gte = LongPrototype.greaterThanOrEqual;
744
745 /**
746 * Compares this Long's value with the specified's.
747 * @param {!Long|number|string} other Other value
748 * @returns {number} 0 if they are the same, 1 if the this is greater and -1
749 * if the given one is greater
750 */
751 LongPrototype.compare = function compare(other) {
752 if (!isLong(other))
753 other = fromValue(other);
754 if (this.eq(other))
755 return 0;
756 var thisNeg = this.isNegative(),
757 otherNeg = other.isNegative();
758 if (thisNeg && !otherNeg)
759 return -1;
760 if (!thisNeg && otherNeg)
761 return 1;
762 // At this point the sign bits are the same
763 if (!this.unsigned)
764 return this.sub(other).isNegative() ? -1 : 1;
765 // Both are positive if at least one is unsigned
766 return (other.high >>> 0) > (this.high >>> 0) || (other.high === this.high && (other.low >>> 0) > (this.low >>> 0)) ? -1 : 1;
767 };
768
769 /**
770 * Compares this Long's value with the specified's. This is an alias of {@link Long#compare}.
771 * @function
772 * @param {!Long|number|string} other Other value
773 * @returns {number} 0 if they are the same, 1 if the this is greater and -1
774 * if the given one is greater
775 */
776 LongPrototype.comp = LongPrototype.compare;
777
778 /**
779 * Negates this Long's value.
780 * @returns {!Long} Negated Long
781 */
782 LongPrototype.negate = function negate() {
783 if (!this.unsigned && this.eq(MIN_VALUE))
784 return MIN_VALUE;
785 return this.not().add(ONE);
786 };
787
788 /**
789 * Negates this Long's value. This is an alias of {@link Long#negate}.
790 * @function
791 * @returns {!Long} Negated Long
792 */
793 LongPrototype.neg = LongPrototype.negate;
794
795 /**
796 * Returns the sum of this and the specified Long.
797 * @param {!Long|number|string} addend Addend
798 * @returns {!Long} Sum
799 */
800 LongPrototype.add = function add(addend) {
801 if (!isLong(addend))
802 addend = fromValue(addend);
803
804 // Divide each number into 4 chunks of 16 bits, and then sum the chunks.
805
806 var a48 = this.high >>> 16;
807 var a32 = this.high & 0xFFFF;
808 var a16 = this.low >>> 16;
809 var a00 = this.low & 0xFFFF;
810
811 var b48 = addend.high >>> 16;
812 var b32 = addend.high & 0xFFFF;
813 var b16 = addend.low >>> 16;
814 var b00 = addend.low & 0xFFFF;
815
816 var c48 = 0, c32 = 0, c16 = 0, c00 = 0;
817 c00 += a00 + b00;
818 c16 += c00 >>> 16;
819 c00 &= 0xFFFF;
820 c16 += a16 + b16;
821 c32 += c16 >>> 16;
822 c16 &= 0xFFFF;
823 c32 += a32 + b32;
824 c48 += c32 >>> 16;
825 c32 &= 0xFFFF;
826 c48 += a48 + b48;
827 c48 &= 0xFFFF;
828 return fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned);
829 };
830
831 /**
832 * Returns the difference of this and the specified Long.
833 * @param {!Long|number|string} subtrahend Subtrahend
834 * @returns {!Long} Difference
835 */
836 LongPrototype.subtract = function subtract(subtrahend) {
837 if (!isLong(subtrahend))
838 subtrahend = fromValue(subtrahend);
839 return this.add(subtrahend.neg());
840 };
841
842 /**
843 * Returns the difference of this and the specified Long. This is an alias of {@link Long#subtract}.
844 * @function
845 * @param {!Long|number|string} subtrahend Subtrahend
846 * @returns {!Long} Difference
847 */
848 LongPrototype.sub = LongPrototype.subtract;
849
850 /**
851 * Returns the product of this and the specified Long.
852 * @param {!Long|number|string} multiplier Multiplier
853 * @returns {!Long} Product
854 */
855 LongPrototype.multiply = function multiply(multiplier) {
856 if (this.isZero())
857 return ZERO;
858 if (!isLong(multiplier))
859 multiplier = fromValue(multiplier);
860 if (multiplier.isZero())
861 return ZERO;
862 if (this.eq(MIN_VALUE))
863 return multiplier.isOdd() ? MIN_VALUE : ZERO;
864 if (multiplier.eq(MIN_VALUE))
865 return this.isOdd() ? MIN_VALUE : ZERO;
866
867 if (this.isNegative()) {
868 if (multiplier.isNegative())
869 return this.neg().mul(multiplier.neg());
870 else
871 return this.neg().mul(multiplier).neg();
872 } else if (multiplier.isNegative())
873 return this.mul(multiplier.neg()).neg();
874
875 // If both longs are small, use float multiplication
876 if (this.lt(TWO_PWR_24) && multiplier.lt(TWO_PWR_24))
877 return fromNumber(this.toNumber() * multiplier.toNumber(), this.unsigned);
878
879 // Divide each long into 4 chunks of 16 bits, and then add up 4x4 products.
880 // We can skip products that would overflow.
881
882 var a48 = this.high >>> 16;
883 var a32 = this.high & 0xFFFF;
884 var a16 = this.low >>> 16;
885 var a00 = this.low & 0xFFFF;
886
887 var b48 = multiplier.high >>> 16;
888 var b32 = multiplier.high & 0xFFFF;
889 var b16 = multiplier.low >>> 16;
890 var b00 = multiplier.low & 0xFFFF;
891
892 var c48 = 0, c32 = 0, c16 = 0, c00 = 0;
893 c00 += a00 * b00;
894 c16 += c00 >>> 16;
895 c00 &= 0xFFFF;
896 c16 += a16 * b00;
897 c32 += c16 >>> 16;
898 c16 &= 0xFFFF;
899 c16 += a00 * b16;
900 c32 += c16 >>> 16;
901 c16 &= 0xFFFF;
902 c32 += a32 * b00;
903 c48 += c32 >>> 16;
904 c32 &= 0xFFFF;
905 c32 += a16 * b16;
906 c48 += c32 >>> 16;
907 c32 &= 0xFFFF;
908 c32 += a00 * b32;
909 c48 += c32 >>> 16;
910 c32 &= 0xFFFF;
911 c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48;
912 c48 &= 0xFFFF;
913 return fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned);
914 };
915
916 /**
917 * Returns the product of this and the specified Long. This is an alias of {@link Long#multiply}.
918 * @function
919 * @param {!Long|number|string} multiplier Multiplier
920 * @returns {!Long} Product
921 */
922 LongPrototype.mul = LongPrototype.multiply;
923
924 /**
925 * Returns this Long divided by the specified. The result is signed if this Long is signed or
926 * unsigned if this Long is unsigned.
927 * @param {!Long|number|string} divisor Divisor
928 * @returns {!Long} Quotient
929 */
930 LongPrototype.divide = function divide(divisor) {
931 if (!isLong(divisor))
932 divisor = fromValue(divisor);
933 if (divisor.isZero())
934 throw Error('division by zero');
935 if (this.isZero())
936 return this.unsigned ? UZERO : ZERO;
937 var approx, rem, res;
938 if (!this.unsigned) {
939 // This section is only relevant for signed longs and is derived from the
940 // closure library as a whole.
941 if (this.eq(MIN_VALUE)) {
942 if (divisor.eq(ONE) || divisor.eq(NEG_ONE))
943 return MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE
944 else if (divisor.eq(MIN_VALUE))
945 return ONE;
946 else {
947 // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|.
948 var halfThis = this.shr(1);
949 approx = halfThis.div(divisor).shl(1);
950 if (approx.eq(ZERO)) {
951 return divisor.isNegative() ? ONE : NEG_ONE;
952 } else {
953 rem = this.sub(divisor.mul(approx));
954 res = approx.add(rem.div(divisor));
955 return res;
956 }
957 }
958 } else if (divisor.eq(MIN_VALUE))
959 return this.unsigned ? UZERO : ZERO;
960 if (this.isNegative()) {
961 if (divisor.isNegative())
962 return this.neg().div(divisor.neg());
963 return this.neg().div(divisor).neg();
964 } else if (divisor.isNegative())
965 return this.div(divisor.neg()).neg();
966 res = ZERO;
967 } else {
968 // The algorithm below has not been made for unsigned longs. It's therefore
969 // required to take special care of the MSB prior to running it.
970 if (!divisor.unsigned)
971 divisor = divisor.toUnsigned();
972 if (divisor.gt(this))
973 return UZERO;
974 if (divisor.gt(this.shru(1))) // 15 >>> 1 = 7 ; with divisor = 8 ; true
975 return UONE;
976 res = UZERO;
977 }
978
979 // Repeat the following until the remainder is less than other: find a
980 // floating-point that approximates remainder / other *from below*, add this
981 // into the result, and subtract it from the remainder. It is critical that
982 // the approximate value is less than or equal to the real value so that the
983 // remainder never becomes negative.
984 rem = this;
985 while (rem.gte(divisor)) {
986 // Approximate the result of division. This may be a little greater or
987 // smaller than the actual value.
988 approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber()));
989
990 // We will tweak the approximate result by changing it in the 48-th digit or
991 // the smallest non-fractional digit, whichever is larger.
992 var log2 = Math.ceil(Math.log(approx) / Math.LN2),
993 delta = (log2 <= 48) ? 1 : pow_dbl(2, log2 - 48),
994
995 // Decrease the approximation until it is smaller than the remainder. Note
996 // that if it is too large, the product overflows and is negative.
997 approxRes = fromNumber(approx),
998 approxRem = approxRes.mul(divisor);
999 while (approxRem.isNegative() || approxRem.gt(rem)) {
1000 approx -= delta;
1001 approxRes = fromNumber(approx, this.unsigned);
1002 approxRem = approxRes.mul(divisor);
1003 }
1004
1005 // We know the answer can't be zero... and actually, zero would cause
1006 // infinite recursion since we would make no progress.
1007 if (approxRes.isZero())
1008 approxRes = ONE;
1009
1010 res = res.add(approxRes);
1011 rem = rem.sub(approxRem);
1012 }
1013 return res;
1014 };
1015
1016 /**
1017 * Returns this Long divided by the specified. This is an alias of {@link Long#divide}.
1018 * @function
1019 * @param {!Long|number|string} divisor Divisor
1020 * @returns {!Long} Quotient
1021 */
1022 LongPrototype.div = LongPrototype.divide;
1023
1024 /**
1025 * Returns this Long modulo the specified.
1026 * @param {!Long|number|string} divisor Divisor
1027 * @returns {!Long} Remainder
1028 */
1029 LongPrototype.modulo = function modulo(divisor) {
1030 if (!isLong(divisor))
1031 divisor = fromValue(divisor);
1032 return this.sub(this.div(divisor).mul(divisor));
1033 };
1034
1035 /**
1036 * Returns this Long modulo the specified. This is an alias of {@link Long#modulo}.
1037 * @function
1038 * @param {!Long|number|string} divisor Divisor
1039 * @returns {!Long} Remainder
1040 */
1041 LongPrototype.mod = LongPrototype.modulo;
1042
1043 /**
1044 * Returns the bitwise NOT of this Long.
1045 * @returns {!Long}
1046 */
1047 LongPrototype.not = function not() {
1048 return fromBits(~this.low, ~this.high, this.unsigned);
1049 };
1050
1051 /**
1052 * Returns the bitwise AND of this Long and the specified.
1053 * @param {!Long|number|string} other Other Long
1054 * @returns {!Long}
1055 */
1056 LongPrototype.and = function and(other) {
1057 if (!isLong(other))
1058 other = fromValue(other);
1059 return fromBits(this.low & other.low, this.high & other.high, this.unsigned);
1060 };
1061
1062 /**
1063 * Returns the bitwise OR of this Long and the specified.
1064 * @param {!Long|number|string} other Other Long
1065 * @returns {!Long}
1066 */
1067 LongPrototype.or = function or(other) {
1068 if (!isLong(other))
1069 other = fromValue(other);
1070 return fromBits(this.low | other.low, this.high | other.high, this.unsigned);
1071 };
1072
1073 /**
1074 * Returns the bitwise XOR of this Long and the given one.
1075 * @param {!Long|number|string} other Other Long
1076 * @returns {!Long}
1077 */
1078 LongPrototype.xor = function xor(other) {
1079 if (!isLong(other))
1080 other = fromValue(other);
1081 return fromBits(this.low ^ other.low, this.high ^ other.high, this.unsigned);
1082 };
1083
1084 /**
1085 * Returns this Long with bits shifted to the left by the given amount.
1086 * @param {number|!Long} numBits Number of bits
1087 * @returns {!Long} Shifted Long
1088 */
1089 LongPrototype.shiftLeft = function shiftLeft(numBits) {
1090 if (isLong(numBits))
1091 numBits = numBits.toInt();
1092 if ((numBits &= 63) === 0)
1093 return this;
1094 else if (numBits < 32)
1095 return fromBits(this.low << numBits, (this.high << numBits) | (this.low >>> (32 - numBits)), this.unsigned);
1096 else
1097 return fromBits(0, this.low << (numBits - 32), this.unsigned);
1098 };
1099
1100 /**
1101 * Returns this Long with bits shifted to the left by the given amount. This is an alias of {@link Long#shiftLeft}.
1102 * @function
1103 * @param {number|!Long} numBits Number of bits
1104 * @returns {!Long} Shifted Long
1105 */
1106 LongPrototype.shl = LongPrototype.shiftLeft;
1107
1108 /**
1109 * Returns this Long with bits arithmetically shifted to the right by the given amount.
1110 * @param {number|!Long} numBits Number of bits
1111 * @returns {!Long} Shifted Long
1112 */
1113 LongPrototype.shiftRight = function shiftRight(numBits) {
1114 if (isLong(numBits))
1115 numBits = numBits.toInt();
1116 if ((numBits &= 63) === 0)
1117 return this;
1118 else if (numBits < 32)
1119 return fromBits((this.low >>> numBits) | (this.high << (32 - numBits)), this.high >> numBits, this.unsigned);
1120 else
1121 return fromBits(this.high >> (numBits - 32), this.high >= 0 ? 0 : -1, this.unsigned);
1122 };
1123
1124 /**
1125 * Returns this Long with bits arithmetically shifted to the right by the given amount. This is an alias of {@link Long#shiftRight}.
1126 * @function
1127 * @param {number|!Long} numBits Number of bits
1128 * @returns {!Long} Shifted Long
1129 */
1130 LongPrototype.shr = LongPrototype.shiftRight;
1131
1132 /**
1133 * Returns this Long with bits logically shifted to the right by the given amount.
1134 * @param {number|!Long} numBits Number of bits
1135 * @returns {!Long} Shifted Long
1136 */
1137 LongPrototype.shiftRightUnsigned = function shiftRightUnsigned(numBits) {
1138 if (isLong(numBits))
1139 numBits = numBits.toInt();
1140 numBits &= 63;
1141 if (numBits === 0)
1142 return this;
1143 else {
1144 var high = this.high;
1145 if (numBits < 32) {
1146 var low = this.low;
1147 return fromBits((low >>> numBits) | (high << (32 - numBits)), high >>> numBits, this.unsigned);
1148 } else if (numBits === 32)
1149 return fromBits(high, 0, this.unsigned);
1150 else
1151 return fromBits(high >>> (numBits - 32), 0, this.unsigned);
1152 }
1153 };
1154
1155 /**
1156 * Returns this Long with bits logically shifted to the right by the given amount. This is an alias of {@link Long#shiftRightUnsigned}.
1157 * @function
1158 * @param {number|!Long} numBits Number of bits
1159 * @returns {!Long} Shifted Long
1160 */
1161 LongPrototype.shru = LongPrototype.shiftRightUnsigned;
1162
1163 /**
1164 * Converts this Long to signed.
1165 * @returns {!Long} Signed long
1166 */
1167 LongPrototype.toSigned = function toSigned() {
1168 if (!this.unsigned)
1169 return this;
1170 return fromBits(this.low, this.high, false);
1171 };
1172
1173 /**
1174 * Converts this Long to unsigned.
1175 * @returns {!Long} Unsigned long
1176 */
1177 LongPrototype.toUnsigned = function toUnsigned() {
1178 if (this.unsigned)
1179 return this;
1180 return fromBits(this.low, this.high, true);
1181 };
1182
1183 /**
1184 * Converts this Long to its byte representation.
1185 * @param {boolean=} le Whether little or big endian, defaults to big endian
1186 * @returns {!Array.<number>} Byte representation
1187 */
1188 LongPrototype.toBytes = function(le) {
1189 return le ? this.toBytesLE() : this.toBytesBE();
1190 };
1191
1192 /**
1193 * Converts this Long to its little endian byte representation.
1194 * @returns {!Array.<number>} Little endian byte representation
1195 */
1196 LongPrototype.toBytesLE = function() {
1197 var hi = this.high,
1198 lo = this.low;
1199 return [
1200 lo & 0xff,
1201 (lo >>> 8) & 0xff,
1202 (lo >>> 16) & 0xff,
1203 (lo >>> 24) & 0xff,
1204 hi & 0xff,
1205 (hi >>> 8) & 0xff,
1206 (hi >>> 16) & 0xff,
1207 (hi >>> 24) & 0xff
1208 ];
1209 };
1210
1211 /**
1212 * Converts this Long to its big endian byte representation.
1213 * @returns {!Array.<number>} Big endian byte representation
1214 */
1215 LongPrototype.toBytesBE = function() {
1216 var hi = this.high,
1217 lo = this.low;
1218 return [
1219 (hi >>> 24) & 0xff,
1220 (hi >>> 16) & 0xff,
1221 (hi >>> 8) & 0xff,
1222 hi & 0xff,
1223 (lo >>> 24) & 0xff,
1224 (lo >>> 16) & 0xff,
1225 (lo >>> 8) & 0xff,
1226 lo & 0xff
1227 ];
1228 };
1229
1230 return Long;
1231 });
1232 });
1233
1234 var bytebuffer = createCommonjsModule(function (module) {
1235 /*
1236 Copyright 2013-2014 Daniel Wirtz <dcode@dcode.io>
1237
1238 Licensed under the Apache License, Version 2.0 (the "License");
1239 you may not use this file except in compliance with the License.
1240 You may obtain a copy of the License at
1241
1242 http://www.apache.org/licenses/LICENSE-2.0
1243
1244 Unless required by applicable law or agreed to in writing, software
1245 distributed under the License is distributed on an "AS IS" BASIS,
1246 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1247 See the License for the specific language governing permissions and
1248 limitations under the License.
1249 */
1250
1251 /**
1252 * @license bytebuffer.js (c) 2015 Daniel Wirtz <dcode@dcode.io>
1253 * Backing buffer: ArrayBuffer, Accessor: Uint8Array
1254 * Released under the Apache License, Version 2.0
1255 * see: https://github.com/dcodeIO/bytebuffer.js for details
1256 */
1257 (function(global, factory) {
1258
1259 /* AMD */ if (typeof commonjsRequire === 'function' && 'object' === "object" && module && module["exports"])
1260 module['exports'] = (function() {
1261 var Long; try { Long = long_1; } catch (e) {}
1262 return factory(Long);
1263 })();
1264 /* Global */ else
1265 (global["dcodeIO"] = global["dcodeIO"] || {})["ByteBuffer"] = factory(global["dcodeIO"]["Long"]);
1266
1267 })(commonjsGlobal, function(Long) {
1268
1269 /**
1270 * Constructs a new ByteBuffer.
1271 * @class The swiss army knife for binary data in JavaScript.
1272 * @exports ByteBuffer
1273 * @constructor
1274 * @param {number=} capacity Initial capacity. Defaults to {@link ByteBuffer.DEFAULT_CAPACITY}.
1275 * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
1276 * {@link ByteBuffer.DEFAULT_ENDIAN}.
1277 * @param {boolean=} noAssert Whether to skip assertions of offsets and values. Defaults to
1278 * {@link ByteBuffer.DEFAULT_NOASSERT}.
1279 * @expose
1280 */
1281 var ByteBuffer = function(capacity, littleEndian, noAssert) {
1282 if (typeof capacity === 'undefined')
1283 capacity = ByteBuffer.DEFAULT_CAPACITY;
1284 if (typeof littleEndian === 'undefined')
1285 littleEndian = ByteBuffer.DEFAULT_ENDIAN;
1286 if (typeof noAssert === 'undefined')
1287 noAssert = ByteBuffer.DEFAULT_NOASSERT;
1288 if (!noAssert) {
1289 capacity = capacity | 0;
1290 if (capacity < 0)
1291 throw RangeError("Illegal capacity");
1292 littleEndian = !!littleEndian;
1293 noAssert = !!noAssert;
1294 }
1295
1296 /**
1297 * Backing ArrayBuffer.
1298 * @type {!ArrayBuffer}
1299 * @expose
1300 */
1301 this.buffer = capacity === 0 ? EMPTY_BUFFER : new ArrayBuffer(capacity);
1302
1303 /**
1304 * Uint8Array utilized to manipulate the backing buffer. Becomes `null` if the backing buffer has a capacity of `0`.
1305 * @type {?Uint8Array}
1306 * @expose
1307 */
1308 this.view = capacity === 0 ? null : new Uint8Array(this.buffer);
1309
1310 /**
1311 * Absolute read/write offset.
1312 * @type {number}
1313 * @expose
1314 * @see ByteBuffer#flip
1315 * @see ByteBuffer#clear
1316 */
1317 this.offset = 0;
1318
1319 /**
1320 * Marked offset.
1321 * @type {number}
1322 * @expose
1323 * @see ByteBuffer#mark
1324 * @see ByteBuffer#reset
1325 */
1326 this.markedOffset = -1;
1327
1328 /**
1329 * Absolute limit of the contained data. Set to the backing buffer's capacity upon allocation.
1330 * @type {number}
1331 * @expose
1332 * @see ByteBuffer#flip
1333 * @see ByteBuffer#clear
1334 */
1335 this.limit = capacity;
1336
1337 /**
1338 * Whether to use little endian byte order, defaults to `false` for big endian.
1339 * @type {boolean}
1340 * @expose
1341 */
1342 this.littleEndian = littleEndian;
1343
1344 /**
1345 * Whether to skip assertions of offsets and values, defaults to `false`.
1346 * @type {boolean}
1347 * @expose
1348 */
1349 this.noAssert = noAssert;
1350 };
1351
1352 /**
1353 * ByteBuffer version.
1354 * @type {string}
1355 * @const
1356 * @expose
1357 */
1358 ByteBuffer.VERSION = "5.0.1";
1359
1360 /**
1361 * Little endian constant that can be used instead of its boolean value. Evaluates to `true`.
1362 * @type {boolean}
1363 * @const
1364 * @expose
1365 */
1366 ByteBuffer.LITTLE_ENDIAN = true;
1367
1368 /**
1369 * Big endian constant that can be used instead of its boolean value. Evaluates to `false`.
1370 * @type {boolean}
1371 * @const
1372 * @expose
1373 */
1374 ByteBuffer.BIG_ENDIAN = false;
1375
1376 /**
1377 * Default initial capacity of `16`.
1378 * @type {number}
1379 * @expose
1380 */
1381 ByteBuffer.DEFAULT_CAPACITY = 16;
1382
1383 /**
1384 * Default endianess of `false` for big endian.
1385 * @type {boolean}
1386 * @expose
1387 */
1388 ByteBuffer.DEFAULT_ENDIAN = ByteBuffer.BIG_ENDIAN;
1389
1390 /**
1391 * Default no assertions flag of `false`.
1392 * @type {boolean}
1393 * @expose
1394 */
1395 ByteBuffer.DEFAULT_NOASSERT = false;
1396
1397 /**
1398 * A `Long` class for representing a 64-bit two's-complement integer value. May be `null` if Long.js has not been loaded
1399 * and int64 support is not available.
1400 * @type {?Long}
1401 * @const
1402 * @see https://github.com/dcodeIO/long.js
1403 * @expose
1404 */
1405 ByteBuffer.Long = Long || null;
1406
1407 /**
1408 * @alias ByteBuffer.prototype
1409 * @inner
1410 */
1411 var ByteBufferPrototype = ByteBuffer.prototype;
1412
1413 /**
1414 * An indicator used to reliably determine if an object is a ByteBuffer or not.
1415 * @type {boolean}
1416 * @const
1417 * @expose
1418 * @private
1419 */
1420 ByteBufferPrototype.__isByteBuffer__;
1421
1422 Object.defineProperty(ByteBufferPrototype, "__isByteBuffer__", {
1423 value: true,
1424 enumerable: false,
1425 configurable: false
1426 });
1427
1428 // helpers
1429
1430 /**
1431 * @type {!ArrayBuffer}
1432 * @inner
1433 */
1434 var EMPTY_BUFFER = new ArrayBuffer(0);
1435
1436 /**
1437 * String.fromCharCode reference for compile-time renaming.
1438 * @type {function(...number):string}
1439 * @inner
1440 */
1441 var stringFromCharCode = String.fromCharCode;
1442
1443 /**
1444 * Creates a source function for a string.
1445 * @param {string} s String to read from
1446 * @returns {function():number|null} Source function returning the next char code respectively `null` if there are
1447 * no more characters left.
1448 * @throws {TypeError} If the argument is invalid
1449 * @inner
1450 */
1451 function stringSource(s) {
1452 var i=0; return function() {
1453 return i < s.length ? s.charCodeAt(i++) : null;
1454 };
1455 }
1456
1457 /**
1458 * Creates a destination function for a string.
1459 * @returns {function(number=):undefined|string} Destination function successively called with the next char code.
1460 * Returns the final string when called without arguments.
1461 * @inner
1462 */
1463 function stringDestination() {
1464 var cs = [], ps = []; return function() {
1465 if (arguments.length === 0)
1466 return ps.join('')+stringFromCharCode.apply(String, cs);
1467 if (cs.length + arguments.length > 1024)
1468 ps.push(stringFromCharCode.apply(String, cs)),
1469 cs.length = 0;
1470 Array.prototype.push.apply(cs, arguments);
1471 };
1472 }
1473
1474 /**
1475 * Gets the accessor type.
1476 * @returns {Function} `Buffer` under node.js, `Uint8Array` respectively `DataView` in the browser (classes)
1477 * @expose
1478 */
1479 ByteBuffer.accessor = function() {
1480 return Uint8Array;
1481 };
1482 /**
1483 * Allocates a new ByteBuffer backed by a buffer of the specified capacity.
1484 * @param {number=} capacity Initial capacity. Defaults to {@link ByteBuffer.DEFAULT_CAPACITY}.
1485 * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
1486 * {@link ByteBuffer.DEFAULT_ENDIAN}.
1487 * @param {boolean=} noAssert Whether to skip assertions of offsets and values. Defaults to
1488 * {@link ByteBuffer.DEFAULT_NOASSERT}.
1489 * @returns {!ByteBuffer}
1490 * @expose
1491 */
1492 ByteBuffer.allocate = function(capacity, littleEndian, noAssert) {
1493 return new ByteBuffer(capacity, littleEndian, noAssert);
1494 };
1495
1496 /**
1497 * Concatenates multiple ByteBuffers into one.
1498 * @param {!Array.<!ByteBuffer|!ArrayBuffer|!Uint8Array|string>} buffers Buffers to concatenate
1499 * @param {(string|boolean)=} encoding String encoding if `buffers` contains a string ("base64", "hex", "binary",
1500 * defaults to "utf8")
1501 * @param {boolean=} littleEndian Whether to use little or big endian byte order for the resulting ByteBuffer. Defaults
1502 * to {@link ByteBuffer.DEFAULT_ENDIAN}.
1503 * @param {boolean=} noAssert Whether to skip assertions of offsets and values for the resulting ByteBuffer. Defaults to
1504 * {@link ByteBuffer.DEFAULT_NOASSERT}.
1505 * @returns {!ByteBuffer} Concatenated ByteBuffer
1506 * @expose
1507 */
1508 ByteBuffer.concat = function(buffers, encoding, littleEndian, noAssert) {
1509 if (typeof encoding === 'boolean' || typeof encoding !== 'string') {
1510 noAssert = littleEndian;
1511 littleEndian = encoding;
1512 encoding = undefined;
1513 }
1514 var capacity = 0;
1515 for (var i=0, k=buffers.length, length; i<k; ++i) {
1516 if (!ByteBuffer.isByteBuffer(buffers[i]))
1517 buffers[i] = ByteBuffer.wrap(buffers[i], encoding);
1518 length = buffers[i].limit - buffers[i].offset;
1519 if (length > 0) capacity += length;
1520 }
1521 if (capacity === 0)
1522 return new ByteBuffer(0, littleEndian, noAssert);
1523 var bb = new ByteBuffer(capacity, littleEndian, noAssert),
1524 bi;
1525 i=0; while (i<k) {
1526 bi = buffers[i++];
1527 length = bi.limit - bi.offset;
1528 if (length <= 0) continue;
1529 bb.view.set(bi.view.subarray(bi.offset, bi.limit), bb.offset);
1530 bb.offset += length;
1531 }
1532 bb.limit = bb.offset;
1533 bb.offset = 0;
1534 return bb;
1535 };
1536
1537 /**
1538 * Tests if the specified type is a ByteBuffer.
1539 * @param {*} bb ByteBuffer to test
1540 * @returns {boolean} `true` if it is a ByteBuffer, otherwise `false`
1541 * @expose
1542 */
1543 ByteBuffer.isByteBuffer = function(bb) {
1544 return (bb && bb["__isByteBuffer__"]) === true;
1545 };
1546 /**
1547 * Gets the backing buffer type.
1548 * @returns {Function} `Buffer` under node.js, `ArrayBuffer` in the browser (classes)
1549 * @expose
1550 */
1551 ByteBuffer.type = function() {
1552 return ArrayBuffer;
1553 };
1554 /**
1555 * Wraps a buffer or a string. Sets the allocated ByteBuffer's {@link ByteBuffer#offset} to `0` and its
1556 * {@link ByteBuffer#limit} to the length of the wrapped data.
1557 * @param {!ByteBuffer|!ArrayBuffer|!Uint8Array|string|!Array.<number>} buffer Anything that can be wrapped
1558 * @param {(string|boolean)=} encoding String encoding if `buffer` is a string ("base64", "hex", "binary", defaults to
1559 * "utf8")
1560 * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
1561 * {@link ByteBuffer.DEFAULT_ENDIAN}.
1562 * @param {boolean=} noAssert Whether to skip assertions of offsets and values. Defaults to
1563 * {@link ByteBuffer.DEFAULT_NOASSERT}.
1564 * @returns {!ByteBuffer} A ByteBuffer wrapping `buffer`
1565 * @expose
1566 */
1567 ByteBuffer.wrap = function(buffer, encoding, littleEndian, noAssert) {
1568 if (typeof encoding !== 'string') {
1569 noAssert = littleEndian;
1570 littleEndian = encoding;
1571 encoding = undefined;
1572 }
1573 if (typeof buffer === 'string') {
1574 if (typeof encoding === 'undefined')
1575 encoding = "utf8";
1576 switch (encoding) {
1577 case "base64":
1578 return ByteBuffer.fromBase64(buffer, littleEndian);
1579 case "hex":
1580 return ByteBuffer.fromHex(buffer, littleEndian);
1581 case "binary":
1582 return ByteBuffer.fromBinary(buffer, littleEndian);
1583 case "utf8":
1584 return ByteBuffer.fromUTF8(buffer, littleEndian);
1585 case "debug":
1586 return ByteBuffer.fromDebug(buffer, littleEndian);
1587 default:
1588 throw Error("Unsupported encoding: "+encoding);
1589 }
1590 }
1591 if (buffer === null || typeof buffer !== 'object')
1592 throw TypeError("Illegal buffer");
1593 var bb;
1594 if (ByteBuffer.isByteBuffer(buffer)) {
1595 bb = ByteBufferPrototype.clone.call(buffer);
1596 bb.markedOffset = -1;
1597 return bb;
1598 }
1599 if (buffer instanceof Uint8Array) { // Extract ArrayBuffer from Uint8Array
1600 bb = new ByteBuffer(0, littleEndian, noAssert);
1601 if (buffer.length > 0) { // Avoid references to more than one EMPTY_BUFFER
1602 bb.buffer = buffer.buffer;
1603 bb.offset = buffer.byteOffset;
1604 bb.limit = buffer.byteOffset + buffer.byteLength;
1605 bb.view = new Uint8Array(buffer.buffer);
1606 }
1607 } else if (buffer instanceof ArrayBuffer) { // Reuse ArrayBuffer
1608 bb = new ByteBuffer(0, littleEndian, noAssert);
1609 if (buffer.byteLength > 0) {
1610 bb.buffer = buffer;
1611 bb.offset = 0;
1612 bb.limit = buffer.byteLength;
1613 bb.view = buffer.byteLength > 0 ? new Uint8Array(buffer) : null;
1614 }
1615 } else if (Object.prototype.toString.call(buffer) === "[object Array]") { // Create from octets
1616 bb = new ByteBuffer(buffer.length, littleEndian, noAssert);
1617 bb.limit = buffer.length;
1618 for (var i=0; i<buffer.length; ++i)
1619 bb.view[i] = buffer[i];
1620 } else
1621 throw TypeError("Illegal buffer"); // Otherwise fail
1622 return bb;
1623 };
1624
1625 /**
1626 * Writes the array as a bitset.
1627 * @param {Array<boolean>} value Array of booleans to write
1628 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `length` if omitted.
1629 * @returns {!ByteBuffer}
1630 * @expose
1631 */
1632 ByteBufferPrototype.writeBitSet = function(value, offset) {
1633 var relative = typeof offset === 'undefined';
1634 if (relative) offset = this.offset;
1635 if (!this.noAssert) {
1636 if (!(value instanceof Array))
1637 throw TypeError("Illegal BitSet: Not an array");
1638 if (typeof offset !== 'number' || offset % 1 !== 0)
1639 throw TypeError("Illegal offset: "+offset+" (not an integer)");
1640 offset >>>= 0;
1641 if (offset < 0 || offset + 0 > this.buffer.byteLength)
1642 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
1643 }
1644
1645 var start = offset,
1646 bits = value.length,
1647 bytes = (bits >> 3),
1648 bit = 0,
1649 k;
1650
1651 offset += this.writeVarint32(bits,offset);
1652
1653 while(bytes--) {
1654 k = (!!value[bit++] & 1) |
1655 ((!!value[bit++] & 1) << 1) |
1656 ((!!value[bit++] & 1) << 2) |
1657 ((!!value[bit++] & 1) << 3) |
1658 ((!!value[bit++] & 1) << 4) |
1659 ((!!value[bit++] & 1) << 5) |
1660 ((!!value[bit++] & 1) << 6) |
1661 ((!!value[bit++] & 1) << 7);
1662 this.writeByte(k,offset++);
1663 }
1664
1665 if(bit < bits) {
1666 var m = 0; k = 0;
1667 while(bit < bits) k = k | ((!!value[bit++] & 1) << (m++));
1668 this.writeByte(k,offset++);
1669 }
1670
1671 if (relative) {
1672 this.offset = offset;
1673 return this;
1674 }
1675 return offset - start;
1676 };
1677
1678 /**
1679 * Reads a BitSet as an array of booleans.
1680 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `length` if omitted.
1681 * @returns {Array<boolean>
1682 * @expose
1683 */
1684 ByteBufferPrototype.readBitSet = function(offset) {
1685 var relative = typeof offset === 'undefined';
1686 if (relative) offset = this.offset;
1687
1688 var ret = this.readVarint32(offset),
1689 bits = ret.value,
1690 bytes = (bits >> 3),
1691 bit = 0,
1692 value = [],
1693 k;
1694
1695 offset += ret.length;
1696
1697 while(bytes--) {
1698 k = this.readByte(offset++);
1699 value[bit++] = !!(k & 0x01);
1700 value[bit++] = !!(k & 0x02);
1701 value[bit++] = !!(k & 0x04);
1702 value[bit++] = !!(k & 0x08);
1703 value[bit++] = !!(k & 0x10);
1704 value[bit++] = !!(k & 0x20);
1705 value[bit++] = !!(k & 0x40);
1706 value[bit++] = !!(k & 0x80);
1707 }
1708
1709 if(bit < bits) {
1710 var m = 0;
1711 k = this.readByte(offset++);
1712 while(bit < bits) value[bit++] = !!((k >> (m++)) & 1);
1713 }
1714
1715 if (relative) {
1716 this.offset = offset;
1717 }
1718 return value;
1719 };
1720 /**
1721 * Reads the specified number of bytes.
1722 * @param {number} length Number of bytes to read
1723 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `length` if omitted.
1724 * @returns {!ByteBuffer}
1725 * @expose
1726 */
1727 ByteBufferPrototype.readBytes = function(length, offset) {
1728 var relative = typeof offset === 'undefined';
1729 if (relative) offset = this.offset;
1730 if (!this.noAssert) {
1731 if (typeof offset !== 'number' || offset % 1 !== 0)
1732 throw TypeError("Illegal offset: "+offset+" (not an integer)");
1733 offset >>>= 0;
1734 if (offset < 0 || offset + length > this.buffer.byteLength)
1735 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+length+") <= "+this.buffer.byteLength);
1736 }
1737 var slice = this.slice(offset, offset + length);
1738 if (relative) this.offset += length;
1739 return slice;
1740 };
1741
1742 /**
1743 * Writes a payload of bytes. This is an alias of {@link ByteBuffer#append}.
1744 * @function
1745 * @param {!ByteBuffer|!ArrayBuffer|!Uint8Array|string} source Data to write. If `source` is a ByteBuffer, its offsets
1746 * will be modified according to the performed read operation.
1747 * @param {(string|number)=} encoding Encoding if `data` is a string ("base64", "hex", "binary", defaults to "utf8")
1748 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
1749 * written if omitted.
1750 * @returns {!ByteBuffer} this
1751 * @expose
1752 */
1753 ByteBufferPrototype.writeBytes = ByteBufferPrototype.append;
1754
1755 // types/ints/int8
1756
1757 /**
1758 * Writes an 8bit signed integer.
1759 * @param {number} value Value to write
1760 * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `1` if omitted.
1761 * @returns {!ByteBuffer} this
1762 * @expose
1763 */
1764 ByteBufferPrototype.writeInt8 = function(value, offset) {
1765 var relative = typeof offset === 'undefined';
1766 if (relative) offset = this.offset;
1767 if (!this.noAssert) {
1768 if (typeof value !== 'number' || value % 1 !== 0)
1769 throw TypeError("Illegal value: "+value+" (not an integer)");
1770 value |= 0;
1771 if (typeof offset !== 'number' || offset % 1 !== 0)
1772 throw TypeError("Illegal offset: "+offset+" (not an integer)");
1773 offset >>>= 0;
1774 if (offset < 0 || offset + 0 > this.buffer.byteLength)
1775 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
1776 }
1777 offset += 1;
1778 var capacity0 = this.buffer.byteLength;
1779 if (offset > capacity0)
1780 this.resize((capacity0 *= 2) > offset ? capacity0 : offset);
1781 offset -= 1;
1782 this.view[offset] = value;
1783 if (relative) this.offset += 1;
1784 return this;
1785 };
1786
1787 /**
1788 * Writes an 8bit signed integer. This is an alias of {@link ByteBuffer#writeInt8}.
1789 * @function
1790 * @param {number} value Value to write
1791 * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `1` if omitted.
1792 * @returns {!ByteBuffer} this
1793 * @expose
1794 */
1795 ByteBufferPrototype.writeByte = ByteBufferPrototype.writeInt8;
1796
1797 /**
1798 * Reads an 8bit signed integer.
1799 * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `1` if omitted.
1800 * @returns {number} Value read
1801 * @expose
1802 */
1803 ByteBufferPrototype.readInt8 = function(offset) {
1804 var relative = typeof offset === 'undefined';
1805 if (relative) offset = this.offset;
1806 if (!this.noAssert) {
1807 if (typeof offset !== 'number' || offset % 1 !== 0)
1808 throw TypeError("Illegal offset: "+offset+" (not an integer)");
1809 offset >>>= 0;
1810 if (offset < 0 || offset + 1 > this.buffer.byteLength)
1811 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+1+") <= "+this.buffer.byteLength);
1812 }
1813 var value = this.view[offset];
1814 if ((value & 0x80) === 0x80) value = -(0xFF - value + 1); // Cast to signed
1815 if (relative) this.offset += 1;
1816 return value;
1817 };
1818
1819 /**
1820 * Reads an 8bit signed integer. This is an alias of {@link ByteBuffer#readInt8}.
1821 * @function
1822 * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `1` if omitted.
1823 * @returns {number} Value read
1824 * @expose
1825 */
1826 ByteBufferPrototype.readByte = ByteBufferPrototype.readInt8;
1827
1828 /**
1829 * Writes an 8bit unsigned integer.
1830 * @param {number} value Value to write
1831 * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `1` if omitted.
1832 * @returns {!ByteBuffer} this
1833 * @expose
1834 */
1835 ByteBufferPrototype.writeUint8 = function(value, offset) {
1836 var relative = typeof offset === 'undefined';
1837 if (relative) offset = this.offset;
1838 if (!this.noAssert) {
1839 if (typeof value !== 'number' || value % 1 !== 0)
1840 throw TypeError("Illegal value: "+value+" (not an integer)");
1841 value >>>= 0;
1842 if (typeof offset !== 'number' || offset % 1 !== 0)
1843 throw TypeError("Illegal offset: "+offset+" (not an integer)");
1844 offset >>>= 0;
1845 if (offset < 0 || offset + 0 > this.buffer.byteLength)
1846 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
1847 }
1848 offset += 1;
1849 var capacity1 = this.buffer.byteLength;
1850 if (offset > capacity1)
1851 this.resize((capacity1 *= 2) > offset ? capacity1 : offset);
1852 offset -= 1;
1853 this.view[offset] = value;
1854 if (relative) this.offset += 1;
1855 return this;
1856 };
1857
1858 /**
1859 * Writes an 8bit unsigned integer. This is an alias of {@link ByteBuffer#writeUint8}.
1860 * @function
1861 * @param {number} value Value to write
1862 * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `1` if omitted.
1863 * @returns {!ByteBuffer} this
1864 * @expose
1865 */
1866 ByteBufferPrototype.writeUInt8 = ByteBufferPrototype.writeUint8;
1867
1868 /**
1869 * Reads an 8bit unsigned integer.
1870 * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `1` if omitted.
1871 * @returns {number} Value read
1872 * @expose
1873 */
1874 ByteBufferPrototype.readUint8 = function(offset) {
1875 var relative = typeof offset === 'undefined';
1876 if (relative) offset = this.offset;
1877 if (!this.noAssert) {
1878 if (typeof offset !== 'number' || offset % 1 !== 0)
1879 throw TypeError("Illegal offset: "+offset+" (not an integer)");
1880 offset >>>= 0;
1881 if (offset < 0 || offset + 1 > this.buffer.byteLength)
1882 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+1+") <= "+this.buffer.byteLength);
1883 }
1884 var value = this.view[offset];
1885 if (relative) this.offset += 1;
1886 return value;
1887 };
1888
1889 /**
1890 * Reads an 8bit unsigned integer. This is an alias of {@link ByteBuffer#readUint8}.
1891 * @function
1892 * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `1` if omitted.
1893 * @returns {number} Value read
1894 * @expose
1895 */
1896 ByteBufferPrototype.readUInt8 = ByteBufferPrototype.readUint8;
1897
1898 // types/ints/int16
1899
1900 /**
1901 * Writes a 16bit signed integer.
1902 * @param {number} value Value to write
1903 * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `2` if omitted.
1904 * @throws {TypeError} If `offset` or `value` is not a valid number
1905 * @throws {RangeError} If `offset` is out of bounds
1906 * @expose
1907 */
1908 ByteBufferPrototype.writeInt16 = function(value, offset) {
1909 var relative = typeof offset === 'undefined';
1910 if (relative) offset = this.offset;
1911 if (!this.noAssert) {
1912 if (typeof value !== 'number' || value % 1 !== 0)
1913 throw TypeError("Illegal value: "+value+" (not an integer)");
1914 value |= 0;
1915 if (typeof offset !== 'number' || offset % 1 !== 0)
1916 throw TypeError("Illegal offset: "+offset+" (not an integer)");
1917 offset >>>= 0;
1918 if (offset < 0 || offset + 0 > this.buffer.byteLength)
1919 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
1920 }
1921 offset += 2;
1922 var capacity2 = this.buffer.byteLength;
1923 if (offset > capacity2)
1924 this.resize((capacity2 *= 2) > offset ? capacity2 : offset);
1925 offset -= 2;
1926 if (this.littleEndian) {
1927 this.view[offset+1] = (value & 0xFF00) >>> 8;
1928 this.view[offset ] = value & 0x00FF;
1929 } else {
1930 this.view[offset] = (value & 0xFF00) >>> 8;
1931 this.view[offset+1] = value & 0x00FF;
1932 }
1933 if (relative) this.offset += 2;
1934 return this;
1935 };
1936
1937 /**
1938 * Writes a 16bit signed integer. This is an alias of {@link ByteBuffer#writeInt16}.
1939 * @function
1940 * @param {number} value Value to write
1941 * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `2` if omitted.
1942 * @throws {TypeError} If `offset` or `value` is not a valid number
1943 * @throws {RangeError} If `offset` is out of bounds
1944 * @expose
1945 */
1946 ByteBufferPrototype.writeShort = ByteBufferPrototype.writeInt16;
1947
1948 /**
1949 * Reads a 16bit signed integer.
1950 * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `2` if omitted.
1951 * @returns {number} Value read
1952 * @throws {TypeError} If `offset` is not a valid number
1953 * @throws {RangeError} If `offset` is out of bounds
1954 * @expose
1955 */
1956 ByteBufferPrototype.readInt16 = function(offset) {
1957 var relative = typeof offset === 'undefined';
1958 if (relative) offset = this.offset;
1959 if (!this.noAssert) {
1960 if (typeof offset !== 'number' || offset % 1 !== 0)
1961 throw TypeError("Illegal offset: "+offset+" (not an integer)");
1962 offset >>>= 0;
1963 if (offset < 0 || offset + 2 > this.buffer.byteLength)
1964 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+2+") <= "+this.buffer.byteLength);
1965 }
1966 var value = 0;
1967 if (this.littleEndian) {
1968 value = this.view[offset ];
1969 value |= this.view[offset+1] << 8;
1970 } else {
1971 value = this.view[offset ] << 8;
1972 value |= this.view[offset+1];
1973 }
1974 if ((value & 0x8000) === 0x8000) value = -(0xFFFF - value + 1); // Cast to signed
1975 if (relative) this.offset += 2;
1976 return value;
1977 };
1978
1979 /**
1980 * Reads a 16bit signed integer. This is an alias of {@link ByteBuffer#readInt16}.
1981 * @function
1982 * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `2` if omitted.
1983 * @returns {number} Value read
1984 * @throws {TypeError} If `offset` is not a valid number
1985 * @throws {RangeError} If `offset` is out of bounds
1986 * @expose
1987 */
1988 ByteBufferPrototype.readShort = ByteBufferPrototype.readInt16;
1989
1990 /**
1991 * Writes a 16bit unsigned integer.
1992 * @param {number} value Value to write
1993 * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `2` if omitted.
1994 * @throws {TypeError} If `offset` or `value` is not a valid number
1995 * @throws {RangeError} If `offset` is out of bounds
1996 * @expose
1997 */
1998 ByteBufferPrototype.writeUint16 = function(value, offset) {
1999 var relative = typeof offset === 'undefined';
2000 if (relative) offset = this.offset;
2001 if (!this.noAssert) {
2002 if (typeof value !== 'number' || value % 1 !== 0)
2003 throw TypeError("Illegal value: "+value+" (not an integer)");
2004 value >>>= 0;
2005 if (typeof offset !== 'number' || offset % 1 !== 0)
2006 throw TypeError("Illegal offset: "+offset+" (not an integer)");
2007 offset >>>= 0;
2008 if (offset < 0 || offset + 0 > this.buffer.byteLength)
2009 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
2010 }
2011 offset += 2;
2012 var capacity3 = this.buffer.byteLength;
2013 if (offset > capacity3)
2014 this.resize((capacity3 *= 2) > offset ? capacity3 : offset);
2015 offset -= 2;
2016 if (this.littleEndian) {
2017 this.view[offset+1] = (value & 0xFF00) >>> 8;
2018 this.view[offset ] = value & 0x00FF;
2019 } else {
2020 this.view[offset] = (value & 0xFF00) >>> 8;
2021 this.view[offset+1] = value & 0x00FF;
2022 }
2023 if (relative) this.offset += 2;
2024 return this;
2025 };
2026
2027 /**
2028 * Writes a 16bit unsigned integer. This is an alias of {@link ByteBuffer#writeUint16}.
2029 * @function
2030 * @param {number} value Value to write
2031 * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `2` if omitted.
2032 * @throws {TypeError} If `offset` or `value` is not a valid number
2033 * @throws {RangeError} If `offset` is out of bounds
2034 * @expose
2035 */
2036 ByteBufferPrototype.writeUInt16 = ByteBufferPrototype.writeUint16;
2037
2038 /**
2039 * Reads a 16bit unsigned integer.
2040 * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `2` if omitted.
2041 * @returns {number} Value read
2042 * @throws {TypeError} If `offset` is not a valid number
2043 * @throws {RangeError} If `offset` is out of bounds
2044 * @expose
2045 */
2046 ByteBufferPrototype.readUint16 = function(offset) {
2047 var relative = typeof offset === 'undefined';
2048 if (relative) offset = this.offset;
2049 if (!this.noAssert) {
2050 if (typeof offset !== 'number' || offset % 1 !== 0)
2051 throw TypeError("Illegal offset: "+offset+" (not an integer)");
2052 offset >>>= 0;
2053 if (offset < 0 || offset + 2 > this.buffer.byteLength)
2054 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+2+") <= "+this.buffer.byteLength);
2055 }
2056 var value = 0;
2057 if (this.littleEndian) {
2058 value = this.view[offset ];
2059 value |= this.view[offset+1] << 8;
2060 } else {
2061 value = this.view[offset ] << 8;
2062 value |= this.view[offset+1];
2063 }
2064 if (relative) this.offset += 2;
2065 return value;
2066 };
2067
2068 /**
2069 * Reads a 16bit unsigned integer. This is an alias of {@link ByteBuffer#readUint16}.
2070 * @function
2071 * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `2` if omitted.
2072 * @returns {number} Value read
2073 * @throws {TypeError} If `offset` is not a valid number
2074 * @throws {RangeError} If `offset` is out of bounds
2075 * @expose
2076 */
2077 ByteBufferPrototype.readUInt16 = ByteBufferPrototype.readUint16;
2078
2079 // types/ints/int32
2080
2081 /**
2082 * Writes a 32bit signed integer.
2083 * @param {number} value Value to write
2084 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
2085 * @expose
2086 */
2087 ByteBufferPrototype.writeInt32 = function(value, offset) {
2088 var relative = typeof offset === 'undefined';
2089 if (relative) offset = this.offset;
2090 if (!this.noAssert) {
2091 if (typeof value !== 'number' || value % 1 !== 0)
2092 throw TypeError("Illegal value: "+value+" (not an integer)");
2093 value |= 0;
2094 if (typeof offset !== 'number' || offset % 1 !== 0)
2095 throw TypeError("Illegal offset: "+offset+" (not an integer)");
2096 offset >>>= 0;
2097 if (offset < 0 || offset + 0 > this.buffer.byteLength)
2098 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
2099 }
2100 offset += 4;
2101 var capacity4 = this.buffer.byteLength;
2102 if (offset > capacity4)
2103 this.resize((capacity4 *= 2) > offset ? capacity4 : offset);
2104 offset -= 4;
2105 if (this.littleEndian) {
2106 this.view[offset+3] = (value >>> 24) & 0xFF;
2107 this.view[offset+2] = (value >>> 16) & 0xFF;
2108 this.view[offset+1] = (value >>> 8) & 0xFF;
2109 this.view[offset ] = value & 0xFF;
2110 } else {
2111 this.view[offset ] = (value >>> 24) & 0xFF;
2112 this.view[offset+1] = (value >>> 16) & 0xFF;
2113 this.view[offset+2] = (value >>> 8) & 0xFF;
2114 this.view[offset+3] = value & 0xFF;
2115 }
2116 if (relative) this.offset += 4;
2117 return this;
2118 };
2119
2120 /**
2121 * Writes a 32bit signed integer. This is an alias of {@link ByteBuffer#writeInt32}.
2122 * @param {number} value Value to write
2123 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
2124 * @expose
2125 */
2126 ByteBufferPrototype.writeInt = ByteBufferPrototype.writeInt32;
2127
2128 /**
2129 * Reads a 32bit signed integer.
2130 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
2131 * @returns {number} Value read
2132 * @expose
2133 */
2134 ByteBufferPrototype.readInt32 = function(offset) {
2135 var relative = typeof offset === 'undefined';
2136 if (relative) offset = this.offset;
2137 if (!this.noAssert) {
2138 if (typeof offset !== 'number' || offset % 1 !== 0)
2139 throw TypeError("Illegal offset: "+offset+" (not an integer)");
2140 offset >>>= 0;
2141 if (offset < 0 || offset + 4 > this.buffer.byteLength)
2142 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+4+") <= "+this.buffer.byteLength);
2143 }
2144 var value = 0;
2145 if (this.littleEndian) {
2146 value = this.view[offset+2] << 16;
2147 value |= this.view[offset+1] << 8;
2148 value |= this.view[offset ];
2149 value += this.view[offset+3] << 24 >>> 0;
2150 } else {
2151 value = this.view[offset+1] << 16;
2152 value |= this.view[offset+2] << 8;
2153 value |= this.view[offset+3];
2154 value += this.view[offset ] << 24 >>> 0;
2155 }
2156 value |= 0; // Cast to signed
2157 if (relative) this.offset += 4;
2158 return value;
2159 };
2160
2161 /**
2162 * Reads a 32bit signed integer. This is an alias of {@link ByteBuffer#readInt32}.
2163 * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `4` if omitted.
2164 * @returns {number} Value read
2165 * @expose
2166 */
2167 ByteBufferPrototype.readInt = ByteBufferPrototype.readInt32;
2168
2169 /**
2170 * Writes a 32bit unsigned integer.
2171 * @param {number} value Value to write
2172 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
2173 * @expose
2174 */
2175 ByteBufferPrototype.writeUint32 = function(value, offset) {
2176 var relative = typeof offset === 'undefined';
2177 if (relative) offset = this.offset;
2178 if (!this.noAssert) {
2179 if (typeof value !== 'number' || value % 1 !== 0)
2180 throw TypeError("Illegal value: "+value+" (not an integer)");
2181 value >>>= 0;
2182 if (typeof offset !== 'number' || offset % 1 !== 0)
2183 throw TypeError("Illegal offset: "+offset+" (not an integer)");
2184 offset >>>= 0;
2185 if (offset < 0 || offset + 0 > this.buffer.byteLength)
2186 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
2187 }
2188 offset += 4;
2189 var capacity5 = this.buffer.byteLength;
2190 if (offset > capacity5)
2191 this.resize((capacity5 *= 2) > offset ? capacity5 : offset);
2192 offset -= 4;
2193 if (this.littleEndian) {
2194 this.view[offset+3] = (value >>> 24) & 0xFF;
2195 this.view[offset+2] = (value >>> 16) & 0xFF;
2196 this.view[offset+1] = (value >>> 8) & 0xFF;
2197 this.view[offset ] = value & 0xFF;
2198 } else {
2199 this.view[offset ] = (value >>> 24) & 0xFF;
2200 this.view[offset+1] = (value >>> 16) & 0xFF;
2201 this.view[offset+2] = (value >>> 8) & 0xFF;
2202 this.view[offset+3] = value & 0xFF;
2203 }
2204 if (relative) this.offset += 4;
2205 return this;
2206 };
2207
2208 /**
2209 * Writes a 32bit unsigned integer. This is an alias of {@link ByteBuffer#writeUint32}.
2210 * @function
2211 * @param {number} value Value to write
2212 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
2213 * @expose
2214 */
2215 ByteBufferPrototype.writeUInt32 = ByteBufferPrototype.writeUint32;
2216
2217 /**
2218 * Reads a 32bit unsigned integer.
2219 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
2220 * @returns {number} Value read
2221 * @expose
2222 */
2223 ByteBufferPrototype.readUint32 = function(offset) {
2224 var relative = typeof offset === 'undefined';
2225 if (relative) offset = this.offset;
2226 if (!this.noAssert) {
2227 if (typeof offset !== 'number' || offset % 1 !== 0)
2228 throw TypeError("Illegal offset: "+offset+" (not an integer)");
2229 offset >>>= 0;
2230 if (offset < 0 || offset + 4 > this.buffer.byteLength)
2231 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+4+") <= "+this.buffer.byteLength);
2232 }
2233 var value = 0;
2234 if (this.littleEndian) {
2235 value = this.view[offset+2] << 16;
2236 value |= this.view[offset+1] << 8;
2237 value |= this.view[offset ];
2238 value += this.view[offset+3] << 24 >>> 0;
2239 } else {
2240 value = this.view[offset+1] << 16;
2241 value |= this.view[offset+2] << 8;
2242 value |= this.view[offset+3];
2243 value += this.view[offset ] << 24 >>> 0;
2244 }
2245 if (relative) this.offset += 4;
2246 return value;
2247 };
2248
2249 /**
2250 * Reads a 32bit unsigned integer. This is an alias of {@link ByteBuffer#readUint32}.
2251 * @function
2252 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
2253 * @returns {number} Value read
2254 * @expose
2255 */
2256 ByteBufferPrototype.readUInt32 = ByteBufferPrototype.readUint32;
2257
2258 // types/ints/int64
2259
2260 if (Long) {
2261
2262 /**
2263 * Writes a 64bit signed integer.
2264 * @param {number|!Long} value Value to write
2265 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
2266 * @returns {!ByteBuffer} this
2267 * @expose
2268 */
2269 ByteBufferPrototype.writeInt64 = function(value, offset) {
2270 var relative = typeof offset === 'undefined';
2271 if (relative) offset = this.offset;
2272 if (!this.noAssert) {
2273 if (typeof value === 'number')
2274 value = Long.fromNumber(value);
2275 else if (typeof value === 'string')
2276 value = Long.fromString(value);
2277 else if (!(value && value instanceof Long))
2278 throw TypeError("Illegal value: "+value+" (not an integer or Long)");
2279 if (typeof offset !== 'number' || offset % 1 !== 0)
2280 throw TypeError("Illegal offset: "+offset+" (not an integer)");
2281 offset >>>= 0;
2282 if (offset < 0 || offset + 0 > this.buffer.byteLength)
2283 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
2284 }
2285 if (typeof value === 'number')
2286 value = Long.fromNumber(value);
2287 else if (typeof value === 'string')
2288 value = Long.fromString(value);
2289 offset += 8;
2290 var capacity6 = this.buffer.byteLength;
2291 if (offset > capacity6)
2292 this.resize((capacity6 *= 2) > offset ? capacity6 : offset);
2293 offset -= 8;
2294 var lo = value.low,
2295 hi = value.high;
2296 if (this.littleEndian) {
2297 this.view[offset+3] = (lo >>> 24) & 0xFF;
2298 this.view[offset+2] = (lo >>> 16) & 0xFF;
2299 this.view[offset+1] = (lo >>> 8) & 0xFF;
2300 this.view[offset ] = lo & 0xFF;
2301 offset += 4;
2302 this.view[offset+3] = (hi >>> 24) & 0xFF;
2303 this.view[offset+2] = (hi >>> 16) & 0xFF;
2304 this.view[offset+1] = (hi >>> 8) & 0xFF;
2305 this.view[offset ] = hi & 0xFF;
2306 } else {
2307 this.view[offset ] = (hi >>> 24) & 0xFF;
2308 this.view[offset+1] = (hi >>> 16) & 0xFF;
2309 this.view[offset+2] = (hi >>> 8) & 0xFF;
2310 this.view[offset+3] = hi & 0xFF;
2311 offset += 4;
2312 this.view[offset ] = (lo >>> 24) & 0xFF;
2313 this.view[offset+1] = (lo >>> 16) & 0xFF;
2314 this.view[offset+2] = (lo >>> 8) & 0xFF;
2315 this.view[offset+3] = lo & 0xFF;
2316 }
2317 if (relative) this.offset += 8;
2318 return this;
2319 };
2320
2321 /**
2322 * Writes a 64bit signed integer. This is an alias of {@link ByteBuffer#writeInt64}.
2323 * @param {number|!Long} value Value to write
2324 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
2325 * @returns {!ByteBuffer} this
2326 * @expose
2327 */
2328 ByteBufferPrototype.writeLong = ByteBufferPrototype.writeInt64;
2329
2330 /**
2331 * Reads a 64bit signed integer.
2332 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
2333 * @returns {!Long}
2334 * @expose
2335 */
2336 ByteBufferPrototype.readInt64 = function(offset) {
2337 var relative = typeof offset === 'undefined';
2338 if (relative) offset = this.offset;
2339 if (!this.noAssert) {
2340 if (typeof offset !== 'number' || offset % 1 !== 0)
2341 throw TypeError("Illegal offset: "+offset+" (not an integer)");
2342 offset >>>= 0;
2343 if (offset < 0 || offset + 8 > this.buffer.byteLength)
2344 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+8+") <= "+this.buffer.byteLength);
2345 }
2346 var lo = 0,
2347 hi = 0;
2348 if (this.littleEndian) {
2349 lo = this.view[offset+2] << 16;
2350 lo |= this.view[offset+1] << 8;
2351 lo |= this.view[offset ];
2352 lo += this.view[offset+3] << 24 >>> 0;
2353 offset += 4;
2354 hi = this.view[offset+2] << 16;
2355 hi |= this.view[offset+1] << 8;
2356 hi |= this.view[offset ];
2357 hi += this.view[offset+3] << 24 >>> 0;
2358 } else {
2359 hi = this.view[offset+1] << 16;
2360 hi |= this.view[offset+2] << 8;
2361 hi |= this.view[offset+3];
2362 hi += this.view[offset ] << 24 >>> 0;
2363 offset += 4;
2364 lo = this.view[offset+1] << 16;
2365 lo |= this.view[offset+2] << 8;
2366 lo |= this.view[offset+3];
2367 lo += this.view[offset ] << 24 >>> 0;
2368 }
2369 var value = new Long(lo, hi, false);
2370 if (relative) this.offset += 8;
2371 return value;
2372 };
2373
2374 /**
2375 * Reads a 64bit signed integer. This is an alias of {@link ByteBuffer#readInt64}.
2376 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
2377 * @returns {!Long}
2378 * @expose
2379 */
2380 ByteBufferPrototype.readLong = ByteBufferPrototype.readInt64;
2381
2382 /**
2383 * Writes a 64bit unsigned integer.
2384 * @param {number|!Long} value Value to write
2385 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
2386 * @returns {!ByteBuffer} this
2387 * @expose
2388 */
2389 ByteBufferPrototype.writeUint64 = function(value, offset) {
2390 var relative = typeof offset === 'undefined';
2391 if (relative) offset = this.offset;
2392 if (!this.noAssert) {
2393 if (typeof value === 'number')
2394 value = Long.fromNumber(value);
2395 else if (typeof value === 'string')
2396 value = Long.fromString(value);
2397 else if (!(value && value instanceof Long))
2398 throw TypeError("Illegal value: "+value+" (not an integer or Long)");
2399 if (typeof offset !== 'number' || offset % 1 !== 0)
2400 throw TypeError("Illegal offset: "+offset+" (not an integer)");
2401 offset >>>= 0;
2402 if (offset < 0 || offset + 0 > this.buffer.byteLength)
2403 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
2404 }
2405 if (typeof value === 'number')
2406 value = Long.fromNumber(value);
2407 else if (typeof value === 'string')
2408 value = Long.fromString(value);
2409 offset += 8;
2410 var capacity7 = this.buffer.byteLength;
2411 if (offset > capacity7)
2412 this.resize((capacity7 *= 2) > offset ? capacity7 : offset);
2413 offset -= 8;
2414 var lo = value.low,
2415 hi = value.high;
2416 if (this.littleEndian) {
2417 this.view[offset+3] = (lo >>> 24) & 0xFF;
2418 this.view[offset+2] = (lo >>> 16) & 0xFF;
2419 this.view[offset+1] = (lo >>> 8) & 0xFF;
2420 this.view[offset ] = lo & 0xFF;
2421 offset += 4;
2422 this.view[offset+3] = (hi >>> 24) & 0xFF;
2423 this.view[offset+2] = (hi >>> 16) & 0xFF;
2424 this.view[offset+1] = (hi >>> 8) & 0xFF;
2425 this.view[offset ] = hi & 0xFF;
2426 } else {
2427 this.view[offset ] = (hi >>> 24) & 0xFF;
2428 this.view[offset+1] = (hi >>> 16) & 0xFF;
2429 this.view[offset+2] = (hi >>> 8) & 0xFF;
2430 this.view[offset+3] = hi & 0xFF;
2431 offset += 4;
2432 this.view[offset ] = (lo >>> 24) & 0xFF;
2433 this.view[offset+1] = (lo >>> 16) & 0xFF;
2434 this.view[offset+2] = (lo >>> 8) & 0xFF;
2435 this.view[offset+3] = lo & 0xFF;
2436 }
2437 if (relative) this.offset += 8;
2438 return this;
2439 };
2440
2441 /**
2442 * Writes a 64bit unsigned integer. This is an alias of {@link ByteBuffer#writeUint64}.
2443 * @function
2444 * @param {number|!Long} value Value to write
2445 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
2446 * @returns {!ByteBuffer} this
2447 * @expose
2448 */
2449 ByteBufferPrototype.writeUInt64 = ByteBufferPrototype.writeUint64;
2450
2451 /**
2452 * Reads a 64bit unsigned integer.
2453 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
2454 * @returns {!Long}
2455 * @expose
2456 */
2457 ByteBufferPrototype.readUint64 = function(offset) {
2458 var relative = typeof offset === 'undefined';
2459 if (relative) offset = this.offset;
2460 if (!this.noAssert) {
2461 if (typeof offset !== 'number' || offset % 1 !== 0)
2462 throw TypeError("Illegal offset: "+offset+" (not an integer)");
2463 offset >>>= 0;
2464 if (offset < 0 || offset + 8 > this.buffer.byteLength)
2465 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+8+") <= "+this.buffer.byteLength);
2466 }
2467 var lo = 0,
2468 hi = 0;
2469 if (this.littleEndian) {
2470 lo = this.view[offset+2] << 16;
2471 lo |= this.view[offset+1] << 8;
2472 lo |= this.view[offset ];
2473 lo += this.view[offset+3] << 24 >>> 0;
2474 offset += 4;
2475 hi = this.view[offset+2] << 16;
2476 hi |= this.view[offset+1] << 8;
2477 hi |= this.view[offset ];
2478 hi += this.view[offset+3] << 24 >>> 0;
2479 } else {
2480 hi = this.view[offset+1] << 16;
2481 hi |= this.view[offset+2] << 8;
2482 hi |= this.view[offset+3];
2483 hi += this.view[offset ] << 24 >>> 0;
2484 offset += 4;
2485 lo = this.view[offset+1] << 16;
2486 lo |= this.view[offset+2] << 8;
2487 lo |= this.view[offset+3];
2488 lo += this.view[offset ] << 24 >>> 0;
2489 }
2490 var value = new Long(lo, hi, true);
2491 if (relative) this.offset += 8;
2492 return value;
2493 };
2494
2495 /**
2496 * Reads a 64bit unsigned integer. This is an alias of {@link ByteBuffer#readUint64}.
2497 * @function
2498 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
2499 * @returns {!Long}
2500 * @expose
2501 */
2502 ByteBufferPrototype.readUInt64 = ByteBufferPrototype.readUint64;
2503
2504 } // Long
2505
2506
2507 // types/floats/float32
2508
2509 /*
2510 ieee754 - https://github.com/feross/ieee754
2511
2512 The MIT License (MIT)
2513
2514 Copyright (c) Feross Aboukhadijeh
2515
2516 Permission is hereby granted, free of charge, to any person obtaining a copy
2517 of this software and associated documentation files (the "Software"), to deal
2518 in the Software without restriction, including without limitation the rights
2519 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
2520 copies of the Software, and to permit persons to whom the Software is
2521 furnished to do so, subject to the following conditions:
2522
2523 The above copyright notice and this permission notice shall be included in
2524 all copies or substantial portions of the Software.
2525
2526 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
2527 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
2528 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
2529 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
2530 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
2531 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
2532 THE SOFTWARE.
2533 */
2534
2535 /**
2536 * Reads an IEEE754 float from a byte array.
2537 * @param {!Array} buffer
2538 * @param {number} offset
2539 * @param {boolean} isLE
2540 * @param {number} mLen
2541 * @param {number} nBytes
2542 * @returns {number}
2543 * @inner
2544 */
2545 function ieee754_read(buffer, offset, isLE, mLen, nBytes) {
2546 var e, m,
2547 eLen = nBytes * 8 - mLen - 1,
2548 eMax = (1 << eLen) - 1,
2549 eBias = eMax >> 1,
2550 nBits = -7,
2551 i = isLE ? (nBytes - 1) : 0,
2552 d = isLE ? -1 : 1,
2553 s = buffer[offset + i];
2554
2555 i += d;
2556
2557 e = s & ((1 << (-nBits)) - 1);
2558 s >>= (-nBits);
2559 nBits += eLen;
2560 for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
2561
2562 m = e & ((1 << (-nBits)) - 1);
2563 e >>= (-nBits);
2564 nBits += mLen;
2565 for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
2566
2567 if (e === 0) {
2568 e = 1 - eBias;
2569 } else if (e === eMax) {
2570 return m ? NaN : ((s ? -1 : 1) * Infinity);
2571 } else {
2572 m = m + Math.pow(2, mLen);
2573 e = e - eBias;
2574 }
2575 return (s ? -1 : 1) * m * Math.pow(2, e - mLen);
2576 }
2577
2578 /**
2579 * Writes an IEEE754 float to a byte array.
2580 * @param {!Array} buffer
2581 * @param {number} value
2582 * @param {number} offset
2583 * @param {boolean} isLE
2584 * @param {number} mLen
2585 * @param {number} nBytes
2586 * @inner
2587 */
2588 function ieee754_write(buffer, value, offset, isLE, mLen, nBytes) {
2589 var e, m, c,
2590 eLen = nBytes * 8 - mLen - 1,
2591 eMax = (1 << eLen) - 1,
2592 eBias = eMax >> 1,
2593 rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0),
2594 i = isLE ? 0 : (nBytes - 1),
2595 d = isLE ? 1 : -1,
2596 s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0;
2597
2598 value = Math.abs(value);
2599
2600 if (isNaN(value) || value === Infinity) {
2601 m = isNaN(value) ? 1 : 0;
2602 e = eMax;
2603 } else {
2604 e = Math.floor(Math.log(value) / Math.LN2);
2605 if (value * (c = Math.pow(2, -e)) < 1) {
2606 e--;
2607 c *= 2;
2608 }
2609 if (e + eBias >= 1) {
2610 value += rt / c;
2611 } else {
2612 value += rt * Math.pow(2, 1 - eBias);
2613 }
2614 if (value * c >= 2) {
2615 e++;
2616 c /= 2;
2617 }
2618
2619 if (e + eBias >= eMax) {
2620 m = 0;
2621 e = eMax;
2622 } else if (e + eBias >= 1) {
2623 m = (value * c - 1) * Math.pow(2, mLen);
2624 e = e + eBias;
2625 } else {
2626 m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
2627 e = 0;
2628 }
2629 }
2630
2631 for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
2632
2633 e = (e << mLen) | m;
2634 eLen += mLen;
2635 for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
2636
2637 buffer[offset + i - d] |= s * 128;
2638 }
2639
2640 /**
2641 * Writes a 32bit float.
2642 * @param {number} value Value to write
2643 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
2644 * @returns {!ByteBuffer} this
2645 * @expose
2646 */
2647 ByteBufferPrototype.writeFloat32 = function(value, offset) {
2648 var relative = typeof offset === 'undefined';
2649 if (relative) offset = this.offset;
2650 if (!this.noAssert) {
2651 if (typeof value !== 'number')
2652 throw TypeError("Illegal value: "+value+" (not a number)");
2653 if (typeof offset !== 'number' || offset % 1 !== 0)
2654 throw TypeError("Illegal offset: "+offset+" (not an integer)");
2655 offset >>>= 0;
2656 if (offset < 0 || offset + 0 > this.buffer.byteLength)
2657 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
2658 }
2659 offset += 4;
2660 var capacity8 = this.buffer.byteLength;
2661 if (offset > capacity8)
2662 this.resize((capacity8 *= 2) > offset ? capacity8 : offset);
2663 offset -= 4;
2664 ieee754_write(this.view, value, offset, this.littleEndian, 23, 4);
2665 if (relative) this.offset += 4;
2666 return this;
2667 };
2668
2669 /**
2670 * Writes a 32bit float. This is an alias of {@link ByteBuffer#writeFloat32}.
2671 * @function
2672 * @param {number} value Value to write
2673 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
2674 * @returns {!ByteBuffer} this
2675 * @expose
2676 */
2677 ByteBufferPrototype.writeFloat = ByteBufferPrototype.writeFloat32;
2678
2679 /**
2680 * Reads a 32bit float.
2681 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
2682 * @returns {number}
2683 * @expose
2684 */
2685 ByteBufferPrototype.readFloat32 = function(offset) {
2686 var relative = typeof offset === 'undefined';
2687 if (relative) offset = this.offset;
2688 if (!this.noAssert) {
2689 if (typeof offset !== 'number' || offset % 1 !== 0)
2690 throw TypeError("Illegal offset: "+offset+" (not an integer)");
2691 offset >>>= 0;
2692 if (offset < 0 || offset + 4 > this.buffer.byteLength)
2693 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+4+") <= "+this.buffer.byteLength);
2694 }
2695 var value = ieee754_read(this.view, offset, this.littleEndian, 23, 4);
2696 if (relative) this.offset += 4;
2697 return value;
2698 };
2699
2700 /**
2701 * Reads a 32bit float. This is an alias of {@link ByteBuffer#readFloat32}.
2702 * @function
2703 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
2704 * @returns {number}
2705 * @expose
2706 */
2707 ByteBufferPrototype.readFloat = ByteBufferPrototype.readFloat32;
2708
2709 // types/floats/float64
2710
2711 /**
2712 * Writes a 64bit float.
2713 * @param {number} value Value to write
2714 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
2715 * @returns {!ByteBuffer} this
2716 * @expose
2717 */
2718 ByteBufferPrototype.writeFloat64 = function(value, offset) {
2719 var relative = typeof offset === 'undefined';
2720 if (relative) offset = this.offset;
2721 if (!this.noAssert) {
2722 if (typeof value !== 'number')
2723 throw TypeError("Illegal value: "+value+" (not a number)");
2724 if (typeof offset !== 'number' || offset % 1 !== 0)
2725 throw TypeError("Illegal offset: "+offset+" (not an integer)");
2726 offset >>>= 0;
2727 if (offset < 0 || offset + 0 > this.buffer.byteLength)
2728 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
2729 }
2730 offset += 8;
2731 var capacity9 = this.buffer.byteLength;
2732 if (offset > capacity9)
2733 this.resize((capacity9 *= 2) > offset ? capacity9 : offset);
2734 offset -= 8;
2735 ieee754_write(this.view, value, offset, this.littleEndian, 52, 8);
2736 if (relative) this.offset += 8;
2737 return this;
2738 };
2739
2740 /**
2741 * Writes a 64bit float. This is an alias of {@link ByteBuffer#writeFloat64}.
2742 * @function
2743 * @param {number} value Value to write
2744 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
2745 * @returns {!ByteBuffer} this
2746 * @expose
2747 */
2748 ByteBufferPrototype.writeDouble = ByteBufferPrototype.writeFloat64;
2749
2750 /**
2751 * Reads a 64bit float.
2752 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
2753 * @returns {number}
2754 * @expose
2755 */
2756 ByteBufferPrototype.readFloat64 = function(offset) {
2757 var relative = typeof offset === 'undefined';
2758 if (relative) offset = this.offset;
2759 if (!this.noAssert) {
2760 if (typeof offset !== 'number' || offset % 1 !== 0)
2761 throw TypeError("Illegal offset: "+offset+" (not an integer)");
2762 offset >>>= 0;
2763 if (offset < 0 || offset + 8 > this.buffer.byteLength)
2764 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+8+") <= "+this.buffer.byteLength);
2765 }
2766 var value = ieee754_read(this.view, offset, this.littleEndian, 52, 8);
2767 if (relative) this.offset += 8;
2768 return value;
2769 };
2770
2771 /**
2772 * Reads a 64bit float. This is an alias of {@link ByteBuffer#readFloat64}.
2773 * @function
2774 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
2775 * @returns {number}
2776 * @expose
2777 */
2778 ByteBufferPrototype.readDouble = ByteBufferPrototype.readFloat64;
2779
2780
2781 // types/varints/varint32
2782
2783 /**
2784 * Maximum number of bytes required to store a 32bit base 128 variable-length integer.
2785 * @type {number}
2786 * @const
2787 * @expose
2788 */
2789 ByteBuffer.MAX_VARINT32_BYTES = 5;
2790
2791 /**
2792 * Calculates the actual number of bytes required to store a 32bit base 128 variable-length integer.
2793 * @param {number} value Value to encode
2794 * @returns {number} Number of bytes required. Capped to {@link ByteBuffer.MAX_VARINT32_BYTES}
2795 * @expose
2796 */
2797 ByteBuffer.calculateVarint32 = function(value) {
2798 // ref: src/google/protobuf/io/coded_stream.cc
2799 value = value >>> 0;
2800 if (value < 1 << 7 ) return 1;
2801 else if (value < 1 << 14) return 2;
2802 else if (value < 1 << 21) return 3;
2803 else if (value < 1 << 28) return 4;
2804 else return 5;
2805 };
2806
2807 /**
2808 * Zigzag encodes a signed 32bit integer so that it can be effectively used with varint encoding.
2809 * @param {number} n Signed 32bit integer
2810 * @returns {number} Unsigned zigzag encoded 32bit integer
2811 * @expose
2812 */
2813 ByteBuffer.zigZagEncode32 = function(n) {
2814 return (((n |= 0) << 1) ^ (n >> 31)) >>> 0; // ref: src/google/protobuf/wire_format_lite.h
2815 };
2816
2817 /**
2818 * Decodes a zigzag encoded signed 32bit integer.
2819 * @param {number} n Unsigned zigzag encoded 32bit integer
2820 * @returns {number} Signed 32bit integer
2821 * @expose
2822 */
2823 ByteBuffer.zigZagDecode32 = function(n) {
2824 return ((n >>> 1) ^ -(n & 1)) | 0; // // ref: src/google/protobuf/wire_format_lite.h
2825 };
2826
2827 /**
2828 * Writes a 32bit base 128 variable-length integer.
2829 * @param {number} value Value to write
2830 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
2831 * written if omitted.
2832 * @returns {!ByteBuffer|number} this if `offset` is omitted, else the actual number of bytes written
2833 * @expose
2834 */
2835 ByteBufferPrototype.writeVarint32 = function(value, offset) {
2836 var relative = typeof offset === 'undefined';
2837 if (relative) offset = this.offset;
2838 if (!this.noAssert) {
2839 if (typeof value !== 'number' || value % 1 !== 0)
2840 throw TypeError("Illegal value: "+value+" (not an integer)");
2841 value |= 0;
2842 if (typeof offset !== 'number' || offset % 1 !== 0)
2843 throw TypeError("Illegal offset: "+offset+" (not an integer)");
2844 offset >>>= 0;
2845 if (offset < 0 || offset + 0 > this.buffer.byteLength)
2846 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
2847 }
2848 var size = ByteBuffer.calculateVarint32(value),
2849 b;
2850 offset += size;
2851 var capacity10 = this.buffer.byteLength;
2852 if (offset > capacity10)
2853 this.resize((capacity10 *= 2) > offset ? capacity10 : offset);
2854 offset -= size;
2855 value >>>= 0;
2856 while (value >= 0x80) {
2857 b = (value & 0x7f) | 0x80;
2858 this.view[offset++] = b;
2859 value >>>= 7;
2860 }
2861 this.view[offset++] = value;
2862 if (relative) {
2863 this.offset = offset;
2864 return this;
2865 }
2866 return size;
2867 };
2868
2869 /**
2870 * Writes a zig-zag encoded (signed) 32bit base 128 variable-length integer.
2871 * @param {number} value Value to write
2872 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
2873 * written if omitted.
2874 * @returns {!ByteBuffer|number} this if `offset` is omitted, else the actual number of bytes written
2875 * @expose
2876 */
2877 ByteBufferPrototype.writeVarint32ZigZag = function(value, offset) {
2878 return this.writeVarint32(ByteBuffer.zigZagEncode32(value), offset);
2879 };
2880
2881 /**
2882 * Reads a 32bit base 128 variable-length integer.
2883 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
2884 * written if omitted.
2885 * @returns {number|!{value: number, length: number}} The value read if offset is omitted, else the value read
2886 * and the actual number of bytes read.
2887 * @throws {Error} If it's not a valid varint. Has a property `truncated = true` if there is not enough data available
2888 * to fully decode the varint.
2889 * @expose
2890 */
2891 ByteBufferPrototype.readVarint32 = function(offset) {
2892 var relative = typeof offset === 'undefined';
2893 if (relative) offset = this.offset;
2894 if (!this.noAssert) {
2895 if (typeof offset !== 'number' || offset % 1 !== 0)
2896 throw TypeError("Illegal offset: "+offset+" (not an integer)");
2897 offset >>>= 0;
2898 if (offset < 0 || offset + 1 > this.buffer.byteLength)
2899 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+1+") <= "+this.buffer.byteLength);
2900 }
2901 var c = 0,
2902 value = 0 >>> 0,
2903 b;
2904 do {
2905 if (!this.noAssert && offset > this.limit) {
2906 var err = Error("Truncated");
2907 err['truncated'] = true;
2908 throw err;
2909 }
2910 b = this.view[offset++];
2911 if (c < 5)
2912 value |= (b & 0x7f) << (7*c);
2913 ++c;
2914 } while ((b & 0x80) !== 0);
2915 value |= 0;
2916 if (relative) {
2917 this.offset = offset;
2918 return value;
2919 }
2920 return {
2921 "value": value,
2922 "length": c
2923 };
2924 };
2925
2926 /**
2927 * Reads a zig-zag encoded (signed) 32bit base 128 variable-length integer.
2928 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
2929 * written if omitted.
2930 * @returns {number|!{value: number, length: number}} The value read if offset is omitted, else the value read
2931 * and the actual number of bytes read.
2932 * @throws {Error} If it's not a valid varint
2933 * @expose
2934 */
2935 ByteBufferPrototype.readVarint32ZigZag = function(offset) {
2936 var val = this.readVarint32(offset);
2937 if (typeof val === 'object')
2938 val["value"] = ByteBuffer.zigZagDecode32(val["value"]);
2939 else
2940 val = ByteBuffer.zigZagDecode32(val);
2941 return val;
2942 };
2943
2944 // types/varints/varint64
2945
2946 if (Long) {
2947
2948 /**
2949 * Maximum number of bytes required to store a 64bit base 128 variable-length integer.
2950 * @type {number}
2951 * @const
2952 * @expose
2953 */
2954 ByteBuffer.MAX_VARINT64_BYTES = 10;
2955
2956 /**
2957 * Calculates the actual number of bytes required to store a 64bit base 128 variable-length integer.
2958 * @param {number|!Long} value Value to encode
2959 * @returns {number} Number of bytes required. Capped to {@link ByteBuffer.MAX_VARINT64_BYTES}
2960 * @expose
2961 */
2962 ByteBuffer.calculateVarint64 = function(value) {
2963 if (typeof value === 'number')
2964 value = Long.fromNumber(value);
2965 else if (typeof value === 'string')
2966 value = Long.fromString(value);
2967 // ref: src/google/protobuf/io/coded_stream.cc
2968 var part0 = value.toInt() >>> 0,
2969 part1 = value.shiftRightUnsigned(28).toInt() >>> 0,
2970 part2 = value.shiftRightUnsigned(56).toInt() >>> 0;
2971 if (part2 == 0) {
2972 if (part1 == 0) {
2973 if (part0 < 1 << 14)
2974 return part0 < 1 << 7 ? 1 : 2;
2975 else
2976 return part0 < 1 << 21 ? 3 : 4;
2977 } else {
2978 if (part1 < 1 << 14)
2979 return part1 < 1 << 7 ? 5 : 6;
2980 else
2981 return part1 < 1 << 21 ? 7 : 8;
2982 }
2983 } else
2984 return part2 < 1 << 7 ? 9 : 10;
2985 };
2986
2987 /**
2988 * Zigzag encodes a signed 64bit integer so that it can be effectively used with varint encoding.
2989 * @param {number|!Long} value Signed long
2990 * @returns {!Long} Unsigned zigzag encoded long
2991 * @expose
2992 */
2993 ByteBuffer.zigZagEncode64 = function(value) {
2994 if (typeof value === 'number')
2995 value = Long.fromNumber(value, false);
2996 else if (typeof value === 'string')
2997 value = Long.fromString(value, false);
2998 else if (value.unsigned !== false) value = value.toSigned();
2999 // ref: src/google/protobuf/wire_format_lite.h
3000 return value.shiftLeft(1).xor(value.shiftRight(63)).toUnsigned();
3001 };
3002
3003 /**
3004 * Decodes a zigzag encoded signed 64bit integer.
3005 * @param {!Long|number} value Unsigned zigzag encoded long or JavaScript number
3006 * @returns {!Long} Signed long
3007 * @expose
3008 */
3009 ByteBuffer.zigZagDecode64 = function(value) {
3010 if (typeof value === 'number')
3011 value = Long.fromNumber(value, false);
3012 else if (typeof value === 'string')
3013 value = Long.fromString(value, false);
3014 else if (value.unsigned !== false) value = value.toSigned();
3015 // ref: src/google/protobuf/wire_format_lite.h
3016 return value.shiftRightUnsigned(1).xor(value.and(Long.ONE).toSigned().negate()).toSigned();
3017 };
3018
3019 /**
3020 * Writes a 64bit base 128 variable-length integer.
3021 * @param {number|Long} value Value to write
3022 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
3023 * written if omitted.
3024 * @returns {!ByteBuffer|number} `this` if offset is omitted, else the actual number of bytes written.
3025 * @expose
3026 */
3027 ByteBufferPrototype.writeVarint64 = function(value, offset) {
3028 var relative = typeof offset === 'undefined';
3029 if (relative) offset = this.offset;
3030 if (!this.noAssert) {
3031 if (typeof value === 'number')
3032 value = Long.fromNumber(value);
3033 else if (typeof value === 'string')
3034 value = Long.fromString(value);
3035 else if (!(value && value instanceof Long))
3036 throw TypeError("Illegal value: "+value+" (not an integer or Long)");
3037 if (typeof offset !== 'number' || offset % 1 !== 0)
3038 throw TypeError("Illegal offset: "+offset+" (not an integer)");
3039 offset >>>= 0;
3040 if (offset < 0 || offset + 0 > this.buffer.byteLength)
3041 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
3042 }
3043 if (typeof value === 'number')
3044 value = Long.fromNumber(value, false);
3045 else if (typeof value === 'string')
3046 value = Long.fromString(value, false);
3047 else if (value.unsigned !== false) value = value.toSigned();
3048 var size = ByteBuffer.calculateVarint64(value),
3049 part0 = value.toInt() >>> 0,
3050 part1 = value.shiftRightUnsigned(28).toInt() >>> 0,
3051 part2 = value.shiftRightUnsigned(56).toInt() >>> 0;
3052 offset += size;
3053 var capacity11 = this.buffer.byteLength;
3054 if (offset > capacity11)
3055 this.resize((capacity11 *= 2) > offset ? capacity11 : offset);
3056 offset -= size;
3057 switch (size) {
3058 case 10: this.view[offset+9] = (part2 >>> 7) & 0x01;
3059 case 9 : this.view[offset+8] = size !== 9 ? (part2 ) | 0x80 : (part2 ) & 0x7F;
3060 case 8 : this.view[offset+7] = size !== 8 ? (part1 >>> 21) | 0x80 : (part1 >>> 21) & 0x7F;
3061 case 7 : this.view[offset+6] = size !== 7 ? (part1 >>> 14) | 0x80 : (part1 >>> 14) & 0x7F;
3062 case 6 : this.view[offset+5] = size !== 6 ? (part1 >>> 7) | 0x80 : (part1 >>> 7) & 0x7F;
3063 case 5 : this.view[offset+4] = size !== 5 ? (part1 ) | 0x80 : (part1 ) & 0x7F;
3064 case 4 : this.view[offset+3] = size !== 4 ? (part0 >>> 21) | 0x80 : (part0 >>> 21) & 0x7F;
3065 case 3 : this.view[offset+2] = size !== 3 ? (part0 >>> 14) | 0x80 : (part0 >>> 14) & 0x7F;
3066 case 2 : this.view[offset+1] = size !== 2 ? (part0 >>> 7) | 0x80 : (part0 >>> 7) & 0x7F;
3067 case 1 : this.view[offset ] = size !== 1 ? (part0 ) | 0x80 : (part0 ) & 0x7F;
3068 }
3069 if (relative) {
3070 this.offset += size;
3071 return this;
3072 } else {
3073 return size;
3074 }
3075 };
3076
3077 /**
3078 * Writes a zig-zag encoded 64bit base 128 variable-length integer.
3079 * @param {number|Long} value Value to write
3080 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
3081 * written if omitted.
3082 * @returns {!ByteBuffer|number} `this` if offset is omitted, else the actual number of bytes written.
3083 * @expose
3084 */
3085 ByteBufferPrototype.writeVarint64ZigZag = function(value, offset) {
3086 return this.writeVarint64(ByteBuffer.zigZagEncode64(value), offset);
3087 };
3088
3089 /**
3090 * Reads a 64bit base 128 variable-length integer. Requires Long.js.
3091 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
3092 * read if omitted.
3093 * @returns {!Long|!{value: Long, length: number}} The value read if offset is omitted, else the value read and
3094 * the actual number of bytes read.
3095 * @throws {Error} If it's not a valid varint
3096 * @expose
3097 */
3098 ByteBufferPrototype.readVarint64 = function(offset) {
3099 var relative = typeof offset === 'undefined';
3100 if (relative) offset = this.offset;
3101 if (!this.noAssert) {
3102 if (typeof offset !== 'number' || offset % 1 !== 0)
3103 throw TypeError("Illegal offset: "+offset+" (not an integer)");
3104 offset >>>= 0;
3105 if (offset < 0 || offset + 1 > this.buffer.byteLength)
3106 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+1+") <= "+this.buffer.byteLength);
3107 }
3108 // ref: src/google/protobuf/io/coded_stream.cc
3109 var start = offset,
3110 part0 = 0,
3111 part1 = 0,
3112 part2 = 0,
3113 b = 0;
3114 b = this.view[offset++]; part0 = (b & 0x7F) ; if ( b & 0x80 ) {
3115 b = this.view[offset++]; part0 |= (b & 0x7F) << 7; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
3116 b = this.view[offset++]; part0 |= (b & 0x7F) << 14; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
3117 b = this.view[offset++]; part0 |= (b & 0x7F) << 21; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
3118 b = this.view[offset++]; part1 = (b & 0x7F) ; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
3119 b = this.view[offset++]; part1 |= (b & 0x7F) << 7; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
3120 b = this.view[offset++]; part1 |= (b & 0x7F) << 14; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
3121 b = this.view[offset++]; part1 |= (b & 0x7F) << 21; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
3122 b = this.view[offset++]; part2 = (b & 0x7F) ; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
3123 b = this.view[offset++]; part2 |= (b & 0x7F) << 7; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
3124 throw Error("Buffer overrun"); }}}}}}}}}}
3125 var value = Long.fromBits(part0 | (part1 << 28), (part1 >>> 4) | (part2) << 24, false);
3126 if (relative) {
3127 this.offset = offset;
3128 return value;
3129 } else {
3130 return {
3131 'value': value,
3132 'length': offset-start
3133 };
3134 }
3135 };
3136
3137 /**
3138 * Reads a zig-zag encoded 64bit base 128 variable-length integer. Requires Long.js.
3139 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
3140 * read if omitted.
3141 * @returns {!Long|!{value: Long, length: number}} The value read if offset is omitted, else the value read and
3142 * the actual number of bytes read.
3143 * @throws {Error} If it's not a valid varint
3144 * @expose
3145 */
3146 ByteBufferPrototype.readVarint64ZigZag = function(offset) {
3147 var val = this.readVarint64(offset);
3148 if (val && val['value'] instanceof Long)
3149 val["value"] = ByteBuffer.zigZagDecode64(val["value"]);
3150 else
3151 val = ByteBuffer.zigZagDecode64(val);
3152 return val;
3153 };
3154
3155 } // Long
3156
3157
3158 // types/strings/cstring
3159
3160 /**
3161 * Writes a NULL-terminated UTF8 encoded string. For this to work the specified string must not contain any NULL
3162 * characters itself.
3163 * @param {string} str String to write
3164 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
3165 * contained in `str` + 1 if omitted.
3166 * @returns {!ByteBuffer|number} this if offset is omitted, else the actual number of bytes written
3167 * @expose
3168 */
3169 ByteBufferPrototype.writeCString = function(str, offset) {
3170 var relative = typeof offset === 'undefined';
3171 if (relative) offset = this.offset;
3172 var i,
3173 k = str.length;
3174 if (!this.noAssert) {
3175 if (typeof str !== 'string')
3176 throw TypeError("Illegal str: Not a string");
3177 for (i=0; i<k; ++i) {
3178 if (str.charCodeAt(i) === 0)
3179 throw RangeError("Illegal str: Contains NULL-characters");
3180 }
3181 if (typeof offset !== 'number' || offset % 1 !== 0)
3182 throw TypeError("Illegal offset: "+offset+" (not an integer)");
3183 offset >>>= 0;
3184 if (offset < 0 || offset + 0 > this.buffer.byteLength)
3185 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
3186 }
3187 // UTF8 strings do not contain zero bytes in between except for the zero character, so:
3188 k = utfx.calculateUTF16asUTF8(stringSource(str))[1];
3189 offset += k+1;
3190 var capacity12 = this.buffer.byteLength;
3191 if (offset > capacity12)
3192 this.resize((capacity12 *= 2) > offset ? capacity12 : offset);
3193 offset -= k+1;
3194 utfx.encodeUTF16toUTF8(stringSource(str), function(b) {
3195 this.view[offset++] = b;
3196 }.bind(this));
3197 this.view[offset++] = 0;
3198 if (relative) {
3199 this.offset = offset;
3200 return this;
3201 }
3202 return k;
3203 };
3204
3205 /**
3206 * Reads a NULL-terminated UTF8 encoded string. For this to work the string read must not contain any NULL characters
3207 * itself.
3208 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
3209 * read if omitted.
3210 * @returns {string|!{string: string, length: number}} The string read if offset is omitted, else the string
3211 * read and the actual number of bytes read.
3212 * @expose
3213 */
3214 ByteBufferPrototype.readCString = function(offset) {
3215 var relative = typeof offset === 'undefined';
3216 if (relative) offset = this.offset;
3217 if (!this.noAssert) {
3218 if (typeof offset !== 'number' || offset % 1 !== 0)
3219 throw TypeError("Illegal offset: "+offset+" (not an integer)");
3220 offset >>>= 0;
3221 if (offset < 0 || offset + 1 > this.buffer.byteLength)
3222 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+1+") <= "+this.buffer.byteLength);
3223 }
3224 var start = offset;
3225 // UTF8 strings do not contain zero bytes in between except for the zero character itself, so:
3226 var sd, b = -1;
3227 utfx.decodeUTF8toUTF16(function() {
3228 if (b === 0) return null;
3229 if (offset >= this.limit)
3230 throw RangeError("Illegal range: Truncated data, "+offset+" < "+this.limit);
3231 b = this.view[offset++];
3232 return b === 0 ? null : b;
3233 }.bind(this), sd = stringDestination(), true);
3234 if (relative) {
3235 this.offset = offset;
3236 return sd();
3237 } else {
3238 return {
3239 "string": sd(),
3240 "length": offset - start
3241 };
3242 }
3243 };
3244
3245 // types/strings/istring
3246
3247 /**
3248 * Writes a length as uint32 prefixed UTF8 encoded string.
3249 * @param {string} str String to write
3250 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
3251 * written if omitted.
3252 * @returns {!ByteBuffer|number} `this` if `offset` is omitted, else the actual number of bytes written
3253 * @expose
3254 * @see ByteBuffer#writeVarint32
3255 */
3256 ByteBufferPrototype.writeIString = function(str, offset) {
3257 var relative = typeof offset === 'undefined';
3258 if (relative) offset = this.offset;
3259 if (!this.noAssert) {
3260 if (typeof str !== 'string')
3261 throw TypeError("Illegal str: Not a string");
3262 if (typeof offset !== 'number' || offset % 1 !== 0)
3263 throw TypeError("Illegal offset: "+offset+" (not an integer)");
3264 offset >>>= 0;
3265 if (offset < 0 || offset + 0 > this.buffer.byteLength)
3266 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
3267 }
3268 var start = offset,
3269 k;
3270 k = utfx.calculateUTF16asUTF8(stringSource(str), this.noAssert)[1];
3271 offset += 4+k;
3272 var capacity13 = this.buffer.byteLength;
3273 if (offset > capacity13)
3274 this.resize((capacity13 *= 2) > offset ? capacity13 : offset);
3275 offset -= 4+k;
3276 if (this.littleEndian) {
3277 this.view[offset+3] = (k >>> 24) & 0xFF;
3278 this.view[offset+2] = (k >>> 16) & 0xFF;
3279 this.view[offset+1] = (k >>> 8) & 0xFF;
3280 this.view[offset ] = k & 0xFF;
3281 } else {
3282 this.view[offset ] = (k >>> 24) & 0xFF;
3283 this.view[offset+1] = (k >>> 16) & 0xFF;
3284 this.view[offset+2] = (k >>> 8) & 0xFF;
3285 this.view[offset+3] = k & 0xFF;
3286 }
3287 offset += 4;
3288 utfx.encodeUTF16toUTF8(stringSource(str), function(b) {
3289 this.view[offset++] = b;
3290 }.bind(this));
3291 if (offset !== start + 4 + k)
3292 throw RangeError("Illegal range: Truncated data, "+offset+" == "+(offset+4+k));
3293 if (relative) {
3294 this.offset = offset;
3295 return this;
3296 }
3297 return offset - start;
3298 };
3299
3300 /**
3301 * Reads a length as uint32 prefixed UTF8 encoded string.
3302 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
3303 * read if omitted.
3304 * @returns {string|!{string: string, length: number}} The string read if offset is omitted, else the string
3305 * read and the actual number of bytes read.
3306 * @expose
3307 * @see ByteBuffer#readVarint32
3308 */
3309 ByteBufferPrototype.readIString = function(offset) {
3310 var relative = typeof offset === 'undefined';
3311 if (relative) offset = this.offset;
3312 if (!this.noAssert) {
3313 if (typeof offset !== 'number' || offset % 1 !== 0)
3314 throw TypeError("Illegal offset: "+offset+" (not an integer)");
3315 offset >>>= 0;
3316 if (offset < 0 || offset + 4 > this.buffer.byteLength)
3317 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+4+") <= "+this.buffer.byteLength);
3318 }
3319 var start = offset;
3320 var len = this.readUint32(offset);
3321 var str = this.readUTF8String(len, ByteBuffer.METRICS_BYTES, offset += 4);
3322 offset += str['length'];
3323 if (relative) {
3324 this.offset = offset;
3325 return str['string'];
3326 } else {
3327 return {
3328 'string': str['string'],
3329 'length': offset - start
3330 };
3331 }
3332 };
3333
3334 // types/strings/utf8string
3335
3336 /**
3337 * Metrics representing number of UTF8 characters. Evaluates to `c`.
3338 * @type {string}
3339 * @const
3340 * @expose
3341 */
3342 ByteBuffer.METRICS_CHARS = 'c';
3343
3344 /**
3345 * Metrics representing number of bytes. Evaluates to `b`.
3346 * @type {string}
3347 * @const
3348 * @expose
3349 */
3350 ByteBuffer.METRICS_BYTES = 'b';
3351
3352 /**
3353 * Writes an UTF8 encoded string.
3354 * @param {string} str String to write
3355 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} if omitted.
3356 * @returns {!ByteBuffer|number} this if offset is omitted, else the actual number of bytes written.
3357 * @expose
3358 */
3359 ByteBufferPrototype.writeUTF8String = function(str, offset) {
3360 var relative = typeof offset === 'undefined';
3361 if (relative) offset = this.offset;
3362 if (!this.noAssert) {
3363 if (typeof offset !== 'number' || offset % 1 !== 0)
3364 throw TypeError("Illegal offset: "+offset+" (not an integer)");
3365 offset >>>= 0;
3366 if (offset < 0 || offset + 0 > this.buffer.byteLength)
3367 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
3368 }
3369 var k;
3370 var start = offset;
3371 k = utfx.calculateUTF16asUTF8(stringSource(str))[1];
3372 offset += k;
3373 var capacity14 = this.buffer.byteLength;
3374 if (offset > capacity14)
3375 this.resize((capacity14 *= 2) > offset ? capacity14 : offset);
3376 offset -= k;
3377 utfx.encodeUTF16toUTF8(stringSource(str), function(b) {
3378 this.view[offset++] = b;
3379 }.bind(this));
3380 if (relative) {
3381 this.offset = offset;
3382 return this;
3383 }
3384 return offset - start;
3385 };
3386
3387 /**
3388 * Writes an UTF8 encoded string. This is an alias of {@link ByteBuffer#writeUTF8String}.
3389 * @function
3390 * @param {string} str String to write
3391 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} if omitted.
3392 * @returns {!ByteBuffer|number} this if offset is omitted, else the actual number of bytes written.
3393 * @expose
3394 */
3395 ByteBufferPrototype.writeString = ByteBufferPrototype.writeUTF8String;
3396
3397 /**
3398 * Calculates the number of UTF8 characters of a string. JavaScript itself uses UTF-16, so that a string's
3399 * `length` property does not reflect its actual UTF8 size if it contains code points larger than 0xFFFF.
3400 * @param {string} str String to calculate
3401 * @returns {number} Number of UTF8 characters
3402 * @expose
3403 */
3404 ByteBuffer.calculateUTF8Chars = function(str) {
3405 return utfx.calculateUTF16asUTF8(stringSource(str))[0];
3406 };
3407
3408 /**
3409 * Calculates the number of UTF8 bytes of a string.
3410 * @param {string} str String to calculate
3411 * @returns {number} Number of UTF8 bytes
3412 * @expose
3413 */
3414 ByteBuffer.calculateUTF8Bytes = function(str) {
3415 return utfx.calculateUTF16asUTF8(stringSource(str))[1];
3416 };
3417
3418 /**
3419 * Calculates the number of UTF8 bytes of a string. This is an alias of {@link ByteBuffer.calculateUTF8Bytes}.
3420 * @function
3421 * @param {string} str String to calculate
3422 * @returns {number} Number of UTF8 bytes
3423 * @expose
3424 */
3425 ByteBuffer.calculateString = ByteBuffer.calculateUTF8Bytes;
3426
3427 /**
3428 * Reads an UTF8 encoded string.
3429 * @param {number} length Number of characters or bytes to read.
3430 * @param {string=} metrics Metrics specifying what `length` is meant to count. Defaults to
3431 * {@link ByteBuffer.METRICS_CHARS}.
3432 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
3433 * read if omitted.
3434 * @returns {string|!{string: string, length: number}} The string read if offset is omitted, else the string
3435 * read and the actual number of bytes read.
3436 * @expose
3437 */
3438 ByteBufferPrototype.readUTF8String = function(length, metrics, offset) {
3439 if (typeof metrics === 'number') {
3440 offset = metrics;
3441 metrics = undefined;
3442 }
3443 var relative = typeof offset === 'undefined';
3444 if (relative) offset = this.offset;
3445 if (typeof metrics === 'undefined') metrics = ByteBuffer.METRICS_CHARS;
3446 if (!this.noAssert) {
3447 if (typeof length !== 'number' || length % 1 !== 0)
3448 throw TypeError("Illegal length: "+length+" (not an integer)");
3449 length |= 0;
3450 if (typeof offset !== 'number' || offset % 1 !== 0)
3451 throw TypeError("Illegal offset: "+offset+" (not an integer)");
3452 offset >>>= 0;
3453 if (offset < 0 || offset + 0 > this.buffer.byteLength)
3454 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
3455 }
3456 var i = 0,
3457 start = offset,
3458 sd;
3459 if (metrics === ByteBuffer.METRICS_CHARS) { // The same for node and the browser
3460 sd = stringDestination();
3461 utfx.decodeUTF8(function() {
3462 return i < length && offset < this.limit ? this.view[offset++] : null;
3463 }.bind(this), function(cp) {
3464 ++i; utfx.UTF8toUTF16(cp, sd);
3465 });
3466 if (i !== length)
3467 throw RangeError("Illegal range: Truncated data, "+i+" == "+length);
3468 if (relative) {
3469 this.offset = offset;
3470 return sd();
3471 } else {
3472 return {
3473 "string": sd(),
3474 "length": offset - start
3475 };
3476 }
3477 } else if (metrics === ByteBuffer.METRICS_BYTES) {
3478 if (!this.noAssert) {
3479 if (typeof offset !== 'number' || offset % 1 !== 0)
3480 throw TypeError("Illegal offset: "+offset+" (not an integer)");
3481 offset >>>= 0;
3482 if (offset < 0 || offset + length > this.buffer.byteLength)
3483 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+length+") <= "+this.buffer.byteLength);
3484 }
3485 var k = offset + length;
3486 utfx.decodeUTF8toUTF16(function() {
3487 return offset < k ? this.view[offset++] : null;
3488 }.bind(this), sd = stringDestination(), this.noAssert);
3489 if (offset !== k)
3490 throw RangeError("Illegal range: Truncated data, "+offset+" == "+k);
3491 if (relative) {
3492 this.offset = offset;
3493 return sd();
3494 } else {
3495 return {
3496 'string': sd(),
3497 'length': offset - start
3498 };
3499 }
3500 } else
3501 throw TypeError("Unsupported metrics: "+metrics);
3502 };
3503
3504 /**
3505 * Reads an UTF8 encoded string. This is an alias of {@link ByteBuffer#readUTF8String}.
3506 * @function
3507 * @param {number} length Number of characters or bytes to read
3508 * @param {number=} metrics Metrics specifying what `n` is meant to count. Defaults to
3509 * {@link ByteBuffer.METRICS_CHARS}.
3510 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
3511 * read if omitted.
3512 * @returns {string|!{string: string, length: number}} The string read if offset is omitted, else the string
3513 * read and the actual number of bytes read.
3514 * @expose
3515 */
3516 ByteBufferPrototype.readString = ByteBufferPrototype.readUTF8String;
3517
3518 // types/strings/vstring
3519
3520 /**
3521 * Writes a length as varint32 prefixed UTF8 encoded string.
3522 * @param {string} str String to write
3523 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
3524 * written if omitted.
3525 * @returns {!ByteBuffer|number} `this` if `offset` is omitted, else the actual number of bytes written
3526 * @expose
3527 * @see ByteBuffer#writeVarint32
3528 */
3529 ByteBufferPrototype.writeVString = function(str, offset) {
3530 var relative = typeof offset === 'undefined';
3531 if (relative) offset = this.offset;
3532 if (!this.noAssert) {
3533 if (typeof str !== 'string')
3534 throw TypeError("Illegal str: Not a string");
3535 if (typeof offset !== 'number' || offset % 1 !== 0)
3536 throw TypeError("Illegal offset: "+offset+" (not an integer)");
3537 offset >>>= 0;
3538 if (offset < 0 || offset + 0 > this.buffer.byteLength)
3539 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
3540 }
3541 var start = offset,
3542 k, l;
3543 k = utfx.calculateUTF16asUTF8(stringSource(str), this.noAssert)[1];
3544 l = ByteBuffer.calculateVarint32(k);
3545 offset += l+k;
3546 var capacity15 = this.buffer.byteLength;
3547 if (offset > capacity15)
3548 this.resize((capacity15 *= 2) > offset ? capacity15 : offset);
3549 offset -= l+k;
3550 offset += this.writeVarint32(k, offset);
3551 utfx.encodeUTF16toUTF8(stringSource(str), function(b) {
3552 this.view[offset++] = b;
3553 }.bind(this));
3554 if (offset !== start+k+l)
3555 throw RangeError("Illegal range: Truncated data, "+offset+" == "+(offset+k+l));
3556 if (relative) {
3557 this.offset = offset;
3558 return this;
3559 }
3560 return offset - start;
3561 };
3562
3563 /**
3564 * Reads a length as varint32 prefixed UTF8 encoded string.
3565 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
3566 * read if omitted.
3567 * @returns {string|!{string: string, length: number}} The string read if offset is omitted, else the string
3568 * read and the actual number of bytes read.
3569 * @expose
3570 * @see ByteBuffer#readVarint32
3571 */
3572 ByteBufferPrototype.readVString = function(offset) {
3573 var relative = typeof offset === 'undefined';
3574 if (relative) offset = this.offset;
3575 if (!this.noAssert) {
3576 if (typeof offset !== 'number' || offset % 1 !== 0)
3577 throw TypeError("Illegal offset: "+offset+" (not an integer)");
3578 offset >>>= 0;
3579 if (offset < 0 || offset + 1 > this.buffer.byteLength)
3580 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+1+") <= "+this.buffer.byteLength);
3581 }
3582 var start = offset;
3583 var len = this.readVarint32(offset);
3584 var str = this.readUTF8String(len['value'], ByteBuffer.METRICS_BYTES, offset += len['length']);
3585 offset += str['length'];
3586 if (relative) {
3587 this.offset = offset;
3588 return str['string'];
3589 } else {
3590 return {
3591 'string': str['string'],
3592 'length': offset - start
3593 };
3594 }
3595 };
3596
3597
3598 /**
3599 * Appends some data to this ByteBuffer. This will overwrite any contents behind the specified offset up to the appended
3600 * data's length.
3601 * @param {!ByteBuffer|!ArrayBuffer|!Uint8Array|string} source Data to append. If `source` is a ByteBuffer, its offsets
3602 * will be modified according to the performed read operation.
3603 * @param {(string|number)=} encoding Encoding if `data` is a string ("base64", "hex", "binary", defaults to "utf8")
3604 * @param {number=} offset Offset to append at. Will use and increase {@link ByteBuffer#offset} by the number of bytes
3605 * written if omitted.
3606 * @returns {!ByteBuffer} this
3607 * @expose
3608 * @example A relative `<01 02>03.append(<04 05>)` will result in `<01 02 04 05>, 04 05|`
3609 * @example An absolute `<01 02>03.append(04 05>, 1)` will result in `<01 04>05, 04 05|`
3610 */
3611 ByteBufferPrototype.append = function(source, encoding, offset) {
3612 if (typeof encoding === 'number' || typeof encoding !== 'string') {
3613 offset = encoding;
3614 encoding = undefined;
3615 }
3616 var relative = typeof offset === 'undefined';
3617 if (relative) offset = this.offset;
3618 if (!this.noAssert) {
3619 if (typeof offset !== 'number' || offset % 1 !== 0)
3620 throw TypeError("Illegal offset: "+offset+" (not an integer)");
3621 offset >>>= 0;
3622 if (offset < 0 || offset + 0 > this.buffer.byteLength)
3623 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
3624 }
3625 if (!(source instanceof ByteBuffer))
3626 source = ByteBuffer.wrap(source, encoding);
3627 var length = source.limit - source.offset;
3628 if (length <= 0) return this; // Nothing to append
3629 offset += length;
3630 var capacity16 = this.buffer.byteLength;
3631 if (offset > capacity16)
3632 this.resize((capacity16 *= 2) > offset ? capacity16 : offset);
3633 offset -= length;
3634 this.view.set(source.view.subarray(source.offset, source.limit), offset);
3635 source.offset += length;
3636 if (relative) this.offset += length;
3637 return this;
3638 };
3639
3640 /**
3641 * Appends this ByteBuffer's contents to another ByteBuffer. This will overwrite any contents at and after the
3642 specified offset up to the length of this ByteBuffer's data.
3643 * @param {!ByteBuffer} target Target ByteBuffer
3644 * @param {number=} offset Offset to append to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
3645 * read if omitted.
3646 * @returns {!ByteBuffer} this
3647 * @expose
3648 * @see ByteBuffer#append
3649 */
3650 ByteBufferPrototype.appendTo = function(target, offset) {
3651 target.append(this, offset);
3652 return this;
3653 };
3654
3655 /**
3656 * Enables or disables assertions of argument types and offsets. Assertions are enabled by default but you can opt to
3657 * disable them if your code already makes sure that everything is valid.
3658 * @param {boolean} assert `true` to enable assertions, otherwise `false`
3659 * @returns {!ByteBuffer} this
3660 * @expose
3661 */
3662 ByteBufferPrototype.assert = function(assert) {
3663 this.noAssert = !assert;
3664 return this;
3665 };
3666
3667 /**
3668 * Gets the capacity of this ByteBuffer's backing buffer.
3669 * @returns {number} Capacity of the backing buffer
3670 * @expose
3671 */
3672 ByteBufferPrototype.capacity = function() {
3673 return this.buffer.byteLength;
3674 };
3675 /**
3676 * Clears this ByteBuffer's offsets by setting {@link ByteBuffer#offset} to `0` and {@link ByteBuffer#limit} to the
3677 * backing buffer's capacity. Discards {@link ByteBuffer#markedOffset}.
3678 * @returns {!ByteBuffer} this
3679 * @expose
3680 */
3681 ByteBufferPrototype.clear = function() {
3682 this.offset = 0;
3683 this.limit = this.buffer.byteLength;
3684 this.markedOffset = -1;
3685 return this;
3686 };
3687
3688 /**
3689 * Creates a cloned instance of this ByteBuffer, preset with this ByteBuffer's values for {@link ByteBuffer#offset},
3690 * {@link ByteBuffer#markedOffset} and {@link ByteBuffer#limit}.
3691 * @param {boolean=} copy Whether to copy the backing buffer or to return another view on the same, defaults to `false`
3692 * @returns {!ByteBuffer} Cloned instance
3693 * @expose
3694 */
3695 ByteBufferPrototype.clone = function(copy) {
3696 var bb = new ByteBuffer(0, this.littleEndian, this.noAssert);
3697 if (copy) {
3698 bb.buffer = new ArrayBuffer(this.buffer.byteLength);
3699 bb.view = new Uint8Array(bb.buffer);
3700 } else {
3701 bb.buffer = this.buffer;
3702 bb.view = this.view;
3703 }
3704 bb.offset = this.offset;
3705 bb.markedOffset = this.markedOffset;
3706 bb.limit = this.limit;
3707 return bb;
3708 };
3709
3710 /**
3711 * Compacts this ByteBuffer to be backed by a {@link ByteBuffer#buffer} of its contents' length. Contents are the bytes
3712 * between {@link ByteBuffer#offset} and {@link ByteBuffer#limit}. Will set `offset = 0` and `limit = capacity` and
3713 * adapt {@link ByteBuffer#markedOffset} to the same relative position if set.
3714 * @param {number=} begin Offset to start at, defaults to {@link ByteBuffer#offset}
3715 * @param {number=} end Offset to end at, defaults to {@link ByteBuffer#limit}
3716 * @returns {!ByteBuffer} this
3717 * @expose
3718 */
3719 ByteBufferPrototype.compact = function(begin, end) {
3720 if (typeof begin === 'undefined') begin = this.offset;
3721 if (typeof end === 'undefined') end = this.limit;
3722 if (!this.noAssert) {
3723 if (typeof begin !== 'number' || begin % 1 !== 0)
3724 throw TypeError("Illegal begin: Not an integer");
3725 begin >>>= 0;
3726 if (typeof end !== 'number' || end % 1 !== 0)
3727 throw TypeError("Illegal end: Not an integer");
3728 end >>>= 0;
3729 if (begin < 0 || begin > end || end > this.buffer.byteLength)
3730 throw RangeError("Illegal range: 0 <= "+begin+" <= "+end+" <= "+this.buffer.byteLength);
3731 }
3732 if (begin === 0 && end === this.buffer.byteLength)
3733 return this; // Already compacted
3734 var len = end - begin;
3735 if (len === 0) {
3736 this.buffer = EMPTY_BUFFER;
3737 this.view = null;
3738 if (this.markedOffset >= 0) this.markedOffset -= begin;
3739 this.offset = 0;
3740 this.limit = 0;
3741 return this;
3742 }
3743 var buffer = new ArrayBuffer(len);
3744 var view = new Uint8Array(buffer);
3745 view.set(this.view.subarray(begin, end));
3746 this.buffer = buffer;
3747 this.view = view;
3748 if (this.markedOffset >= 0) this.markedOffset -= begin;
3749 this.offset = 0;
3750 this.limit = len;
3751 return this;
3752 };
3753
3754 /**
3755 * Creates a copy of this ByteBuffer's contents. Contents are the bytes between {@link ByteBuffer#offset} and
3756 * {@link ByteBuffer#limit}.
3757 * @param {number=} begin Begin offset, defaults to {@link ByteBuffer#offset}.
3758 * @param {number=} end End offset, defaults to {@link ByteBuffer#limit}.
3759 * @returns {!ByteBuffer} Copy
3760 * @expose
3761 */
3762 ByteBufferPrototype.copy = function(begin, end) {
3763 if (typeof begin === 'undefined') begin = this.offset;
3764 if (typeof end === 'undefined') end = this.limit;
3765 if (!this.noAssert) {
3766 if (typeof begin !== 'number' || begin % 1 !== 0)
3767 throw TypeError("Illegal begin: Not an integer");
3768 begin >>>= 0;
3769 if (typeof end !== 'number' || end % 1 !== 0)
3770 throw TypeError("Illegal end: Not an integer");
3771 end >>>= 0;
3772 if (begin < 0 || begin > end || end > this.buffer.byteLength)
3773 throw RangeError("Illegal range: 0 <= "+begin+" <= "+end+" <= "+this.buffer.byteLength);
3774 }
3775 if (begin === end)
3776 return new ByteBuffer(0, this.littleEndian, this.noAssert);
3777 var capacity = end - begin,
3778 bb = new ByteBuffer(capacity, this.littleEndian, this.noAssert);
3779 bb.offset = 0;
3780 bb.limit = capacity;
3781 if (bb.markedOffset >= 0) bb.markedOffset -= begin;
3782 this.copyTo(bb, 0, begin, end);
3783 return bb;
3784 };
3785
3786 /**
3787 * Copies this ByteBuffer's contents to another ByteBuffer. Contents are the bytes between {@link ByteBuffer#offset} and
3788 * {@link ByteBuffer#limit}.
3789 * @param {!ByteBuffer} target Target ByteBuffer
3790 * @param {number=} targetOffset Offset to copy to. Will use and increase the target's {@link ByteBuffer#offset}
3791 * by the number of bytes copied if omitted.
3792 * @param {number=} sourceOffset Offset to start copying from. Will use and increase {@link ByteBuffer#offset} by the
3793 * number of bytes copied if omitted.
3794 * @param {number=} sourceLimit Offset to end copying from, defaults to {@link ByteBuffer#limit}
3795 * @returns {!ByteBuffer} this
3796 * @expose
3797 */
3798 ByteBufferPrototype.copyTo = function(target, targetOffset, sourceOffset, sourceLimit) {
3799 var relative,
3800 targetRelative;
3801 if (!this.noAssert) {
3802 if (!ByteBuffer.isByteBuffer(target))
3803 throw TypeError("Illegal target: Not a ByteBuffer");
3804 }
3805 targetOffset = (targetRelative = typeof targetOffset === 'undefined') ? target.offset : targetOffset | 0;
3806 sourceOffset = (relative = typeof sourceOffset === 'undefined') ? this.offset : sourceOffset | 0;
3807 sourceLimit = typeof sourceLimit === 'undefined' ? this.limit : sourceLimit | 0;
3808
3809 if (targetOffset < 0 || targetOffset > target.buffer.byteLength)
3810 throw RangeError("Illegal target range: 0 <= "+targetOffset+" <= "+target.buffer.byteLength);
3811 if (sourceOffset < 0 || sourceLimit > this.buffer.byteLength)
3812 throw RangeError("Illegal source range: 0 <= "+sourceOffset+" <= "+this.buffer.byteLength);
3813
3814 var len = sourceLimit - sourceOffset;
3815 if (len === 0)
3816 return target; // Nothing to copy
3817
3818 target.ensureCapacity(targetOffset + len);
3819
3820 target.view.set(this.view.subarray(sourceOffset, sourceLimit), targetOffset);
3821
3822 if (relative) this.offset += len;
3823 if (targetRelative) target.offset += len;
3824
3825 return this;
3826 };
3827
3828 /**
3829 * Makes sure that this ByteBuffer is backed by a {@link ByteBuffer#buffer} of at least the specified capacity. If the
3830 * current capacity is exceeded, it will be doubled. If double the current capacity is less than the required capacity,
3831 * the required capacity will be used instead.
3832 * @param {number} capacity Required capacity
3833 * @returns {!ByteBuffer} this
3834 * @expose
3835 */
3836 ByteBufferPrototype.ensureCapacity = function(capacity) {
3837 var current = this.buffer.byteLength;
3838 if (current < capacity)
3839 return this.resize((current *= 2) > capacity ? current : capacity);
3840 return this;
3841 };
3842
3843 /**
3844 * Overwrites this ByteBuffer's contents with the specified value. Contents are the bytes between
3845 * {@link ByteBuffer#offset} and {@link ByteBuffer#limit}.
3846 * @param {number|string} value Byte value to fill with. If given as a string, the first character is used.
3847 * @param {number=} begin Begin offset. Will use and increase {@link ByteBuffer#offset} by the number of bytes
3848 * written if omitted. defaults to {@link ByteBuffer#offset}.
3849 * @param {number=} end End offset, defaults to {@link ByteBuffer#limit}.
3850 * @returns {!ByteBuffer} this
3851 * @expose
3852 * @example `someByteBuffer.clear().fill(0)` fills the entire backing buffer with zeroes
3853 */
3854 ByteBufferPrototype.fill = function(value, begin, end) {
3855 var relative = typeof begin === 'undefined';
3856 if (relative) begin = this.offset;
3857 if (typeof value === 'string' && value.length > 0)
3858 value = value.charCodeAt(0);
3859 if (typeof begin === 'undefined') begin = this.offset;
3860 if (typeof end === 'undefined') end = this.limit;
3861 if (!this.noAssert) {
3862 if (typeof value !== 'number' || value % 1 !== 0)
3863 throw TypeError("Illegal value: "+value+" (not an integer)");
3864 value |= 0;
3865 if (typeof begin !== 'number' || begin % 1 !== 0)
3866 throw TypeError("Illegal begin: Not an integer");
3867 begin >>>= 0;
3868 if (typeof end !== 'number' || end % 1 !== 0)
3869 throw TypeError("Illegal end: Not an integer");
3870 end >>>= 0;
3871 if (begin < 0 || begin > end || end > this.buffer.byteLength)
3872 throw RangeError("Illegal range: 0 <= "+begin+" <= "+end+" <= "+this.buffer.byteLength);
3873 }
3874 if (begin >= end)
3875 return this; // Nothing to fill
3876 while (begin < end) this.view[begin++] = value;
3877 if (relative) this.offset = begin;
3878 return this;
3879 };
3880
3881 /**
3882 * Makes this ByteBuffer ready for a new sequence of write or relative read operations. Sets `limit = offset` and
3883 * `offset = 0`. Make sure always to flip a ByteBuffer when all relative read or write operations are complete.
3884 * @returns {!ByteBuffer} this
3885 * @expose
3886 */
3887 ByteBufferPrototype.flip = function() {
3888 this.limit = this.offset;
3889 this.offset = 0;
3890 return this;
3891 };
3892 /**
3893 * Marks an offset on this ByteBuffer to be used later.
3894 * @param {number=} offset Offset to mark. Defaults to {@link ByteBuffer#offset}.
3895 * @returns {!ByteBuffer} this
3896 * @throws {TypeError} If `offset` is not a valid number
3897 * @throws {RangeError} If `offset` is out of bounds
3898 * @see ByteBuffer#reset
3899 * @expose
3900 */
3901 ByteBufferPrototype.mark = function(offset) {
3902 offset = typeof offset === 'undefined' ? this.offset : offset;
3903 if (!this.noAssert) {
3904 if (typeof offset !== 'number' || offset % 1 !== 0)
3905 throw TypeError("Illegal offset: "+offset+" (not an integer)");
3906 offset >>>= 0;
3907 if (offset < 0 || offset + 0 > this.buffer.byteLength)
3908 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
3909 }
3910 this.markedOffset = offset;
3911 return this;
3912 };
3913 /**
3914 * Sets the byte order.
3915 * @param {boolean} littleEndian `true` for little endian byte order, `false` for big endian
3916 * @returns {!ByteBuffer} this
3917 * @expose
3918 */
3919 ByteBufferPrototype.order = function(littleEndian) {
3920 if (!this.noAssert) {
3921 if (typeof littleEndian !== 'boolean')
3922 throw TypeError("Illegal littleEndian: Not a boolean");
3923 }
3924 this.littleEndian = !!littleEndian;
3925 return this;
3926 };
3927
3928 /**
3929 * Switches (to) little endian byte order.
3930 * @param {boolean=} littleEndian Defaults to `true`, otherwise uses big endian
3931 * @returns {!ByteBuffer} this
3932 * @expose
3933 */
3934 ByteBufferPrototype.LE = function(littleEndian) {
3935 this.littleEndian = typeof littleEndian !== 'undefined' ? !!littleEndian : true;
3936 return this;
3937 };
3938
3939 /**
3940 * Switches (to) big endian byte order.
3941 * @param {boolean=} bigEndian Defaults to `true`, otherwise uses little endian
3942 * @returns {!ByteBuffer} this
3943 * @expose
3944 */
3945 ByteBufferPrototype.BE = function(bigEndian) {
3946 this.littleEndian = typeof bigEndian !== 'undefined' ? !bigEndian : false;
3947 return this;
3948 };
3949 /**
3950 * Prepends some data to this ByteBuffer. This will overwrite any contents before the specified offset up to the
3951 * prepended data's length. If there is not enough space available before the specified `offset`, the backing buffer
3952 * will be resized and its contents moved accordingly.
3953 * @param {!ByteBuffer|string|!ArrayBuffer} source Data to prepend. If `source` is a ByteBuffer, its offset will be
3954 * modified according to the performed read operation.
3955 * @param {(string|number)=} encoding Encoding if `data` is a string ("base64", "hex", "binary", defaults to "utf8")
3956 * @param {number=} offset Offset to prepend at. Will use and decrease {@link ByteBuffer#offset} by the number of bytes
3957 * prepended if omitted.
3958 * @returns {!ByteBuffer} this
3959 * @expose
3960 * @example A relative `00<01 02 03>.prepend(<04 05>)` results in `<04 05 01 02 03>, 04 05|`
3961 * @example An absolute `00<01 02 03>.prepend(<04 05>, 2)` results in `04<05 02 03>, 04 05|`
3962 */
3963 ByteBufferPrototype.prepend = function(source, encoding, offset) {
3964 if (typeof encoding === 'number' || typeof encoding !== 'string') {
3965 offset = encoding;
3966 encoding = undefined;
3967 }
3968 var relative = typeof offset === 'undefined';
3969 if (relative) offset = this.offset;
3970 if (!this.noAssert) {
3971 if (typeof offset !== 'number' || offset % 1 !== 0)
3972 throw TypeError("Illegal offset: "+offset+" (not an integer)");
3973 offset >>>= 0;
3974 if (offset < 0 || offset + 0 > this.buffer.byteLength)
3975 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
3976 }
3977 if (!(source instanceof ByteBuffer))
3978 source = ByteBuffer.wrap(source, encoding);
3979 var len = source.limit - source.offset;
3980 if (len <= 0) return this; // Nothing to prepend
3981 var diff = len - offset;
3982 if (diff > 0) { // Not enough space before offset, so resize + move
3983 var buffer = new ArrayBuffer(this.buffer.byteLength + diff);
3984 var view = new Uint8Array(buffer);
3985 view.set(this.view.subarray(offset, this.buffer.byteLength), len);
3986 this.buffer = buffer;
3987 this.view = view;
3988 this.offset += diff;
3989 if (this.markedOffset >= 0) this.markedOffset += diff;
3990 this.limit += diff;
3991 offset += diff;
3992 } else {
3993 var arrayView = new Uint8Array(this.buffer);
3994 }
3995 this.view.set(source.view.subarray(source.offset, source.limit), offset - len);
3996
3997 source.offset = source.limit;
3998 if (relative)
3999 this.offset -= len;
4000 return this;
4001 };
4002
4003 /**
4004 * Prepends this ByteBuffer to another ByteBuffer. This will overwrite any contents before the specified offset up to the
4005 * prepended data's length. If there is not enough space available before the specified `offset`, the backing buffer
4006 * will be resized and its contents moved accordingly.
4007 * @param {!ByteBuffer} target Target ByteBuffer
4008 * @param {number=} offset Offset to prepend at. Will use and decrease {@link ByteBuffer#offset} by the number of bytes
4009 * prepended if omitted.
4010 * @returns {!ByteBuffer} this
4011 * @expose
4012 * @see ByteBuffer#prepend
4013 */
4014 ByteBufferPrototype.prependTo = function(target, offset) {
4015 target.prepend(this, offset);
4016 return this;
4017 };
4018 /**
4019 * Prints debug information about this ByteBuffer's contents.
4020 * @param {function(string)=} out Output function to call, defaults to console.log
4021 * @expose
4022 */
4023 ByteBufferPrototype.printDebug = function(out) {
4024 if (typeof out !== 'function') out = console.log.bind(console);
4025 out(
4026 this.toString()+"\n"+
4027 "-------------------------------------------------------------------\n"+
4028 this.toDebug(/* columns */ true)
4029 );
4030 };
4031
4032 /**
4033 * Gets the number of remaining readable bytes. Contents are the bytes between {@link ByteBuffer#offset} and
4034 * {@link ByteBuffer#limit}, so this returns `limit - offset`.
4035 * @returns {number} Remaining readable bytes. May be negative if `offset > limit`.
4036 * @expose
4037 */
4038 ByteBufferPrototype.remaining = function() {
4039 return this.limit - this.offset;
4040 };
4041 /**
4042 * Resets this ByteBuffer's {@link ByteBuffer#offset}. If an offset has been marked through {@link ByteBuffer#mark}
4043 * before, `offset` will be set to {@link ByteBuffer#markedOffset}, which will then be discarded. If no offset has been
4044 * marked, sets `offset = 0`.
4045 * @returns {!ByteBuffer} this
4046 * @see ByteBuffer#mark
4047 * @expose
4048 */
4049 ByteBufferPrototype.reset = function() {
4050 if (this.markedOffset >= 0) {
4051 this.offset = this.markedOffset;
4052 this.markedOffset = -1;
4053 } else {
4054 this.offset = 0;
4055 }
4056 return this;
4057 };
4058 /**
4059 * Resizes this ByteBuffer to be backed by a buffer of at least the given capacity. Will do nothing if already that
4060 * large or larger.
4061 * @param {number} capacity Capacity required
4062 * @returns {!ByteBuffer} this
4063 * @throws {TypeError} If `capacity` is not a number
4064 * @throws {RangeError} If `capacity < 0`
4065 * @expose
4066 */
4067 ByteBufferPrototype.resize = function(capacity) {
4068 if (!this.noAssert) {
4069 if (typeof capacity !== 'number' || capacity % 1 !== 0)
4070 throw TypeError("Illegal capacity: "+capacity+" (not an integer)");
4071 capacity |= 0;
4072 if (capacity < 0)
4073 throw RangeError("Illegal capacity: 0 <= "+capacity);
4074 }
4075 if (this.buffer.byteLength < capacity) {
4076 var buffer = new ArrayBuffer(capacity);
4077 var view = new Uint8Array(buffer);
4078 view.set(this.view);
4079 this.buffer = buffer;
4080 this.view = view;
4081 }
4082 return this;
4083 };
4084 /**
4085 * Reverses this ByteBuffer's contents.
4086 * @param {number=} begin Offset to start at, defaults to {@link ByteBuffer#offset}
4087 * @param {number=} end Offset to end at, defaults to {@link ByteBuffer#limit}
4088 * @returns {!ByteBuffer} this
4089 * @expose
4090 */
4091 ByteBufferPrototype.reverse = function(begin, end) {
4092 if (typeof begin === 'undefined') begin = this.offset;
4093 if (typeof end === 'undefined') end = this.limit;
4094 if (!this.noAssert) {
4095 if (typeof begin !== 'number' || begin % 1 !== 0)
4096 throw TypeError("Illegal begin: Not an integer");
4097 begin >>>= 0;
4098 if (typeof end !== 'number' || end % 1 !== 0)
4099 throw TypeError("Illegal end: Not an integer");
4100 end >>>= 0;
4101 if (begin < 0 || begin > end || end > this.buffer.byteLength)
4102 throw RangeError("Illegal range: 0 <= "+begin+" <= "+end+" <= "+this.buffer.byteLength);
4103 }
4104 if (begin === end)
4105 return this; // Nothing to reverse
4106 Array.prototype.reverse.call(this.view.subarray(begin, end));
4107 return this;
4108 };
4109 /**
4110 * Skips the next `length` bytes. This will just advance
4111 * @param {number} length Number of bytes to skip. May also be negative to move the offset back.
4112 * @returns {!ByteBuffer} this
4113 * @expose
4114 */
4115 ByteBufferPrototype.skip = function(length) {
4116 if (!this.noAssert) {
4117 if (typeof length !== 'number' || length % 1 !== 0)
4118 throw TypeError("Illegal length: "+length+" (not an integer)");
4119 length |= 0;
4120 }
4121 var offset = this.offset + length;
4122 if (!this.noAssert) {
4123 if (offset < 0 || offset > this.buffer.byteLength)
4124 throw RangeError("Illegal length: 0 <= "+this.offset+" + "+length+" <= "+this.buffer.byteLength);
4125 }
4126 this.offset = offset;
4127 return this;
4128 };
4129
4130 /**
4131 * Slices this ByteBuffer by creating a cloned instance with `offset = begin` and `limit = end`.
4132 * @param {number=} begin Begin offset, defaults to {@link ByteBuffer#offset}.
4133 * @param {number=} end End offset, defaults to {@link ByteBuffer#limit}.
4134 * @returns {!ByteBuffer} Clone of this ByteBuffer with slicing applied, backed by the same {@link ByteBuffer#buffer}
4135 * @expose
4136 */
4137 ByteBufferPrototype.slice = function(begin, end) {
4138 if (typeof begin === 'undefined') begin = this.offset;
4139 if (typeof end === 'undefined') end = this.limit;
4140 if (!this.noAssert) {
4141 if (typeof begin !== 'number' || begin % 1 !== 0)
4142 throw TypeError("Illegal begin: Not an integer");
4143 begin >>>= 0;
4144 if (typeof end !== 'number' || end % 1 !== 0)
4145 throw TypeError("Illegal end: Not an integer");
4146 end >>>= 0;
4147 if (begin < 0 || begin > end || end > this.buffer.byteLength)
4148 throw RangeError("Illegal range: 0 <= "+begin+" <= "+end+" <= "+this.buffer.byteLength);
4149 }
4150 var bb = this.clone();
4151 bb.offset = begin;
4152 bb.limit = end;
4153 return bb;
4154 };
4155 /**
4156 * Returns a copy of the backing buffer that contains this ByteBuffer's contents. Contents are the bytes between
4157 * {@link ByteBuffer#offset} and {@link ByteBuffer#limit}.
4158 * @param {boolean=} forceCopy If `true` returns a copy, otherwise returns a view referencing the same memory if
4159 * possible. Defaults to `false`
4160 * @returns {!ArrayBuffer} Contents as an ArrayBuffer
4161 * @expose
4162 */
4163 ByteBufferPrototype.toBuffer = function(forceCopy) {
4164 var offset = this.offset,
4165 limit = this.limit;
4166 if (!this.noAssert) {
4167 if (typeof offset !== 'number' || offset % 1 !== 0)
4168 throw TypeError("Illegal offset: Not an integer");
4169 offset >>>= 0;
4170 if (typeof limit !== 'number' || limit % 1 !== 0)
4171 throw TypeError("Illegal limit: Not an integer");
4172 limit >>>= 0;
4173 if (offset < 0 || offset > limit || limit > this.buffer.byteLength)
4174 throw RangeError("Illegal range: 0 <= "+offset+" <= "+limit+" <= "+this.buffer.byteLength);
4175 }
4176 // NOTE: It's not possible to have another ArrayBuffer reference the same memory as the backing buffer. This is
4177 // possible with Uint8Array#subarray only, but we have to return an ArrayBuffer by contract. So:
4178 if (!forceCopy && offset === 0 && limit === this.buffer.byteLength)
4179 return this.buffer;
4180 if (offset === limit)
4181 return EMPTY_BUFFER;
4182 var buffer = new ArrayBuffer(limit - offset);
4183 new Uint8Array(buffer).set(new Uint8Array(this.buffer).subarray(offset, limit), 0);
4184 return buffer;
4185 };
4186
4187 /**
4188 * Returns a raw buffer compacted to contain this ByteBuffer's contents. Contents are the bytes between
4189 * {@link ByteBuffer#offset} and {@link ByteBuffer#limit}. This is an alias of {@link ByteBuffer#toBuffer}.
4190 * @function
4191 * @param {boolean=} forceCopy If `true` returns a copy, otherwise returns a view referencing the same memory.
4192 * Defaults to `false`
4193 * @returns {!ArrayBuffer} Contents as an ArrayBuffer
4194 * @expose
4195 */
4196 ByteBufferPrototype.toArrayBuffer = ByteBufferPrototype.toBuffer;
4197
4198 /**
4199 * Converts the ByteBuffer's contents to a string.
4200 * @param {string=} encoding Output encoding. Returns an informative string representation if omitted but also allows
4201 * direct conversion to "utf8", "hex", "base64" and "binary" encoding. "debug" returns a hex representation with
4202 * highlighted offsets.
4203 * @param {number=} begin Offset to begin at, defaults to {@link ByteBuffer#offset}
4204 * @param {number=} end Offset to end at, defaults to {@link ByteBuffer#limit}
4205 * @returns {string} String representation
4206 * @throws {Error} If `encoding` is invalid
4207 * @expose
4208 */
4209 ByteBufferPrototype.toString = function(encoding, begin, end) {
4210 if (typeof encoding === 'undefined')
4211 return "ByteBufferAB(offset="+this.offset+",markedOffset="+this.markedOffset+",limit="+this.limit+",capacity="+this.capacity()+")";
4212 if (typeof encoding === 'number')
4213 encoding = "utf8",
4214 begin = encoding,
4215 end = begin;
4216 switch (encoding) {
4217 case "utf8":
4218 return this.toUTF8(begin, end);
4219 case "base64":
4220 return this.toBase64(begin, end);
4221 case "hex":
4222 return this.toHex(begin, end);
4223 case "binary":
4224 return this.toBinary(begin, end);
4225 case "debug":
4226 return this.toDebug();
4227 case "columns":
4228 return this.toColumns();
4229 default:
4230 throw Error("Unsupported encoding: "+encoding);
4231 }
4232 };
4233
4234 // lxiv-embeddable
4235
4236 /**
4237 * lxiv-embeddable (c) 2014 Daniel Wirtz <dcode@dcode.io>
4238 * Released under the Apache License, Version 2.0
4239 * see: https://github.com/dcodeIO/lxiv for details
4240 */
4241 var lxiv = function() {
4242
4243 /**
4244 * lxiv namespace.
4245 * @type {!Object.<string,*>}
4246 * @exports lxiv
4247 */
4248 var lxiv = {};
4249
4250 /**
4251 * Character codes for output.
4252 * @type {!Array.<number>}
4253 * @inner
4254 */
4255 var aout = [
4256 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80,
4257 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 97, 98, 99, 100, 101, 102,
4258 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118,
4259 119, 120, 121, 122, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 43, 47
4260 ];
4261
4262 /**
4263 * Character codes for input.
4264 * @type {!Array.<number>}
4265 * @inner
4266 */
4267 var ain = [];
4268 for (var i=0, k=aout.length; i<k; ++i)
4269 ain[aout[i]] = i;
4270
4271 /**
4272 * Encodes bytes to base64 char codes.
4273 * @param {!function():number|null} src Bytes source as a function returning the next byte respectively `null` if
4274 * there are no more bytes left.
4275 * @param {!function(number)} dst Characters destination as a function successively called with each encoded char
4276 * code.
4277 */
4278 lxiv.encode = function(src, dst) {
4279 var b, t;
4280 while ((b = src()) !== null) {
4281 dst(aout[(b>>2)&0x3f]);
4282 t = (b&0x3)<<4;
4283 if ((b = src()) !== null) {
4284 t |= (b>>4)&0xf;
4285 dst(aout[(t|((b>>4)&0xf))&0x3f]);
4286 t = (b&0xf)<<2;
4287 if ((b = src()) !== null)
4288 dst(aout[(t|((b>>6)&0x3))&0x3f]),
4289 dst(aout[b&0x3f]);
4290 else
4291 dst(aout[t&0x3f]),
4292 dst(61);
4293 } else
4294 dst(aout[t&0x3f]),
4295 dst(61),
4296 dst(61);
4297 }
4298 };
4299
4300 /**
4301 * Decodes base64 char codes to bytes.
4302 * @param {!function():number|null} src Characters source as a function returning the next char code respectively
4303 * `null` if there are no more characters left.
4304 * @param {!function(number)} dst Bytes destination as a function successively called with the next byte.
4305 * @throws {Error} If a character code is invalid
4306 */
4307 lxiv.decode = function(src, dst) {
4308 var c, t1, t2;
4309 function fail(c) {
4310 throw Error("Illegal character code: "+c);
4311 }
4312 while ((c = src()) !== null) {
4313 t1 = ain[c];
4314 if (typeof t1 === 'undefined') fail(c);
4315 if ((c = src()) !== null) {
4316 t2 = ain[c];
4317 if (typeof t2 === 'undefined') fail(c);
4318 dst((t1<<2)>>>0|(t2&0x30)>>4);
4319 if ((c = src()) !== null) {
4320 t1 = ain[c];
4321 if (typeof t1 === 'undefined')
4322 if (c === 61) break; else fail(c);
4323 dst(((t2&0xf)<<4)>>>0|(t1&0x3c)>>2);
4324 if ((c = src()) !== null) {
4325 t2 = ain[c];
4326 if (typeof t2 === 'undefined')
4327 if (c === 61) break; else fail(c);
4328 dst(((t1&0x3)<<6)>>>0|t2);
4329 }
4330 }
4331 }
4332 }
4333 };
4334
4335 /**
4336 * Tests if a string is valid base64.
4337 * @param {string} str String to test
4338 * @returns {boolean} `true` if valid, otherwise `false`
4339 */
4340 lxiv.test = function(str) {
4341 return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(str);
4342 };
4343
4344 return lxiv;
4345 }();
4346
4347 // encodings/base64
4348
4349 /**
4350 * Encodes this ByteBuffer's contents to a base64 encoded string.
4351 * @param {number=} begin Offset to begin at, defaults to {@link ByteBuffer#offset}.
4352 * @param {number=} end Offset to end at, defaults to {@link ByteBuffer#limit}.
4353 * @returns {string} Base64 encoded string
4354 * @throws {RangeError} If `begin` or `end` is out of bounds
4355 * @expose
4356 */
4357 ByteBufferPrototype.toBase64 = function(begin, end) {
4358 if (typeof begin === 'undefined')
4359 begin = this.offset;
4360 if (typeof end === 'undefined')
4361 end = this.limit;
4362 begin = begin | 0; end = end | 0;
4363 if (begin < 0 || end > this.capacity || begin > end)
4364 throw RangeError("begin, end");
4365 var sd; lxiv.encode(function() {
4366 return begin < end ? this.view[begin++] : null;
4367 }.bind(this), sd = stringDestination());
4368 return sd();
4369 };
4370
4371 /**
4372 * Decodes a base64 encoded string to a ByteBuffer.
4373 * @param {string} str String to decode
4374 * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
4375 * {@link ByteBuffer.DEFAULT_ENDIAN}.
4376 * @returns {!ByteBuffer} ByteBuffer
4377 * @expose
4378 */
4379 ByteBuffer.fromBase64 = function(str, littleEndian) {
4380 if (typeof str !== 'string')
4381 throw TypeError("str");
4382 var bb = new ByteBuffer(str.length/4*3, littleEndian),
4383 i = 0;
4384 lxiv.decode(stringSource(str), function(b) {
4385 bb.view[i++] = b;
4386 });
4387 bb.limit = i;
4388 return bb;
4389 };
4390
4391 /**
4392 * Encodes a binary string to base64 like `window.btoa` does.
4393 * @param {string} str Binary string
4394 * @returns {string} Base64 encoded string
4395 * @see https://developer.mozilla.org/en-US/docs/Web/API/Window.btoa
4396 * @expose
4397 */
4398 ByteBuffer.btoa = function(str) {
4399 return ByteBuffer.fromBinary(str).toBase64();
4400 };
4401
4402 /**
4403 * Decodes a base64 encoded string to binary like `window.atob` does.
4404 * @param {string} b64 Base64 encoded string
4405 * @returns {string} Binary string
4406 * @see https://developer.mozilla.org/en-US/docs/Web/API/Window.atob
4407 * @expose
4408 */
4409 ByteBuffer.atob = function(b64) {
4410 return ByteBuffer.fromBase64(b64).toBinary();
4411 };
4412
4413 // encodings/binary
4414
4415 /**
4416 * Encodes this ByteBuffer to a binary encoded string, that is using only characters 0x00-0xFF as bytes.
4417 * @param {number=} begin Offset to begin at. Defaults to {@link ByteBuffer#offset}.
4418 * @param {number=} end Offset to end at. Defaults to {@link ByteBuffer#limit}.
4419 * @returns {string} Binary encoded string
4420 * @throws {RangeError} If `offset > limit`
4421 * @expose
4422 */
4423 ByteBufferPrototype.toBinary = function(begin, end) {
4424 if (typeof begin === 'undefined')
4425 begin = this.offset;
4426 if (typeof end === 'undefined')
4427 end = this.limit;
4428 begin |= 0; end |= 0;
4429 if (begin < 0 || end > this.capacity() || begin > end)
4430 throw RangeError("begin, end");
4431 if (begin === end)
4432 return "";
4433 var chars = [],
4434 parts = [];
4435 while (begin < end) {
4436 chars.push(this.view[begin++]);
4437 if (chars.length >= 1024)
4438 parts.push(String.fromCharCode.apply(String, chars)),
4439 chars = [];
4440 }
4441 return parts.join('') + String.fromCharCode.apply(String, chars);
4442 };
4443
4444 /**
4445 * Decodes a binary encoded string, that is using only characters 0x00-0xFF as bytes, to a ByteBuffer.
4446 * @param {string} str String to decode
4447 * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
4448 * {@link ByteBuffer.DEFAULT_ENDIAN}.
4449 * @returns {!ByteBuffer} ByteBuffer
4450 * @expose
4451 */
4452 ByteBuffer.fromBinary = function(str, littleEndian) {
4453 if (typeof str !== 'string')
4454 throw TypeError("str");
4455 var i = 0,
4456 k = str.length,
4457 charCode,
4458 bb = new ByteBuffer(k, littleEndian);
4459 while (i<k) {
4460 charCode = str.charCodeAt(i);
4461 if (charCode > 0xff)
4462 throw RangeError("illegal char code: "+charCode);
4463 bb.view[i++] = charCode;
4464 }
4465 bb.limit = k;
4466 return bb;
4467 };
4468
4469 // encodings/debug
4470
4471 /**
4472 * Encodes this ByteBuffer to a hex encoded string with marked offsets. Offset symbols are:
4473 * * `<` : offset,
4474 * * `'` : markedOffset,
4475 * * `>` : limit,
4476 * * `|` : offset and limit,
4477 * * `[` : offset and markedOffset,
4478 * * `]` : markedOffset and limit,
4479 * * `!` : offset, markedOffset and limit
4480 * @param {boolean=} columns If `true` returns two columns hex + ascii, defaults to `false`
4481 * @returns {string|!Array.<string>} Debug string or array of lines if `asArray = true`
4482 * @expose
4483 * @example `>00'01 02<03` contains four bytes with `limit=0, markedOffset=1, offset=3`
4484 * @example `00[01 02 03>` contains four bytes with `offset=markedOffset=1, limit=4`
4485 * @example `00|01 02 03` contains four bytes with `offset=limit=1, markedOffset=-1`
4486 * @example `|` contains zero bytes with `offset=limit=0, markedOffset=-1`
4487 */
4488 ByteBufferPrototype.toDebug = function(columns) {
4489 var i = -1,
4490 k = this.buffer.byteLength,
4491 b,
4492 hex = "",
4493 asc = "",
4494 out = "";
4495 while (i<k) {
4496 if (i !== -1) {
4497 b = this.view[i];
4498 if (b < 0x10) hex += "0"+b.toString(16).toUpperCase();
4499 else hex += b.toString(16).toUpperCase();
4500 if (columns)
4501 asc += b > 32 && b < 127 ? String.fromCharCode(b) : '.';
4502 }
4503 ++i;
4504 if (columns) {
4505 if (i > 0 && i % 16 === 0 && i !== k) {
4506 while (hex.length < 3*16+3) hex += " ";
4507 out += hex+asc+"\n";
4508 hex = asc = "";
4509 }
4510 }
4511 if (i === this.offset && i === this.limit)
4512 hex += i === this.markedOffset ? "!" : "|";
4513 else if (i === this.offset)
4514 hex += i === this.markedOffset ? "[" : "<";
4515 else if (i === this.limit)
4516 hex += i === this.markedOffset ? "]" : ">";
4517 else
4518 hex += i === this.markedOffset ? "'" : (columns || (i !== 0 && i !== k) ? " " : "");
4519 }
4520 if (columns && hex !== " ") {
4521 while (hex.length < 3*16+3)
4522 hex += " ";
4523 out += hex + asc + "\n";
4524 }
4525 return columns ? out : hex;
4526 };
4527
4528 /**
4529 * Decodes a hex encoded string with marked offsets to a ByteBuffer.
4530 * @param {string} str Debug string to decode (not be generated with `columns = true`)
4531 * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
4532 * {@link ByteBuffer.DEFAULT_ENDIAN}.
4533 * @param {boolean=} noAssert Whether to skip assertions of offsets and values. Defaults to
4534 * {@link ByteBuffer.DEFAULT_NOASSERT}.
4535 * @returns {!ByteBuffer} ByteBuffer
4536 * @expose
4537 * @see ByteBuffer#toDebug
4538 */
4539 ByteBuffer.fromDebug = function(str, littleEndian, noAssert) {
4540 var k = str.length,
4541 bb = new ByteBuffer(((k+1)/3)|0, littleEndian, noAssert);
4542 var i = 0, j = 0, ch, b,
4543 rs = false, // Require symbol next
4544 ho = false, hm = false, hl = false, // Already has offset (ho), markedOffset (hm), limit (hl)?
4545 fail = false;
4546 while (i<k) {
4547 switch (ch = str.charAt(i++)) {
4548 case '!':
4549 if (!noAssert) {
4550 if (ho || hm || hl) {
4551 fail = true;
4552 break;
4553 }
4554 ho = hm = hl = true;
4555 }
4556 bb.offset = bb.markedOffset = bb.limit = j;
4557 rs = false;
4558 break;
4559 case '|':
4560 if (!noAssert) {
4561 if (ho || hl) {
4562 fail = true;
4563 break;
4564 }
4565 ho = hl = true;
4566 }
4567 bb.offset = bb.limit = j;
4568 rs = false;
4569 break;
4570 case '[':
4571 if (!noAssert) {
4572 if (ho || hm) {
4573 fail = true;
4574 break;
4575 }
4576 ho = hm = true;
4577 }
4578 bb.offset = bb.markedOffset = j;
4579 rs = false;
4580 break;
4581 case '<':
4582 if (!noAssert) {
4583 if (ho) {
4584 fail = true;
4585 break;
4586 }
4587 ho = true;
4588 }
4589 bb.offset = j;
4590 rs = false;
4591 break;
4592 case ']':
4593 if (!noAssert) {
4594 if (hl || hm) {
4595 fail = true;
4596 break;
4597 }
4598 hl = hm = true;
4599 }
4600 bb.limit = bb.markedOffset = j;
4601 rs = false;
4602 break;
4603 case '>':
4604 if (!noAssert) {
4605 if (hl) {
4606 fail = true;
4607 break;
4608 }
4609 hl = true;
4610 }
4611 bb.limit = j;
4612 rs = false;
4613 break;
4614 case "'":
4615 if (!noAssert) {
4616 if (hm) {
4617 fail = true;
4618 break;
4619 }
4620 hm = true;
4621 }
4622 bb.markedOffset = j;
4623 rs = false;
4624 break;
4625 case ' ':
4626 rs = false;
4627 break;
4628 default:
4629 if (!noAssert) {
4630 if (rs) {
4631 fail = true;
4632 break;
4633 }
4634 }
4635 b = parseInt(ch+str.charAt(i++), 16);
4636 if (!noAssert) {
4637 if (isNaN(b) || b < 0 || b > 255)
4638 throw TypeError("Illegal str: Not a debug encoded string");
4639 }
4640 bb.view[j++] = b;
4641 rs = true;
4642 }
4643 if (fail)
4644 throw TypeError("Illegal str: Invalid symbol at "+i);
4645 }
4646 if (!noAssert) {
4647 if (!ho || !hl)
4648 throw TypeError("Illegal str: Missing offset or limit");
4649 if (j<bb.buffer.byteLength)
4650 throw TypeError("Illegal str: Not a debug encoded string (is it hex?) "+j+" < "+k);
4651 }
4652 return bb;
4653 };
4654
4655 // encodings/hex
4656
4657 /**
4658 * Encodes this ByteBuffer's contents to a hex encoded string.
4659 * @param {number=} begin Offset to begin at. Defaults to {@link ByteBuffer#offset}.
4660 * @param {number=} end Offset to end at. Defaults to {@link ByteBuffer#limit}.
4661 * @returns {string} Hex encoded string
4662 * @expose
4663 */
4664 ByteBufferPrototype.toHex = function(begin, end) {
4665 begin = typeof begin === 'undefined' ? this.offset : begin;
4666 end = typeof end === 'undefined' ? this.limit : end;
4667 if (!this.noAssert) {
4668 if (typeof begin !== 'number' || begin % 1 !== 0)
4669 throw TypeError("Illegal begin: Not an integer");
4670 begin >>>= 0;
4671 if (typeof end !== 'number' || end % 1 !== 0)
4672 throw TypeError("Illegal end: Not an integer");
4673 end >>>= 0;
4674 if (begin < 0 || begin > end || end > this.buffer.byteLength)
4675 throw RangeError("Illegal range: 0 <= "+begin+" <= "+end+" <= "+this.buffer.byteLength);
4676 }
4677 var out = new Array(end - begin),
4678 b;
4679 while (begin < end) {
4680 b = this.view[begin++];
4681 if (b < 0x10)
4682 out.push("0", b.toString(16));
4683 else out.push(b.toString(16));
4684 }
4685 return out.join('');
4686 };
4687
4688 /**
4689 * Decodes a hex encoded string to a ByteBuffer.
4690 * @param {string} str String to decode
4691 * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
4692 * {@link ByteBuffer.DEFAULT_ENDIAN}.
4693 * @param {boolean=} noAssert Whether to skip assertions of offsets and values. Defaults to
4694 * {@link ByteBuffer.DEFAULT_NOASSERT}.
4695 * @returns {!ByteBuffer} ByteBuffer
4696 * @expose
4697 */
4698 ByteBuffer.fromHex = function(str, littleEndian, noAssert) {
4699 if (!noAssert) {
4700 if (typeof str !== 'string')
4701 throw TypeError("Illegal str: Not a string");
4702 if (str.length % 2 !== 0)
4703 throw TypeError("Illegal str: Length not a multiple of 2");
4704 }
4705 var k = str.length,
4706 bb = new ByteBuffer((k / 2) | 0, littleEndian),
4707 b;
4708 for (var i=0, j=0; i<k; i+=2) {
4709 b = parseInt(str.substring(i, i+2), 16);
4710 if (!noAssert)
4711 if (!isFinite(b) || b < 0 || b > 255)
4712 throw TypeError("Illegal str: Contains non-hex characters");
4713 bb.view[j++] = b;
4714 }
4715 bb.limit = j;
4716 return bb;
4717 };
4718
4719 // utfx-embeddable
4720
4721 /**
4722 * utfx-embeddable (c) 2014 Daniel Wirtz <dcode@dcode.io>
4723 * Released under the Apache License, Version 2.0
4724 * see: https://github.com/dcodeIO/utfx for details
4725 */
4726 var utfx = function() {
4727
4728 /**
4729 * utfx namespace.
4730 * @inner
4731 * @type {!Object.<string,*>}
4732 */
4733 var utfx = {};
4734
4735 /**
4736 * Maximum valid code point.
4737 * @type {number}
4738 * @const
4739 */
4740 utfx.MAX_CODEPOINT = 0x10FFFF;
4741
4742 /**
4743 * Encodes UTF8 code points to UTF8 bytes.
4744 * @param {(!function():number|null) | number} src Code points source, either as a function returning the next code point
4745 * respectively `null` if there are no more code points left or a single numeric code point.
4746 * @param {!function(number)} dst Bytes destination as a function successively called with the next byte
4747 */
4748 utfx.encodeUTF8 = function(src, dst) {
4749 var cp = null;
4750 if (typeof src === 'number')
4751 cp = src,
4752 src = function() { return null; };
4753 while (cp !== null || (cp = src()) !== null) {
4754 if (cp < 0x80)
4755 dst(cp&0x7F);
4756 else if (cp < 0x800)
4757 dst(((cp>>6)&0x1F)|0xC0),
4758 dst((cp&0x3F)|0x80);
4759 else if (cp < 0x10000)
4760 dst(((cp>>12)&0x0F)|0xE0),
4761 dst(((cp>>6)&0x3F)|0x80),
4762 dst((cp&0x3F)|0x80);
4763 else
4764 dst(((cp>>18)&0x07)|0xF0),
4765 dst(((cp>>12)&0x3F)|0x80),
4766 dst(((cp>>6)&0x3F)|0x80),
4767 dst((cp&0x3F)|0x80);
4768 cp = null;
4769 }
4770 };
4771
4772 /**
4773 * Decodes UTF8 bytes to UTF8 code points.
4774 * @param {!function():number|null} src Bytes source as a function returning the next byte respectively `null` if there
4775 * are no more bytes left.
4776 * @param {!function(number)} dst Code points destination as a function successively called with each decoded code point.
4777 * @throws {RangeError} If a starting byte is invalid in UTF8
4778 * @throws {Error} If the last sequence is truncated. Has an array property `bytes` holding the
4779 * remaining bytes.
4780 */
4781 utfx.decodeUTF8 = function(src, dst) {
4782 var a, b, c, d, fail = function(b) {
4783 b = b.slice(0, b.indexOf(null));
4784 var err = Error(b.toString());
4785 err.name = "TruncatedError";
4786 err['bytes'] = b;
4787 throw err;
4788 };
4789 while ((a = src()) !== null) {
4790 if ((a&0x80) === 0)
4791 dst(a);
4792 else if ((a&0xE0) === 0xC0)
4793 ((b = src()) === null) && fail([a, b]),
4794 dst(((a&0x1F)<<6) | (b&0x3F));
4795 else if ((a&0xF0) === 0xE0)
4796 ((b=src()) === null || (c=src()) === null) && fail([a, b, c]),
4797 dst(((a&0x0F)<<12) | ((b&0x3F)<<6) | (c&0x3F));
4798 else if ((a&0xF8) === 0xF0)
4799 ((b=src()) === null || (c=src()) === null || (d=src()) === null) && fail([a, b, c ,d]),
4800 dst(((a&0x07)<<18) | ((b&0x3F)<<12) | ((c&0x3F)<<6) | (d&0x3F));
4801 else throw RangeError("Illegal starting byte: "+a);
4802 }
4803 };
4804
4805 /**
4806 * Converts UTF16 characters to UTF8 code points.
4807 * @param {!function():number|null} src Characters source as a function returning the next char code respectively
4808 * `null` if there are no more characters left.
4809 * @param {!function(number)} dst Code points destination as a function successively called with each converted code
4810 * point.
4811 */
4812 utfx.UTF16toUTF8 = function(src, dst) {
4813 var c1, c2 = null;
4814 while (true) {
4815 if ((c1 = c2 !== null ? c2 : src()) === null)
4816 break;
4817 if (c1 >= 0xD800 && c1 <= 0xDFFF) {
4818 if ((c2 = src()) !== null) {
4819 if (c2 >= 0xDC00 && c2 <= 0xDFFF) {
4820 dst((c1-0xD800)*0x400+c2-0xDC00+0x10000);
4821 c2 = null; continue;
4822 }
4823 }
4824 }
4825 dst(c1);
4826 }
4827 if (c2 !== null) dst(c2);
4828 };
4829
4830 /**
4831 * Converts UTF8 code points to UTF16 characters.
4832 * @param {(!function():number|null) | number} src Code points source, either as a function returning the next code point
4833 * respectively `null` if there are no more code points left or a single numeric code point.
4834 * @param {!function(number)} dst Characters destination as a function successively called with each converted char code.
4835 * @throws {RangeError} If a code point is out of range
4836 */
4837 utfx.UTF8toUTF16 = function(src, dst) {
4838 var cp = null;
4839 if (typeof src === 'number')
4840 cp = src, src = function() { return null; };
4841 while (cp !== null || (cp = src()) !== null) {
4842 if (cp <= 0xFFFF)
4843 dst(cp);
4844 else
4845 cp -= 0x10000,
4846 dst((cp>>10)+0xD800),
4847 dst((cp%0x400)+0xDC00);
4848 cp = null;
4849 }
4850 };
4851
4852 /**
4853 * Converts and encodes UTF16 characters to UTF8 bytes.
4854 * @param {!function():number|null} src Characters source as a function returning the next char code respectively `null`
4855 * if there are no more characters left.
4856 * @param {!function(number)} dst Bytes destination as a function successively called with the next byte.
4857 */
4858 utfx.encodeUTF16toUTF8 = function(src, dst) {
4859 utfx.UTF16toUTF8(src, function(cp) {
4860 utfx.encodeUTF8(cp, dst);
4861 });
4862 };
4863
4864 /**
4865 * Decodes and converts UTF8 bytes to UTF16 characters.
4866 * @param {!function():number|null} src Bytes source as a function returning the next byte respectively `null` if there
4867 * are no more bytes left.
4868 * @param {!function(number)} dst Characters destination as a function successively called with each converted char code.
4869 * @throws {RangeError} If a starting byte is invalid in UTF8
4870 * @throws {Error} If the last sequence is truncated. Has an array property `bytes` holding the remaining bytes.
4871 */
4872 utfx.decodeUTF8toUTF16 = function(src, dst) {
4873 utfx.decodeUTF8(src, function(cp) {
4874 utfx.UTF8toUTF16(cp, dst);
4875 });
4876 };
4877
4878 /**
4879 * Calculates the byte length of an UTF8 code point.
4880 * @param {number} cp UTF8 code point
4881 * @returns {number} Byte length
4882 */
4883 utfx.calculateCodePoint = function(cp) {
4884 return (cp < 0x80) ? 1 : (cp < 0x800) ? 2 : (cp < 0x10000) ? 3 : 4;
4885 };
4886
4887 /**
4888 * Calculates the number of UTF8 bytes required to store UTF8 code points.
4889 * @param {(!function():number|null)} src Code points source as a function returning the next code point respectively
4890 * `null` if there are no more code points left.
4891 * @returns {number} The number of UTF8 bytes required
4892 */
4893 utfx.calculateUTF8 = function(src) {
4894 var cp, l=0;
4895 while ((cp = src()) !== null)
4896 l += (cp < 0x80) ? 1 : (cp < 0x800) ? 2 : (cp < 0x10000) ? 3 : 4;
4897 return l;
4898 };
4899
4900 /**
4901 * Calculates the number of UTF8 code points respectively UTF8 bytes required to store UTF16 char codes.
4902 * @param {(!function():number|null)} src Characters source as a function returning the next char code respectively
4903 * `null` if there are no more characters left.
4904 * @returns {!Array.<number>} The number of UTF8 code points at index 0 and the number of UTF8 bytes required at index 1.
4905 */
4906 utfx.calculateUTF16asUTF8 = function(src) {
4907 var n=0, l=0;
4908 utfx.UTF16toUTF8(src, function(cp) {
4909 ++n; l += (cp < 0x80) ? 1 : (cp < 0x800) ? 2 : (cp < 0x10000) ? 3 : 4;
4910 });
4911 return [n,l];
4912 };
4913
4914 return utfx;
4915 }();
4916
4917 // encodings/utf8
4918
4919 /**
4920 * Encodes this ByteBuffer's contents between {@link ByteBuffer#offset} and {@link ByteBuffer#limit} to an UTF8 encoded
4921 * string.
4922 * @returns {string} Hex encoded string
4923 * @throws {RangeError} If `offset > limit`
4924 * @expose
4925 */
4926 ByteBufferPrototype.toUTF8 = function(begin, end) {
4927 if (typeof begin === 'undefined') begin = this.offset;
4928 if (typeof end === 'undefined') end = this.limit;
4929 if (!this.noAssert) {
4930 if (typeof begin !== 'number' || begin % 1 !== 0)
4931 throw TypeError("Illegal begin: Not an integer");
4932 begin >>>= 0;
4933 if (typeof end !== 'number' || end % 1 !== 0)
4934 throw TypeError("Illegal end: Not an integer");
4935 end >>>= 0;
4936 if (begin < 0 || begin > end || end > this.buffer.byteLength)
4937 throw RangeError("Illegal range: 0 <= "+begin+" <= "+end+" <= "+this.buffer.byteLength);
4938 }
4939 var sd; try {
4940 utfx.decodeUTF8toUTF16(function() {
4941 return begin < end ? this.view[begin++] : null;
4942 }.bind(this), sd = stringDestination());
4943 } catch (e) {
4944 if (begin !== end)
4945 throw RangeError("Illegal range: Truncated data, "+begin+" != "+end);
4946 }
4947 return sd();
4948 };
4949
4950 /**
4951 * Decodes an UTF8 encoded string to a ByteBuffer.
4952 * @param {string} str String to decode
4953 * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
4954 * {@link ByteBuffer.DEFAULT_ENDIAN}.
4955 * @param {boolean=} noAssert Whether to skip assertions of offsets and values. Defaults to
4956 * {@link ByteBuffer.DEFAULT_NOASSERT}.
4957 * @returns {!ByteBuffer} ByteBuffer
4958 * @expose
4959 */
4960 ByteBuffer.fromUTF8 = function(str, littleEndian, noAssert) {
4961 if (!noAssert)
4962 if (typeof str !== 'string')
4963 throw TypeError("Illegal str: Not a string");
4964 var bb = new ByteBuffer(utfx.calculateUTF16asUTF8(stringSource(str), true)[1], littleEndian, noAssert),
4965 i = 0;
4966 utfx.encodeUTF16toUTF8(stringSource(str), function(b) {
4967 bb.view[i++] = b;
4968 });
4969 bb.limit = i;
4970 return bb;
4971 };
4972
4973 return ByteBuffer;
4974 });
4975 });
4976
4977 var require$$2 = {};
4978
4979 var protobufLight = createCommonjsModule(function (module) {
4980 /*
4981 Copyright 2013 Daniel Wirtz <dcode@dcode.io>
4982
4983 Licensed under the Apache License, Version 2.0 (the "License");
4984 you may not use this file except in compliance with the License.
4985 You may obtain a copy of the License at
4986
4987 http://www.apache.org/licenses/LICENSE-2.0
4988
4989 Unless required by applicable law or agreed to in writing, software
4990 distributed under the License is distributed on an "AS IS" BASIS,
4991 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
4992 See the License for the specific language governing permissions and
4993 limitations under the License.
4994 */
4995
4996 /**
4997 * @license protobuf.js (c) 2013 Daniel Wirtz <dcode@dcode.io>
4998 * Released under the Apache License, Version 2.0
4999 * see: https://github.com/dcodeIO/protobuf.js for details
5000 */
5001 (function(global, factory) {
5002
5003 /* AMD */ if (typeof commonjsRequire === "function" && 'object' === "object" && module && module["exports"])
5004 module["exports"] = factory(bytebuffer, true);
5005 /* Global */ else
5006 (global["dcodeIO"] = global["dcodeIO"] || {})["ProtoBuf"] = factory(global["dcodeIO"]["ByteBuffer"]);
5007
5008 })(commonjsGlobal, function(ByteBuffer, isCommonJS) {
5009
5010 /**
5011 * The ProtoBuf namespace.
5012 * @exports ProtoBuf
5013 * @namespace
5014 * @expose
5015 */
5016 var ProtoBuf = {};
5017
5018 /**
5019 * @type {!function(new: ByteBuffer, ...[*])}
5020 * @expose
5021 */
5022 ProtoBuf.ByteBuffer = ByteBuffer;
5023
5024 /**
5025 * @type {?function(new: Long, ...[*])}
5026 * @expose
5027 */
5028 ProtoBuf.Long = ByteBuffer.Long || null;
5029
5030 /**
5031 * ProtoBuf.js version.
5032 * @type {string}
5033 * @const
5034 * @expose
5035 */
5036 ProtoBuf.VERSION = "5.0.3";
5037
5038 /**
5039 * Wire types.
5040 * @type {Object.<string,number>}
5041 * @const
5042 * @expose
5043 */
5044 ProtoBuf.WIRE_TYPES = {};
5045
5046 /**
5047 * Varint wire type.
5048 * @type {number}
5049 * @expose
5050 */
5051 ProtoBuf.WIRE_TYPES.VARINT = 0;
5052
5053 /**
5054 * Fixed 64 bits wire type.
5055 * @type {number}
5056 * @const
5057 * @expose
5058 */
5059 ProtoBuf.WIRE_TYPES.BITS64 = 1;
5060
5061 /**
5062 * Length delimited wire type.
5063 * @type {number}
5064 * @const
5065 * @expose
5066 */
5067 ProtoBuf.WIRE_TYPES.LDELIM = 2;
5068
5069 /**
5070 * Start group wire type.
5071 * @type {number}
5072 * @const
5073 * @expose
5074 */
5075 ProtoBuf.WIRE_TYPES.STARTGROUP = 3;
5076
5077 /**
5078 * End group wire type.
5079 * @type {number}
5080 * @const
5081 * @expose
5082 */
5083 ProtoBuf.WIRE_TYPES.ENDGROUP = 4;
5084
5085 /**
5086 * Fixed 32 bits wire type.
5087 * @type {number}
5088 * @const
5089 * @expose
5090 */
5091 ProtoBuf.WIRE_TYPES.BITS32 = 5;
5092
5093 /**
5094 * Packable wire types.
5095 * @type {!Array.<number>}
5096 * @const
5097 * @expose
5098 */
5099 ProtoBuf.PACKABLE_WIRE_TYPES = [
5100 ProtoBuf.WIRE_TYPES.VARINT,
5101 ProtoBuf.WIRE_TYPES.BITS64,
5102 ProtoBuf.WIRE_TYPES.BITS32
5103 ];
5104
5105 /**
5106 * Types.
5107 * @dict
5108 * @type {!Object.<string,{name: string, wireType: number, defaultValue: *}>}
5109 * @const
5110 * @expose
5111 */
5112 ProtoBuf.TYPES = {
5113 // According to the protobuf spec.
5114 "int32": {
5115 name: "int32",
5116 wireType: ProtoBuf.WIRE_TYPES.VARINT,
5117 defaultValue: 0
5118 },
5119 "uint32": {
5120 name: "uint32",
5121 wireType: ProtoBuf.WIRE_TYPES.VARINT,
5122 defaultValue: 0
5123 },
5124 "sint32": {
5125 name: "sint32",
5126 wireType: ProtoBuf.WIRE_TYPES.VARINT,
5127 defaultValue: 0
5128 },
5129 "int64": {
5130 name: "int64",
5131 wireType: ProtoBuf.WIRE_TYPES.VARINT,
5132 defaultValue: ProtoBuf.Long ? ProtoBuf.Long.ZERO : undefined
5133 },
5134 "uint64": {
5135 name: "uint64",
5136 wireType: ProtoBuf.WIRE_TYPES.VARINT,
5137 defaultValue: ProtoBuf.Long ? ProtoBuf.Long.UZERO : undefined
5138 },
5139 "sint64": {
5140 name: "sint64",
5141 wireType: ProtoBuf.WIRE_TYPES.VARINT,
5142 defaultValue: ProtoBuf.Long ? ProtoBuf.Long.ZERO : undefined
5143 },
5144 "bool": {
5145 name: "bool",
5146 wireType: ProtoBuf.WIRE_TYPES.VARINT,
5147 defaultValue: false
5148 },
5149 "double": {
5150 name: "double",
5151 wireType: ProtoBuf.WIRE_TYPES.BITS64,
5152 defaultValue: 0
5153 },
5154 "string": {
5155 name: "string",
5156 wireType: ProtoBuf.WIRE_TYPES.LDELIM,
5157 defaultValue: ""
5158 },
5159 "bytes": {
5160 name: "bytes",
5161 wireType: ProtoBuf.WIRE_TYPES.LDELIM,
5162 defaultValue: null // overridden in the code, must be a unique instance
5163 },
5164 "fixed32": {
5165 name: "fixed32",
5166 wireType: ProtoBuf.WIRE_TYPES.BITS32,
5167 defaultValue: 0
5168 },
5169 "sfixed32": {
5170 name: "sfixed32",
5171 wireType: ProtoBuf.WIRE_TYPES.BITS32,
5172 defaultValue: 0
5173 },
5174 "fixed64": {
5175 name: "fixed64",
5176 wireType: ProtoBuf.WIRE_TYPES.BITS64,
5177 defaultValue: ProtoBuf.Long ? ProtoBuf.Long.UZERO : undefined
5178 },
5179 "sfixed64": {
5180 name: "sfixed64",
5181 wireType: ProtoBuf.WIRE_TYPES.BITS64,
5182 defaultValue: ProtoBuf.Long ? ProtoBuf.Long.ZERO : undefined
5183 },
5184 "float": {
5185 name: "float",
5186 wireType: ProtoBuf.WIRE_TYPES.BITS32,
5187 defaultValue: 0
5188 },
5189 "enum": {
5190 name: "enum",
5191 wireType: ProtoBuf.WIRE_TYPES.VARINT,
5192 defaultValue: 0
5193 },
5194 "message": {
5195 name: "message",
5196 wireType: ProtoBuf.WIRE_TYPES.LDELIM,
5197 defaultValue: null
5198 },
5199 "group": {
5200 name: "group",
5201 wireType: ProtoBuf.WIRE_TYPES.STARTGROUP,
5202 defaultValue: null
5203 }
5204 };
5205
5206 /**
5207 * Valid map key types.
5208 * @type {!Array.<!Object.<string,{name: string, wireType: number, defaultValue: *}>>}
5209 * @const
5210 * @expose
5211 */
5212 ProtoBuf.MAP_KEY_TYPES = [
5213 ProtoBuf.TYPES["int32"],
5214 ProtoBuf.TYPES["sint32"],
5215 ProtoBuf.TYPES["sfixed32"],
5216 ProtoBuf.TYPES["uint32"],
5217 ProtoBuf.TYPES["fixed32"],
5218 ProtoBuf.TYPES["int64"],
5219 ProtoBuf.TYPES["sint64"],
5220 ProtoBuf.TYPES["sfixed64"],
5221 ProtoBuf.TYPES["uint64"],
5222 ProtoBuf.TYPES["fixed64"],
5223 ProtoBuf.TYPES["bool"],
5224 ProtoBuf.TYPES["string"],
5225 ProtoBuf.TYPES["bytes"]
5226 ];
5227
5228 /**
5229 * Minimum field id.
5230 * @type {number}
5231 * @const
5232 * @expose
5233 */
5234 ProtoBuf.ID_MIN = 1;
5235
5236 /**
5237 * Maximum field id.
5238 * @type {number}
5239 * @const
5240 * @expose
5241 */
5242 ProtoBuf.ID_MAX = 0x1FFFFFFF;
5243
5244 /**
5245 * If set to `true`, field names will be converted from underscore notation to camel case. Defaults to `false`.
5246 * Must be set prior to parsing.
5247 * @type {boolean}
5248 * @expose
5249 */
5250 ProtoBuf.convertFieldsToCamelCase = false;
5251
5252 /**
5253 * By default, messages are populated with (setX, set_x) accessors for each field. This can be disabled by
5254 * setting this to `false` prior to building messages.
5255 * @type {boolean}
5256 * @expose
5257 */
5258 ProtoBuf.populateAccessors = true;
5259
5260 /**
5261 * By default, messages are populated with default values if a field is not present on the wire. To disable
5262 * this behavior, set this setting to `false`.
5263 * @type {boolean}
5264 * @expose
5265 */
5266 ProtoBuf.populateDefaults = true;
5267
5268 /**
5269 * @alias ProtoBuf.Util
5270 * @expose
5271 */
5272 ProtoBuf.Util = (function() {
5273
5274 /**
5275 * ProtoBuf utilities.
5276 * @exports ProtoBuf.Util
5277 * @namespace
5278 */
5279 var Util = {};
5280
5281 /**
5282 * Flag if running in node or not.
5283 * @type {boolean}
5284 * @const
5285 * @expose
5286 */
5287 Util.IS_NODE = !!(
5288 typeof process === 'object' && process+'' === '[object process]' && !process['browser']
5289 );
5290
5291 /**
5292 * Constructs a XMLHttpRequest object.
5293 * @return {XMLHttpRequest}
5294 * @throws {Error} If XMLHttpRequest is not supported
5295 * @expose
5296 */
5297 Util.XHR = function() {
5298 // No dependencies please, ref: http://www.quirksmode.org/js/xmlhttp.html
5299 var XMLHttpFactories = [
5300 function () {return new XMLHttpRequest()},
5301 function () {return new ActiveXObject("Msxml2.XMLHTTP")},
5302 function () {return new ActiveXObject("Msxml3.XMLHTTP")},
5303 function () {return new ActiveXObject("Microsoft.XMLHTTP")}
5304 ];
5305 /** @type {?XMLHttpRequest} */
5306 var xhr = null;
5307 for (var i=0;i<XMLHttpFactories.length;i++) {
5308 try { xhr = XMLHttpFactories[i](); }
5309 catch (e) { continue; }
5310 break;
5311 }
5312 if (!xhr)
5313 throw Error("XMLHttpRequest is not supported");
5314 return xhr;
5315 };
5316
5317 /**
5318 * Fetches a resource.
5319 * @param {string} path Resource path
5320 * @param {function(?string)=} callback Callback receiving the resource's contents. If omitted the resource will
5321 * be fetched synchronously. If the request failed, contents will be null.
5322 * @return {?string|undefined} Resource contents if callback is omitted (null if the request failed), else undefined.
5323 * @expose
5324 */
5325 Util.fetch = function(path, callback) {
5326 if (callback && typeof callback != 'function')
5327 callback = null;
5328 if (Util.IS_NODE) {
5329 var fs = require$$2;
5330 if (callback) {
5331 fs.readFile(path, function(err, data) {
5332 if (err)
5333 callback(null);
5334 else
5335 callback(""+data);
5336 });
5337 } else
5338 try {
5339 return fs.readFileSync(path);
5340 } catch (e) {
5341 return null;
5342 }
5343 } else {
5344 var xhr = Util.XHR();
5345 xhr.open('GET', path, callback ? true : false);
5346 // xhr.setRequestHeader('User-Agent', 'XMLHTTP/1.0');
5347 xhr.setRequestHeader('Accept', 'text/plain');
5348 if (typeof xhr.overrideMimeType === 'function') xhr.overrideMimeType('text/plain');
5349 if (callback) {
5350 xhr.onreadystatechange = function() {
5351 if (xhr.readyState != 4) return;
5352 if (/* remote */ xhr.status == 200 || /* local */ (xhr.status == 0 && typeof xhr.responseText === 'string'))
5353 callback(xhr.responseText);
5354 else
5355 callback(null);
5356 };
5357 if (xhr.readyState == 4)
5358 return;
5359 xhr.send(null);
5360 } else {
5361 xhr.send(null);
5362 if (/* remote */ xhr.status == 200 || /* local */ (xhr.status == 0 && typeof xhr.responseText === 'string'))
5363 return xhr.responseText;
5364 return null;
5365 }
5366 }
5367 };
5368
5369 /**
5370 * Converts a string to camel case.
5371 * @param {string} str
5372 * @returns {string}
5373 * @expose
5374 */
5375 Util.toCamelCase = function(str) {
5376 return str.replace(/_([a-zA-Z])/g, function ($0, $1) {
5377 return $1.toUpperCase();
5378 });
5379 };
5380
5381 return Util;
5382 })();
5383
5384 /**
5385 * Language expressions.
5386 * @type {!Object.<string,!RegExp>}
5387 * @expose
5388 */
5389 ProtoBuf.Lang = {
5390
5391 // Characters always ending a statement
5392 DELIM: /[\s\{\}=;:\[\],'"\(\)<>]/g,
5393
5394 // Field rules
5395 RULE: /^(?:required|optional|repeated|map)$/,
5396
5397 // Field types
5398 TYPE: /^(?:double|float|int32|uint32|sint32|int64|uint64|sint64|fixed32|sfixed32|fixed64|sfixed64|bool|string|bytes)$/,
5399
5400 // Names
5401 NAME: /^[a-zA-Z_][a-zA-Z_0-9]*$/,
5402
5403 // Type definitions
5404 TYPEDEF: /^[a-zA-Z][a-zA-Z_0-9]*$/,
5405
5406 // Type references
5407 TYPEREF: /^(?:\.?[a-zA-Z_][a-zA-Z_0-9]*)(?:\.[a-zA-Z_][a-zA-Z_0-9]*)*$/,
5408
5409 // Fully qualified type references
5410 FQTYPEREF: /^(?:\.[a-zA-Z_][a-zA-Z_0-9]*)+$/,
5411
5412 // All numbers
5413 NUMBER: /^-?(?:[1-9][0-9]*|0|0[xX][0-9a-fA-F]+|0[0-7]+|([0-9]*(\.[0-9]*)?([Ee][+-]?[0-9]+)?)|inf|nan)$/,
5414
5415 // Decimal numbers
5416 NUMBER_DEC: /^(?:[1-9][0-9]*|0)$/,
5417
5418 // Hexadecimal numbers
5419 NUMBER_HEX: /^0[xX][0-9a-fA-F]+$/,
5420
5421 // Octal numbers
5422 NUMBER_OCT: /^0[0-7]+$/,
5423
5424 // Floating point numbers
5425 NUMBER_FLT: /^([0-9]*(\.[0-9]*)?([Ee][+-]?[0-9]+)?|inf|nan)$/,
5426
5427 // Booleans
5428 BOOL: /^(?:true|false)$/i,
5429
5430 // Id numbers
5431 ID: /^(?:[1-9][0-9]*|0|0[xX][0-9a-fA-F]+|0[0-7]+)$/,
5432
5433 // Negative id numbers (enum values)
5434 NEGID: /^\-?(?:[1-9][0-9]*|0|0[xX][0-9a-fA-F]+|0[0-7]+)$/,
5435
5436 // Whitespaces
5437 WHITESPACE: /\s/,
5438
5439 // All strings
5440 STRING: /(?:"([^"\\]*(?:\\.[^"\\]*)*)")|(?:'([^'\\]*(?:\\.[^'\\]*)*)')/g,
5441
5442 // Double quoted strings
5443 STRING_DQ: /(?:"([^"\\]*(?:\\.[^"\\]*)*)")/g,
5444
5445 // Single quoted strings
5446 STRING_SQ: /(?:'([^'\\]*(?:\\.[^'\\]*)*)')/g
5447 };
5448
5449
5450 /**
5451 * @alias ProtoBuf.Reflect
5452 * @expose
5453 */
5454 ProtoBuf.Reflect = (function(ProtoBuf) {
5455
5456 /**
5457 * Reflection types.
5458 * @exports ProtoBuf.Reflect
5459 * @namespace
5460 */
5461 var Reflect = {};
5462
5463 /**
5464 * Constructs a Reflect base class.
5465 * @exports ProtoBuf.Reflect.T
5466 * @constructor
5467 * @abstract
5468 * @param {!ProtoBuf.Builder} builder Builder reference
5469 * @param {?ProtoBuf.Reflect.T} parent Parent object
5470 * @param {string} name Object name
5471 */
5472 var T = function(builder, parent, name) {
5473
5474 /**
5475 * Builder reference.
5476 * @type {!ProtoBuf.Builder}
5477 * @expose
5478 */
5479 this.builder = builder;
5480
5481 /**
5482 * Parent object.
5483 * @type {?ProtoBuf.Reflect.T}
5484 * @expose
5485 */
5486 this.parent = parent;
5487
5488 /**
5489 * Object name in namespace.
5490 * @type {string}
5491 * @expose
5492 */
5493 this.name = name;
5494
5495 /**
5496 * Fully qualified class name
5497 * @type {string}
5498 * @expose
5499 */
5500 this.className;
5501 };
5502
5503 /**
5504 * @alias ProtoBuf.Reflect.T.prototype
5505 * @inner
5506 */
5507 var TPrototype = T.prototype;
5508
5509 /**
5510 * Returns the fully qualified name of this object.
5511 * @returns {string} Fully qualified name as of ".PATH.TO.THIS"
5512 * @expose
5513 */
5514 TPrototype.fqn = function() {
5515 var name = this.name,
5516 ptr = this;
5517 do {
5518 ptr = ptr.parent;
5519 if (ptr == null)
5520 break;
5521 name = ptr.name+"."+name;
5522 } while (true);
5523 return name;
5524 };
5525
5526 /**
5527 * Returns a string representation of this Reflect object (its fully qualified name).
5528 * @param {boolean=} includeClass Set to true to include the class name. Defaults to false.
5529 * @return String representation
5530 * @expose
5531 */
5532 TPrototype.toString = function(includeClass) {
5533 return (includeClass ? this.className + " " : "") + this.fqn();
5534 };
5535
5536 /**
5537 * Builds this type.
5538 * @throws {Error} If this type cannot be built directly
5539 * @expose
5540 */
5541 TPrototype.build = function() {
5542 throw Error(this.toString(true)+" cannot be built directly");
5543 };
5544
5545 /**
5546 * @alias ProtoBuf.Reflect.T
5547 * @expose
5548 */
5549 Reflect.T = T;
5550
5551 /**
5552 * Constructs a new Namespace.
5553 * @exports ProtoBuf.Reflect.Namespace
5554 * @param {!ProtoBuf.Builder} builder Builder reference
5555 * @param {?ProtoBuf.Reflect.Namespace} parent Namespace parent
5556 * @param {string} name Namespace name
5557 * @param {Object.<string,*>=} options Namespace options
5558 * @param {string?} syntax The syntax level of this definition (e.g., proto3)
5559 * @constructor
5560 * @extends ProtoBuf.Reflect.T
5561 */
5562 var Namespace = function(builder, parent, name, options, syntax) {
5563 T.call(this, builder, parent, name);
5564
5565 /**
5566 * @override
5567 */
5568 this.className = "Namespace";
5569
5570 /**
5571 * Children inside the namespace.
5572 * @type {!Array.<ProtoBuf.Reflect.T>}
5573 */
5574 this.children = [];
5575
5576 /**
5577 * Options.
5578 * @type {!Object.<string, *>}
5579 */
5580 this.options = options || {};
5581
5582 /**
5583 * Syntax level (e.g., proto2 or proto3).
5584 * @type {!string}
5585 */
5586 this.syntax = syntax || "proto2";
5587 };
5588
5589 /**
5590 * @alias ProtoBuf.Reflect.Namespace.prototype
5591 * @inner
5592 */
5593 var NamespacePrototype = Namespace.prototype = Object.create(T.prototype);
5594
5595 /**
5596 * Returns an array of the namespace's children.
5597 * @param {ProtoBuf.Reflect.T=} type Filter type (returns instances of this type only). Defaults to null (all children).
5598 * @return {Array.<ProtoBuf.Reflect.T>}
5599 * @expose
5600 */
5601 NamespacePrototype.getChildren = function(type) {
5602 type = type || null;
5603 if (type == null)
5604 return this.children.slice();
5605 var children = [];
5606 for (var i=0, k=this.children.length; i<k; ++i)
5607 if (this.children[i] instanceof type)
5608 children.push(this.children[i]);
5609 return children;
5610 };
5611
5612 /**
5613 * Adds a child to the namespace.
5614 * @param {ProtoBuf.Reflect.T} child Child
5615 * @throws {Error} If the child cannot be added (duplicate)
5616 * @expose
5617 */
5618 NamespacePrototype.addChild = function(child) {
5619 var other;
5620 if (other = this.getChild(child.name)) {
5621 // Try to revert camelcase transformation on collision
5622 if (other instanceof Message.Field && other.name !== other.originalName && this.getChild(other.originalName) === null)
5623 other.name = other.originalName; // Revert previous first (effectively keeps both originals)
5624 else if (child instanceof Message.Field && child.name !== child.originalName && this.getChild(child.originalName) === null)
5625 child.name = child.originalName;
5626 else
5627 throw Error("Duplicate name in namespace "+this.toString(true)+": "+child.name);
5628 }
5629 this.children.push(child);
5630 };
5631
5632 /**
5633 * Gets a child by its name or id.
5634 * @param {string|number} nameOrId Child name or id
5635 * @return {?ProtoBuf.Reflect.T} The child or null if not found
5636 * @expose
5637 */
5638 NamespacePrototype.getChild = function(nameOrId) {
5639 var key = typeof nameOrId === 'number' ? 'id' : 'name';
5640 for (var i=0, k=this.children.length; i<k; ++i)
5641 if (this.children[i][key] === nameOrId)
5642 return this.children[i];
5643 return null;
5644 };
5645
5646 /**
5647 * Resolves a reflect object inside of this namespace.
5648 * @param {string|!Array.<string>} qn Qualified name to resolve
5649 * @param {boolean=} excludeNonNamespace Excludes non-namespace types, defaults to `false`
5650 * @return {?ProtoBuf.Reflect.Namespace} The resolved type or null if not found
5651 * @expose
5652 */
5653 NamespacePrototype.resolve = function(qn, excludeNonNamespace) {
5654 var part = typeof qn === 'string' ? qn.split(".") : qn,
5655 ptr = this,
5656 i = 0;
5657 if (part[i] === "") { // Fully qualified name, e.g. ".My.Message'
5658 while (ptr.parent !== null)
5659 ptr = ptr.parent;
5660 i++;
5661 }
5662 var child;
5663 do {
5664 do {
5665 if (!(ptr instanceof Reflect.Namespace)) {
5666 ptr = null;
5667 break;
5668 }
5669 child = ptr.getChild(part[i]);
5670 if (!child || !(child instanceof Reflect.T) || (excludeNonNamespace && !(child instanceof Reflect.Namespace))) {
5671 ptr = null;
5672 break;
5673 }
5674 ptr = child; i++;
5675 } while (i < part.length);
5676 if (ptr != null)
5677 break; // Found
5678 // Else search the parent
5679 if (this.parent !== null)
5680 return this.parent.resolve(qn, excludeNonNamespace);
5681 } while (ptr != null);
5682 return ptr;
5683 };
5684
5685 /**
5686 * Determines the shortest qualified name of the specified type, if any, relative to this namespace.
5687 * @param {!ProtoBuf.Reflect.T} t Reflection type
5688 * @returns {string} The shortest qualified name or, if there is none, the fqn
5689 * @expose
5690 */
5691 NamespacePrototype.qn = function(t) {
5692 var part = [], ptr = t;
5693 do {
5694 part.unshift(ptr.name);
5695 ptr = ptr.parent;
5696 } while (ptr !== null);
5697 for (var len=1; len <= part.length; len++) {
5698 var qn = part.slice(part.length-len);
5699 if (t === this.resolve(qn, t instanceof Reflect.Namespace))
5700 return qn.join(".");
5701 }
5702 return t.fqn();
5703 };
5704
5705 /**
5706 * Builds the namespace and returns the runtime counterpart.
5707 * @return {Object.<string,Function|Object>} Runtime namespace
5708 * @expose
5709 */
5710 NamespacePrototype.build = function() {
5711 /** @dict */
5712 var ns = {};
5713 var children = this.children;
5714 for (var i=0, k=children.length, child; i<k; ++i) {
5715 child = children[i];
5716 if (child instanceof Namespace)
5717 ns[child.name] = child.build();
5718 }
5719 if (Object.defineProperty)
5720 Object.defineProperty(ns, "$options", { "value": this.buildOpt() });
5721 return ns;
5722 };
5723
5724 /**
5725 * Builds the namespace's '$options' property.
5726 * @return {Object.<string,*>}
5727 */
5728 NamespacePrototype.buildOpt = function() {
5729 var opt = {},
5730 keys = Object.keys(this.options);
5731 for (var i=0, k=keys.length; i<k; ++i) {
5732 var key = keys[i],
5733 val = this.options[keys[i]];
5734 // TODO: Options are not resolved, yet.
5735 // if (val instanceof Namespace) {
5736 // opt[key] = val.build();
5737 // } else {
5738 opt[key] = val;
5739 // }
5740 }
5741 return opt;
5742 };
5743
5744 /**
5745 * Gets the value assigned to the option with the specified name.
5746 * @param {string=} name Returns the option value if specified, otherwise all options are returned.
5747 * @return {*|Object.<string,*>}null} Option value or NULL if there is no such option
5748 */
5749 NamespacePrototype.getOption = function(name) {
5750 if (typeof name === 'undefined')
5751 return this.options;
5752 return typeof this.options[name] !== 'undefined' ? this.options[name] : null;
5753 };
5754
5755 /**
5756 * @alias ProtoBuf.Reflect.Namespace
5757 * @expose
5758 */
5759 Reflect.Namespace = Namespace;
5760
5761 /**
5762 * Constructs a new Element implementation that checks and converts values for a
5763 * particular field type, as appropriate.
5764 *
5765 * An Element represents a single value: either the value of a singular field,
5766 * or a value contained in one entry of a repeated field or map field. This
5767 * class does not implement these higher-level concepts; it only encapsulates
5768 * the low-level typechecking and conversion.
5769 *
5770 * @exports ProtoBuf.Reflect.Element
5771 * @param {{name: string, wireType: number}} type Resolved data type
5772 * @param {ProtoBuf.Reflect.T|null} resolvedType Resolved type, if relevant
5773 * (e.g. submessage field).
5774 * @param {boolean} isMapKey Is this element a Map key? The value will be
5775 * converted to string form if so.
5776 * @param {string} syntax Syntax level of defining message type, e.g.,
5777 * proto2 or proto3.
5778 * @param {string} name Name of the field containing this element (for error
5779 * messages)
5780 * @constructor
5781 */
5782 var Element = function(type, resolvedType, isMapKey, syntax, name) {
5783
5784 /**
5785 * Element type, as a string (e.g., int32).
5786 * @type {{name: string, wireType: number}}
5787 */
5788 this.type = type;
5789
5790 /**
5791 * Element type reference to submessage or enum definition, if needed.
5792 * @type {ProtoBuf.Reflect.T|null}
5793 */
5794 this.resolvedType = resolvedType;
5795
5796 /**
5797 * Element is a map key.
5798 * @type {boolean}
5799 */
5800 this.isMapKey = isMapKey;
5801
5802 /**
5803 * Syntax level of defining message type, e.g., proto2 or proto3.
5804 * @type {string}
5805 */
5806 this.syntax = syntax;
5807
5808 /**
5809 * Name of the field containing this element (for error messages)
5810 * @type {string}
5811 */
5812 this.name = name;
5813
5814 if (isMapKey && ProtoBuf.MAP_KEY_TYPES.indexOf(type) < 0)
5815 throw Error("Invalid map key type: " + type.name);
5816 };
5817
5818 var ElementPrototype = Element.prototype;
5819
5820 /**
5821 * Obtains a (new) default value for the specified type.
5822 * @param type {string|{name: string, wireType: number}} Field type
5823 * @returns {*} Default value
5824 * @inner
5825 */
5826 function mkDefault(type) {
5827 if (typeof type === 'string')
5828 type = ProtoBuf.TYPES[type];
5829 if (typeof type.defaultValue === 'undefined')
5830 throw Error("default value for type "+type.name+" is not supported");
5831 if (type == ProtoBuf.TYPES["bytes"])
5832 return new ByteBuffer(0);
5833 return type.defaultValue;
5834 }
5835
5836 /**
5837 * Returns the default value for this field in proto3.
5838 * @function
5839 * @param type {string|{name: string, wireType: number}} the field type
5840 * @returns {*} Default value
5841 */
5842 Element.defaultFieldValue = mkDefault;
5843
5844 /**
5845 * Makes a Long from a value.
5846 * @param {{low: number, high: number, unsigned: boolean}|string|number} value Value
5847 * @param {boolean=} unsigned Whether unsigned or not, defaults to reuse it from Long-like objects or to signed for
5848 * strings and numbers
5849 * @returns {!Long}
5850 * @throws {Error} If the value cannot be converted to a Long
5851 * @inner
5852 */
5853 function mkLong(value, unsigned) {
5854 if (value && typeof value.low === 'number' && typeof value.high === 'number' && typeof value.unsigned === 'boolean'
5855 && value.low === value.low && value.high === value.high)
5856 return new ProtoBuf.Long(value.low, value.high, typeof unsigned === 'undefined' ? value.unsigned : unsigned);
5857 if (typeof value === 'string')
5858 return ProtoBuf.Long.fromString(value, unsigned || false, 10);
5859 if (typeof value === 'number')
5860 return ProtoBuf.Long.fromNumber(value, unsigned || false);
5861 throw Error("not convertible to Long");
5862 }
5863
5864 ElementPrototype.toString = function() {
5865 return (this.name || '') + (this.isMapKey ? 'map' : 'value') + ' element';
5866 };
5867
5868 /**
5869 * Checks if the given value can be set for an element of this type (singular
5870 * field or one element of a repeated field or map).
5871 * @param {*} value Value to check
5872 * @return {*} Verified, maybe adjusted, value
5873 * @throws {Error} If the value cannot be verified for this element slot
5874 * @expose
5875 */
5876 ElementPrototype.verifyValue = function(value) {
5877 var self = this;
5878 function fail(val, msg) {
5879 throw Error("Illegal value for "+self.toString(true)+" of type "+self.type.name+": "+val+" ("+msg+")");
5880 }
5881 switch (this.type) {
5882 // Signed 32bit
5883 case ProtoBuf.TYPES["int32"]:
5884 case ProtoBuf.TYPES["sint32"]:
5885 case ProtoBuf.TYPES["sfixed32"]:
5886 // Account for !NaN: value === value
5887 if (typeof value !== 'number' || (value === value && value % 1 !== 0))
5888 fail(typeof value, "not an integer");
5889 return value > 4294967295 ? value | 0 : value;
5890
5891 // Unsigned 32bit
5892 case ProtoBuf.TYPES["uint32"]:
5893 case ProtoBuf.TYPES["fixed32"]:
5894 if (typeof value !== 'number' || (value === value && value % 1 !== 0))
5895 fail(typeof value, "not an integer");
5896 return value < 0 ? value >>> 0 : value;
5897
5898 // Signed 64bit
5899 case ProtoBuf.TYPES["int64"]:
5900 case ProtoBuf.TYPES["sint64"]:
5901 case ProtoBuf.TYPES["sfixed64"]: {
5902 if (ProtoBuf.Long)
5903 try {
5904 return mkLong(value, false);
5905 } catch (e) {
5906 fail(typeof value, e.message);
5907 }
5908 else
5909 fail(typeof value, "requires Long.js");
5910 }
5911
5912 // Unsigned 64bit
5913 case ProtoBuf.TYPES["uint64"]:
5914 case ProtoBuf.TYPES["fixed64"]: {
5915 if (ProtoBuf.Long)
5916 try {
5917 return mkLong(value, true);
5918 } catch (e) {
5919 fail(typeof value, e.message);
5920 }
5921 else
5922 fail(typeof value, "requires Long.js");
5923 }
5924
5925 // Bool
5926 case ProtoBuf.TYPES["bool"]:
5927 if (typeof value !== 'boolean')
5928 fail(typeof value, "not a boolean");
5929 return value;
5930
5931 // Float
5932 case ProtoBuf.TYPES["float"]:
5933 case ProtoBuf.TYPES["double"]:
5934 if (typeof value !== 'number')
5935 fail(typeof value, "not a number");
5936 return value;
5937
5938 // Length-delimited string
5939 case ProtoBuf.TYPES["string"]:
5940 if (typeof value !== 'string' && !(value && value instanceof String))
5941 fail(typeof value, "not a string");
5942 return ""+value; // Convert String object to string
5943
5944 // Length-delimited bytes
5945 case ProtoBuf.TYPES["bytes"]:
5946 if (ByteBuffer.isByteBuffer(value))
5947 return value;
5948 return ByteBuffer.wrap(value, "base64");
5949
5950 // Constant enum value
5951 case ProtoBuf.TYPES["enum"]: {
5952 var values = this.resolvedType.getChildren(ProtoBuf.Reflect.Enum.Value);
5953 for (i=0; i<values.length; i++)
5954 if (values[i].name == value)
5955 return values[i].id;
5956 else if (values[i].id == value)
5957 return values[i].id;
5958
5959 if (this.syntax === 'proto3') {
5960 // proto3: just make sure it's an integer.
5961 if (typeof value !== 'number' || (value === value && value % 1 !== 0))
5962 fail(typeof value, "not an integer");
5963 if (value > 4294967295 || value < 0)
5964 fail(typeof value, "not in range for uint32");
5965 return value;
5966 } else {
5967 // proto2 requires enum values to be valid.
5968 fail(value, "not a valid enum value");
5969 }
5970 }
5971 // Embedded message
5972 case ProtoBuf.TYPES["group"]:
5973 case ProtoBuf.TYPES["message"]: {
5974 if (!value || typeof value !== 'object')
5975 fail(typeof value, "object expected");
5976 if (value instanceof this.resolvedType.clazz)
5977 return value;
5978 if (value instanceof ProtoBuf.Builder.Message) {
5979 // Mismatched type: Convert to object (see: https://github.com/dcodeIO/ProtoBuf.js/issues/180)
5980 var obj = {};
5981 for (var i in value)
5982 if (value.hasOwnProperty(i))
5983 obj[i] = value[i];
5984 value = obj;
5985 }
5986 // Else let's try to construct one from a key-value object
5987 return new (this.resolvedType.clazz)(value); // May throw for a hundred of reasons
5988 }
5989 }
5990
5991 // We should never end here
5992 throw Error("[INTERNAL] Illegal value for "+this.toString(true)+": "+value+" (undefined type "+this.type+")");
5993 };
5994
5995 /**
5996 * Calculates the byte length of an element on the wire.
5997 * @param {number} id Field number
5998 * @param {*} value Field value
5999 * @returns {number} Byte length
6000 * @throws {Error} If the value cannot be calculated
6001 * @expose
6002 */
6003 ElementPrototype.calculateLength = function(id, value) {
6004 if (value === null) return 0; // Nothing to encode
6005 // Tag has already been written
6006 var n;
6007 switch (this.type) {
6008 case ProtoBuf.TYPES["int32"]:
6009 return value < 0 ? ByteBuffer.calculateVarint64(value) : ByteBuffer.calculateVarint32(value);
6010 case ProtoBuf.TYPES["uint32"]:
6011 return ByteBuffer.calculateVarint32(value);
6012 case ProtoBuf.TYPES["sint32"]:
6013 return ByteBuffer.calculateVarint32(ByteBuffer.zigZagEncode32(value));
6014 case ProtoBuf.TYPES["fixed32"]:
6015 case ProtoBuf.TYPES["sfixed32"]:
6016 case ProtoBuf.TYPES["float"]:
6017 return 4;
6018 case ProtoBuf.TYPES["int64"]:
6019 case ProtoBuf.TYPES["uint64"]:
6020 return ByteBuffer.calculateVarint64(value);
6021 case ProtoBuf.TYPES["sint64"]:
6022 return ByteBuffer.calculateVarint64(ByteBuffer.zigZagEncode64(value));
6023 case ProtoBuf.TYPES["fixed64"]:
6024 case ProtoBuf.TYPES["sfixed64"]:
6025 return 8;
6026 case ProtoBuf.TYPES["bool"]:
6027 return 1;
6028 case ProtoBuf.TYPES["enum"]:
6029 return ByteBuffer.calculateVarint32(value);
6030 case ProtoBuf.TYPES["double"]:
6031 return 8;
6032 case ProtoBuf.TYPES["string"]:
6033 n = ByteBuffer.calculateUTF8Bytes(value);
6034 return ByteBuffer.calculateVarint32(n) + n;
6035 case ProtoBuf.TYPES["bytes"]:
6036 if (value.remaining() < 0)
6037 throw Error("Illegal value for "+this.toString(true)+": "+value.remaining()+" bytes remaining");
6038 return ByteBuffer.calculateVarint32(value.remaining()) + value.remaining();
6039 case ProtoBuf.TYPES["message"]:
6040 n = this.resolvedType.calculate(value);
6041 return ByteBuffer.calculateVarint32(n) + n;
6042 case ProtoBuf.TYPES["group"]:
6043 n = this.resolvedType.calculate(value);
6044 return n + ByteBuffer.calculateVarint32((id << 3) | ProtoBuf.WIRE_TYPES.ENDGROUP);
6045 }
6046 // We should never end here
6047 throw Error("[INTERNAL] Illegal value to encode in "+this.toString(true)+": "+value+" (unknown type)");
6048 };
6049
6050 /**
6051 * Encodes a value to the specified buffer. Does not encode the key.
6052 * @param {number} id Field number
6053 * @param {*} value Field value
6054 * @param {ByteBuffer} buffer ByteBuffer to encode to
6055 * @return {ByteBuffer} The ByteBuffer for chaining
6056 * @throws {Error} If the value cannot be encoded
6057 * @expose
6058 */
6059 ElementPrototype.encodeValue = function(id, value, buffer) {
6060 if (value === null) return buffer; // Nothing to encode
6061 // Tag has already been written
6062
6063 switch (this.type) {
6064 // 32bit signed varint
6065 case ProtoBuf.TYPES["int32"]:
6066 // "If you use int32 or int64 as the type for a negative number, the resulting varint is always ten bytes
6067 // long – it is, effectively, treated like a very large unsigned integer." (see #122)
6068 if (value < 0)
6069 buffer.writeVarint64(value);
6070 else
6071 buffer.writeVarint32(value);
6072 break;
6073
6074 // 32bit unsigned varint
6075 case ProtoBuf.TYPES["uint32"]:
6076 buffer.writeVarint32(value);
6077 break;
6078
6079 // 32bit varint zig-zag
6080 case ProtoBuf.TYPES["sint32"]:
6081 buffer.writeVarint32ZigZag(value);
6082 break;
6083
6084 // Fixed unsigned 32bit
6085 case ProtoBuf.TYPES["fixed32"]:
6086 buffer.writeUint32(value);
6087 break;
6088
6089 // Fixed signed 32bit
6090 case ProtoBuf.TYPES["sfixed32"]:
6091 buffer.writeInt32(value);
6092 break;
6093
6094 // 64bit varint as-is
6095 case ProtoBuf.TYPES["int64"]:
6096 case ProtoBuf.TYPES["uint64"]:
6097 buffer.writeVarint64(value); // throws
6098 break;
6099
6100 // 64bit varint zig-zag
6101 case ProtoBuf.TYPES["sint64"]:
6102 buffer.writeVarint64ZigZag(value); // throws
6103 break;
6104
6105 // Fixed unsigned 64bit
6106 case ProtoBuf.TYPES["fixed64"]:
6107 buffer.writeUint64(value); // throws
6108 break;
6109
6110 // Fixed signed 64bit
6111 case ProtoBuf.TYPES["sfixed64"]:
6112 buffer.writeInt64(value); // throws
6113 break;
6114
6115 // Bool
6116 case ProtoBuf.TYPES["bool"]:
6117 if (typeof value === 'string')
6118 buffer.writeVarint32(value.toLowerCase() === 'false' ? 0 : !!value);
6119 else
6120 buffer.writeVarint32(value ? 1 : 0);
6121 break;
6122
6123 // Constant enum value
6124 case ProtoBuf.TYPES["enum"]:
6125 buffer.writeVarint32(value);
6126 break;
6127
6128 // 32bit float
6129 case ProtoBuf.TYPES["float"]:
6130 buffer.writeFloat32(value);
6131 break;
6132
6133 // 64bit float
6134 case ProtoBuf.TYPES["double"]:
6135 buffer.writeFloat64(value);
6136 break;
6137
6138 // Length-delimited string
6139 case ProtoBuf.TYPES["string"]:
6140 buffer.writeVString(value);
6141 break;
6142
6143 // Length-delimited bytes
6144 case ProtoBuf.TYPES["bytes"]:
6145 if (value.remaining() < 0)
6146 throw Error("Illegal value for "+this.toString(true)+": "+value.remaining()+" bytes remaining");
6147 var prevOffset = value.offset;
6148 buffer.writeVarint32(value.remaining());
6149 buffer.append(value);
6150 value.offset = prevOffset;
6151 break;
6152
6153 // Embedded message
6154 case ProtoBuf.TYPES["message"]:
6155 var bb = new ByteBuffer().LE();
6156 this.resolvedType.encode(value, bb);
6157 buffer.writeVarint32(bb.offset);
6158 buffer.append(bb.flip());
6159 break;
6160
6161 // Legacy group
6162 case ProtoBuf.TYPES["group"]:
6163 this.resolvedType.encode(value, buffer);
6164 buffer.writeVarint32((id << 3) | ProtoBuf.WIRE_TYPES.ENDGROUP);
6165 break;
6166
6167 default:
6168 // We should never end here
6169 throw Error("[INTERNAL] Illegal value to encode in "+this.toString(true)+": "+value+" (unknown type)");
6170 }
6171 return buffer;
6172 };
6173
6174 /**
6175 * Decode one element value from the specified buffer.
6176 * @param {ByteBuffer} buffer ByteBuffer to decode from
6177 * @param {number} wireType The field wire type
6178 * @param {number} id The field number
6179 * @return {*} Decoded value
6180 * @throws {Error} If the field cannot be decoded
6181 * @expose
6182 */
6183 ElementPrototype.decode = function(buffer, wireType, id) {
6184 if (wireType != this.type.wireType)
6185 throw Error("Unexpected wire type for element");
6186
6187 var value, nBytes;
6188 switch (this.type) {
6189 // 32bit signed varint
6190 case ProtoBuf.TYPES["int32"]:
6191 return buffer.readVarint32() | 0;
6192
6193 // 32bit unsigned varint
6194 case ProtoBuf.TYPES["uint32"]:
6195 return buffer.readVarint32() >>> 0;
6196
6197 // 32bit signed varint zig-zag
6198 case ProtoBuf.TYPES["sint32"]:
6199 return buffer.readVarint32ZigZag() | 0;
6200
6201 // Fixed 32bit unsigned
6202 case ProtoBuf.TYPES["fixed32"]:
6203 return buffer.readUint32() >>> 0;
6204
6205 case ProtoBuf.TYPES["sfixed32"]:
6206 return buffer.readInt32() | 0;
6207
6208 // 64bit signed varint
6209 case ProtoBuf.TYPES["int64"]:
6210 return buffer.readVarint64();
6211
6212 // 64bit unsigned varint
6213 case ProtoBuf.TYPES["uint64"]:
6214 return buffer.readVarint64().toUnsigned();
6215
6216 // 64bit signed varint zig-zag
6217 case ProtoBuf.TYPES["sint64"]:
6218 return buffer.readVarint64ZigZag();
6219
6220 // Fixed 64bit unsigned
6221 case ProtoBuf.TYPES["fixed64"]:
6222 return buffer.readUint64();
6223
6224 // Fixed 64bit signed
6225 case ProtoBuf.TYPES["sfixed64"]:
6226 return buffer.readInt64();
6227
6228 // Bool varint
6229 case ProtoBuf.TYPES["bool"]:
6230 return !!buffer.readVarint32();
6231
6232 // Constant enum value (varint)
6233 case ProtoBuf.TYPES["enum"]:
6234 // The following Builder.Message#set will already throw
6235 return buffer.readVarint32();
6236
6237 // 32bit float
6238 case ProtoBuf.TYPES["float"]:
6239 return buffer.readFloat();
6240
6241 // 64bit float
6242 case ProtoBuf.TYPES["double"]:
6243 return buffer.readDouble();
6244
6245 // Length-delimited string
6246 case ProtoBuf.TYPES["string"]:
6247 return buffer.readVString();
6248
6249 // Length-delimited bytes
6250 case ProtoBuf.TYPES["bytes"]: {
6251 nBytes = buffer.readVarint32();
6252 if (buffer.remaining() < nBytes)
6253 throw Error("Illegal number of bytes for "+this.toString(true)+": "+nBytes+" required but got only "+buffer.remaining());
6254 value = buffer.clone(); // Offset already set
6255 value.limit = value.offset+nBytes;
6256 buffer.offset += nBytes;
6257 return value;
6258 }
6259
6260 // Length-delimited embedded message
6261 case ProtoBuf.TYPES["message"]: {
6262 nBytes = buffer.readVarint32();
6263 return this.resolvedType.decode(buffer, nBytes);
6264 }
6265
6266 // Legacy group
6267 case ProtoBuf.TYPES["group"]:
6268 return this.resolvedType.decode(buffer, -1, id);
6269 }
6270
6271 // We should never end here
6272 throw Error("[INTERNAL] Illegal decode type");
6273 };
6274
6275 /**
6276 * Converts a value from a string to the canonical element type.
6277 *
6278 * Legal only when isMapKey is true.
6279 *
6280 * @param {string} str The string value
6281 * @returns {*} The value
6282 */
6283 ElementPrototype.valueFromString = function(str) {
6284 if (!this.isMapKey) {
6285 throw Error("valueFromString() called on non-map-key element");
6286 }
6287
6288 switch (this.type) {
6289 case ProtoBuf.TYPES["int32"]:
6290 case ProtoBuf.TYPES["sint32"]:
6291 case ProtoBuf.TYPES["sfixed32"]:
6292 case ProtoBuf.TYPES["uint32"]:
6293 case ProtoBuf.TYPES["fixed32"]:
6294 return this.verifyValue(parseInt(str));
6295
6296 case ProtoBuf.TYPES["int64"]:
6297 case ProtoBuf.TYPES["sint64"]:
6298 case ProtoBuf.TYPES["sfixed64"]:
6299 case ProtoBuf.TYPES["uint64"]:
6300 case ProtoBuf.TYPES["fixed64"]:
6301 // Long-based fields support conversions from string already.
6302 return this.verifyValue(str);
6303
6304 case ProtoBuf.TYPES["bool"]:
6305 return str === "true";
6306
6307 case ProtoBuf.TYPES["string"]:
6308 return this.verifyValue(str);
6309
6310 case ProtoBuf.TYPES["bytes"]:
6311 return ByteBuffer.fromBinary(str);
6312 }
6313 };
6314
6315 /**
6316 * Converts a value from the canonical element type to a string.
6317 *
6318 * It should be the case that `valueFromString(valueToString(val))` returns
6319 * a value equivalent to `verifyValue(val)` for every legal value of `val`
6320 * according to this element type.
6321 *
6322 * This may be used when the element must be stored or used as a string,
6323 * e.g., as a map key on an Object.
6324 *
6325 * Legal only when isMapKey is true.
6326 *
6327 * @param {*} val The value
6328 * @returns {string} The string form of the value.
6329 */
6330 ElementPrototype.valueToString = function(value) {
6331 if (!this.isMapKey) {
6332 throw Error("valueToString() called on non-map-key element");
6333 }
6334
6335 if (this.type === ProtoBuf.TYPES["bytes"]) {
6336 return value.toString("binary");
6337 } else {
6338 return value.toString();
6339 }
6340 };
6341
6342 /**
6343 * @alias ProtoBuf.Reflect.Element
6344 * @expose
6345 */
6346 Reflect.Element = Element;
6347
6348 /**
6349 * Constructs a new Message.
6350 * @exports ProtoBuf.Reflect.Message
6351 * @param {!ProtoBuf.Builder} builder Builder reference
6352 * @param {!ProtoBuf.Reflect.Namespace} parent Parent message or namespace
6353 * @param {string} name Message name
6354 * @param {Object.<string,*>=} options Message options
6355 * @param {boolean=} isGroup `true` if this is a legacy group
6356 * @param {string?} syntax The syntax level of this definition (e.g., proto3)
6357 * @constructor
6358 * @extends ProtoBuf.Reflect.Namespace
6359 */
6360 var Message = function(builder, parent, name, options, isGroup, syntax) {
6361 Namespace.call(this, builder, parent, name, options, syntax);
6362
6363 /**
6364 * @override
6365 */
6366 this.className = "Message";
6367
6368 /**
6369 * Extensions range.
6370 * @type {!Array.<number>|undefined}
6371 * @expose
6372 */
6373 this.extensions = undefined;
6374
6375 /**
6376 * Runtime message class.
6377 * @type {?function(new:ProtoBuf.Builder.Message)}
6378 * @expose
6379 */
6380 this.clazz = null;
6381
6382 /**
6383 * Whether this is a legacy group or not.
6384 * @type {boolean}
6385 * @expose
6386 */
6387 this.isGroup = !!isGroup;
6388
6389 // The following cached collections are used to efficiently iterate over or look up fields when decoding.
6390
6391 /**
6392 * Cached fields.
6393 * @type {?Array.<!ProtoBuf.Reflect.Message.Field>}
6394 * @private
6395 */
6396 this._fields = null;
6397
6398 /**
6399 * Cached fields by id.
6400 * @type {?Object.<number,!ProtoBuf.Reflect.Message.Field>}
6401 * @private
6402 */
6403 this._fieldsById = null;
6404
6405 /**
6406 * Cached fields by name.
6407 * @type {?Object.<string,!ProtoBuf.Reflect.Message.Field>}
6408 * @private
6409 */
6410 this._fieldsByName = null;
6411 };
6412
6413 /**
6414 * @alias ProtoBuf.Reflect.Message.prototype
6415 * @inner
6416 */
6417 var MessagePrototype = Message.prototype = Object.create(Namespace.prototype);
6418
6419 /**
6420 * Builds the message and returns the runtime counterpart, which is a fully functional class.
6421 * @see ProtoBuf.Builder.Message
6422 * @param {boolean=} rebuild Whether to rebuild or not, defaults to false
6423 * @return {ProtoBuf.Reflect.Message} Message class
6424 * @throws {Error} If the message cannot be built
6425 * @expose
6426 */
6427 MessagePrototype.build = function(rebuild) {
6428 if (this.clazz && !rebuild)
6429 return this.clazz;
6430
6431 // Create the runtime Message class in its own scope
6432 var clazz = (function(ProtoBuf, T) {
6433
6434 var fields = T.getChildren(ProtoBuf.Reflect.Message.Field),
6435 oneofs = T.getChildren(ProtoBuf.Reflect.Message.OneOf);
6436
6437 /**
6438 * Constructs a new runtime Message.
6439 * @name ProtoBuf.Builder.Message
6440 * @class Barebone of all runtime messages.
6441 * @param {!Object.<string,*>|string} values Preset values
6442 * @param {...string} var_args
6443 * @constructor
6444 * @throws {Error} If the message cannot be created
6445 */
6446 var Message = function(values, var_args) {
6447 ProtoBuf.Builder.Message.call(this);
6448
6449 // Create virtual oneof properties
6450 for (var i=0, k=oneofs.length; i<k; ++i)
6451 this[oneofs[i].name] = null;
6452 // Create fields and set default values
6453 for (i=0, k=fields.length; i<k; ++i) {
6454 var field = fields[i];
6455 this[field.name] =
6456 field.repeated ? [] :
6457 (field.map ? new ProtoBuf.Map(field) : null);
6458 if ((field.required || T.syntax === 'proto3') &&
6459 field.defaultValue !== null)
6460 this[field.name] = field.defaultValue;
6461 }
6462
6463 if (arguments.length > 0) {
6464 var value;
6465 // Set field values from a values object
6466 if (arguments.length === 1 && values !== null && typeof values === 'object' &&
6467 /* not _another_ Message */ (typeof values.encode !== 'function' || values instanceof Message) &&
6468 /* not a repeated field */ !Array.isArray(values) &&
6469 /* not a Map */ !(values instanceof ProtoBuf.Map) &&
6470 /* not a ByteBuffer */ !ByteBuffer.isByteBuffer(values) &&
6471 /* not an ArrayBuffer */ !(values instanceof ArrayBuffer) &&
6472 /* not a Long */ !(ProtoBuf.Long && values instanceof ProtoBuf.Long)) {
6473 this.$set(values);
6474 } else // Set field values from arguments, in declaration order
6475 for (i=0, k=arguments.length; i<k; ++i)
6476 if (typeof (value = arguments[i]) !== 'undefined')
6477 this.$set(fields[i].name, value); // May throw
6478 }
6479 };
6480
6481 /**
6482 * @alias ProtoBuf.Builder.Message.prototype
6483 * @inner
6484 */
6485 var MessagePrototype = Message.prototype = Object.create(ProtoBuf.Builder.Message.prototype);
6486
6487 /**
6488 * Adds a value to a repeated field.
6489 * @name ProtoBuf.Builder.Message#add
6490 * @function
6491 * @param {string} key Field name
6492 * @param {*} value Value to add
6493 * @param {boolean=} noAssert Whether to assert the value or not (asserts by default)
6494 * @returns {!ProtoBuf.Builder.Message} this
6495 * @throws {Error} If the value cannot be added
6496 * @expose
6497 */
6498 MessagePrototype.add = function(key, value, noAssert) {
6499 var field = T._fieldsByName[key];
6500 if (!noAssert) {
6501 if (!field)
6502 throw Error(this+"#"+key+" is undefined");
6503 if (!(field instanceof ProtoBuf.Reflect.Message.Field))
6504 throw Error(this+"#"+key+" is not a field: "+field.toString(true)); // May throw if it's an enum or embedded message
6505 if (!field.repeated)
6506 throw Error(this+"#"+key+" is not a repeated field");
6507 value = field.verifyValue(value, true);
6508 }
6509 if (this[key] === null)
6510 this[key] = [];
6511 this[key].push(value);
6512 return this;
6513 };
6514
6515 /**
6516 * Adds a value to a repeated field. This is an alias for {@link ProtoBuf.Builder.Message#add}.
6517 * @name ProtoBuf.Builder.Message#$add
6518 * @function
6519 * @param {string} key Field name
6520 * @param {*} value Value to add
6521 * @param {boolean=} noAssert Whether to assert the value or not (asserts by default)
6522 * @returns {!ProtoBuf.Builder.Message} this
6523 * @throws {Error} If the value cannot be added
6524 * @expose
6525 */
6526 MessagePrototype.$add = MessagePrototype.add;
6527
6528 /**
6529 * Sets a field's value.
6530 * @name ProtoBuf.Builder.Message#set
6531 * @function
6532 * @param {string|!Object.<string,*>} keyOrObj String key or plain object holding multiple values
6533 * @param {(*|boolean)=} value Value to set if key is a string, otherwise omitted
6534 * @param {boolean=} noAssert Whether to not assert for an actual field / proper value type, defaults to `false`
6535 * @returns {!ProtoBuf.Builder.Message} this
6536 * @throws {Error} If the value cannot be set
6537 * @expose
6538 */
6539 MessagePrototype.set = function(keyOrObj, value, noAssert) {
6540 if (keyOrObj && typeof keyOrObj === 'object') {
6541 noAssert = value;
6542 for (var ikey in keyOrObj) {
6543 // Check if virtual oneof field - don't set these
6544 if (keyOrObj.hasOwnProperty(ikey) && typeof (value = keyOrObj[ikey]) !== 'undefined' && T._oneofsByName[ikey] === undefined)
6545 this.$set(ikey, value, noAssert);
6546 }
6547 return this;
6548 }
6549 var field = T._fieldsByName[keyOrObj];
6550 if (!noAssert) {
6551 if (!field)
6552 throw Error(this+"#"+keyOrObj+" is not a field: undefined");
6553 if (!(field instanceof ProtoBuf.Reflect.Message.Field))
6554 throw Error(this+"#"+keyOrObj+" is not a field: "+field.toString(true));
6555 this[field.name] = (value = field.verifyValue(value)); // May throw
6556 } else
6557 this[keyOrObj] = value;
6558 if (field && field.oneof) { // Field is part of an OneOf (not a virtual OneOf field)
6559 var currentField = this[field.oneof.name]; // Virtual field references currently set field
6560 if (value !== null) {
6561 if (currentField !== null && currentField !== field.name)
6562 this[currentField] = null; // Clear currently set field
6563 this[field.oneof.name] = field.name; // Point virtual field at this field
6564 } else if (/* value === null && */currentField === keyOrObj)
6565 this[field.oneof.name] = null; // Clear virtual field (current field explicitly cleared)
6566 }
6567 return this;
6568 };
6569
6570 /**
6571 * Sets a field's value. This is an alias for [@link ProtoBuf.Builder.Message#set}.
6572 * @name ProtoBuf.Builder.Message#$set
6573 * @function
6574 * @param {string|!Object.<string,*>} keyOrObj String key or plain object holding multiple values
6575 * @param {(*|boolean)=} value Value to set if key is a string, otherwise omitted
6576 * @param {boolean=} noAssert Whether to not assert the value, defaults to `false`
6577 * @throws {Error} If the value cannot be set
6578 * @expose
6579 */
6580 MessagePrototype.$set = MessagePrototype.set;
6581
6582 /**
6583 * Gets a field's value.
6584 * @name ProtoBuf.Builder.Message#get
6585 * @function
6586 * @param {string} key Key
6587 * @param {boolean=} noAssert Whether to not assert for an actual field, defaults to `false`
6588 * @return {*} Value
6589 * @throws {Error} If there is no such field
6590 * @expose
6591 */
6592 MessagePrototype.get = function(key, noAssert) {
6593 if (noAssert)
6594 return this[key];
6595 var field = T._fieldsByName[key];
6596 if (!field || !(field instanceof ProtoBuf.Reflect.Message.Field))
6597 throw Error(this+"#"+key+" is not a field: undefined");
6598 if (!(field instanceof ProtoBuf.Reflect.Message.Field))
6599 throw Error(this+"#"+key+" is not a field: "+field.toString(true));
6600 return this[field.name];
6601 };
6602
6603 /**
6604 * Gets a field's value. This is an alias for {@link ProtoBuf.Builder.Message#$get}.
6605 * @name ProtoBuf.Builder.Message#$get
6606 * @function
6607 * @param {string} key Key
6608 * @return {*} Value
6609 * @throws {Error} If there is no such field
6610 * @expose
6611 */
6612 MessagePrototype.$get = MessagePrototype.get;
6613
6614 // Getters and setters
6615
6616 for (var i=0; i<fields.length; i++) {
6617 var field = fields[i];
6618 // no setters for extension fields as these are named by their fqn
6619 if (field instanceof ProtoBuf.Reflect.Message.ExtensionField)
6620 continue;
6621
6622 if (T.builder.options['populateAccessors'])
6623 (function(field) {
6624 // set/get[SomeValue]
6625 var Name = field.originalName.replace(/(_[a-zA-Z])/g, function(match) {
6626 return match.toUpperCase().replace('_','');
6627 });
6628 Name = Name.substring(0,1).toUpperCase() + Name.substring(1);
6629
6630 // set/get_[some_value] FIXME: Do we really need these?
6631 var name = field.originalName.replace(/([A-Z])/g, function(match) {
6632 return "_"+match;
6633 });
6634
6635 /**
6636 * The current field's unbound setter function.
6637 * @function
6638 * @param {*} value
6639 * @param {boolean=} noAssert
6640 * @returns {!ProtoBuf.Builder.Message}
6641 * @inner
6642 */
6643 var setter = function(value, noAssert) {
6644 this[field.name] = noAssert ? value : field.verifyValue(value);
6645 return this;
6646 };
6647
6648 /**
6649 * The current field's unbound getter function.
6650 * @function
6651 * @returns {*}
6652 * @inner
6653 */
6654 var getter = function() {
6655 return this[field.name];
6656 };
6657
6658 if (T.getChild("set"+Name) === null)
6659 /**
6660 * Sets a value. This method is present for each field, but only if there is no name conflict with
6661 * another field.
6662 * @name ProtoBuf.Builder.Message#set[SomeField]
6663 * @function
6664 * @param {*} value Value to set
6665 * @param {boolean=} noAssert Whether to not assert the value, defaults to `false`
6666 * @returns {!ProtoBuf.Builder.Message} this
6667 * @abstract
6668 * @throws {Error} If the value cannot be set
6669 */
6670 MessagePrototype["set"+Name] = setter;
6671
6672 if (T.getChild("set_"+name) === null)
6673 /**
6674 * Sets a value. This method is present for each field, but only if there is no name conflict with
6675 * another field.
6676 * @name ProtoBuf.Builder.Message#set_[some_field]
6677 * @function
6678 * @param {*} value Value to set
6679 * @param {boolean=} noAssert Whether to not assert the value, defaults to `false`
6680 * @returns {!ProtoBuf.Builder.Message} this
6681 * @abstract
6682 * @throws {Error} If the value cannot be set
6683 */
6684 MessagePrototype["set_"+name] = setter;
6685
6686 if (T.getChild("get"+Name) === null)
6687 /**
6688 * Gets a value. This method is present for each field, but only if there is no name conflict with
6689 * another field.
6690 * @name ProtoBuf.Builder.Message#get[SomeField]
6691 * @function
6692 * @abstract
6693 * @return {*} The value
6694 */
6695 MessagePrototype["get"+Name] = getter;
6696
6697 if (T.getChild("get_"+name) === null)
6698 /**
6699 * Gets a value. This method is present for each field, but only if there is no name conflict with
6700 * another field.
6701 * @name ProtoBuf.Builder.Message#get_[some_field]
6702 * @function
6703 * @return {*} The value
6704 * @abstract
6705 */
6706 MessagePrototype["get_"+name] = getter;
6707
6708 })(field);
6709 }
6710
6711 // En-/decoding
6712
6713 /**
6714 * Encodes the message.
6715 * @name ProtoBuf.Builder.Message#$encode
6716 * @function
6717 * @param {(!ByteBuffer|boolean)=} buffer ByteBuffer to encode to. Will create a new one and flip it if omitted.
6718 * @param {boolean=} noVerify Whether to not verify field values, defaults to `false`
6719 * @return {!ByteBuffer} Encoded message as a ByteBuffer
6720 * @throws {Error} If the message cannot be encoded or if required fields are missing. The later still
6721 * returns the encoded ByteBuffer in the `encoded` property on the error.
6722 * @expose
6723 * @see ProtoBuf.Builder.Message#encode64
6724 * @see ProtoBuf.Builder.Message#encodeHex
6725 * @see ProtoBuf.Builder.Message#encodeAB
6726 */
6727 MessagePrototype.encode = function(buffer, noVerify) {
6728 if (typeof buffer === 'boolean')
6729 noVerify = buffer,
6730 buffer = undefined;
6731 var isNew = false;
6732 if (!buffer)
6733 buffer = new ByteBuffer(),
6734 isNew = true;
6735 var le = buffer.littleEndian;
6736 try {
6737 T.encode(this, buffer.LE(), noVerify);
6738 return (isNew ? buffer.flip() : buffer).LE(le);
6739 } catch (e) {
6740 buffer.LE(le);
6741 throw(e);
6742 }
6743 };
6744
6745 /**
6746 * Encodes a message using the specified data payload.
6747 * @param {!Object.<string,*>} data Data payload
6748 * @param {(!ByteBuffer|boolean)=} buffer ByteBuffer to encode to. Will create a new one and flip it if omitted.
6749 * @param {boolean=} noVerify Whether to not verify field values, defaults to `false`
6750 * @return {!ByteBuffer} Encoded message as a ByteBuffer
6751 * @expose
6752 */
6753 Message.encode = function(data, buffer, noVerify) {
6754 return new Message(data).encode(buffer, noVerify);
6755 };
6756
6757 /**
6758 * Calculates the byte length of the message.
6759 * @name ProtoBuf.Builder.Message#calculate
6760 * @function
6761 * @returns {number} Byte length
6762 * @throws {Error} If the message cannot be calculated or if required fields are missing.
6763 * @expose
6764 */
6765 MessagePrototype.calculate = function() {
6766 return T.calculate(this);
6767 };
6768
6769 /**
6770 * Encodes the varint32 length-delimited message.
6771 * @name ProtoBuf.Builder.Message#encodeDelimited
6772 * @function
6773 * @param {(!ByteBuffer|boolean)=} buffer ByteBuffer to encode to. Will create a new one and flip it if omitted.
6774 * @param {boolean=} noVerify Whether to not verify field values, defaults to `false`
6775 * @return {!ByteBuffer} Encoded message as a ByteBuffer
6776 * @throws {Error} If the message cannot be encoded or if required fields are missing. The later still
6777 * returns the encoded ByteBuffer in the `encoded` property on the error.
6778 * @expose
6779 */
6780 MessagePrototype.encodeDelimited = function(buffer, noVerify) {
6781 var isNew = false;
6782 if (!buffer)
6783 buffer = new ByteBuffer(),
6784 isNew = true;
6785 var enc = new ByteBuffer().LE();
6786 T.encode(this, enc, noVerify).flip();
6787 buffer.writeVarint32(enc.remaining());
6788 buffer.append(enc);
6789 return isNew ? buffer.flip() : buffer;
6790 };
6791
6792 /**
6793 * Directly encodes the message to an ArrayBuffer.
6794 * @name ProtoBuf.Builder.Message#encodeAB
6795 * @function
6796 * @return {ArrayBuffer} Encoded message as ArrayBuffer
6797 * @throws {Error} If the message cannot be encoded or if required fields are missing. The later still
6798 * returns the encoded ArrayBuffer in the `encoded` property on the error.
6799 * @expose
6800 */
6801 MessagePrototype.encodeAB = function() {
6802 try {
6803 return this.encode().toArrayBuffer();
6804 } catch (e) {
6805 if (e["encoded"]) e["encoded"] = e["encoded"].toArrayBuffer();
6806 throw(e);
6807 }
6808 };
6809
6810 /**
6811 * Returns the message as an ArrayBuffer. This is an alias for {@link ProtoBuf.Builder.Message#encodeAB}.
6812 * @name ProtoBuf.Builder.Message#toArrayBuffer
6813 * @function
6814 * @return {ArrayBuffer} Encoded message as ArrayBuffer
6815 * @throws {Error} If the message cannot be encoded or if required fields are missing. The later still
6816 * returns the encoded ArrayBuffer in the `encoded` property on the error.
6817 * @expose
6818 */
6819 MessagePrototype.toArrayBuffer = MessagePrototype.encodeAB;
6820
6821 /**
6822 * Directly encodes the message to a node Buffer.
6823 * @name ProtoBuf.Builder.Message#encodeNB
6824 * @function
6825 * @return {!Buffer}
6826 * @throws {Error} If the message cannot be encoded, not running under node.js or if required fields are
6827 * missing. The later still returns the encoded node Buffer in the `encoded` property on the error.
6828 * @expose
6829 */
6830 MessagePrototype.encodeNB = function() {
6831 try {
6832 return this.encode().toBuffer();
6833 } catch (e) {
6834 if (e["encoded"]) e["encoded"] = e["encoded"].toBuffer();
6835 throw(e);
6836 }
6837 };
6838
6839 /**
6840 * Returns the message as a node Buffer. This is an alias for {@link ProtoBuf.Builder.Message#encodeNB}.
6841 * @name ProtoBuf.Builder.Message#toBuffer
6842 * @function
6843 * @return {!Buffer}
6844 * @throws {Error} If the message cannot be encoded or if required fields are missing. The later still
6845 * returns the encoded node Buffer in the `encoded` property on the error.
6846 * @expose
6847 */
6848 MessagePrototype.toBuffer = MessagePrototype.encodeNB;
6849
6850 /**
6851 * Directly encodes the message to a base64 encoded string.
6852 * @name ProtoBuf.Builder.Message#encode64
6853 * @function
6854 * @return {string} Base64 encoded string
6855 * @throws {Error} If the underlying buffer cannot be encoded or if required fields are missing. The later
6856 * still returns the encoded base64 string in the `encoded` property on the error.
6857 * @expose
6858 */
6859 MessagePrototype.encode64 = function() {
6860 try {
6861 return this.encode().toBase64();
6862 } catch (e) {
6863 if (e["encoded"]) e["encoded"] = e["encoded"].toBase64();
6864 throw(e);
6865 }
6866 };
6867
6868 /**
6869 * Returns the message as a base64 encoded string. This is an alias for {@link ProtoBuf.Builder.Message#encode64}.
6870 * @name ProtoBuf.Builder.Message#toBase64
6871 * @function
6872 * @return {string} Base64 encoded string
6873 * @throws {Error} If the message cannot be encoded or if required fields are missing. The later still
6874 * returns the encoded base64 string in the `encoded` property on the error.
6875 * @expose
6876 */
6877 MessagePrototype.toBase64 = MessagePrototype.encode64;
6878
6879 /**
6880 * Directly encodes the message to a hex encoded string.
6881 * @name ProtoBuf.Builder.Message#encodeHex
6882 * @function
6883 * @return {string} Hex encoded string
6884 * @throws {Error} If the underlying buffer cannot be encoded or if required fields are missing. The later
6885 * still returns the encoded hex string in the `encoded` property on the error.
6886 * @expose
6887 */
6888 MessagePrototype.encodeHex = function() {
6889 try {
6890 return this.encode().toHex();
6891 } catch (e) {
6892 if (e["encoded"]) e["encoded"] = e["encoded"].toHex();
6893 throw(e);
6894 }
6895 };
6896
6897 /**
6898 * Returns the message as a hex encoded string. This is an alias for {@link ProtoBuf.Builder.Message#encodeHex}.
6899 * @name ProtoBuf.Builder.Message#toHex
6900 * @function
6901 * @return {string} Hex encoded string
6902 * @throws {Error} If the message cannot be encoded or if required fields are missing. The later still
6903 * returns the encoded hex string in the `encoded` property on the error.
6904 * @expose
6905 */
6906 MessagePrototype.toHex = MessagePrototype.encodeHex;
6907
6908 /**
6909 * Clones a message object or field value to a raw object.
6910 * @param {*} obj Object to clone
6911 * @param {boolean} binaryAsBase64 Whether to include binary data as base64 strings or as a buffer otherwise
6912 * @param {boolean} longsAsStrings Whether to encode longs as strings
6913 * @param {!ProtoBuf.Reflect.T=} resolvedType The resolved field type if a field
6914 * @returns {*} Cloned object
6915 * @inner
6916 */
6917 function cloneRaw(obj, binaryAsBase64, longsAsStrings, resolvedType) {
6918 if (obj === null || typeof obj !== 'object') {
6919 // Convert enum values to their respective names
6920 if (resolvedType && resolvedType instanceof ProtoBuf.Reflect.Enum) {
6921 var name = ProtoBuf.Reflect.Enum.getName(resolvedType.object, obj);
6922 if (name !== null)
6923 return name;
6924 }
6925 // Pass-through string, number, boolean, null...
6926 return obj;
6927 }
6928 // Convert ByteBuffers to raw buffer or strings
6929 if (ByteBuffer.isByteBuffer(obj))
6930 return binaryAsBase64 ? obj.toBase64() : obj.toBuffer();
6931 // Convert Longs to proper objects or strings
6932 if (ProtoBuf.Long.isLong(obj))
6933 return longsAsStrings ? obj.toString() : ProtoBuf.Long.fromValue(obj);
6934 var clone;
6935 // Clone arrays
6936 if (Array.isArray(obj)) {
6937 clone = [];
6938 obj.forEach(function(v, k) {
6939 clone[k] = cloneRaw(v, binaryAsBase64, longsAsStrings, resolvedType);
6940 });
6941 return clone;
6942 }
6943 clone = {};
6944 // Convert maps to objects
6945 if (obj instanceof ProtoBuf.Map) {
6946 var it = obj.entries();
6947 for (var e = it.next(); !e.done; e = it.next())
6948 clone[obj.keyElem.valueToString(e.value[0])] = cloneRaw(e.value[1], binaryAsBase64, longsAsStrings, obj.valueElem.resolvedType);
6949 return clone;
6950 }
6951 // Everything else is a non-null object
6952 var type = obj.$type,
6953 field = undefined;
6954 for (var i in obj)
6955 if (obj.hasOwnProperty(i)) {
6956 if (type && (field = type.getChild(i)))
6957 clone[i] = cloneRaw(obj[i], binaryAsBase64, longsAsStrings, field.resolvedType);
6958 else
6959 clone[i] = cloneRaw(obj[i], binaryAsBase64, longsAsStrings);
6960 }
6961 return clone;
6962 }
6963
6964 /**
6965 * Returns the message's raw payload.
6966 * @param {boolean=} binaryAsBase64 Whether to include binary data as base64 strings instead of Buffers, defaults to `false`
6967 * @param {boolean} longsAsStrings Whether to encode longs as strings
6968 * @returns {Object.<string,*>} Raw payload
6969 * @expose
6970 */
6971 MessagePrototype.toRaw = function(binaryAsBase64, longsAsStrings) {
6972 return cloneRaw(this, !!binaryAsBase64, !!longsAsStrings, this.$type);
6973 };
6974
6975 /**
6976 * Encodes a message to JSON.
6977 * @returns {string} JSON string
6978 * @expose
6979 */
6980 MessagePrototype.encodeJSON = function() {
6981 return JSON.stringify(
6982 cloneRaw(this,
6983 /* binary-as-base64 */ true,
6984 /* longs-as-strings */ true,
6985 this.$type
6986 )
6987 );
6988 };
6989
6990 /**
6991 * Decodes a message from the specified buffer or string.
6992 * @name ProtoBuf.Builder.Message.decode
6993 * @function
6994 * @param {!ByteBuffer|!ArrayBuffer|!Buffer|string} buffer Buffer to decode from
6995 * @param {(number|string)=} length Message length. Defaults to decode all the remainig data.
6996 * @param {string=} enc Encoding if buffer is a string: hex, utf8 (not recommended), defaults to base64
6997 * @return {!ProtoBuf.Builder.Message} Decoded message
6998 * @throws {Error} If the message cannot be decoded or if required fields are missing. The later still
6999 * returns the decoded message with missing fields in the `decoded` property on the error.
7000 * @expose
7001 * @see ProtoBuf.Builder.Message.decode64
7002 * @see ProtoBuf.Builder.Message.decodeHex
7003 */
7004 Message.decode = function(buffer, length, enc) {
7005 if (typeof length === 'string')
7006 enc = length,
7007 length = -1;
7008 if (typeof buffer === 'string')
7009 buffer = ByteBuffer.wrap(buffer, enc ? enc : "base64");
7010 else if (!ByteBuffer.isByteBuffer(buffer))
7011 buffer = ByteBuffer.wrap(buffer); // May throw
7012 var le = buffer.littleEndian;
7013 try {
7014 var msg = T.decode(buffer.LE(), length);
7015 buffer.LE(le);
7016 return msg;
7017 } catch (e) {
7018 buffer.LE(le);
7019 throw(e);
7020 }
7021 };
7022
7023 /**
7024 * Decodes a varint32 length-delimited message from the specified buffer or string.
7025 * @name ProtoBuf.Builder.Message.decodeDelimited
7026 * @function
7027 * @param {!ByteBuffer|!ArrayBuffer|!Buffer|string} buffer Buffer to decode from
7028 * @param {string=} enc Encoding if buffer is a string: hex, utf8 (not recommended), defaults to base64
7029 * @return {ProtoBuf.Builder.Message} Decoded message or `null` if not enough bytes are available yet
7030 * @throws {Error} If the message cannot be decoded or if required fields are missing. The later still
7031 * returns the decoded message with missing fields in the `decoded` property on the error.
7032 * @expose
7033 */
7034 Message.decodeDelimited = function(buffer, enc) {
7035 if (typeof buffer === 'string')
7036 buffer = ByteBuffer.wrap(buffer, enc ? enc : "base64");
7037 else if (!ByteBuffer.isByteBuffer(buffer))
7038 buffer = ByteBuffer.wrap(buffer); // May throw
7039 if (buffer.remaining() < 1)
7040 return null;
7041 var off = buffer.offset,
7042 len = buffer.readVarint32();
7043 if (buffer.remaining() < len) {
7044 buffer.offset = off;
7045 return null;
7046 }
7047 try {
7048 var msg = T.decode(buffer.slice(buffer.offset, buffer.offset + len).LE());
7049 buffer.offset += len;
7050 return msg;
7051 } catch (err) {
7052 buffer.offset += len;
7053 throw err;
7054 }
7055 };
7056
7057 /**
7058 * Decodes the message from the specified base64 encoded string.
7059 * @name ProtoBuf.Builder.Message.decode64
7060 * @function
7061 * @param {string} str String to decode from
7062 * @return {!ProtoBuf.Builder.Message} Decoded message
7063 * @throws {Error} If the message cannot be decoded or if required fields are missing. The later still
7064 * returns the decoded message with missing fields in the `decoded` property on the error.
7065 * @expose
7066 */
7067 Message.decode64 = function(str) {
7068 return Message.decode(str, "base64");
7069 };
7070
7071 /**
7072 * Decodes the message from the specified hex encoded string.
7073 * @name ProtoBuf.Builder.Message.decodeHex
7074 * @function
7075 * @param {string} str String to decode from
7076 * @return {!ProtoBuf.Builder.Message} Decoded message
7077 * @throws {Error} If the message cannot be decoded or if required fields are missing. The later still
7078 * returns the decoded message with missing fields in the `decoded` property on the error.
7079 * @expose
7080 */
7081 Message.decodeHex = function(str) {
7082 return Message.decode(str, "hex");
7083 };
7084
7085 /**
7086 * Decodes the message from a JSON string.
7087 * @name ProtoBuf.Builder.Message.decodeJSON
7088 * @function
7089 * @param {string} str String to decode from
7090 * @return {!ProtoBuf.Builder.Message} Decoded message
7091 * @throws {Error} If the message cannot be decoded or if required fields are
7092 * missing.
7093 * @expose
7094 */
7095 Message.decodeJSON = function(str) {
7096 return new Message(JSON.parse(str));
7097 };
7098
7099 // Utility
7100
7101 /**
7102 * Returns a string representation of this Message.
7103 * @name ProtoBuf.Builder.Message#toString
7104 * @function
7105 * @return {string} String representation as of ".Fully.Qualified.MessageName"
7106 * @expose
7107 */
7108 MessagePrototype.toString = function() {
7109 return T.toString();
7110 };
7111
7112 if (Object.defineProperty)
7113 Object.defineProperty(Message, '$options', { "value": T.buildOpt() }),
7114 Object.defineProperty(MessagePrototype, "$options", { "value": Message["$options"] }),
7115 Object.defineProperty(Message, "$type", { "value": T }),
7116 Object.defineProperty(MessagePrototype, "$type", { "value": T });
7117
7118 return Message;
7119
7120 })(ProtoBuf, this);
7121
7122 // Static enums and prototyped sub-messages / cached collections
7123 this._fields = [];
7124 this._fieldsById = {};
7125 this._fieldsByName = {};
7126 this._oneofsByName = {};
7127 for (var i=0, k=this.children.length, child; i<k; i++) {
7128 child = this.children[i];
7129 if (child instanceof Enum || child instanceof Message || child instanceof Service) {
7130 if (clazz.hasOwnProperty(child.name))
7131 throw Error("Illegal reflect child of "+this.toString(true)+": "+child.toString(true)+" cannot override static property '"+child.name+"'");
7132 clazz[child.name] = child.build();
7133 } else if (child instanceof Message.Field)
7134 child.build(),
7135 this._fields.push(child),
7136 this._fieldsById[child.id] = child,
7137 this._fieldsByName[child.name] = child;
7138 else if (child instanceof Message.OneOf) {
7139 this._oneofsByName[child.name] = child;
7140 }
7141 else if (!(child instanceof Message.OneOf) && !(child instanceof Extension)) // Not built
7142 throw Error("Illegal reflect child of "+this.toString(true)+": "+this.children[i].toString(true));
7143 }
7144
7145 return this.clazz = clazz;
7146 };
7147
7148 /**
7149 * Encodes a runtime message's contents to the specified buffer.
7150 * @param {!ProtoBuf.Builder.Message} message Runtime message to encode
7151 * @param {ByteBuffer} buffer ByteBuffer to write to
7152 * @param {boolean=} noVerify Whether to not verify field values, defaults to `false`
7153 * @return {ByteBuffer} The ByteBuffer for chaining
7154 * @throws {Error} If required fields are missing or the message cannot be encoded for another reason
7155 * @expose
7156 */
7157 MessagePrototype.encode = function(message, buffer, noVerify) {
7158 var fieldMissing = null,
7159 field;
7160 for (var i=0, k=this._fields.length, val; i<k; ++i) {
7161 field = this._fields[i];
7162 val = message[field.name];
7163 if (field.required && val === null) {
7164 if (fieldMissing === null)
7165 fieldMissing = field;
7166 } else
7167 field.encode(noVerify ? val : field.verifyValue(val), buffer, message);
7168 }
7169 if (fieldMissing !== null) {
7170 var err = Error("Missing at least one required field for "+this.toString(true)+": "+fieldMissing);
7171 err["encoded"] = buffer; // Still expose what we got
7172 throw(err);
7173 }
7174 return buffer;
7175 };
7176
7177 /**
7178 * Calculates a runtime message's byte length.
7179 * @param {!ProtoBuf.Builder.Message} message Runtime message to encode
7180 * @returns {number} Byte length
7181 * @throws {Error} If required fields are missing or the message cannot be calculated for another reason
7182 * @expose
7183 */
7184 MessagePrototype.calculate = function(message) {
7185 for (var n=0, i=0, k=this._fields.length, field, val; i<k; ++i) {
7186 field = this._fields[i];
7187 val = message[field.name];
7188 if (field.required && val === null)
7189 throw Error("Missing at least one required field for "+this.toString(true)+": "+field);
7190 else
7191 n += field.calculate(val, message);
7192 }
7193 return n;
7194 };
7195
7196 /**
7197 * Skips all data until the end of the specified group has been reached.
7198 * @param {number} expectedId Expected GROUPEND id
7199 * @param {!ByteBuffer} buf ByteBuffer
7200 * @returns {boolean} `true` if a value as been skipped, `false` if the end has been reached
7201 * @throws {Error} If it wasn't possible to find the end of the group (buffer overrun or end tag mismatch)
7202 * @inner
7203 */
7204 function skipTillGroupEnd(expectedId, buf) {
7205 var tag = buf.readVarint32(), // Throws on OOB
7206 wireType = tag & 0x07,
7207 id = tag >>> 3;
7208 switch (wireType) {
7209 case ProtoBuf.WIRE_TYPES.VARINT:
7210 do tag = buf.readUint8();
7211 while ((tag & 0x80) === 0x80);
7212 break;
7213 case ProtoBuf.WIRE_TYPES.BITS64:
7214 buf.offset += 8;
7215 break;
7216 case ProtoBuf.WIRE_TYPES.LDELIM:
7217 tag = buf.readVarint32(); // reads the varint
7218 buf.offset += tag; // skips n bytes
7219 break;
7220 case ProtoBuf.WIRE_TYPES.STARTGROUP:
7221 skipTillGroupEnd(id, buf);
7222 break;
7223 case ProtoBuf.WIRE_TYPES.ENDGROUP:
7224 if (id === expectedId)
7225 return false;
7226 else
7227 throw Error("Illegal GROUPEND after unknown group: "+id+" ("+expectedId+" expected)");
7228 case ProtoBuf.WIRE_TYPES.BITS32:
7229 buf.offset += 4;
7230 break;
7231 default:
7232 throw Error("Illegal wire type in unknown group "+expectedId+": "+wireType);
7233 }
7234 return true;
7235 }
7236
7237 /**
7238 * Decodes an encoded message and returns the decoded message.
7239 * @param {ByteBuffer} buffer ByteBuffer to decode from
7240 * @param {number=} length Message length. Defaults to decode all remaining data.
7241 * @param {number=} expectedGroupEndId Expected GROUPEND id if this is a legacy group
7242 * @return {ProtoBuf.Builder.Message} Decoded message
7243 * @throws {Error} If the message cannot be decoded
7244 * @expose
7245 */
7246 MessagePrototype.decode = function(buffer, length, expectedGroupEndId) {
7247 if (typeof length !== 'number')
7248 length = -1;
7249 var start = buffer.offset,
7250 msg = new (this.clazz)(),
7251 tag, wireType, id, field;
7252 while (buffer.offset < start+length || (length === -1 && buffer.remaining() > 0)) {
7253 tag = buffer.readVarint32();
7254 wireType = tag & 0x07;
7255 id = tag >>> 3;
7256 if (wireType === ProtoBuf.WIRE_TYPES.ENDGROUP) {
7257 if (id !== expectedGroupEndId)
7258 throw Error("Illegal group end indicator for "+this.toString(true)+": "+id+" ("+(expectedGroupEndId ? expectedGroupEndId+" expected" : "not a group")+")");
7259 break;
7260 }
7261 if (!(field = this._fieldsById[id])) {
7262 // "messages created by your new code can be parsed by your old code: old binaries simply ignore the new field when parsing."
7263 switch (wireType) {
7264 case ProtoBuf.WIRE_TYPES.VARINT:
7265 buffer.readVarint32();
7266 break;
7267 case ProtoBuf.WIRE_TYPES.BITS32:
7268 buffer.offset += 4;
7269 break;
7270 case ProtoBuf.WIRE_TYPES.BITS64:
7271 buffer.offset += 8;
7272 break;
7273 case ProtoBuf.WIRE_TYPES.LDELIM:
7274 var len = buffer.readVarint32();
7275 buffer.offset += len;
7276 break;
7277 case ProtoBuf.WIRE_TYPES.STARTGROUP:
7278 while (skipTillGroupEnd(id, buffer)) {}
7279 break;
7280 default:
7281 throw Error("Illegal wire type for unknown field "+id+" in "+this.toString(true)+"#decode: "+wireType);
7282 }
7283 continue;
7284 }
7285 if (field.repeated && !field.options["packed"]) {
7286 msg[field.name].push(field.decode(wireType, buffer));
7287 } else if (field.map) {
7288 var keyval = field.decode(wireType, buffer);
7289 msg[field.name].set(keyval[0], keyval[1]);
7290 } else {
7291 msg[field.name] = field.decode(wireType, buffer);
7292 if (field.oneof) { // Field is part of an OneOf (not a virtual OneOf field)
7293 var currentField = msg[field.oneof.name]; // Virtual field references currently set field
7294 if (currentField !== null && currentField !== field.name)
7295 msg[currentField] = null; // Clear currently set field
7296 msg[field.oneof.name] = field.name; // Point virtual field at this field
7297 }
7298 }
7299 }
7300
7301 // Check if all required fields are present and set default values for optional fields that are not
7302 for (var i=0, k=this._fields.length; i<k; ++i) {
7303 field = this._fields[i];
7304 if (msg[field.name] === null) {
7305 if (this.syntax === "proto3") { // Proto3 sets default values by specification
7306 msg[field.name] = field.defaultValue;
7307 } else if (field.required) {
7308 var err = Error("Missing at least one required field for " + this.toString(true) + ": " + field.name);
7309 err["decoded"] = msg; // Still expose what we got
7310 throw(err);
7311 } else if (ProtoBuf.populateDefaults && field.defaultValue !== null)
7312 msg[field.name] = field.defaultValue;
7313 }
7314 }
7315 return msg;
7316 };
7317
7318 /**
7319 * @alias ProtoBuf.Reflect.Message
7320 * @expose
7321 */
7322 Reflect.Message = Message;
7323
7324 /**
7325 * Constructs a new Message Field.
7326 * @exports ProtoBuf.Reflect.Message.Field
7327 * @param {!ProtoBuf.Builder} builder Builder reference
7328 * @param {!ProtoBuf.Reflect.Message} message Message reference
7329 * @param {string} rule Rule, one of requried, optional, repeated
7330 * @param {string?} keytype Key data type, if any.
7331 * @param {string} type Data type, e.g. int32
7332 * @param {string} name Field name
7333 * @param {number} id Unique field id
7334 * @param {Object.<string,*>=} options Options
7335 * @param {!ProtoBuf.Reflect.Message.OneOf=} oneof Enclosing OneOf
7336 * @param {string?} syntax The syntax level of this definition (e.g., proto3)
7337 * @constructor
7338 * @extends ProtoBuf.Reflect.T
7339 */
7340 var Field = function(builder, message, rule, keytype, type, name, id, options, oneof, syntax) {
7341 T.call(this, builder, message, name);
7342
7343 /**
7344 * @override
7345 */
7346 this.className = "Message.Field";
7347
7348 /**
7349 * Message field required flag.
7350 * @type {boolean}
7351 * @expose
7352 */
7353 this.required = rule === "required";
7354
7355 /**
7356 * Message field repeated flag.
7357 * @type {boolean}
7358 * @expose
7359 */
7360 this.repeated = rule === "repeated";
7361
7362 /**
7363 * Message field map flag.
7364 * @type {boolean}
7365 * @expose
7366 */
7367 this.map = rule === "map";
7368
7369 /**
7370 * Message field key type. Type reference string if unresolved, protobuf
7371 * type if resolved. Valid only if this.map === true, null otherwise.
7372 * @type {string|{name: string, wireType: number}|null}
7373 * @expose
7374 */
7375 this.keyType = keytype || null;
7376
7377 /**
7378 * Message field type. Type reference string if unresolved, protobuf type if
7379 * resolved. In a map field, this is the value type.
7380 * @type {string|{name: string, wireType: number}}
7381 * @expose
7382 */
7383 this.type = type;
7384
7385 /**
7386 * Resolved type reference inside the global namespace.
7387 * @type {ProtoBuf.Reflect.T|null}
7388 * @expose
7389 */
7390 this.resolvedType = null;
7391
7392 /**
7393 * Unique message field id.
7394 * @type {number}
7395 * @expose
7396 */
7397 this.id = id;
7398
7399 /**
7400 * Message field options.
7401 * @type {!Object.<string,*>}
7402 * @dict
7403 * @expose
7404 */
7405 this.options = options || {};
7406
7407 /**
7408 * Default value.
7409 * @type {*}
7410 * @expose
7411 */
7412 this.defaultValue = null;
7413
7414 /**
7415 * Enclosing OneOf.
7416 * @type {?ProtoBuf.Reflect.Message.OneOf}
7417 * @expose
7418 */
7419 this.oneof = oneof || null;
7420
7421 /**
7422 * Syntax level of this definition (e.g., proto3).
7423 * @type {string}
7424 * @expose
7425 */
7426 this.syntax = syntax || 'proto2';
7427
7428 /**
7429 * Original field name.
7430 * @type {string}
7431 * @expose
7432 */
7433 this.originalName = this.name; // Used to revert camelcase transformation on naming collisions
7434
7435 /**
7436 * Element implementation. Created in build() after types are resolved.
7437 * @type {ProtoBuf.Element}
7438 * @expose
7439 */
7440 this.element = null;
7441
7442 /**
7443 * Key element implementation, for map fields. Created in build() after
7444 * types are resolved.
7445 * @type {ProtoBuf.Element}
7446 * @expose
7447 */
7448 this.keyElement = null;
7449
7450 // Convert field names to camel case notation if the override is set
7451 if (this.builder.options['convertFieldsToCamelCase'] && !(this instanceof Message.ExtensionField))
7452 this.name = ProtoBuf.Util.toCamelCase(this.name);
7453 };
7454
7455 /**
7456 * @alias ProtoBuf.Reflect.Message.Field.prototype
7457 * @inner
7458 */
7459 var FieldPrototype = Field.prototype = Object.create(T.prototype);
7460
7461 /**
7462 * Builds the field.
7463 * @override
7464 * @expose
7465 */
7466 FieldPrototype.build = function() {
7467 this.element = new Element(this.type, this.resolvedType, false, this.syntax, this.name);
7468 if (this.map)
7469 this.keyElement = new Element(this.keyType, undefined, true, this.syntax, this.name);
7470
7471 // In proto3, fields do not have field presence, and every field is set to
7472 // its type's default value ("", 0, 0.0, or false).
7473 if (this.syntax === 'proto3' && !this.repeated && !this.map)
7474 this.defaultValue = Element.defaultFieldValue(this.type);
7475
7476 // Otherwise, default values are present when explicitly specified
7477 else if (typeof this.options['default'] !== 'undefined')
7478 this.defaultValue = this.verifyValue(this.options['default']);
7479 };
7480
7481 /**
7482 * Checks if the given value can be set for this field.
7483 * @param {*} value Value to check
7484 * @param {boolean=} skipRepeated Whether to skip the repeated value check or not. Defaults to false.
7485 * @return {*} Verified, maybe adjusted, value
7486 * @throws {Error} If the value cannot be set for this field
7487 * @expose
7488 */
7489 FieldPrototype.verifyValue = function(value, skipRepeated) {
7490 skipRepeated = skipRepeated || false;
7491 var self = this;
7492 function fail(val, msg) {
7493 throw Error("Illegal value for "+self.toString(true)+" of type "+self.type.name+": "+val+" ("+msg+")");
7494 }
7495 if (value === null) { // NULL values for optional fields
7496 if (this.required)
7497 fail(typeof value, "required");
7498 if (this.syntax === 'proto3' && this.type !== ProtoBuf.TYPES["message"])
7499 fail(typeof value, "proto3 field without field presence cannot be null");
7500 return null;
7501 }
7502 var i;
7503 if (this.repeated && !skipRepeated) { // Repeated values as arrays
7504 if (!Array.isArray(value))
7505 value = [value];
7506 var res = [];
7507 for (i=0; i<value.length; i++)
7508 res.push(this.element.verifyValue(value[i]));
7509 return res;
7510 }
7511 if (this.map && !skipRepeated) { // Map values as objects
7512 if (!(value instanceof ProtoBuf.Map)) {
7513 // If not already a Map, attempt to convert.
7514 if (!(value instanceof Object)) {
7515 fail(typeof value,
7516 "expected ProtoBuf.Map or raw object for map field");
7517 }
7518 return new ProtoBuf.Map(this, value);
7519 } else {
7520 return value;
7521 }
7522 }
7523 // All non-repeated fields expect no array
7524 if (!this.repeated && Array.isArray(value))
7525 fail(typeof value, "no array expected");
7526
7527 return this.element.verifyValue(value);
7528 };
7529
7530 /**
7531 * Determines whether the field will have a presence on the wire given its
7532 * value.
7533 * @param {*} value Verified field value
7534 * @param {!ProtoBuf.Builder.Message} message Runtime message
7535 * @return {boolean} Whether the field will be present on the wire
7536 */
7537 FieldPrototype.hasWirePresence = function(value, message) {
7538 if (this.syntax !== 'proto3')
7539 return (value !== null);
7540 if (this.oneof && message[this.oneof.name] === this.name)
7541 return true;
7542 switch (this.type) {
7543 case ProtoBuf.TYPES["int32"]:
7544 case ProtoBuf.TYPES["sint32"]:
7545 case ProtoBuf.TYPES["sfixed32"]:
7546 case ProtoBuf.TYPES["uint32"]:
7547 case ProtoBuf.TYPES["fixed32"]:
7548 return value !== 0;
7549
7550 case ProtoBuf.TYPES["int64"]:
7551 case ProtoBuf.TYPES["sint64"]:
7552 case ProtoBuf.TYPES["sfixed64"]:
7553 case ProtoBuf.TYPES["uint64"]:
7554 case ProtoBuf.TYPES["fixed64"]:
7555 return value.low !== 0 || value.high !== 0;
7556
7557 case ProtoBuf.TYPES["bool"]:
7558 return value;
7559
7560 case ProtoBuf.TYPES["float"]:
7561 case ProtoBuf.TYPES["double"]:
7562 return value !== 0.0;
7563
7564 case ProtoBuf.TYPES["string"]:
7565 return value.length > 0;
7566
7567 case ProtoBuf.TYPES["bytes"]:
7568 return value.remaining() > 0;
7569
7570 case ProtoBuf.TYPES["enum"]:
7571 return value !== 0;
7572
7573 case ProtoBuf.TYPES["message"]:
7574 return value !== null;
7575 default:
7576 return true;
7577 }
7578 };
7579
7580 /**
7581 * Encodes the specified field value to the specified buffer.
7582 * @param {*} value Verified field value
7583 * @param {ByteBuffer} buffer ByteBuffer to encode to
7584 * @param {!ProtoBuf.Builder.Message} message Runtime message
7585 * @return {ByteBuffer} The ByteBuffer for chaining
7586 * @throws {Error} If the field cannot be encoded
7587 * @expose
7588 */
7589 FieldPrototype.encode = function(value, buffer, message) {
7590 if (this.type === null || typeof this.type !== 'object')
7591 throw Error("[INTERNAL] Unresolved type in "+this.toString(true)+": "+this.type);
7592 if (value === null || (this.repeated && value.length == 0))
7593 return buffer; // Optional omitted
7594 try {
7595 if (this.repeated) {
7596 var i;
7597 // "Only repeated fields of primitive numeric types (types which use the varint, 32-bit, or 64-bit wire
7598 // types) can be declared 'packed'."
7599 if (this.options["packed"] && ProtoBuf.PACKABLE_WIRE_TYPES.indexOf(this.type.wireType) >= 0) {
7600 // "All of the elements of the field are packed into a single key-value pair with wire type 2
7601 // (length-delimited). Each element is encoded the same way it would be normally, except without a
7602 // tag preceding it."
7603 buffer.writeVarint32((this.id << 3) | ProtoBuf.WIRE_TYPES.LDELIM);
7604 buffer.ensureCapacity(buffer.offset += 1); // We do not know the length yet, so let's assume a varint of length 1
7605 var start = buffer.offset; // Remember where the contents begin
7606 for (i=0; i<value.length; i++)
7607 this.element.encodeValue(this.id, value[i], buffer);
7608 var len = buffer.offset-start,
7609 varintLen = ByteBuffer.calculateVarint32(len);
7610 if (varintLen > 1) { // We need to move the contents
7611 var contents = buffer.slice(start, buffer.offset);
7612 start += varintLen-1;
7613 buffer.offset = start;
7614 buffer.append(contents);
7615 }
7616 buffer.writeVarint32(len, start-varintLen);
7617 } else {
7618 // "If your message definition has repeated elements (without the [packed=true] option), the encoded
7619 // message has zero or more key-value pairs with the same tag number"
7620 for (i=0; i<value.length; i++)
7621 buffer.writeVarint32((this.id << 3) | this.type.wireType),
7622 this.element.encodeValue(this.id, value[i], buffer);
7623 }
7624 } else if (this.map) {
7625 // Write out each map entry as a submessage.
7626 value.forEach(function(val, key, m) {
7627 // Compute the length of the submessage (key, val) pair.
7628 var length =
7629 ByteBuffer.calculateVarint32((1 << 3) | this.keyType.wireType) +
7630 this.keyElement.calculateLength(1, key) +
7631 ByteBuffer.calculateVarint32((2 << 3) | this.type.wireType) +
7632 this.element.calculateLength(2, val);
7633
7634 // Submessage with wire type of length-delimited.
7635 buffer.writeVarint32((this.id << 3) | ProtoBuf.WIRE_TYPES.LDELIM);
7636 buffer.writeVarint32(length);
7637
7638 // Write out the key and val.
7639 buffer.writeVarint32((1 << 3) | this.keyType.wireType);
7640 this.keyElement.encodeValue(1, key, buffer);
7641 buffer.writeVarint32((2 << 3) | this.type.wireType);
7642 this.element.encodeValue(2, val, buffer);
7643 }, this);
7644 } else {
7645 if (this.hasWirePresence(value, message)) {
7646 buffer.writeVarint32((this.id << 3) | this.type.wireType);
7647 this.element.encodeValue(this.id, value, buffer);
7648 }
7649 }
7650 } catch (e) {
7651 throw Error("Illegal value for "+this.toString(true)+": "+value+" ("+e+")");
7652 }
7653 return buffer;
7654 };
7655
7656 /**
7657 * Calculates the length of this field's value on the network level.
7658 * @param {*} value Field value
7659 * @param {!ProtoBuf.Builder.Message} message Runtime message
7660 * @returns {number} Byte length
7661 * @expose
7662 */
7663 FieldPrototype.calculate = function(value, message) {
7664 value = this.verifyValue(value); // May throw
7665 if (this.type === null || typeof this.type !== 'object')
7666 throw Error("[INTERNAL] Unresolved type in "+this.toString(true)+": "+this.type);
7667 if (value === null || (this.repeated && value.length == 0))
7668 return 0; // Optional omitted
7669 var n = 0;
7670 try {
7671 if (this.repeated) {
7672 var i, ni;
7673 if (this.options["packed"] && ProtoBuf.PACKABLE_WIRE_TYPES.indexOf(this.type.wireType) >= 0) {
7674 n += ByteBuffer.calculateVarint32((this.id << 3) | ProtoBuf.WIRE_TYPES.LDELIM);
7675 ni = 0;
7676 for (i=0; i<value.length; i++)
7677 ni += this.element.calculateLength(this.id, value[i]);
7678 n += ByteBuffer.calculateVarint32(ni);
7679 n += ni;
7680 } else {
7681 for (i=0; i<value.length; i++)
7682 n += ByteBuffer.calculateVarint32((this.id << 3) | this.type.wireType),
7683 n += this.element.calculateLength(this.id, value[i]);
7684 }
7685 } else if (this.map) {
7686 // Each map entry becomes a submessage.
7687 value.forEach(function(val, key, m) {
7688 // Compute the length of the submessage (key, val) pair.
7689 var length =
7690 ByteBuffer.calculateVarint32((1 << 3) | this.keyType.wireType) +
7691 this.keyElement.calculateLength(1, key) +
7692 ByteBuffer.calculateVarint32((2 << 3) | this.type.wireType) +
7693 this.element.calculateLength(2, val);
7694
7695 n += ByteBuffer.calculateVarint32((this.id << 3) | ProtoBuf.WIRE_TYPES.LDELIM);
7696 n += ByteBuffer.calculateVarint32(length);
7697 n += length;
7698 }, this);
7699 } else {
7700 if (this.hasWirePresence(value, message)) {
7701 n += ByteBuffer.calculateVarint32((this.id << 3) | this.type.wireType);
7702 n += this.element.calculateLength(this.id, value);
7703 }
7704 }
7705 } catch (e) {
7706 throw Error("Illegal value for "+this.toString(true)+": "+value+" ("+e+")");
7707 }
7708 return n;
7709 };
7710
7711 /**
7712 * Decode the field value from the specified buffer.
7713 * @param {number} wireType Leading wire type
7714 * @param {ByteBuffer} buffer ByteBuffer to decode from
7715 * @param {boolean=} skipRepeated Whether to skip the repeated check or not. Defaults to false.
7716 * @return {*} Decoded value: array for packed repeated fields, [key, value] for
7717 * map fields, or an individual value otherwise.
7718 * @throws {Error} If the field cannot be decoded
7719 * @expose
7720 */
7721 FieldPrototype.decode = function(wireType, buffer, skipRepeated) {
7722 var value, nBytes;
7723
7724 // We expect wireType to match the underlying type's wireType unless we see
7725 // a packed repeated field, or unless this is a map field.
7726 var wireTypeOK =
7727 (!this.map && wireType == this.type.wireType) ||
7728 (!skipRepeated && this.repeated && this.options["packed"] &&
7729 wireType == ProtoBuf.WIRE_TYPES.LDELIM) ||
7730 (this.map && wireType == ProtoBuf.WIRE_TYPES.LDELIM);
7731 if (!wireTypeOK)
7732 throw Error("Illegal wire type for field "+this.toString(true)+": "+wireType+" ("+this.type.wireType+" expected)");
7733
7734 // Handle packed repeated fields.
7735 if (wireType == ProtoBuf.WIRE_TYPES.LDELIM && this.repeated && this.options["packed"] && ProtoBuf.PACKABLE_WIRE_TYPES.indexOf(this.type.wireType) >= 0) {
7736 if (!skipRepeated) {
7737 nBytes = buffer.readVarint32();
7738 nBytes = buffer.offset + nBytes; // Limit
7739 var values = [];
7740 while (buffer.offset < nBytes)
7741 values.push(this.decode(this.type.wireType, buffer, true));
7742 return values;
7743 }
7744 // Read the next value otherwise...
7745 }
7746
7747 // Handle maps.
7748 if (this.map) {
7749 // Read one (key, value) submessage, and return [key, value]
7750 var key = Element.defaultFieldValue(this.keyType);
7751 value = Element.defaultFieldValue(this.type);
7752
7753 // Read the length
7754 nBytes = buffer.readVarint32();
7755 if (buffer.remaining() < nBytes)
7756 throw Error("Illegal number of bytes for "+this.toString(true)+": "+nBytes+" required but got only "+buffer.remaining());
7757
7758 // Get a sub-buffer of this key/value submessage
7759 var msgbuf = buffer.clone();
7760 msgbuf.limit = msgbuf.offset + nBytes;
7761 buffer.offset += nBytes;
7762
7763 while (msgbuf.remaining() > 0) {
7764 var tag = msgbuf.readVarint32();
7765 wireType = tag & 0x07;
7766 var id = tag >>> 3;
7767 if (id === 1) {
7768 key = this.keyElement.decode(msgbuf, wireType, id);
7769 } else if (id === 2) {
7770 value = this.element.decode(msgbuf, wireType, id);
7771 } else {
7772 throw Error("Unexpected tag in map field key/value submessage");
7773 }
7774 }
7775
7776 return [key, value];
7777 }
7778
7779 // Handle singular and non-packed repeated field values.
7780 return this.element.decode(buffer, wireType, this.id);
7781 };
7782
7783 /**
7784 * @alias ProtoBuf.Reflect.Message.Field
7785 * @expose
7786 */
7787 Reflect.Message.Field = Field;
7788
7789 /**
7790 * Constructs a new Message ExtensionField.
7791 * @exports ProtoBuf.Reflect.Message.ExtensionField
7792 * @param {!ProtoBuf.Builder} builder Builder reference
7793 * @param {!ProtoBuf.Reflect.Message} message Message reference
7794 * @param {string} rule Rule, one of requried, optional, repeated
7795 * @param {string} type Data type, e.g. int32
7796 * @param {string} name Field name
7797 * @param {number} id Unique field id
7798 * @param {!Object.<string,*>=} options Options
7799 * @constructor
7800 * @extends ProtoBuf.Reflect.Message.Field
7801 */
7802 var ExtensionField = function(builder, message, rule, type, name, id, options) {
7803 Field.call(this, builder, message, rule, /* keytype = */ null, type, name, id, options);
7804
7805 /**
7806 * Extension reference.
7807 * @type {!ProtoBuf.Reflect.Extension}
7808 * @expose
7809 */
7810 this.extension;
7811 };
7812
7813 // Extends Field
7814 ExtensionField.prototype = Object.create(Field.prototype);
7815
7816 /**
7817 * @alias ProtoBuf.Reflect.Message.ExtensionField
7818 * @expose
7819 */
7820 Reflect.Message.ExtensionField = ExtensionField;
7821
7822 /**
7823 * Constructs a new Message OneOf.
7824 * @exports ProtoBuf.Reflect.Message.OneOf
7825 * @param {!ProtoBuf.Builder} builder Builder reference
7826 * @param {!ProtoBuf.Reflect.Message} message Message reference
7827 * @param {string} name OneOf name
7828 * @constructor
7829 * @extends ProtoBuf.Reflect.T
7830 */
7831 var OneOf = function(builder, message, name) {
7832 T.call(this, builder, message, name);
7833
7834 /**
7835 * Enclosed fields.
7836 * @type {!Array.<!ProtoBuf.Reflect.Message.Field>}
7837 * @expose
7838 */
7839 this.fields = [];
7840 };
7841
7842 /**
7843 * @alias ProtoBuf.Reflect.Message.OneOf
7844 * @expose
7845 */
7846 Reflect.Message.OneOf = OneOf;
7847
7848 /**
7849 * Constructs a new Enum.
7850 * @exports ProtoBuf.Reflect.Enum
7851 * @param {!ProtoBuf.Builder} builder Builder reference
7852 * @param {!ProtoBuf.Reflect.T} parent Parent Reflect object
7853 * @param {string} name Enum name
7854 * @param {Object.<string,*>=} options Enum options
7855 * @param {string?} syntax The syntax level (e.g., proto3)
7856 * @constructor
7857 * @extends ProtoBuf.Reflect.Namespace
7858 */
7859 var Enum = function(builder, parent, name, options, syntax) {
7860 Namespace.call(this, builder, parent, name, options, syntax);
7861
7862 /**
7863 * @override
7864 */
7865 this.className = "Enum";
7866
7867 /**
7868 * Runtime enum object.
7869 * @type {Object.<string,number>|null}
7870 * @expose
7871 */
7872 this.object = null;
7873 };
7874
7875 /**
7876 * Gets the string name of an enum value.
7877 * @param {!ProtoBuf.Builder.Enum} enm Runtime enum
7878 * @param {number} value Enum value
7879 * @returns {?string} Name or `null` if not present
7880 * @expose
7881 */
7882 Enum.getName = function(enm, value) {
7883 var keys = Object.keys(enm);
7884 for (var i=0, key; i<keys.length; ++i)
7885 if (enm[key = keys[i]] === value)
7886 return key;
7887 return null;
7888 };
7889
7890 /**
7891 * @alias ProtoBuf.Reflect.Enum.prototype
7892 * @inner
7893 */
7894 var EnumPrototype = Enum.prototype = Object.create(Namespace.prototype);
7895
7896 /**
7897 * Builds this enum and returns the runtime counterpart.
7898 * @param {boolean} rebuild Whether to rebuild or not, defaults to false
7899 * @returns {!Object.<string,number>}
7900 * @expose
7901 */
7902 EnumPrototype.build = function(rebuild) {
7903 if (this.object && !rebuild)
7904 return this.object;
7905 var enm = new ProtoBuf.Builder.Enum(),
7906 values = this.getChildren(Enum.Value);
7907 for (var i=0, k=values.length; i<k; ++i)
7908 enm[values[i]['name']] = values[i]['id'];
7909 if (Object.defineProperty)
7910 Object.defineProperty(enm, '$options', {
7911 "value": this.buildOpt(),
7912 "enumerable": false
7913 });
7914 return this.object = enm;
7915 };
7916
7917 /**
7918 * @alias ProtoBuf.Reflect.Enum
7919 * @expose
7920 */
7921 Reflect.Enum = Enum;
7922
7923 /**
7924 * Constructs a new Enum Value.
7925 * @exports ProtoBuf.Reflect.Enum.Value
7926 * @param {!ProtoBuf.Builder} builder Builder reference
7927 * @param {!ProtoBuf.Reflect.Enum} enm Enum reference
7928 * @param {string} name Field name
7929 * @param {number} id Unique field id
7930 * @constructor
7931 * @extends ProtoBuf.Reflect.T
7932 */
7933 var Value = function(builder, enm, name, id) {
7934 T.call(this, builder, enm, name);
7935
7936 /**
7937 * @override
7938 */
7939 this.className = "Enum.Value";
7940
7941 /**
7942 * Unique enum value id.
7943 * @type {number}
7944 * @expose
7945 */
7946 this.id = id;
7947 };
7948
7949 // Extends T
7950 Value.prototype = Object.create(T.prototype);
7951
7952 /**
7953 * @alias ProtoBuf.Reflect.Enum.Value
7954 * @expose
7955 */
7956 Reflect.Enum.Value = Value;
7957
7958 /**
7959 * An extension (field).
7960 * @exports ProtoBuf.Reflect.Extension
7961 * @constructor
7962 * @param {!ProtoBuf.Builder} builder Builder reference
7963 * @param {!ProtoBuf.Reflect.T} parent Parent object
7964 * @param {string} name Object name
7965 * @param {!ProtoBuf.Reflect.Message.Field} field Extension field
7966 */
7967 var Extension = function(builder, parent, name, field) {
7968 T.call(this, builder, parent, name);
7969
7970 /**
7971 * Extended message field.
7972 * @type {!ProtoBuf.Reflect.Message.Field}
7973 * @expose
7974 */
7975 this.field = field;
7976 };
7977
7978 // Extends T
7979 Extension.prototype = Object.create(T.prototype);
7980
7981 /**
7982 * @alias ProtoBuf.Reflect.Extension
7983 * @expose
7984 */
7985 Reflect.Extension = Extension;
7986
7987 /**
7988 * Constructs a new Service.
7989 * @exports ProtoBuf.Reflect.Service
7990 * @param {!ProtoBuf.Builder} builder Builder reference
7991 * @param {!ProtoBuf.Reflect.Namespace} root Root
7992 * @param {string} name Service name
7993 * @param {Object.<string,*>=} options Options
7994 * @constructor
7995 * @extends ProtoBuf.Reflect.Namespace
7996 */
7997 var Service = function(builder, root, name, options) {
7998 Namespace.call(this, builder, root, name, options);
7999
8000 /**
8001 * @override
8002 */
8003 this.className = "Service";
8004
8005 /**
8006 * Built runtime service class.
8007 * @type {?function(new:ProtoBuf.Builder.Service)}
8008 */
8009 this.clazz = null;
8010 };
8011
8012 /**
8013 * @alias ProtoBuf.Reflect.Service.prototype
8014 * @inner
8015 */
8016 var ServicePrototype = Service.prototype = Object.create(Namespace.prototype);
8017
8018 /**
8019 * Builds the service and returns the runtime counterpart, which is a fully functional class.
8020 * @see ProtoBuf.Builder.Service
8021 * @param {boolean=} rebuild Whether to rebuild or not
8022 * @return {Function} Service class
8023 * @throws {Error} If the message cannot be built
8024 * @expose
8025 */
8026 ServicePrototype.build = function(rebuild) {
8027 if (this.clazz && !rebuild)
8028 return this.clazz;
8029
8030 // Create the runtime Service class in its own scope
8031 return this.clazz = (function(ProtoBuf, T) {
8032
8033 /**
8034 * Constructs a new runtime Service.
8035 * @name ProtoBuf.Builder.Service
8036 * @param {function(string, ProtoBuf.Builder.Message, function(Error, ProtoBuf.Builder.Message=))=} rpcImpl RPC implementation receiving the method name and the message
8037 * @class Barebone of all runtime services.
8038 * @constructor
8039 * @throws {Error} If the service cannot be created
8040 */
8041 var Service = function(rpcImpl) {
8042 ProtoBuf.Builder.Service.call(this);
8043
8044 /**
8045 * Service implementation.
8046 * @name ProtoBuf.Builder.Service#rpcImpl
8047 * @type {!function(string, ProtoBuf.Builder.Message, function(Error, ProtoBuf.Builder.Message=))}
8048 * @expose
8049 */
8050 this.rpcImpl = rpcImpl || function(name, msg, callback) {
8051 // This is what a user has to implement: A function receiving the method name, the actual message to
8052 // send (type checked) and the callback that's either provided with the error as its first
8053 // argument or null and the actual response message.
8054 setTimeout(callback.bind(this, Error("Not implemented, see: https://github.com/dcodeIO/ProtoBuf.js/wiki/Services")), 0); // Must be async!
8055 };
8056 };
8057
8058 /**
8059 * @alias ProtoBuf.Builder.Service.prototype
8060 * @inner
8061 */
8062 var ServicePrototype = Service.prototype = Object.create(ProtoBuf.Builder.Service.prototype);
8063
8064 /**
8065 * Asynchronously performs an RPC call using the given RPC implementation.
8066 * @name ProtoBuf.Builder.Service.[Method]
8067 * @function
8068 * @param {!function(string, ProtoBuf.Builder.Message, function(Error, ProtoBuf.Builder.Message=))} rpcImpl RPC implementation
8069 * @param {ProtoBuf.Builder.Message} req Request
8070 * @param {function(Error, (ProtoBuf.Builder.Message|ByteBuffer|Buffer|string)=)} callback Callback receiving
8071 * the error if any and the response either as a pre-parsed message or as its raw bytes
8072 * @abstract
8073 */
8074
8075 /**
8076 * Asynchronously performs an RPC call using the instance's RPC implementation.
8077 * @name ProtoBuf.Builder.Service#[Method]
8078 * @function
8079 * @param {ProtoBuf.Builder.Message} req Request
8080 * @param {function(Error, (ProtoBuf.Builder.Message|ByteBuffer|Buffer|string)=)} callback Callback receiving
8081 * the error if any and the response either as a pre-parsed message or as its raw bytes
8082 * @abstract
8083 */
8084
8085 var rpc = T.getChildren(ProtoBuf.Reflect.Service.RPCMethod);
8086 for (var i=0; i<rpc.length; i++) {
8087 (function(method) {
8088
8089 // service#Method(message, callback)
8090 ServicePrototype[method.name] = function(req, callback) {
8091 try {
8092 try {
8093 // If given as a buffer, decode the request. Will throw a TypeError if not a valid buffer.
8094 req = method.resolvedRequestType.clazz.decode(ByteBuffer.wrap(req));
8095 } catch (err) {
8096 if (!(err instanceof TypeError))
8097 throw err;
8098 }
8099 if (req === null || typeof req !== 'object')
8100 throw Error("Illegal arguments");
8101 if (!(req instanceof method.resolvedRequestType.clazz))
8102 req = new method.resolvedRequestType.clazz(req);
8103 this.rpcImpl(method.fqn(), req, function(err, res) { // Assumes that this is properly async
8104 if (err) {
8105 callback(err);
8106 return;
8107 }
8108 // Coalesce to empty string when service response has empty content
8109 if (res === null)
8110 res = '';
8111 try { res = method.resolvedResponseType.clazz.decode(res); } catch (notABuffer) {}
8112 if (!res || !(res instanceof method.resolvedResponseType.clazz)) {
8113 callback(Error("Illegal response type received in service method "+ T.name+"#"+method.name));
8114 return;
8115 }
8116 callback(null, res);
8117 });
8118 } catch (err) {
8119 setTimeout(callback.bind(this, err), 0);
8120 }
8121 };
8122
8123 // Service.Method(rpcImpl, message, callback)
8124 Service[method.name] = function(rpcImpl, req, callback) {
8125 new Service(rpcImpl)[method.name](req, callback);
8126 };
8127
8128 if (Object.defineProperty)
8129 Object.defineProperty(Service[method.name], "$options", { "value": method.buildOpt() }),
8130 Object.defineProperty(ServicePrototype[method.name], "$options", { "value": Service[method.name]["$options"] });
8131 })(rpc[i]);
8132 }
8133
8134 if (Object.defineProperty)
8135 Object.defineProperty(Service, "$options", { "value": T.buildOpt() }),
8136 Object.defineProperty(ServicePrototype, "$options", { "value": Service["$options"] }),
8137 Object.defineProperty(Service, "$type", { "value": T }),
8138 Object.defineProperty(ServicePrototype, "$type", { "value": T });
8139
8140 return Service;
8141
8142 })(ProtoBuf, this);
8143 };
8144
8145 /**
8146 * @alias ProtoBuf.Reflect.Service
8147 * @expose
8148 */
8149 Reflect.Service = Service;
8150
8151 /**
8152 * Abstract service method.
8153 * @exports ProtoBuf.Reflect.Service.Method
8154 * @param {!ProtoBuf.Builder} builder Builder reference
8155 * @param {!ProtoBuf.Reflect.Service} svc Service
8156 * @param {string} name Method name
8157 * @param {Object.<string,*>=} options Options
8158 * @constructor
8159 * @extends ProtoBuf.Reflect.T
8160 */
8161 var Method = function(builder, svc, name, options) {
8162 T.call(this, builder, svc, name);
8163
8164 /**
8165 * @override
8166 */
8167 this.className = "Service.Method";
8168
8169 /**
8170 * Options.
8171 * @type {Object.<string, *>}
8172 * @expose
8173 */
8174 this.options = options || {};
8175 };
8176
8177 /**
8178 * @alias ProtoBuf.Reflect.Service.Method.prototype
8179 * @inner
8180 */
8181 var MethodPrototype = Method.prototype = Object.create(T.prototype);
8182
8183 /**
8184 * Builds the method's '$options' property.
8185 * @name ProtoBuf.Reflect.Service.Method#buildOpt
8186 * @function
8187 * @return {Object.<string,*>}
8188 */
8189 MethodPrototype.buildOpt = NamespacePrototype.buildOpt;
8190
8191 /**
8192 * @alias ProtoBuf.Reflect.Service.Method
8193 * @expose
8194 */
8195 Reflect.Service.Method = Method;
8196
8197 /**
8198 * RPC service method.
8199 * @exports ProtoBuf.Reflect.Service.RPCMethod
8200 * @param {!ProtoBuf.Builder} builder Builder reference
8201 * @param {!ProtoBuf.Reflect.Service} svc Service
8202 * @param {string} name Method name
8203 * @param {string} request Request message name
8204 * @param {string} response Response message name
8205 * @param {boolean} request_stream Whether requests are streamed
8206 * @param {boolean} response_stream Whether responses are streamed
8207 * @param {Object.<string,*>=} options Options
8208 * @constructor
8209 * @extends ProtoBuf.Reflect.Service.Method
8210 */
8211 var RPCMethod = function(builder, svc, name, request, response, request_stream, response_stream, options) {
8212 Method.call(this, builder, svc, name, options);
8213
8214 /**
8215 * @override
8216 */
8217 this.className = "Service.RPCMethod";
8218
8219 /**
8220 * Request message name.
8221 * @type {string}
8222 * @expose
8223 */
8224 this.requestName = request;
8225
8226 /**
8227 * Response message name.
8228 * @type {string}
8229 * @expose
8230 */
8231 this.responseName = response;
8232
8233 /**
8234 * Whether requests are streamed
8235 * @type {bool}
8236 * @expose
8237 */
8238 this.requestStream = request_stream;
8239
8240 /**
8241 * Whether responses are streamed
8242 * @type {bool}
8243 * @expose
8244 */
8245 this.responseStream = response_stream;
8246
8247 /**
8248 * Resolved request message type.
8249 * @type {ProtoBuf.Reflect.Message}
8250 * @expose
8251 */
8252 this.resolvedRequestType = null;
8253
8254 /**
8255 * Resolved response message type.
8256 * @type {ProtoBuf.Reflect.Message}
8257 * @expose
8258 */
8259 this.resolvedResponseType = null;
8260 };
8261
8262 // Extends Method
8263 RPCMethod.prototype = Object.create(Method.prototype);
8264
8265 /**
8266 * @alias ProtoBuf.Reflect.Service.RPCMethod
8267 * @expose
8268 */
8269 Reflect.Service.RPCMethod = RPCMethod;
8270
8271 return Reflect;
8272
8273 })(ProtoBuf);
8274
8275 /**
8276 * @alias ProtoBuf.Builder
8277 * @expose
8278 */
8279 ProtoBuf.Builder = (function(ProtoBuf, Lang, Reflect) {
8280
8281 /**
8282 * Constructs a new Builder.
8283 * @exports ProtoBuf.Builder
8284 * @class Provides the functionality to build protocol messages.
8285 * @param {Object.<string,*>=} options Options
8286 * @constructor
8287 */
8288 var Builder = function(options) {
8289
8290 /**
8291 * Namespace.
8292 * @type {ProtoBuf.Reflect.Namespace}
8293 * @expose
8294 */
8295 this.ns = new Reflect.Namespace(this, null, ""); // Global namespace
8296
8297 /**
8298 * Namespace pointer.
8299 * @type {ProtoBuf.Reflect.T}
8300 * @expose
8301 */
8302 this.ptr = this.ns;
8303
8304 /**
8305 * Resolved flag.
8306 * @type {boolean}
8307 * @expose
8308 */
8309 this.resolved = false;
8310
8311 /**
8312 * The current building result.
8313 * @type {Object.<string,ProtoBuf.Builder.Message|Object>|null}
8314 * @expose
8315 */
8316 this.result = null;
8317
8318 /**
8319 * Imported files.
8320 * @type {Array.<string>}
8321 * @expose
8322 */
8323 this.files = {};
8324
8325 /**
8326 * Import root override.
8327 * @type {?string}
8328 * @expose
8329 */
8330 this.importRoot = null;
8331
8332 /**
8333 * Options.
8334 * @type {!Object.<string, *>}
8335 * @expose
8336 */
8337 this.options = options || {};
8338 };
8339
8340 /**
8341 * @alias ProtoBuf.Builder.prototype
8342 * @inner
8343 */
8344 var BuilderPrototype = Builder.prototype;
8345
8346 // ----- Definition tests -----
8347
8348 /**
8349 * Tests if a definition most likely describes a message.
8350 * @param {!Object} def
8351 * @returns {boolean}
8352 * @expose
8353 */
8354 Builder.isMessage = function(def) {
8355 // Messages require a string name
8356 if (typeof def["name"] !== 'string')
8357 return false;
8358 // Messages do not contain values (enum) or rpc methods (service)
8359 if (typeof def["values"] !== 'undefined' || typeof def["rpc"] !== 'undefined')
8360 return false;
8361 return true;
8362 };
8363
8364 /**
8365 * Tests if a definition most likely describes a message field.
8366 * @param {!Object} def
8367 * @returns {boolean}
8368 * @expose
8369 */
8370 Builder.isMessageField = function(def) {
8371 // Message fields require a string rule, name and type and an id
8372 if (typeof def["rule"] !== 'string' || typeof def["name"] !== 'string' || typeof def["type"] !== 'string' || typeof def["id"] === 'undefined')
8373 return false;
8374 return true;
8375 };
8376
8377 /**
8378 * Tests if a definition most likely describes an enum.
8379 * @param {!Object} def
8380 * @returns {boolean}
8381 * @expose
8382 */
8383 Builder.isEnum = function(def) {
8384 // Enums require a string name
8385 if (typeof def["name"] !== 'string')
8386 return false;
8387 // Enums require at least one value
8388 if (typeof def["values"] === 'undefined' || !Array.isArray(def["values"]) || def["values"].length === 0)
8389 return false;
8390 return true;
8391 };
8392
8393 /**
8394 * Tests if a definition most likely describes a service.
8395 * @param {!Object} def
8396 * @returns {boolean}
8397 * @expose
8398 */
8399 Builder.isService = function(def) {
8400 // Services require a string name and an rpc object
8401 if (typeof def["name"] !== 'string' || typeof def["rpc"] !== 'object' || !def["rpc"])
8402 return false;
8403 return true;
8404 };
8405
8406 /**
8407 * Tests if a definition most likely describes an extended message
8408 * @param {!Object} def
8409 * @returns {boolean}
8410 * @expose
8411 */
8412 Builder.isExtend = function(def) {
8413 // Extends rquire a string ref
8414 if (typeof def["ref"] !== 'string')
8415 return false;
8416 return true;
8417 };
8418
8419 // ----- Building -----
8420
8421 /**
8422 * Resets the pointer to the root namespace.
8423 * @returns {!ProtoBuf.Builder} this
8424 * @expose
8425 */
8426 BuilderPrototype.reset = function() {
8427 this.ptr = this.ns;
8428 return this;
8429 };
8430
8431 /**
8432 * Defines a namespace on top of the current pointer position and places the pointer on it.
8433 * @param {string} namespace
8434 * @return {!ProtoBuf.Builder} this
8435 * @expose
8436 */
8437 BuilderPrototype.define = function(namespace) {
8438 if (typeof namespace !== 'string' || !Lang.TYPEREF.test(namespace))
8439 throw Error("illegal namespace: "+namespace);
8440 namespace.split(".").forEach(function(part) {
8441 var ns = this.ptr.getChild(part);
8442 if (ns === null) // Keep existing
8443 this.ptr.addChild(ns = new Reflect.Namespace(this, this.ptr, part));
8444 this.ptr = ns;
8445 }, this);
8446 return this;
8447 };
8448
8449 /**
8450 * Creates the specified definitions at the current pointer position.
8451 * @param {!Array.<!Object>} defs Messages, enums or services to create
8452 * @returns {!ProtoBuf.Builder} this
8453 * @throws {Error} If a message definition is invalid
8454 * @expose
8455 */
8456 BuilderPrototype.create = function(defs) {
8457 if (!defs)
8458 return this; // Nothing to create
8459 if (!Array.isArray(defs))
8460 defs = [defs];
8461 else {
8462 if (defs.length === 0)
8463 return this;
8464 defs = defs.slice();
8465 }
8466
8467 // It's quite hard to keep track of scopes and memory here, so let's do this iteratively.
8468 var stack = [defs];
8469 while (stack.length > 0) {
8470 defs = stack.pop();
8471
8472 if (!Array.isArray(defs)) // Stack always contains entire namespaces
8473 throw Error("not a valid namespace: "+JSON.stringify(defs));
8474
8475 while (defs.length > 0) {
8476 var def = defs.shift(); // Namespaces always contain an array of messages, enums and services
8477
8478 if (Builder.isMessage(def)) {
8479 var obj = new Reflect.Message(this, this.ptr, def["name"], def["options"], def["isGroup"], def["syntax"]);
8480
8481 // Create OneOfs
8482 var oneofs = {};
8483 if (def["oneofs"])
8484 Object.keys(def["oneofs"]).forEach(function(name) {
8485 obj.addChild(oneofs[name] = new Reflect.Message.OneOf(this, obj, name));
8486 }, this);
8487
8488 // Create fields
8489 if (def["fields"])
8490 def["fields"].forEach(function(fld) {
8491 if (obj.getChild(fld["id"]|0) !== null)
8492 throw Error("duplicate or invalid field id in "+obj.name+": "+fld['id']);
8493 if (fld["options"] && typeof fld["options"] !== 'object')
8494 throw Error("illegal field options in "+obj.name+"#"+fld["name"]);
8495 var oneof = null;
8496 if (typeof fld["oneof"] === 'string' && !(oneof = oneofs[fld["oneof"]]))
8497 throw Error("illegal oneof in "+obj.name+"#"+fld["name"]+": "+fld["oneof"]);
8498 fld = new Reflect.Message.Field(this, obj, fld["rule"], fld["keytype"], fld["type"], fld["name"], fld["id"], fld["options"], oneof, def["syntax"]);
8499 if (oneof)
8500 oneof.fields.push(fld);
8501 obj.addChild(fld);
8502 }, this);
8503
8504 // Push children to stack
8505 var subObj = [];
8506 if (def["enums"])
8507 def["enums"].forEach(function(enm) {
8508 subObj.push(enm);
8509 });
8510 if (def["messages"])
8511 def["messages"].forEach(function(msg) {
8512 subObj.push(msg);
8513 });
8514 if (def["services"])
8515 def["services"].forEach(function(svc) {
8516 subObj.push(svc);
8517 });
8518
8519 // Set extension ranges
8520 if (def["extensions"]) {
8521 if (typeof def["extensions"][0] === 'number') // pre 5.0.1
8522 obj.extensions = [ def["extensions"] ];
8523 else
8524 obj.extensions = def["extensions"];
8525 }
8526
8527 // Create on top of current namespace
8528 this.ptr.addChild(obj);
8529 if (subObj.length > 0) {
8530 stack.push(defs); // Push the current level back
8531 defs = subObj; // Continue processing sub level
8532 subObj = null;
8533 this.ptr = obj; // And move the pointer to this namespace
8534 obj = null;
8535 continue;
8536 }
8537 subObj = null;
8538
8539 } else if (Builder.isEnum(def)) {
8540
8541 obj = new Reflect.Enum(this, this.ptr, def["name"], def["options"], def["syntax"]);
8542 def["values"].forEach(function(val) {
8543 obj.addChild(new Reflect.Enum.Value(this, obj, val["name"], val["id"]));
8544 }, this);
8545 this.ptr.addChild(obj);
8546
8547 } else if (Builder.isService(def)) {
8548
8549 obj = new Reflect.Service(this, this.ptr, def["name"], def["options"]);
8550 Object.keys(def["rpc"]).forEach(function(name) {
8551 var mtd = def["rpc"][name];
8552 obj.addChild(new Reflect.Service.RPCMethod(this, obj, name, mtd["request"], mtd["response"], !!mtd["request_stream"], !!mtd["response_stream"], mtd["options"]));
8553 }, this);
8554 this.ptr.addChild(obj);
8555
8556 } else if (Builder.isExtend(def)) {
8557
8558 obj = this.ptr.resolve(def["ref"], true);
8559 if (obj) {
8560 def["fields"].forEach(function(fld) {
8561 if (obj.getChild(fld['id']|0) !== null)
8562 throw Error("duplicate extended field id in "+obj.name+": "+fld['id']);
8563 // Check if field id is allowed to be extended
8564 if (obj.extensions) {
8565 var valid = false;
8566 obj.extensions.forEach(function(range) {
8567 if (fld["id"] >= range[0] && fld["id"] <= range[1])
8568 valid = true;
8569 });
8570 if (!valid)
8571 throw Error("illegal extended field id in "+obj.name+": "+fld['id']+" (not within valid ranges)");
8572 }
8573 // Convert extension field names to camel case notation if the override is set
8574 var name = fld["name"];
8575 if (this.options['convertFieldsToCamelCase'])
8576 name = ProtoBuf.Util.toCamelCase(name);
8577 // see #161: Extensions use their fully qualified name as their runtime key and...
8578 var field = new Reflect.Message.ExtensionField(this, obj, fld["rule"], fld["type"], this.ptr.fqn()+'.'+name, fld["id"], fld["options"]);
8579 // ...are added on top of the current namespace as an extension which is used for
8580 // resolving their type later on (the extension always keeps the original name to
8581 // prevent naming collisions)
8582 var ext = new Reflect.Extension(this, this.ptr, fld["name"], field);
8583 field.extension = ext;
8584 this.ptr.addChild(ext);
8585 obj.addChild(field);
8586 }, this);
8587
8588 } else if (!/\.?google\.protobuf\./.test(def["ref"])) // Silently skip internal extensions
8589 throw Error("extended message "+def["ref"]+" is not defined");
8590
8591 } else
8592 throw Error("not a valid definition: "+JSON.stringify(def));
8593
8594 def = null;
8595 obj = null;
8596 }
8597 // Break goes here
8598 defs = null;
8599 this.ptr = this.ptr.parent; // Namespace done, continue at parent
8600 }
8601 this.resolved = false; // Require re-resolve
8602 this.result = null; // Require re-build
8603 return this;
8604 };
8605
8606 /**
8607 * Propagates syntax to all children.
8608 * @param {!Object} parent
8609 * @inner
8610 */
8611 function propagateSyntax(parent) {
8612 if (parent['messages']) {
8613 parent['messages'].forEach(function(child) {
8614 child["syntax"] = parent["syntax"];
8615 propagateSyntax(child);
8616 });
8617 }
8618 if (parent['enums']) {
8619 parent['enums'].forEach(function(child) {
8620 child["syntax"] = parent["syntax"];
8621 });
8622 }
8623 }
8624
8625 /**
8626 * Imports another definition into this builder.
8627 * @param {Object.<string,*>} json Parsed import
8628 * @param {(string|{root: string, file: string})=} filename Imported file name
8629 * @returns {!ProtoBuf.Builder} this
8630 * @throws {Error} If the definition or file cannot be imported
8631 * @expose
8632 */
8633 BuilderPrototype["import"] = function(json, filename) {
8634 var delim = '/';
8635
8636 // Make sure to skip duplicate imports
8637
8638 if (typeof filename === 'string') {
8639
8640 if (ProtoBuf.Util.IS_NODE)
8641 filename = require$$2['resolve'](filename);
8642 if (this.files[filename] === true)
8643 return this.reset();
8644 this.files[filename] = true;
8645
8646 } else if (typeof filename === 'object') { // Object with root, file.
8647
8648 var root = filename.root;
8649 if (ProtoBuf.Util.IS_NODE)
8650 root = require$$2['resolve'](root);
8651 if (root.indexOf("\\") >= 0 || filename.file.indexOf("\\") >= 0)
8652 delim = '\\';
8653 var fname;
8654 if (ProtoBuf.Util.IS_NODE)
8655 fname = require$$2['join'](root, filename.file);
8656 else
8657 fname = root + delim + filename.file;
8658 if (this.files[fname] === true)
8659 return this.reset();
8660 this.files[fname] = true;
8661 }
8662
8663 // Import imports
8664
8665 if (json['imports'] && json['imports'].length > 0) {
8666 var importRoot,
8667 resetRoot = false;
8668
8669 if (typeof filename === 'object') { // If an import root is specified, override
8670
8671 this.importRoot = filename["root"]; resetRoot = true; // ... and reset afterwards
8672 importRoot = this.importRoot;
8673 filename = filename["file"];
8674 if (importRoot.indexOf("\\") >= 0 || filename.indexOf("\\") >= 0)
8675 delim = '\\';
8676
8677 } else if (typeof filename === 'string') {
8678
8679 if (this.importRoot) // If import root is overridden, use it
8680 importRoot = this.importRoot;
8681 else { // Otherwise compute from filename
8682 if (filename.indexOf("/") >= 0) { // Unix
8683 importRoot = filename.replace(/\/[^\/]*$/, "");
8684 if (/* /file.proto */ importRoot === "")
8685 importRoot = "/";
8686 } else if (filename.indexOf("\\") >= 0) { // Windows
8687 importRoot = filename.replace(/\\[^\\]*$/, "");
8688 delim = '\\';
8689 } else
8690 importRoot = ".";
8691 }
8692
8693 } else
8694 importRoot = null;
8695
8696 for (var i=0; i<json['imports'].length; i++) {
8697 if (typeof json['imports'][i] === 'string') { // Import file
8698 if (!importRoot)
8699 throw Error("cannot determine import root");
8700 var importFilename = json['imports'][i];
8701 if (importFilename === "google/protobuf/descriptor.proto")
8702 continue; // Not needed and therefore not used
8703 if (ProtoBuf.Util.IS_NODE)
8704 importFilename = require$$2['join'](importRoot, importFilename);
8705 else
8706 importFilename = importRoot + delim + importFilename;
8707 if (this.files[importFilename] === true)
8708 continue; // Already imported
8709 if (/\.proto$/i.test(importFilename) && !ProtoBuf.DotProto) // If this is a light build
8710 importFilename = importFilename.replace(/\.proto$/, ".json"); // always load the JSON file
8711 var contents = ProtoBuf.Util.fetch(importFilename);
8712 if (contents === null)
8713 throw Error("failed to import '"+importFilename+"' in '"+filename+"': file not found");
8714 if (/\.json$/i.test(importFilename)) // Always possible
8715 this["import"](JSON.parse(contents+""), importFilename); // May throw
8716 else
8717 this["import"](ProtoBuf.DotProto.Parser.parse(contents), importFilename); // May throw
8718 } else // Import structure
8719 if (!filename)
8720 this["import"](json['imports'][i]);
8721 else if (/\.(\w+)$/.test(filename)) // With extension: Append _importN to the name portion to make it unique
8722 this["import"](json['imports'][i], filename.replace(/^(.+)\.(\w+)$/, function($0, $1, $2) { return $1+"_import"+i+"."+$2; }));
8723 else // Without extension: Append _importN to make it unique
8724 this["import"](json['imports'][i], filename+"_import"+i);
8725 }
8726 if (resetRoot) // Reset import root override when all imports are done
8727 this.importRoot = null;
8728 }
8729
8730 // Import structures
8731
8732 if (json['package'])
8733 this.define(json['package']);
8734 if (json['syntax'])
8735 propagateSyntax(json);
8736 var base = this.ptr;
8737 if (json['options'])
8738 Object.keys(json['options']).forEach(function(key) {
8739 base.options[key] = json['options'][key];
8740 });
8741 if (json['messages'])
8742 this.create(json['messages']),
8743 this.ptr = base;
8744 if (json['enums'])
8745 this.create(json['enums']),
8746 this.ptr = base;
8747 if (json['services'])
8748 this.create(json['services']),
8749 this.ptr = base;
8750 if (json['extends'])
8751 this.create(json['extends']);
8752
8753 return this.reset();
8754 };
8755
8756 /**
8757 * Resolves all namespace objects.
8758 * @throws {Error} If a type cannot be resolved
8759 * @returns {!ProtoBuf.Builder} this
8760 * @expose
8761 */
8762 BuilderPrototype.resolveAll = function() {
8763 // Resolve all reflected objects
8764 var res;
8765 if (this.ptr == null || typeof this.ptr.type === 'object')
8766 return this; // Done (already resolved)
8767
8768 if (this.ptr instanceof Reflect.Namespace) { // Resolve children
8769
8770 this.ptr.children.forEach(function(child) {
8771 this.ptr = child;
8772 this.resolveAll();
8773 }, this);
8774
8775 } else if (this.ptr instanceof Reflect.Message.Field) { // Resolve type
8776
8777 if (!Lang.TYPE.test(this.ptr.type)) {
8778 if (!Lang.TYPEREF.test(this.ptr.type))
8779 throw Error("illegal type reference in "+this.ptr.toString(true)+": "+this.ptr.type);
8780 res = (this.ptr instanceof Reflect.Message.ExtensionField ? this.ptr.extension.parent : this.ptr.parent).resolve(this.ptr.type, true);
8781 if (!res)
8782 throw Error("unresolvable type reference in "+this.ptr.toString(true)+": "+this.ptr.type);
8783 this.ptr.resolvedType = res;
8784 if (res instanceof Reflect.Enum) {
8785 this.ptr.type = ProtoBuf.TYPES["enum"];
8786 if (this.ptr.syntax === 'proto3' && res.syntax !== 'proto3')
8787 throw Error("proto3 message cannot reference proto2 enum");
8788 }
8789 else if (res instanceof Reflect.Message)
8790 this.ptr.type = res.isGroup ? ProtoBuf.TYPES["group"] : ProtoBuf.TYPES["message"];
8791 else
8792 throw Error("illegal type reference in "+this.ptr.toString(true)+": "+this.ptr.type);
8793 } else
8794 this.ptr.type = ProtoBuf.TYPES[this.ptr.type];
8795
8796 // If it's a map field, also resolve the key type. The key type can be only a numeric, string, or bool type
8797 // (i.e., no enums or messages), so we don't need to resolve against the current namespace.
8798 if (this.ptr.map) {
8799 if (!Lang.TYPE.test(this.ptr.keyType))
8800 throw Error("illegal key type for map field in "+this.ptr.toString(true)+": "+this.ptr.keyType);
8801 this.ptr.keyType = ProtoBuf.TYPES[this.ptr.keyType];
8802 }
8803
8804 // If it's a repeated and packable field then proto3 mandates it should be packed by
8805 // default
8806 if (
8807 this.ptr.syntax === 'proto3' &&
8808 this.ptr.repeated && this.ptr.options.packed === undefined &&
8809 ProtoBuf.PACKABLE_WIRE_TYPES.indexOf(this.ptr.type.wireType) !== -1
8810 ) {
8811 this.ptr.options.packed = true;
8812 }
8813
8814 } else if (this.ptr instanceof ProtoBuf.Reflect.Service.Method) {
8815
8816 if (this.ptr instanceof ProtoBuf.Reflect.Service.RPCMethod) {
8817 res = this.ptr.parent.resolve(this.ptr.requestName, true);
8818 if (!res || !(res instanceof ProtoBuf.Reflect.Message))
8819 throw Error("Illegal type reference in "+this.ptr.toString(true)+": "+this.ptr.requestName);
8820 this.ptr.resolvedRequestType = res;
8821 res = this.ptr.parent.resolve(this.ptr.responseName, true);
8822 if (!res || !(res instanceof ProtoBuf.Reflect.Message))
8823 throw Error("Illegal type reference in "+this.ptr.toString(true)+": "+this.ptr.responseName);
8824 this.ptr.resolvedResponseType = res;
8825 } else // Should not happen as nothing else is implemented
8826 throw Error("illegal service type in "+this.ptr.toString(true));
8827
8828 } else if (
8829 !(this.ptr instanceof ProtoBuf.Reflect.Message.OneOf) && // Not built
8830 !(this.ptr instanceof ProtoBuf.Reflect.Extension) && // Not built
8831 !(this.ptr instanceof ProtoBuf.Reflect.Enum.Value) // Built in enum
8832 )
8833 throw Error("illegal object in namespace: "+typeof(this.ptr)+": "+this.ptr);
8834
8835 return this.reset();
8836 };
8837
8838 /**
8839 * Builds the protocol. This will first try to resolve all definitions and, if this has been successful,
8840 * return the built package.
8841 * @param {(string|Array.<string>)=} path Specifies what to return. If omitted, the entire namespace will be returned.
8842 * @returns {!ProtoBuf.Builder.Message|!Object.<string,*>}
8843 * @throws {Error} If a type could not be resolved
8844 * @expose
8845 */
8846 BuilderPrototype.build = function(path) {
8847 this.reset();
8848 if (!this.resolved)
8849 this.resolveAll(),
8850 this.resolved = true,
8851 this.result = null; // Require re-build
8852 if (this.result === null) // (Re-)Build
8853 this.result = this.ns.build();
8854 if (!path)
8855 return this.result;
8856 var part = typeof path === 'string' ? path.split(".") : path,
8857 ptr = this.result; // Build namespace pointer (no hasChild etc.)
8858 for (var i=0; i<part.length; i++)
8859 if (ptr[part[i]])
8860 ptr = ptr[part[i]];
8861 else {
8862 ptr = null;
8863 break;
8864 }
8865 return ptr;
8866 };
8867
8868 /**
8869 * Similar to {@link ProtoBuf.Builder#build}, but looks up the internal reflection descriptor.
8870 * @param {string=} path Specifies what to return. If omitted, the entire namespace wiil be returned.
8871 * @param {boolean=} excludeNonNamespace Excludes non-namespace types like fields, defaults to `false`
8872 * @returns {?ProtoBuf.Reflect.T} Reflection descriptor or `null` if not found
8873 */
8874 BuilderPrototype.lookup = function(path, excludeNonNamespace) {
8875 return path ? this.ns.resolve(path, excludeNonNamespace) : this.ns;
8876 };
8877
8878 /**
8879 * Returns a string representation of this object.
8880 * @return {string} String representation as of "Builder"
8881 * @expose
8882 */
8883 BuilderPrototype.toString = function() {
8884 return "Builder";
8885 };
8886
8887 // ----- Base classes -----
8888 // Exist for the sole purpose of being able to "... instanceof ProtoBuf.Builder.Message" etc.
8889
8890 /**
8891 * @alias ProtoBuf.Builder.Message
8892 */
8893 Builder.Message = function() {};
8894
8895 /**
8896 * @alias ProtoBuf.Builder.Enum
8897 */
8898 Builder.Enum = function() {};
8899
8900 /**
8901 * @alias ProtoBuf.Builder.Message
8902 */
8903 Builder.Service = function() {};
8904
8905 return Builder;
8906
8907 })(ProtoBuf, ProtoBuf.Lang, ProtoBuf.Reflect);
8908
8909 /**
8910 * @alias ProtoBuf.Map
8911 * @expose
8912 */
8913 ProtoBuf.Map = (function(ProtoBuf, Reflect) {
8914
8915 /**
8916 * Constructs a new Map. A Map is a container that is used to implement map
8917 * fields on message objects. It closely follows the ES6 Map API; however,
8918 * it is distinct because we do not want to depend on external polyfills or
8919 * on ES6 itself.
8920 *
8921 * @exports ProtoBuf.Map
8922 * @param {!ProtoBuf.Reflect.Field} field Map field
8923 * @param {Object.<string,*>=} contents Initial contents
8924 * @constructor
8925 */
8926 var Map = function(field, contents) {
8927 if (!field.map)
8928 throw Error("field is not a map");
8929
8930 /**
8931 * The field corresponding to this map.
8932 * @type {!ProtoBuf.Reflect.Field}
8933 */
8934 this.field = field;
8935
8936 /**
8937 * Element instance corresponding to key type.
8938 * @type {!ProtoBuf.Reflect.Element}
8939 */
8940 this.keyElem = new Reflect.Element(field.keyType, null, true, field.syntax);
8941
8942 /**
8943 * Element instance corresponding to value type.
8944 * @type {!ProtoBuf.Reflect.Element}
8945 */
8946 this.valueElem = new Reflect.Element(field.type, field.resolvedType, false, field.syntax);
8947
8948 /**
8949 * Internal map: stores mapping of (string form of key) -> (key, value)
8950 * pair.
8951 *
8952 * We provide map semantics for arbitrary key types, but we build on top
8953 * of an Object, which has only string keys. In order to avoid the need
8954 * to convert a string key back to its native type in many situations,
8955 * we store the native key value alongside the value. Thus, we only need
8956 * a one-way mapping from a key type to its string form that guarantees
8957 * uniqueness and equality (i.e., str(K1) === str(K2) if and only if K1
8958 * === K2).
8959 *
8960 * @type {!Object<string, {key: *, value: *}>}
8961 */
8962 this.map = {};
8963
8964 /**
8965 * Returns the number of elements in the map.
8966 */
8967 Object.defineProperty(this, "size", {
8968 get: function() { return Object.keys(this.map).length; }
8969 });
8970
8971 // Fill initial contents from a raw object.
8972 if (contents) {
8973 var keys = Object.keys(contents);
8974 for (var i = 0; i < keys.length; i++) {
8975 var key = this.keyElem.valueFromString(keys[i]);
8976 var val = this.valueElem.verifyValue(contents[keys[i]]);
8977 this.map[this.keyElem.valueToString(key)] =
8978 { key: key, value: val };
8979 }
8980 }
8981 };
8982
8983 var MapPrototype = Map.prototype;
8984
8985 /**
8986 * Helper: return an iterator over an array.
8987 * @param {!Array<*>} arr the array
8988 * @returns {!Object} an iterator
8989 * @inner
8990 */
8991 function arrayIterator(arr) {
8992 var idx = 0;
8993 return {
8994 next: function() {
8995 if (idx < arr.length)
8996 return { done: false, value: arr[idx++] };
8997 return { done: true };
8998 }
8999 }
9000 }
9001
9002 /**
9003 * Clears the map.
9004 */
9005 MapPrototype.clear = function() {
9006 this.map = {};
9007 };
9008
9009 /**
9010 * Deletes a particular key from the map.
9011 * @returns {boolean} Whether any entry with this key was deleted.
9012 */
9013 MapPrototype["delete"] = function(key) {
9014 var keyValue = this.keyElem.valueToString(this.keyElem.verifyValue(key));
9015 var hadKey = keyValue in this.map;
9016 delete this.map[keyValue];
9017 return hadKey;
9018 };
9019
9020 /**
9021 * Returns an iterator over [key, value] pairs in the map.
9022 * @returns {Object} The iterator
9023 */
9024 MapPrototype.entries = function() {
9025 var entries = [];
9026 var strKeys = Object.keys(this.map);
9027 for (var i = 0, entry; i < strKeys.length; i++)
9028 entries.push([(entry=this.map[strKeys[i]]).key, entry.value]);
9029 return arrayIterator(entries);
9030 };
9031
9032 /**
9033 * Returns an iterator over keys in the map.
9034 * @returns {Object} The iterator
9035 */
9036 MapPrototype.keys = function() {
9037 var keys = [];
9038 var strKeys = Object.keys(this.map);
9039 for (var i = 0; i < strKeys.length; i++)
9040 keys.push(this.map[strKeys[i]].key);
9041 return arrayIterator(keys);
9042 };
9043
9044 /**
9045 * Returns an iterator over values in the map.
9046 * @returns {!Object} The iterator
9047 */
9048 MapPrototype.values = function() {
9049 var values = [];
9050 var strKeys = Object.keys(this.map);
9051 for (var i = 0; i < strKeys.length; i++)
9052 values.push(this.map[strKeys[i]].value);
9053 return arrayIterator(values);
9054 };
9055
9056 /**
9057 * Iterates over entries in the map, calling a function on each.
9058 * @param {function(this:*, *, *, *)} cb The callback to invoke with value, key, and map arguments.
9059 * @param {Object=} thisArg The `this` value for the callback
9060 */
9061 MapPrototype.forEach = function(cb, thisArg) {
9062 var strKeys = Object.keys(this.map);
9063 for (var i = 0, entry; i < strKeys.length; i++)
9064 cb.call(thisArg, (entry=this.map[strKeys[i]]).value, entry.key, this);
9065 };
9066
9067 /**
9068 * Sets a key in the map to the given value.
9069 * @param {*} key The key
9070 * @param {*} value The value
9071 * @returns {!ProtoBuf.Map} The map instance
9072 */
9073 MapPrototype.set = function(key, value) {
9074 var keyValue = this.keyElem.verifyValue(key);
9075 var valValue = this.valueElem.verifyValue(value);
9076 this.map[this.keyElem.valueToString(keyValue)] =
9077 { key: keyValue, value: valValue };
9078 return this;
9079 };
9080
9081 /**
9082 * Gets the value corresponding to a key in the map.
9083 * @param {*} key The key
9084 * @returns {*|undefined} The value, or `undefined` if key not present
9085 */
9086 MapPrototype.get = function(key) {
9087 var keyValue = this.keyElem.valueToString(this.keyElem.verifyValue(key));
9088 if (!(keyValue in this.map))
9089 return undefined;
9090 return this.map[keyValue].value;
9091 };
9092
9093 /**
9094 * Determines whether the given key is present in the map.
9095 * @param {*} key The key
9096 * @returns {boolean} `true` if the key is present
9097 */
9098 MapPrototype.has = function(key) {
9099 var keyValue = this.keyElem.valueToString(this.keyElem.verifyValue(key));
9100 return (keyValue in this.map);
9101 };
9102
9103 return Map;
9104 })(ProtoBuf, ProtoBuf.Reflect);
9105
9106
9107 /**
9108 * Constructs a new empty Builder.
9109 * @param {Object.<string,*>=} options Builder options, defaults to global options set on ProtoBuf
9110 * @return {!ProtoBuf.Builder} Builder
9111 * @expose
9112 */
9113 ProtoBuf.newBuilder = function(options) {
9114 options = options || {};
9115 if (typeof options['convertFieldsToCamelCase'] === 'undefined')
9116 options['convertFieldsToCamelCase'] = ProtoBuf.convertFieldsToCamelCase;
9117 if (typeof options['populateAccessors'] === 'undefined')
9118 options['populateAccessors'] = ProtoBuf.populateAccessors;
9119 return new ProtoBuf.Builder(options);
9120 };
9121
9122 /**
9123 * Loads a .json definition and returns the Builder.
9124 * @param {!*|string} json JSON definition
9125 * @param {(ProtoBuf.Builder|string|{root: string, file: string})=} builder Builder to append to. Will create a new one if omitted.
9126 * @param {(string|{root: string, file: string})=} filename The corresponding file name if known. Must be specified for imports.
9127 * @return {ProtoBuf.Builder} Builder to create new messages
9128 * @throws {Error} If the definition cannot be parsed or built
9129 * @expose
9130 */
9131 ProtoBuf.loadJson = function(json, builder, filename) {
9132 if (typeof builder === 'string' || (builder && typeof builder["file"] === 'string' && typeof builder["root"] === 'string'))
9133 filename = builder,
9134 builder = null;
9135 if (!builder || typeof builder !== 'object')
9136 builder = ProtoBuf.newBuilder();
9137 if (typeof json === 'string')
9138 json = JSON.parse(json);
9139 builder["import"](json, filename);
9140 builder.resolveAll();
9141 return builder;
9142 };
9143
9144 /**
9145 * Loads a .json file and returns the Builder.
9146 * @param {string|!{root: string, file: string}} filename Path to json file or an object specifying 'file' with
9147 * an overridden 'root' path for all imported files.
9148 * @param {function(?Error, !ProtoBuf.Builder=)=} callback Callback that will receive `null` as the first and
9149 * the Builder as its second argument on success, otherwise the error as its first argument. If omitted, the
9150 * file will be read synchronously and this function will return the Builder.
9151 * @param {ProtoBuf.Builder=} builder Builder to append to. Will create a new one if omitted.
9152 * @return {?ProtoBuf.Builder|undefined} The Builder if synchronous (no callback specified, will be NULL if the
9153 * request has failed), else undefined
9154 * @expose
9155 */
9156 ProtoBuf.loadJsonFile = function(filename, callback, builder) {
9157 if (callback && typeof callback === 'object')
9158 builder = callback,
9159 callback = null;
9160 else if (!callback || typeof callback !== 'function')
9161 callback = null;
9162 if (callback)
9163 return ProtoBuf.Util.fetch(typeof filename === 'string' ? filename : filename["root"]+"/"+filename["file"], function(contents) {
9164 if (contents === null) {
9165 callback(Error("Failed to fetch file"));
9166 return;
9167 }
9168 try {
9169 callback(null, ProtoBuf.loadJson(JSON.parse(contents), builder, filename));
9170 } catch (e) {
9171 callback(e);
9172 }
9173 });
9174 var contents = ProtoBuf.Util.fetch(typeof filename === 'object' ? filename["root"]+"/"+filename["file"] : filename);
9175 return contents === null ? null : ProtoBuf.loadJson(JSON.parse(contents), builder, filename);
9176 };
9177
9178 return ProtoBuf;
9179 });
9180 });
9181
9182 var messageCompiled = protobufLight.newBuilder({})['import']({
9183 package: 'push_server.messages2',
9184 syntax: 'proto2',
9185 options: {
9186 objc_class_prefix: 'AVIM'
9187 },
9188 messages: [{
9189 name: 'JsonObjectMessage',
9190 syntax: 'proto2',
9191 fields: [{
9192 rule: 'required',
9193 type: 'string',
9194 name: 'data',
9195 id: 1
9196 }]
9197 }, {
9198 name: 'UnreadTuple',
9199 syntax: 'proto2',
9200 fields: [{
9201 rule: 'required',
9202 type: 'string',
9203 name: 'cid',
9204 id: 1
9205 }, {
9206 rule: 'required',
9207 type: 'int32',
9208 name: 'unread',
9209 id: 2
9210 }, {
9211 rule: 'optional',
9212 type: 'string',
9213 name: 'mid',
9214 id: 3
9215 }, {
9216 rule: 'optional',
9217 type: 'int64',
9218 name: 'timestamp',
9219 id: 4
9220 }, {
9221 rule: 'optional',
9222 type: 'string',
9223 name: 'from',
9224 id: 5
9225 }, {
9226 rule: 'optional',
9227 type: 'string',
9228 name: 'data',
9229 id: 6
9230 }, {
9231 rule: 'optional',
9232 type: 'int64',
9233 name: 'patchTimestamp',
9234 id: 7
9235 }, {
9236 rule: 'optional',
9237 type: 'bool',
9238 name: 'mentioned',
9239 id: 8
9240 }, {
9241 rule: 'optional',
9242 type: 'bytes',
9243 name: 'binaryMsg',
9244 id: 9
9245 }, {
9246 rule: 'optional',
9247 type: 'int32',
9248 name: 'convType',
9249 id: 10
9250 }]
9251 }, {
9252 name: 'LogItem',
9253 syntax: 'proto2',
9254 fields: [{
9255 rule: 'optional',
9256 type: 'string',
9257 name: 'from',
9258 id: 1
9259 }, {
9260 rule: 'optional',
9261 type: 'string',
9262 name: 'data',
9263 id: 2
9264 }, {
9265 rule: 'optional',
9266 type: 'int64',
9267 name: 'timestamp',
9268 id: 3
9269 }, {
9270 rule: 'optional',
9271 type: 'string',
9272 name: 'msgId',
9273 id: 4
9274 }, {
9275 rule: 'optional',
9276 type: 'int64',
9277 name: 'ackAt',
9278 id: 5
9279 }, {
9280 rule: 'optional',
9281 type: 'int64',
9282 name: 'readAt',
9283 id: 6
9284 }, {
9285 rule: 'optional',
9286 type: 'int64',
9287 name: 'patchTimestamp',
9288 id: 7
9289 }, {
9290 rule: 'optional',
9291 type: 'bool',
9292 name: 'mentionAll',
9293 id: 8
9294 }, {
9295 rule: 'repeated',
9296 type: 'string',
9297 name: 'mentionPids',
9298 id: 9
9299 }, {
9300 rule: 'optional',
9301 type: 'bool',
9302 name: 'bin',
9303 id: 10
9304 }, {
9305 rule: 'optional',
9306 type: 'int32',
9307 name: 'convType',
9308 id: 11
9309 }]
9310 }, {
9311 name: 'ConvMemberInfo',
9312 syntax: 'proto2',
9313 fields: [{
9314 rule: 'optional',
9315 type: 'string',
9316 name: 'pid',
9317 id: 1
9318 }, {
9319 rule: 'optional',
9320 type: 'string',
9321 name: 'role',
9322 id: 2
9323 }, {
9324 rule: 'optional',
9325 type: 'string',
9326 name: 'infoId',
9327 id: 3
9328 }]
9329 }, {
9330 name: 'DataCommand',
9331 syntax: 'proto2',
9332 fields: [{
9333 rule: 'repeated',
9334 type: 'string',
9335 name: 'ids',
9336 id: 1
9337 }, {
9338 rule: 'repeated',
9339 type: 'JsonObjectMessage',
9340 name: 'msg',
9341 id: 2
9342 }, {
9343 rule: 'optional',
9344 type: 'bool',
9345 name: 'offline',
9346 id: 3
9347 }]
9348 }, {
9349 name: 'SessionCommand',
9350 syntax: 'proto2',
9351 fields: [{
9352 rule: 'optional',
9353 type: 'int64',
9354 name: 't',
9355 id: 1
9356 }, {
9357 rule: 'optional',
9358 type: 'string',
9359 name: 'n',
9360 id: 2
9361 }, {
9362 rule: 'optional',
9363 type: 'string',
9364 name: 's',
9365 id: 3
9366 }, {
9367 rule: 'optional',
9368 type: 'string',
9369 name: 'ua',
9370 id: 4
9371 }, {
9372 rule: 'optional',
9373 type: 'bool',
9374 name: 'r',
9375 id: 5
9376 }, {
9377 rule: 'optional',
9378 type: 'string',
9379 name: 'tag',
9380 id: 6
9381 }, {
9382 rule: 'optional',
9383 type: 'string',
9384 name: 'deviceId',
9385 id: 7
9386 }, {
9387 rule: 'repeated',
9388 type: 'string',
9389 name: 'sessionPeerIds',
9390 id: 8
9391 }, {
9392 rule: 'repeated',
9393 type: 'string',
9394 name: 'onlineSessionPeerIds',
9395 id: 9
9396 }, {
9397 rule: 'optional',
9398 type: 'string',
9399 name: 'st',
9400 id: 10
9401 }, {
9402 rule: 'optional',
9403 type: 'int32',
9404 name: 'stTtl',
9405 id: 11
9406 }, {
9407 rule: 'optional',
9408 type: 'int32',
9409 name: 'code',
9410 id: 12
9411 }, {
9412 rule: 'optional',
9413 type: 'string',
9414 name: 'reason',
9415 id: 13
9416 }, {
9417 rule: 'optional',
9418 type: 'string',
9419 name: 'deviceToken',
9420 id: 14
9421 }, {
9422 rule: 'optional',
9423 type: 'bool',
9424 name: 'sp',
9425 id: 15
9426 }, {
9427 rule: 'optional',
9428 type: 'string',
9429 name: 'detail',
9430 id: 16
9431 }, {
9432 rule: 'optional',
9433 type: 'int64',
9434 name: 'lastUnreadNotifTime',
9435 id: 17
9436 }, {
9437 rule: 'optional',
9438 type: 'int64',
9439 name: 'lastPatchTime',
9440 id: 18
9441 }, {
9442 rule: 'optional',
9443 type: 'int64',
9444 name: 'configBitmap',
9445 id: 19
9446 }]
9447 }, {
9448 name: 'ErrorCommand',
9449 syntax: 'proto2',
9450 fields: [{
9451 rule: 'required',
9452 type: 'int32',
9453 name: 'code',
9454 id: 1
9455 }, {
9456 rule: 'required',
9457 type: 'string',
9458 name: 'reason',
9459 id: 2
9460 }, {
9461 rule: 'optional',
9462 type: 'int32',
9463 name: 'appCode',
9464 id: 3
9465 }, {
9466 rule: 'optional',
9467 type: 'string',
9468 name: 'detail',
9469 id: 4
9470 }, {
9471 rule: 'repeated',
9472 type: 'string',
9473 name: 'pids',
9474 id: 5
9475 }, {
9476 rule: 'optional',
9477 type: 'string',
9478 name: 'appMsg',
9479 id: 6
9480 }]
9481 }, {
9482 name: 'DirectCommand',
9483 syntax: 'proto2',
9484 fields: [{
9485 rule: 'optional',
9486 type: 'string',
9487 name: 'msg',
9488 id: 1
9489 }, {
9490 rule: 'optional',
9491 type: 'string',
9492 name: 'uid',
9493 id: 2
9494 }, {
9495 rule: 'optional',
9496 type: 'string',
9497 name: 'fromPeerId',
9498 id: 3
9499 }, {
9500 rule: 'optional',
9501 type: 'int64',
9502 name: 'timestamp',
9503 id: 4
9504 }, {
9505 rule: 'optional',
9506 type: 'bool',
9507 name: 'offline',
9508 id: 5
9509 }, {
9510 rule: 'optional',
9511 type: 'bool',
9512 name: 'hasMore',
9513 id: 6
9514 }, {
9515 rule: 'repeated',
9516 type: 'string',
9517 name: 'toPeerIds',
9518 id: 7
9519 }, {
9520 rule: 'optional',
9521 type: 'bool',
9522 name: 'r',
9523 id: 10
9524 }, {
9525 rule: 'optional',
9526 type: 'string',
9527 name: 'cid',
9528 id: 11
9529 }, {
9530 rule: 'optional',
9531 type: 'string',
9532 name: 'id',
9533 id: 12
9534 }, {
9535 rule: 'optional',
9536 type: 'bool',
9537 name: 'transient',
9538 id: 13
9539 }, {
9540 rule: 'optional',
9541 type: 'string',
9542 name: 'dt',
9543 id: 14
9544 }, {
9545 rule: 'optional',
9546 type: 'string',
9547 name: 'roomId',
9548 id: 15
9549 }, {
9550 rule: 'optional',
9551 type: 'string',
9552 name: 'pushData',
9553 id: 16
9554 }, {
9555 rule: 'optional',
9556 type: 'bool',
9557 name: 'will',
9558 id: 17
9559 }, {
9560 rule: 'optional',
9561 type: 'int64',
9562 name: 'patchTimestamp',
9563 id: 18
9564 }, {
9565 rule: 'optional',
9566 type: 'bytes',
9567 name: 'binaryMsg',
9568 id: 19
9569 }, {
9570 rule: 'repeated',
9571 type: 'string',
9572 name: 'mentionPids',
9573 id: 20
9574 }, {
9575 rule: 'optional',
9576 type: 'bool',
9577 name: 'mentionAll',
9578 id: 21
9579 }, {
9580 rule: 'optional',
9581 type: 'int32',
9582 name: 'convType',
9583 id: 22
9584 }]
9585 }, {
9586 name: 'AckCommand',
9587 syntax: 'proto2',
9588 fields: [{
9589 rule: 'optional',
9590 type: 'int32',
9591 name: 'code',
9592 id: 1
9593 }, {
9594 rule: 'optional',
9595 type: 'string',
9596 name: 'reason',
9597 id: 2
9598 }, {
9599 rule: 'optional',
9600 type: 'string',
9601 name: 'mid',
9602 id: 3
9603 }, {
9604 rule: 'optional',
9605 type: 'string',
9606 name: 'cid',
9607 id: 4
9608 }, {
9609 rule: 'optional',
9610 type: 'int64',
9611 name: 't',
9612 id: 5
9613 }, {
9614 rule: 'optional',
9615 type: 'string',
9616 name: 'uid',
9617 id: 6
9618 }, {
9619 rule: 'optional',
9620 type: 'int64',
9621 name: 'fromts',
9622 id: 7
9623 }, {
9624 rule: 'optional',
9625 type: 'int64',
9626 name: 'tots',
9627 id: 8
9628 }, {
9629 rule: 'optional',
9630 type: 'string',
9631 name: 'type',
9632 id: 9
9633 }, {
9634 rule: 'repeated',
9635 type: 'string',
9636 name: 'ids',
9637 id: 10
9638 }, {
9639 rule: 'optional',
9640 type: 'int32',
9641 name: 'appCode',
9642 id: 11
9643 }, {
9644 rule: 'optional',
9645 type: 'string',
9646 name: 'appMsg',
9647 id: 12
9648 }]
9649 }, {
9650 name: 'UnreadCommand',
9651 syntax: 'proto2',
9652 fields: [{
9653 rule: 'repeated',
9654 type: 'UnreadTuple',
9655 name: 'convs',
9656 id: 1
9657 }, {
9658 rule: 'optional',
9659 type: 'int64',
9660 name: 'notifTime',
9661 id: 2
9662 }]
9663 }, {
9664 name: 'ConvCommand',
9665 syntax: 'proto2',
9666 fields: [{
9667 rule: 'repeated',
9668 type: 'string',
9669 name: 'm',
9670 id: 1
9671 }, {
9672 rule: 'optional',
9673 type: 'bool',
9674 name: 'transient',
9675 id: 2
9676 }, {
9677 rule: 'optional',
9678 type: 'bool',
9679 name: 'unique',
9680 id: 3
9681 }, {
9682 rule: 'optional',
9683 type: 'string',
9684 name: 'cid',
9685 id: 4
9686 }, {
9687 rule: 'optional',
9688 type: 'string',
9689 name: 'cdate',
9690 id: 5
9691 }, {
9692 rule: 'optional',
9693 type: 'string',
9694 name: 'initBy',
9695 id: 6
9696 }, {
9697 rule: 'optional',
9698 type: 'string',
9699 name: 'sort',
9700 id: 7
9701 }, {
9702 rule: 'optional',
9703 type: 'int32',
9704 name: 'limit',
9705 id: 8
9706 }, {
9707 rule: 'optional',
9708 type: 'int32',
9709 name: 'skip',
9710 id: 9
9711 }, {
9712 rule: 'optional',
9713 type: 'int32',
9714 name: 'flag',
9715 id: 10
9716 }, {
9717 rule: 'optional',
9718 type: 'int32',
9719 name: 'count',
9720 id: 11
9721 }, {
9722 rule: 'optional',
9723 type: 'string',
9724 name: 'udate',
9725 id: 12
9726 }, {
9727 rule: 'optional',
9728 type: 'int64',
9729 name: 't',
9730 id: 13
9731 }, {
9732 rule: 'optional',
9733 type: 'string',
9734 name: 'n',
9735 id: 14
9736 }, {
9737 rule: 'optional',
9738 type: 'string',
9739 name: 's',
9740 id: 15
9741 }, {
9742 rule: 'optional',
9743 type: 'bool',
9744 name: 'statusSub',
9745 id: 16
9746 }, {
9747 rule: 'optional',
9748 type: 'bool',
9749 name: 'statusPub',
9750 id: 17
9751 }, {
9752 rule: 'optional',
9753 type: 'int32',
9754 name: 'statusTTL',
9755 id: 18
9756 }, {
9757 rule: 'optional',
9758 type: 'string',
9759 name: 'uniqueId',
9760 id: 19
9761 }, {
9762 rule: 'optional',
9763 type: 'string',
9764 name: 'targetClientId',
9765 id: 20
9766 }, {
9767 rule: 'optional',
9768 type: 'int64',
9769 name: 'maxReadTimestamp',
9770 id: 21
9771 }, {
9772 rule: 'optional',
9773 type: 'int64',
9774 name: 'maxAckTimestamp',
9775 id: 22
9776 }, {
9777 rule: 'optional',
9778 type: 'bool',
9779 name: 'queryAllMembers',
9780 id: 23
9781 }, {
9782 rule: 'repeated',
9783 type: 'MaxReadTuple',
9784 name: 'maxReadTuples',
9785 id: 24
9786 }, {
9787 rule: 'repeated',
9788 type: 'string',
9789 name: 'cids',
9790 id: 25
9791 }, {
9792 rule: 'optional',
9793 type: 'ConvMemberInfo',
9794 name: 'info',
9795 id: 26
9796 }, {
9797 rule: 'optional',
9798 type: 'bool',
9799 name: 'tempConv',
9800 id: 27
9801 }, {
9802 rule: 'optional',
9803 type: 'int32',
9804 name: 'tempConvTTL',
9805 id: 28
9806 }, {
9807 rule: 'repeated',
9808 type: 'string',
9809 name: 'tempConvIds',
9810 id: 29
9811 }, {
9812 rule: 'repeated',
9813 type: 'string',
9814 name: 'allowedPids',
9815 id: 30
9816 }, {
9817 rule: 'repeated',
9818 type: 'ErrorCommand',
9819 name: 'failedPids',
9820 id: 31
9821 }, {
9822 rule: 'optional',
9823 type: 'string',
9824 name: 'next',
9825 id: 40
9826 }, {
9827 rule: 'optional',
9828 type: 'JsonObjectMessage',
9829 name: 'results',
9830 id: 100
9831 }, {
9832 rule: 'optional',
9833 type: 'JsonObjectMessage',
9834 name: 'where',
9835 id: 101
9836 }, {
9837 rule: 'optional',
9838 type: 'JsonObjectMessage',
9839 name: 'attr',
9840 id: 103
9841 }, {
9842 rule: 'optional',
9843 type: 'JsonObjectMessage',
9844 name: 'attrModified',
9845 id: 104
9846 }]
9847 }, {
9848 name: 'RoomCommand',
9849 syntax: 'proto2',
9850 fields: [{
9851 rule: 'optional',
9852 type: 'string',
9853 name: 'roomId',
9854 id: 1
9855 }, {
9856 rule: 'optional',
9857 type: 'string',
9858 name: 's',
9859 id: 2
9860 }, {
9861 rule: 'optional',
9862 type: 'int64',
9863 name: 't',
9864 id: 3
9865 }, {
9866 rule: 'optional',
9867 type: 'string',
9868 name: 'n',
9869 id: 4
9870 }, {
9871 rule: 'optional',
9872 type: 'bool',
9873 name: 'transient',
9874 id: 5
9875 }, {
9876 rule: 'repeated',
9877 type: 'string',
9878 name: 'roomPeerIds',
9879 id: 6
9880 }, {
9881 rule: 'optional',
9882 type: 'string',
9883 name: 'byPeerId',
9884 id: 7
9885 }]
9886 }, {
9887 name: 'LogsCommand',
9888 syntax: 'proto2',
9889 fields: [{
9890 rule: 'optional',
9891 type: 'string',
9892 name: 'cid',
9893 id: 1
9894 }, {
9895 rule: 'optional',
9896 type: 'int32',
9897 name: 'l',
9898 id: 2
9899 }, {
9900 rule: 'optional',
9901 type: 'int32',
9902 name: 'limit',
9903 id: 3
9904 }, {
9905 rule: 'optional',
9906 type: 'int64',
9907 name: 't',
9908 id: 4
9909 }, {
9910 rule: 'optional',
9911 type: 'int64',
9912 name: 'tt',
9913 id: 5
9914 }, {
9915 rule: 'optional',
9916 type: 'string',
9917 name: 'tmid',
9918 id: 6
9919 }, {
9920 rule: 'optional',
9921 type: 'string',
9922 name: 'mid',
9923 id: 7
9924 }, {
9925 rule: 'optional',
9926 type: 'string',
9927 name: 'checksum',
9928 id: 8
9929 }, {
9930 rule: 'optional',
9931 type: 'bool',
9932 name: 'stored',
9933 id: 9
9934 }, {
9935 rule: 'optional',
9936 type: 'QueryDirection',
9937 name: 'direction',
9938 id: 10,
9939 options: {
9940 default: 'OLD'
9941 }
9942 }, {
9943 rule: 'optional',
9944 type: 'bool',
9945 name: 'tIncluded',
9946 id: 11
9947 }, {
9948 rule: 'optional',
9949 type: 'bool',
9950 name: 'ttIncluded',
9951 id: 12
9952 }, {
9953 rule: 'optional',
9954 type: 'int32',
9955 name: 'lctype',
9956 id: 13
9957 }, {
9958 rule: 'repeated',
9959 type: 'LogItem',
9960 name: 'logs',
9961 id: 105
9962 }],
9963 enums: [{
9964 name: 'QueryDirection',
9965 syntax: 'proto2',
9966 values: [{
9967 name: 'OLD',
9968 id: 1
9969 }, {
9970 name: 'NEW',
9971 id: 2
9972 }]
9973 }]
9974 }, {
9975 name: 'RcpCommand',
9976 syntax: 'proto2',
9977 fields: [{
9978 rule: 'optional',
9979 type: 'string',
9980 name: 'id',
9981 id: 1
9982 }, {
9983 rule: 'optional',
9984 type: 'string',
9985 name: 'cid',
9986 id: 2
9987 }, {
9988 rule: 'optional',
9989 type: 'int64',
9990 name: 't',
9991 id: 3
9992 }, {
9993 rule: 'optional',
9994 type: 'bool',
9995 name: 'read',
9996 id: 4
9997 }, {
9998 rule: 'optional',
9999 type: 'string',
10000 name: 'from',
10001 id: 5
10002 }]
10003 }, {
10004 name: 'ReadTuple',
10005 syntax: 'proto2',
10006 fields: [{
10007 rule: 'required',
10008 type: 'string',
10009 name: 'cid',
10010 id: 1
10011 }, {
10012 rule: 'optional',
10013 type: 'int64',
10014 name: 'timestamp',
10015 id: 2
10016 }, {
10017 rule: 'optional',
10018 type: 'string',
10019 name: 'mid',
10020 id: 3
10021 }]
10022 }, {
10023 name: 'MaxReadTuple',
10024 syntax: 'proto2',
10025 fields: [{
10026 rule: 'optional',
10027 type: 'string',
10028 name: 'pid',
10029 id: 1
10030 }, {
10031 rule: 'optional',
10032 type: 'int64',
10033 name: 'maxAckTimestamp',
10034 id: 2
10035 }, {
10036 rule: 'optional',
10037 type: 'int64',
10038 name: 'maxReadTimestamp',
10039 id: 3
10040 }]
10041 }, {
10042 name: 'ReadCommand',
10043 syntax: 'proto2',
10044 fields: [{
10045 rule: 'optional',
10046 type: 'string',
10047 name: 'cid',
10048 id: 1
10049 }, {
10050 rule: 'repeated',
10051 type: 'string',
10052 name: 'cids',
10053 id: 2
10054 }, {
10055 rule: 'repeated',
10056 type: 'ReadTuple',
10057 name: 'convs',
10058 id: 3
10059 }]
10060 }, {
10061 name: 'PresenceCommand',
10062 syntax: 'proto2',
10063 fields: [{
10064 rule: 'optional',
10065 type: 'StatusType',
10066 name: 'status',
10067 id: 1
10068 }, {
10069 rule: 'repeated',
10070 type: 'string',
10071 name: 'sessionPeerIds',
10072 id: 2
10073 }, {
10074 rule: 'optional',
10075 type: 'string',
10076 name: 'cid',
10077 id: 3
10078 }]
10079 }, {
10080 name: 'ReportCommand',
10081 syntax: 'proto2',
10082 fields: [{
10083 rule: 'optional',
10084 type: 'bool',
10085 name: 'initiative',
10086 id: 1
10087 }, {
10088 rule: 'optional',
10089 type: 'string',
10090 name: 'type',
10091 id: 2
10092 }, {
10093 rule: 'optional',
10094 type: 'string',
10095 name: 'data',
10096 id: 3
10097 }]
10098 }, {
10099 name: 'PatchItem',
10100 syntax: 'proto2',
10101 fields: [{
10102 rule: 'optional',
10103 type: 'string',
10104 name: 'cid',
10105 id: 1
10106 }, {
10107 rule: 'optional',
10108 type: 'string',
10109 name: 'mid',
10110 id: 2
10111 }, {
10112 rule: 'optional',
10113 type: 'int64',
10114 name: 'timestamp',
10115 id: 3
10116 }, {
10117 rule: 'optional',
10118 type: 'bool',
10119 name: 'recall',
10120 id: 4
10121 }, {
10122 rule: 'optional',
10123 type: 'string',
10124 name: 'data',
10125 id: 5
10126 }, {
10127 rule: 'optional',
10128 type: 'int64',
10129 name: 'patchTimestamp',
10130 id: 6
10131 }, {
10132 rule: 'optional',
10133 type: 'string',
10134 name: 'from',
10135 id: 7
10136 }, {
10137 rule: 'optional',
10138 type: 'bytes',
10139 name: 'binaryMsg',
10140 id: 8
10141 }, {
10142 rule: 'optional',
10143 type: 'bool',
10144 name: 'mentionAll',
10145 id: 9
10146 }, {
10147 rule: 'repeated',
10148 type: 'string',
10149 name: 'mentionPids',
10150 id: 10
10151 }, {
10152 rule: 'optional',
10153 type: 'int64',
10154 name: 'patchCode',
10155 id: 11
10156 }, {
10157 rule: 'optional',
10158 type: 'string',
10159 name: 'patchReason',
10160 id: 12
10161 }]
10162 }, {
10163 name: 'PatchCommand',
10164 syntax: 'proto2',
10165 fields: [{
10166 rule: 'repeated',
10167 type: 'PatchItem',
10168 name: 'patches',
10169 id: 1
10170 }, {
10171 rule: 'optional',
10172 type: 'int64',
10173 name: 'lastPatchTime',
10174 id: 2
10175 }]
10176 }, {
10177 name: 'PubsubCommand',
10178 syntax: 'proto2',
10179 fields: [{
10180 rule: 'optional',
10181 type: 'string',
10182 name: 'cid',
10183 id: 1
10184 }, {
10185 rule: 'repeated',
10186 type: 'string',
10187 name: 'cids',
10188 id: 2
10189 }, {
10190 rule: 'optional',
10191 type: 'string',
10192 name: 'topic',
10193 id: 3
10194 }, {
10195 rule: 'optional',
10196 type: 'string',
10197 name: 'subtopic',
10198 id: 4
10199 }, {
10200 rule: 'repeated',
10201 type: 'string',
10202 name: 'topics',
10203 id: 5
10204 }, {
10205 rule: 'repeated',
10206 type: 'string',
10207 name: 'subtopics',
10208 id: 6
10209 }, {
10210 rule: 'optional',
10211 type: 'JsonObjectMessage',
10212 name: 'results',
10213 id: 7
10214 }]
10215 }, {
10216 name: 'BlacklistCommand',
10217 syntax: 'proto2',
10218 fields: [{
10219 rule: 'optional',
10220 type: 'string',
10221 name: 'srcCid',
10222 id: 1
10223 }, {
10224 rule: 'repeated',
10225 type: 'string',
10226 name: 'toPids',
10227 id: 2
10228 }, {
10229 rule: 'optional',
10230 type: 'string',
10231 name: 'srcPid',
10232 id: 3
10233 }, {
10234 rule: 'repeated',
10235 type: 'string',
10236 name: 'toCids',
10237 id: 4
10238 }, {
10239 rule: 'optional',
10240 type: 'int32',
10241 name: 'limit',
10242 id: 5
10243 }, {
10244 rule: 'optional',
10245 type: 'string',
10246 name: 'next',
10247 id: 6
10248 }, {
10249 rule: 'repeated',
10250 type: 'string',
10251 name: 'blockedPids',
10252 id: 8
10253 }, {
10254 rule: 'repeated',
10255 type: 'string',
10256 name: 'blockedCids',
10257 id: 9
10258 }, {
10259 rule: 'repeated',
10260 type: 'string',
10261 name: 'allowedPids',
10262 id: 10
10263 }, {
10264 rule: 'repeated',
10265 type: 'ErrorCommand',
10266 name: 'failedPids',
10267 id: 11
10268 }, {
10269 rule: 'optional',
10270 type: 'int64',
10271 name: 't',
10272 id: 12
10273 }, {
10274 rule: 'optional',
10275 type: 'string',
10276 name: 'n',
10277 id: 13
10278 }, {
10279 rule: 'optional',
10280 type: 'string',
10281 name: 's',
10282 id: 14
10283 }]
10284 }, {
10285 name: 'GenericCommand',
10286 syntax: 'proto2',
10287 fields: [{
10288 rule: 'optional',
10289 type: 'CommandType',
10290 name: 'cmd',
10291 id: 1
10292 }, {
10293 rule: 'optional',
10294 type: 'OpType',
10295 name: 'op',
10296 id: 2
10297 }, {
10298 rule: 'optional',
10299 type: 'string',
10300 name: 'appId',
10301 id: 3
10302 }, {
10303 rule: 'optional',
10304 type: 'string',
10305 name: 'peerId',
10306 id: 4
10307 }, {
10308 rule: 'optional',
10309 type: 'int32',
10310 name: 'i',
10311 id: 5
10312 }, {
10313 rule: 'optional',
10314 type: 'string',
10315 name: 'installationId',
10316 id: 6
10317 }, {
10318 rule: 'optional',
10319 type: 'int32',
10320 name: 'priority',
10321 id: 7
10322 }, {
10323 rule: 'optional',
10324 type: 'int32',
10325 name: 'service',
10326 id: 8
10327 }, {
10328 rule: 'optional',
10329 type: 'int64',
10330 name: 'serverTs',
10331 id: 9
10332 }, {
10333 rule: 'optional',
10334 type: 'int64',
10335 name: 'clientTs',
10336 id: 10
10337 }, {
10338 rule: 'optional',
10339 type: 'int32',
10340 name: 'notificationType',
10341 id: 11
10342 }, {
10343 rule: 'optional',
10344 type: 'DataCommand',
10345 name: 'dataMessage',
10346 id: 101
10347 }, {
10348 rule: 'optional',
10349 type: 'SessionCommand',
10350 name: 'sessionMessage',
10351 id: 102
10352 }, {
10353 rule: 'optional',
10354 type: 'ErrorCommand',
10355 name: 'errorMessage',
10356 id: 103
10357 }, {
10358 rule: 'optional',
10359 type: 'DirectCommand',
10360 name: 'directMessage',
10361 id: 104
10362 }, {
10363 rule: 'optional',
10364 type: 'AckCommand',
10365 name: 'ackMessage',
10366 id: 105
10367 }, {
10368 rule: 'optional',
10369 type: 'UnreadCommand',
10370 name: 'unreadMessage',
10371 id: 106
10372 }, {
10373 rule: 'optional',
10374 type: 'ReadCommand',
10375 name: 'readMessage',
10376 id: 107
10377 }, {
10378 rule: 'optional',
10379 type: 'RcpCommand',
10380 name: 'rcpMessage',
10381 id: 108
10382 }, {
10383 rule: 'optional',
10384 type: 'LogsCommand',
10385 name: 'logsMessage',
10386 id: 109
10387 }, {
10388 rule: 'optional',
10389 type: 'ConvCommand',
10390 name: 'convMessage',
10391 id: 110
10392 }, {
10393 rule: 'optional',
10394 type: 'RoomCommand',
10395 name: 'roomMessage',
10396 id: 111
10397 }, {
10398 rule: 'optional',
10399 type: 'PresenceCommand',
10400 name: 'presenceMessage',
10401 id: 112
10402 }, {
10403 rule: 'optional',
10404 type: 'ReportCommand',
10405 name: 'reportMessage',
10406 id: 113
10407 }, {
10408 rule: 'optional',
10409 type: 'PatchCommand',
10410 name: 'patchMessage',
10411 id: 114
10412 }, {
10413 rule: 'optional',
10414 type: 'PubsubCommand',
10415 name: 'pubsubMessage',
10416 id: 115
10417 }, {
10418 rule: 'optional',
10419 type: 'BlacklistCommand',
10420 name: 'blacklistMessage',
10421 id: 116
10422 }]
10423 }],
10424 enums: [{
10425 name: 'CommandType',
10426 syntax: 'proto2',
10427 values: [{
10428 name: 'session',
10429 id: 0
10430 }, {
10431 name: 'conv',
10432 id: 1
10433 }, {
10434 name: 'direct',
10435 id: 2
10436 }, {
10437 name: 'ack',
10438 id: 3
10439 }, {
10440 name: 'rcp',
10441 id: 4
10442 }, {
10443 name: 'unread',
10444 id: 5
10445 }, {
10446 name: 'logs',
10447 id: 6
10448 }, {
10449 name: 'error',
10450 id: 7
10451 }, {
10452 name: 'login',
10453 id: 8
10454 }, {
10455 name: 'data',
10456 id: 9
10457 }, {
10458 name: 'room',
10459 id: 10
10460 }, {
10461 name: 'read',
10462 id: 11
10463 }, {
10464 name: 'presence',
10465 id: 12
10466 }, {
10467 name: 'report',
10468 id: 13
10469 }, {
10470 name: 'echo',
10471 id: 14
10472 }, {
10473 name: 'loggedin',
10474 id: 15
10475 }, {
10476 name: 'logout',
10477 id: 16
10478 }, {
10479 name: 'loggedout',
10480 id: 17
10481 }, {
10482 name: 'patch',
10483 id: 18
10484 }, {
10485 name: 'pubsub',
10486 id: 19
10487 }, {
10488 name: 'blacklist',
10489 id: 20
10490 }, {
10491 name: 'goaway',
10492 id: 21
10493 }]
10494 }, {
10495 name: 'OpType',
10496 syntax: 'proto2',
10497 values: [{
10498 name: 'open',
10499 id: 1
10500 }, {
10501 name: 'add',
10502 id: 2
10503 }, {
10504 name: 'remove',
10505 id: 3
10506 }, {
10507 name: 'close',
10508 id: 4
10509 }, {
10510 name: 'opened',
10511 id: 5
10512 }, {
10513 name: 'closed',
10514 id: 6
10515 }, {
10516 name: 'query',
10517 id: 7
10518 }, {
10519 name: 'query_result',
10520 id: 8
10521 }, {
10522 name: 'conflict',
10523 id: 9
10524 }, {
10525 name: 'added',
10526 id: 10
10527 }, {
10528 name: 'removed',
10529 id: 11
10530 }, {
10531 name: 'refresh',
10532 id: 12
10533 }, {
10534 name: 'refreshed',
10535 id: 13
10536 }, {
10537 name: 'start',
10538 id: 30
10539 }, {
10540 name: 'started',
10541 id: 31
10542 }, {
10543 name: 'joined',
10544 id: 32
10545 }, {
10546 name: 'members_joined',
10547 id: 33
10548 }, {
10549 name: 'left',
10550 id: 39
10551 }, {
10552 name: 'members_left',
10553 id: 40
10554 }, {
10555 name: 'results',
10556 id: 42
10557 }, {
10558 name: 'count',
10559 id: 43
10560 }, {
10561 name: 'result',
10562 id: 44
10563 }, {
10564 name: 'update',
10565 id: 45
10566 }, {
10567 name: 'updated',
10568 id: 46
10569 }, {
10570 name: 'mute',
10571 id: 47
10572 }, {
10573 name: 'unmute',
10574 id: 48
10575 }, {
10576 name: 'status',
10577 id: 49
10578 }, {
10579 name: 'members',
10580 id: 50
10581 }, {
10582 name: 'max_read',
10583 id: 51
10584 }, {
10585 name: 'is_member',
10586 id: 52
10587 }, {
10588 name: 'member_info_update',
10589 id: 53
10590 }, {
10591 name: 'member_info_updated',
10592 id: 54
10593 }, {
10594 name: 'member_info_changed',
10595 id: 55
10596 }, {
10597 name: 'join',
10598 id: 80
10599 }, {
10600 name: 'invite',
10601 id: 81
10602 }, {
10603 name: 'leave',
10604 id: 82
10605 }, {
10606 name: 'kick',
10607 id: 83
10608 }, {
10609 name: 'reject',
10610 id: 84
10611 }, {
10612 name: 'invited',
10613 id: 85
10614 }, {
10615 name: 'kicked',
10616 id: 86
10617 }, {
10618 name: 'upload',
10619 id: 100
10620 }, {
10621 name: 'uploaded',
10622 id: 101
10623 }, {
10624 name: 'subscribe',
10625 id: 120
10626 }, {
10627 name: 'subscribed',
10628 id: 121
10629 }, {
10630 name: 'unsubscribe',
10631 id: 122
10632 }, {
10633 name: 'unsubscribed',
10634 id: 123
10635 }, {
10636 name: 'is_subscribed',
10637 id: 124
10638 }, {
10639 name: 'modify',
10640 id: 150
10641 }, {
10642 name: 'modified',
10643 id: 151
10644 }, {
10645 name: 'block',
10646 id: 170
10647 }, {
10648 name: 'unblock',
10649 id: 171
10650 }, {
10651 name: 'blocked',
10652 id: 172
10653 }, {
10654 name: 'unblocked',
10655 id: 173
10656 }, {
10657 name: 'members_blocked',
10658 id: 174
10659 }, {
10660 name: 'members_unblocked',
10661 id: 175
10662 }, {
10663 name: 'check_block',
10664 id: 176
10665 }, {
10666 name: 'check_result',
10667 id: 177
10668 }, {
10669 name: 'add_shutup',
10670 id: 180
10671 }, {
10672 name: 'remove_shutup',
10673 id: 181
10674 }, {
10675 name: 'query_shutup',
10676 id: 182
10677 }, {
10678 name: 'shutup_added',
10679 id: 183
10680 }, {
10681 name: 'shutup_removed',
10682 id: 184
10683 }, {
10684 name: 'shutup_result',
10685 id: 185
10686 }, {
10687 name: 'shutuped',
10688 id: 186
10689 }, {
10690 name: 'unshutuped',
10691 id: 187
10692 }, {
10693 name: 'members_shutuped',
10694 id: 188
10695 }, {
10696 name: 'members_unshutuped',
10697 id: 189
10698 }, {
10699 name: 'check_shutup',
10700 id: 190
10701 }]
10702 }, {
10703 name: 'StatusType',
10704 syntax: 'proto2',
10705 values: [{
10706 name: 'on',
10707 id: 1
10708 }, {
10709 name: 'off',
10710 id: 2
10711 }]
10712 }],
10713 isNamespace: true
10714 }).build();
10715
10716 var _messages$push_server = messageCompiled.push_server.messages2,
10717 JsonObjectMessage = _messages$push_server.JsonObjectMessage,
10718 UnreadTuple = _messages$push_server.UnreadTuple,
10719 LogItem = _messages$push_server.LogItem,
10720 DataCommand = _messages$push_server.DataCommand,
10721 SessionCommand = _messages$push_server.SessionCommand,
10722 ErrorCommand = _messages$push_server.ErrorCommand,
10723 DirectCommand = _messages$push_server.DirectCommand,
10724 AckCommand = _messages$push_server.AckCommand,
10725 UnreadCommand = _messages$push_server.UnreadCommand,
10726 ConvCommand = _messages$push_server.ConvCommand,
10727 RoomCommand = _messages$push_server.RoomCommand,
10728 LogsCommand = _messages$push_server.LogsCommand,
10729 RcpCommand = _messages$push_server.RcpCommand,
10730 ReadTuple = _messages$push_server.ReadTuple,
10731 MaxReadTuple = _messages$push_server.MaxReadTuple,
10732 ReadCommand = _messages$push_server.ReadCommand,
10733 PresenceCommand = _messages$push_server.PresenceCommand,
10734 ReportCommand = _messages$push_server.ReportCommand,
10735 GenericCommand = _messages$push_server.GenericCommand,
10736 BlacklistCommand = _messages$push_server.BlacklistCommand,
10737 PatchCommand = _messages$push_server.PatchCommand,
10738 PatchItem = _messages$push_server.PatchItem,
10739 ConvMemberInfo = _messages$push_server.ConvMemberInfo,
10740 CommandType = _messages$push_server.CommandType,
10741 OpType = _messages$push_server.OpType,
10742 StatusType = _messages$push_server.StatusType;
10743
10744 var message = /*#__PURE__*/Object.freeze({
10745 JsonObjectMessage: JsonObjectMessage,
10746 UnreadTuple: UnreadTuple,
10747 LogItem: LogItem,
10748 DataCommand: DataCommand,
10749 SessionCommand: SessionCommand,
10750 ErrorCommand: ErrorCommand,
10751 DirectCommand: DirectCommand,
10752 AckCommand: AckCommand,
10753 UnreadCommand: UnreadCommand,
10754 ConvCommand: ConvCommand,
10755 RoomCommand: RoomCommand,
10756 LogsCommand: LogsCommand,
10757 RcpCommand: RcpCommand,
10758 ReadTuple: ReadTuple,
10759 MaxReadTuple: MaxReadTuple,
10760 ReadCommand: ReadCommand,
10761 PresenceCommand: PresenceCommand,
10762 ReportCommand: ReportCommand,
10763 GenericCommand: GenericCommand,
10764 BlacklistCommand: BlacklistCommand,
10765 PatchCommand: PatchCommand,
10766 PatchItem: PatchItem,
10767 ConvMemberInfo: ConvMemberInfo,
10768 CommandType: CommandType,
10769 OpType: OpType,
10770 StatusType: StatusType
10771 });
10772
10773 var eventemitter3 = createCommonjsModule(function (module) {
10774
10775 var has = Object.prototype.hasOwnProperty
10776 , prefix = '~';
10777
10778 /**
10779 * Constructor to create a storage for our `EE` objects.
10780 * An `Events` instance is a plain object whose properties are event names.
10781 *
10782 * @constructor
10783 * @private
10784 */
10785 function Events() {}
10786
10787 //
10788 // We try to not inherit from `Object.prototype`. In some engines creating an
10789 // instance in this way is faster than calling `Object.create(null)` directly.
10790 // If `Object.create(null)` is not supported we prefix the event names with a
10791 // character to make sure that the built-in object properties are not
10792 // overridden or used as an attack vector.
10793 //
10794 if (Object.create) {
10795 Events.prototype = Object.create(null);
10796
10797 //
10798 // This hack is needed because the `__proto__` property is still inherited in
10799 // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.
10800 //
10801 if (!new Events().__proto__) prefix = false;
10802 }
10803
10804 /**
10805 * Representation of a single event listener.
10806 *
10807 * @param {Function} fn The listener function.
10808 * @param {*} context The context to invoke the listener with.
10809 * @param {Boolean} [once=false] Specify if the listener is a one-time listener.
10810 * @constructor
10811 * @private
10812 */
10813 function EE(fn, context, once) {
10814 this.fn = fn;
10815 this.context = context;
10816 this.once = once || false;
10817 }
10818
10819 /**
10820 * Add a listener for a given event.
10821 *
10822 * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
10823 * @param {(String|Symbol)} event The event name.
10824 * @param {Function} fn The listener function.
10825 * @param {*} context The context to invoke the listener with.
10826 * @param {Boolean} once Specify if the listener is a one-time listener.
10827 * @returns {EventEmitter}
10828 * @private
10829 */
10830 function addListener(emitter, event, fn, context, once) {
10831 if (typeof fn !== 'function') {
10832 throw new TypeError('The listener must be a function');
10833 }
10834
10835 var listener = new EE(fn, context || emitter, once)
10836 , evt = prefix ? prefix + event : event;
10837
10838 if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;
10839 else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);
10840 else emitter._events[evt] = [emitter._events[evt], listener];
10841
10842 return emitter;
10843 }
10844
10845 /**
10846 * Clear event by name.
10847 *
10848 * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
10849 * @param {(String|Symbol)} evt The Event name.
10850 * @private
10851 */
10852 function clearEvent(emitter, evt) {
10853 if (--emitter._eventsCount === 0) emitter._events = new Events();
10854 else delete emitter._events[evt];
10855 }
10856
10857 /**
10858 * Minimal `EventEmitter` interface that is molded against the Node.js
10859 * `EventEmitter` interface.
10860 *
10861 * @constructor
10862 * @public
10863 */
10864 function EventEmitter() {
10865 this._events = new Events();
10866 this._eventsCount = 0;
10867 }
10868
10869 /**
10870 * Return an array listing the events for which the emitter has registered
10871 * listeners.
10872 *
10873 * @returns {Array}
10874 * @public
10875 */
10876 EventEmitter.prototype.eventNames = function eventNames() {
10877 var names = []
10878 , events
10879 , name;
10880
10881 if (this._eventsCount === 0) return names;
10882
10883 for (name in (events = this._events)) {
10884 if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);
10885 }
10886
10887 if (Object.getOwnPropertySymbols) {
10888 return names.concat(Object.getOwnPropertySymbols(events));
10889 }
10890
10891 return names;
10892 };
10893
10894 /**
10895 * Return the listeners registered for a given event.
10896 *
10897 * @param {(String|Symbol)} event The event name.
10898 * @returns {Array} The registered listeners.
10899 * @public
10900 */
10901 EventEmitter.prototype.listeners = function listeners(event) {
10902 var evt = prefix ? prefix + event : event
10903 , handlers = this._events[evt];
10904
10905 if (!handlers) return [];
10906 if (handlers.fn) return [handlers.fn];
10907
10908 for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {
10909 ee[i] = handlers[i].fn;
10910 }
10911
10912 return ee;
10913 };
10914
10915 /**
10916 * Return the number of listeners listening to a given event.
10917 *
10918 * @param {(String|Symbol)} event The event name.
10919 * @returns {Number} The number of listeners.
10920 * @public
10921 */
10922 EventEmitter.prototype.listenerCount = function listenerCount(event) {
10923 var evt = prefix ? prefix + event : event
10924 , listeners = this._events[evt];
10925
10926 if (!listeners) return 0;
10927 if (listeners.fn) return 1;
10928 return listeners.length;
10929 };
10930
10931 /**
10932 * Calls each of the listeners registered for a given event.
10933 *
10934 * @param {(String|Symbol)} event The event name.
10935 * @returns {Boolean} `true` if the event had listeners, else `false`.
10936 * @public
10937 */
10938 EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {
10939 var evt = prefix ? prefix + event : event;
10940
10941 if (!this._events[evt]) return false;
10942
10943 var listeners = this._events[evt]
10944 , len = arguments.length
10945 , args
10946 , i;
10947
10948 if (listeners.fn) {
10949 if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);
10950
10951 switch (len) {
10952 case 1: return listeners.fn.call(listeners.context), true;
10953 case 2: return listeners.fn.call(listeners.context, a1), true;
10954 case 3: return listeners.fn.call(listeners.context, a1, a2), true;
10955 case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;
10956 case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;
10957 case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;
10958 }
10959
10960 for (i = 1, args = new Array(len -1); i < len; i++) {
10961 args[i - 1] = arguments[i];
10962 }
10963
10964 listeners.fn.apply(listeners.context, args);
10965 } else {
10966 var length = listeners.length
10967 , j;
10968
10969 for (i = 0; i < length; i++) {
10970 if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);
10971
10972 switch (len) {
10973 case 1: listeners[i].fn.call(listeners[i].context); break;
10974 case 2: listeners[i].fn.call(listeners[i].context, a1); break;
10975 case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;
10976 case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;
10977 default:
10978 if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {
10979 args[j - 1] = arguments[j];
10980 }
10981
10982 listeners[i].fn.apply(listeners[i].context, args);
10983 }
10984 }
10985 }
10986
10987 return true;
10988 };
10989
10990 /**
10991 * Add a listener for a given event.
10992 *
10993 * @param {(String|Symbol)} event The event name.
10994 * @param {Function} fn The listener function.
10995 * @param {*} [context=this] The context to invoke the listener with.
10996 * @returns {EventEmitter} `this`.
10997 * @public
10998 */
10999 EventEmitter.prototype.on = function on(event, fn, context) {
11000 return addListener(this, event, fn, context, false);
11001 };
11002
11003 /**
11004 * Add a one-time listener for a given event.
11005 *
11006 * @param {(String|Symbol)} event The event name.
11007 * @param {Function} fn The listener function.
11008 * @param {*} [context=this] The context to invoke the listener with.
11009 * @returns {EventEmitter} `this`.
11010 * @public
11011 */
11012 EventEmitter.prototype.once = function once(event, fn, context) {
11013 return addListener(this, event, fn, context, true);
11014 };
11015
11016 /**
11017 * Remove the listeners of a given event.
11018 *
11019 * @param {(String|Symbol)} event The event name.
11020 * @param {Function} fn Only remove the listeners that match this function.
11021 * @param {*} context Only remove the listeners that have this context.
11022 * @param {Boolean} once Only remove one-time listeners.
11023 * @returns {EventEmitter} `this`.
11024 * @public
11025 */
11026 EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {
11027 var evt = prefix ? prefix + event : event;
11028
11029 if (!this._events[evt]) return this;
11030 if (!fn) {
11031 clearEvent(this, evt);
11032 return this;
11033 }
11034
11035 var listeners = this._events[evt];
11036
11037 if (listeners.fn) {
11038 if (
11039 listeners.fn === fn &&
11040 (!once || listeners.once) &&
11041 (!context || listeners.context === context)
11042 ) {
11043 clearEvent(this, evt);
11044 }
11045 } else {
11046 for (var i = 0, events = [], length = listeners.length; i < length; i++) {
11047 if (
11048 listeners[i].fn !== fn ||
11049 (once && !listeners[i].once) ||
11050 (context && listeners[i].context !== context)
11051 ) {
11052 events.push(listeners[i]);
11053 }
11054 }
11055
11056 //
11057 // Reset the array, or remove it completely if we have no more listeners.
11058 //
11059 if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;
11060 else clearEvent(this, evt);
11061 }
11062
11063 return this;
11064 };
11065
11066 /**
11067 * Remove all listeners, or those of the specified event.
11068 *
11069 * @param {(String|Symbol)} [event] The event name.
11070 * @returns {EventEmitter} `this`.
11071 * @public
11072 */
11073 EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {
11074 var evt;
11075
11076 if (event) {
11077 evt = prefix ? prefix + event : event;
11078 if (this._events[evt]) clearEvent(this, evt);
11079 } else {
11080 this._events = new Events();
11081 this._eventsCount = 0;
11082 }
11083
11084 return this;
11085 };
11086
11087 //
11088 // Alias methods names because people roll like that.
11089 //
11090 EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
11091 EventEmitter.prototype.addListener = EventEmitter.prototype.on;
11092
11093 //
11094 // Expose the prefix.
11095 //
11096 EventEmitter.prefixed = prefix;
11097
11098 //
11099 // Allow `EventEmitter` to be imported as module namespace.
11100 //
11101 EventEmitter.EventEmitter = EventEmitter;
11102
11103 //
11104 // Expose the module.
11105 //
11106 {
11107 module.exports = EventEmitter;
11108 }
11109 });
11110
11111 var runtime = createCommonjsModule(function (module) {
11112 /**
11113 * Copyright (c) 2014-present, Facebook, Inc.
11114 *
11115 * This source code is licensed under the MIT license found in the
11116 * LICENSE file in the root directory of this source tree.
11117 */
11118
11119 !(function(global) {
11120
11121 var Op = Object.prototype;
11122 var hasOwn = Op.hasOwnProperty;
11123 var undefined$1; // More compressible than void 0.
11124 var $Symbol = typeof Symbol === "function" ? Symbol : {};
11125 var iteratorSymbol = $Symbol.iterator || "@@iterator";
11126 var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator";
11127 var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";
11128 var runtime = global.regeneratorRuntime;
11129 if (runtime) {
11130 {
11131 // If regeneratorRuntime is defined globally and we're in a module,
11132 // make the exports object identical to regeneratorRuntime.
11133 module.exports = runtime;
11134 }
11135 // Don't bother evaluating the rest of this file if the runtime was
11136 // already defined globally.
11137 return;
11138 }
11139
11140 // Define the runtime globally (as expected by generated code) as either
11141 // module.exports (if we're in a module) or a new, empty object.
11142 runtime = global.regeneratorRuntime = module.exports;
11143
11144 function wrap(innerFn, outerFn, self, tryLocsList) {
11145 // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator.
11146 var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator;
11147 var generator = Object.create(protoGenerator.prototype);
11148 var context = new Context(tryLocsList || []);
11149
11150 // The ._invoke method unifies the implementations of the .next,
11151 // .throw, and .return methods.
11152 generator._invoke = makeInvokeMethod(innerFn, self, context);
11153
11154 return generator;
11155 }
11156 runtime.wrap = wrap;
11157
11158 // Try/catch helper to minimize deoptimizations. Returns a completion
11159 // record like context.tryEntries[i].completion. This interface could
11160 // have been (and was previously) designed to take a closure to be
11161 // invoked without arguments, but in all the cases we care about we
11162 // already have an existing method we want to call, so there's no need
11163 // to create a new function object. We can even get away with assuming
11164 // the method takes exactly one argument, since that happens to be true
11165 // in every case, so we don't have to touch the arguments object. The
11166 // only additional allocation required is the completion record, which
11167 // has a stable shape and so hopefully should be cheap to allocate.
11168 function tryCatch(fn, obj, arg) {
11169 try {
11170 return { type: "normal", arg: fn.call(obj, arg) };
11171 } catch (err) {
11172 return { type: "throw", arg: err };
11173 }
11174 }
11175
11176 var GenStateSuspendedStart = "suspendedStart";
11177 var GenStateSuspendedYield = "suspendedYield";
11178 var GenStateExecuting = "executing";
11179 var GenStateCompleted = "completed";
11180
11181 // Returning this object from the innerFn has the same effect as
11182 // breaking out of the dispatch switch statement.
11183 var ContinueSentinel = {};
11184
11185 // Dummy constructor functions that we use as the .constructor and
11186 // .constructor.prototype properties for functions that return Generator
11187 // objects. For full spec compliance, you may wish to configure your
11188 // minifier not to mangle the names of these two functions.
11189 function Generator() {}
11190 function GeneratorFunction() {}
11191 function GeneratorFunctionPrototype() {}
11192
11193 // This is a polyfill for %IteratorPrototype% for environments that
11194 // don't natively support it.
11195 var IteratorPrototype = {};
11196 IteratorPrototype[iteratorSymbol] = function () {
11197 return this;
11198 };
11199
11200 var getProto = Object.getPrototypeOf;
11201 var NativeIteratorPrototype = getProto && getProto(getProto(values([])));
11202 if (NativeIteratorPrototype &&
11203 NativeIteratorPrototype !== Op &&
11204 hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) {
11205 // This environment has a native %IteratorPrototype%; use it instead
11206 // of the polyfill.
11207 IteratorPrototype = NativeIteratorPrototype;
11208 }
11209
11210 var Gp = GeneratorFunctionPrototype.prototype =
11211 Generator.prototype = Object.create(IteratorPrototype);
11212 GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype;
11213 GeneratorFunctionPrototype.constructor = GeneratorFunction;
11214 GeneratorFunctionPrototype[toStringTagSymbol] =
11215 GeneratorFunction.displayName = "GeneratorFunction";
11216
11217 // Helper for defining the .next, .throw, and .return methods of the
11218 // Iterator interface in terms of a single ._invoke method.
11219 function defineIteratorMethods(prototype) {
11220 ["next", "throw", "return"].forEach(function(method) {
11221 prototype[method] = function(arg) {
11222 return this._invoke(method, arg);
11223 };
11224 });
11225 }
11226
11227 runtime.isGeneratorFunction = function(genFun) {
11228 var ctor = typeof genFun === "function" && genFun.constructor;
11229 return ctor
11230 ? ctor === GeneratorFunction ||
11231 // For the native GeneratorFunction constructor, the best we can
11232 // do is to check its .name property.
11233 (ctor.displayName || ctor.name) === "GeneratorFunction"
11234 : false;
11235 };
11236
11237 runtime.mark = function(genFun) {
11238 if (Object.setPrototypeOf) {
11239 Object.setPrototypeOf(genFun, GeneratorFunctionPrototype);
11240 } else {
11241 genFun.__proto__ = GeneratorFunctionPrototype;
11242 if (!(toStringTagSymbol in genFun)) {
11243 genFun[toStringTagSymbol] = "GeneratorFunction";
11244 }
11245 }
11246 genFun.prototype = Object.create(Gp);
11247 return genFun;
11248 };
11249
11250 // Within the body of any async function, `await x` is transformed to
11251 // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test
11252 // `hasOwn.call(value, "__await")` to determine if the yielded value is
11253 // meant to be awaited.
11254 runtime.awrap = function(arg) {
11255 return { __await: arg };
11256 };
11257
11258 function AsyncIterator(generator) {
11259 function invoke(method, arg, resolve, reject) {
11260 var record = tryCatch(generator[method], generator, arg);
11261 if (record.type === "throw") {
11262 reject(record.arg);
11263 } else {
11264 var result = record.arg;
11265 var value = result.value;
11266 if (value &&
11267 typeof value === "object" &&
11268 hasOwn.call(value, "__await")) {
11269 return Promise.resolve(value.__await).then(function(value) {
11270 invoke("next", value, resolve, reject);
11271 }, function(err) {
11272 invoke("throw", err, resolve, reject);
11273 });
11274 }
11275
11276 return Promise.resolve(value).then(function(unwrapped) {
11277 // When a yielded Promise is resolved, its final value becomes
11278 // the .value of the Promise<{value,done}> result for the
11279 // current iteration.
11280 result.value = unwrapped;
11281 resolve(result);
11282 }, function(error) {
11283 // If a rejected Promise was yielded, throw the rejection back
11284 // into the async generator function so it can be handled there.
11285 return invoke("throw", error, resolve, reject);
11286 });
11287 }
11288 }
11289
11290 var previousPromise;
11291
11292 function enqueue(method, arg) {
11293 function callInvokeWithMethodAndArg() {
11294 return new Promise(function(resolve, reject) {
11295 invoke(method, arg, resolve, reject);
11296 });
11297 }
11298
11299 return previousPromise =
11300 // If enqueue has been called before, then we want to wait until
11301 // all previous Promises have been resolved before calling invoke,
11302 // so that results are always delivered in the correct order. If
11303 // enqueue has not been called before, then it is important to
11304 // call invoke immediately, without waiting on a callback to fire,
11305 // so that the async generator function has the opportunity to do
11306 // any necessary setup in a predictable way. This predictability
11307 // is why the Promise constructor synchronously invokes its
11308 // executor callback, and why async functions synchronously
11309 // execute code before the first await. Since we implement simple
11310 // async functions in terms of async generators, it is especially
11311 // important to get this right, even though it requires care.
11312 previousPromise ? previousPromise.then(
11313 callInvokeWithMethodAndArg,
11314 // Avoid propagating failures to Promises returned by later
11315 // invocations of the iterator.
11316 callInvokeWithMethodAndArg
11317 ) : callInvokeWithMethodAndArg();
11318 }
11319
11320 // Define the unified helper method that is used to implement .next,
11321 // .throw, and .return (see defineIteratorMethods).
11322 this._invoke = enqueue;
11323 }
11324
11325 defineIteratorMethods(AsyncIterator.prototype);
11326 AsyncIterator.prototype[asyncIteratorSymbol] = function () {
11327 return this;
11328 };
11329 runtime.AsyncIterator = AsyncIterator;
11330
11331 // Note that simple async functions are implemented on top of
11332 // AsyncIterator objects; they just return a Promise for the value of
11333 // the final result produced by the iterator.
11334 runtime.async = function(innerFn, outerFn, self, tryLocsList) {
11335 var iter = new AsyncIterator(
11336 wrap(innerFn, outerFn, self, tryLocsList)
11337 );
11338
11339 return runtime.isGeneratorFunction(outerFn)
11340 ? iter // If outerFn is a generator, return the full iterator.
11341 : iter.next().then(function(result) {
11342 return result.done ? result.value : iter.next();
11343 });
11344 };
11345
11346 function makeInvokeMethod(innerFn, self, context) {
11347 var state = GenStateSuspendedStart;
11348
11349 return function invoke(method, arg) {
11350 if (state === GenStateExecuting) {
11351 throw new Error("Generator is already running");
11352 }
11353
11354 if (state === GenStateCompleted) {
11355 if (method === "throw") {
11356 throw arg;
11357 }
11358
11359 // Be forgiving, per 25.3.3.3.3 of the spec:
11360 // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume
11361 return doneResult();
11362 }
11363
11364 context.method = method;
11365 context.arg = arg;
11366
11367 while (true) {
11368 var delegate = context.delegate;
11369 if (delegate) {
11370 var delegateResult = maybeInvokeDelegate(delegate, context);
11371 if (delegateResult) {
11372 if (delegateResult === ContinueSentinel) continue;
11373 return delegateResult;
11374 }
11375 }
11376
11377 if (context.method === "next") {
11378 // Setting context._sent for legacy support of Babel's
11379 // function.sent implementation.
11380 context.sent = context._sent = context.arg;
11381
11382 } else if (context.method === "throw") {
11383 if (state === GenStateSuspendedStart) {
11384 state = GenStateCompleted;
11385 throw context.arg;
11386 }
11387
11388 context.dispatchException(context.arg);
11389
11390 } else if (context.method === "return") {
11391 context.abrupt("return", context.arg);
11392 }
11393
11394 state = GenStateExecuting;
11395
11396 var record = tryCatch(innerFn, self, context);
11397 if (record.type === "normal") {
11398 // If an exception is thrown from innerFn, we leave state ===
11399 // GenStateExecuting and loop back for another invocation.
11400 state = context.done
11401 ? GenStateCompleted
11402 : GenStateSuspendedYield;
11403
11404 if (record.arg === ContinueSentinel) {
11405 continue;
11406 }
11407
11408 return {
11409 value: record.arg,
11410 done: context.done
11411 };
11412
11413 } else if (record.type === "throw") {
11414 state = GenStateCompleted;
11415 // Dispatch the exception by looping back around to the
11416 // context.dispatchException(context.arg) call above.
11417 context.method = "throw";
11418 context.arg = record.arg;
11419 }
11420 }
11421 };
11422 }
11423
11424 // Call delegate.iterator[context.method](context.arg) and handle the
11425 // result, either by returning a { value, done } result from the
11426 // delegate iterator, or by modifying context.method and context.arg,
11427 // setting context.delegate to null, and returning the ContinueSentinel.
11428 function maybeInvokeDelegate(delegate, context) {
11429 var method = delegate.iterator[context.method];
11430 if (method === undefined$1) {
11431 // A .throw or .return when the delegate iterator has no .throw
11432 // method always terminates the yield* loop.
11433 context.delegate = null;
11434
11435 if (context.method === "throw") {
11436 if (delegate.iterator.return) {
11437 // If the delegate iterator has a return method, give it a
11438 // chance to clean up.
11439 context.method = "return";
11440 context.arg = undefined$1;
11441 maybeInvokeDelegate(delegate, context);
11442
11443 if (context.method === "throw") {
11444 // If maybeInvokeDelegate(context) changed context.method from
11445 // "return" to "throw", let that override the TypeError below.
11446 return ContinueSentinel;
11447 }
11448 }
11449
11450 context.method = "throw";
11451 context.arg = new TypeError(
11452 "The iterator does not provide a 'throw' method");
11453 }
11454
11455 return ContinueSentinel;
11456 }
11457
11458 var record = tryCatch(method, delegate.iterator, context.arg);
11459
11460 if (record.type === "throw") {
11461 context.method = "throw";
11462 context.arg = record.arg;
11463 context.delegate = null;
11464 return ContinueSentinel;
11465 }
11466
11467 var info = record.arg;
11468
11469 if (! info) {
11470 context.method = "throw";
11471 context.arg = new TypeError("iterator result is not an object");
11472 context.delegate = null;
11473 return ContinueSentinel;
11474 }
11475
11476 if (info.done) {
11477 // Assign the result of the finished delegate to the temporary
11478 // variable specified by delegate.resultName (see delegateYield).
11479 context[delegate.resultName] = info.value;
11480
11481 // Resume execution at the desired location (see delegateYield).
11482 context.next = delegate.nextLoc;
11483
11484 // If context.method was "throw" but the delegate handled the
11485 // exception, let the outer generator proceed normally. If
11486 // context.method was "next", forget context.arg since it has been
11487 // "consumed" by the delegate iterator. If context.method was
11488 // "return", allow the original .return call to continue in the
11489 // outer generator.
11490 if (context.method !== "return") {
11491 context.method = "next";
11492 context.arg = undefined$1;
11493 }
11494
11495 } else {
11496 // Re-yield the result returned by the delegate method.
11497 return info;
11498 }
11499
11500 // The delegate iterator is finished, so forget it and continue with
11501 // the outer generator.
11502 context.delegate = null;
11503 return ContinueSentinel;
11504 }
11505
11506 // Define Generator.prototype.{next,throw,return} in terms of the
11507 // unified ._invoke helper method.
11508 defineIteratorMethods(Gp);
11509
11510 Gp[toStringTagSymbol] = "Generator";
11511
11512 // A Generator should always return itself as the iterator object when the
11513 // @@iterator function is called on it. Some browsers' implementations of the
11514 // iterator prototype chain incorrectly implement this, causing the Generator
11515 // object to not be returned from this call. This ensures that doesn't happen.
11516 // See https://github.com/facebook/regenerator/issues/274 for more details.
11517 Gp[iteratorSymbol] = function() {
11518 return this;
11519 };
11520
11521 Gp.toString = function() {
11522 return "[object Generator]";
11523 };
11524
11525 function pushTryEntry(locs) {
11526 var entry = { tryLoc: locs[0] };
11527
11528 if (1 in locs) {
11529 entry.catchLoc = locs[1];
11530 }
11531
11532 if (2 in locs) {
11533 entry.finallyLoc = locs[2];
11534 entry.afterLoc = locs[3];
11535 }
11536
11537 this.tryEntries.push(entry);
11538 }
11539
11540 function resetTryEntry(entry) {
11541 var record = entry.completion || {};
11542 record.type = "normal";
11543 delete record.arg;
11544 entry.completion = record;
11545 }
11546
11547 function Context(tryLocsList) {
11548 // The root entry object (effectively a try statement without a catch
11549 // or a finally block) gives us a place to store values thrown from
11550 // locations where there is no enclosing try statement.
11551 this.tryEntries = [{ tryLoc: "root" }];
11552 tryLocsList.forEach(pushTryEntry, this);
11553 this.reset(true);
11554 }
11555
11556 runtime.keys = function(object) {
11557 var keys = [];
11558 for (var key in object) {
11559 keys.push(key);
11560 }
11561 keys.reverse();
11562
11563 // Rather than returning an object with a next method, we keep
11564 // things simple and return the next function itself.
11565 return function next() {
11566 while (keys.length) {
11567 var key = keys.pop();
11568 if (key in object) {
11569 next.value = key;
11570 next.done = false;
11571 return next;
11572 }
11573 }
11574
11575 // To avoid creating an additional object, we just hang the .value
11576 // and .done properties off the next function object itself. This
11577 // also ensures that the minifier will not anonymize the function.
11578 next.done = true;
11579 return next;
11580 };
11581 };
11582
11583 function values(iterable) {
11584 if (iterable) {
11585 var iteratorMethod = iterable[iteratorSymbol];
11586 if (iteratorMethod) {
11587 return iteratorMethod.call(iterable);
11588 }
11589
11590 if (typeof iterable.next === "function") {
11591 return iterable;
11592 }
11593
11594 if (!isNaN(iterable.length)) {
11595 var i = -1, next = function next() {
11596 while (++i < iterable.length) {
11597 if (hasOwn.call(iterable, i)) {
11598 next.value = iterable[i];
11599 next.done = false;
11600 return next;
11601 }
11602 }
11603
11604 next.value = undefined$1;
11605 next.done = true;
11606
11607 return next;
11608 };
11609
11610 return next.next = next;
11611 }
11612 }
11613
11614 // Return an iterator with no values.
11615 return { next: doneResult };
11616 }
11617 runtime.values = values;
11618
11619 function doneResult() {
11620 return { value: undefined$1, done: true };
11621 }
11622
11623 Context.prototype = {
11624 constructor: Context,
11625
11626 reset: function(skipTempReset) {
11627 this.prev = 0;
11628 this.next = 0;
11629 // Resetting context._sent for legacy support of Babel's
11630 // function.sent implementation.
11631 this.sent = this._sent = undefined$1;
11632 this.done = false;
11633 this.delegate = null;
11634
11635 this.method = "next";
11636 this.arg = undefined$1;
11637
11638 this.tryEntries.forEach(resetTryEntry);
11639
11640 if (!skipTempReset) {
11641 for (var name in this) {
11642 // Not sure about the optimal order of these conditions:
11643 if (name.charAt(0) === "t" &&
11644 hasOwn.call(this, name) &&
11645 !isNaN(+name.slice(1))) {
11646 this[name] = undefined$1;
11647 }
11648 }
11649 }
11650 },
11651
11652 stop: function() {
11653 this.done = true;
11654
11655 var rootEntry = this.tryEntries[0];
11656 var rootRecord = rootEntry.completion;
11657 if (rootRecord.type === "throw") {
11658 throw rootRecord.arg;
11659 }
11660
11661 return this.rval;
11662 },
11663
11664 dispatchException: function(exception) {
11665 if (this.done) {
11666 throw exception;
11667 }
11668
11669 var context = this;
11670 function handle(loc, caught) {
11671 record.type = "throw";
11672 record.arg = exception;
11673 context.next = loc;
11674
11675 if (caught) {
11676 // If the dispatched exception was caught by a catch block,
11677 // then let that catch block handle the exception normally.
11678 context.method = "next";
11679 context.arg = undefined$1;
11680 }
11681
11682 return !! caught;
11683 }
11684
11685 for (var i = this.tryEntries.length - 1; i >= 0; --i) {
11686 var entry = this.tryEntries[i];
11687 var record = entry.completion;
11688
11689 if (entry.tryLoc === "root") {
11690 // Exception thrown outside of any try block that could handle
11691 // it, so set the completion value of the entire function to
11692 // throw the exception.
11693 return handle("end");
11694 }
11695
11696 if (entry.tryLoc <= this.prev) {
11697 var hasCatch = hasOwn.call(entry, "catchLoc");
11698 var hasFinally = hasOwn.call(entry, "finallyLoc");
11699
11700 if (hasCatch && hasFinally) {
11701 if (this.prev < entry.catchLoc) {
11702 return handle(entry.catchLoc, true);
11703 } else if (this.prev < entry.finallyLoc) {
11704 return handle(entry.finallyLoc);
11705 }
11706
11707 } else if (hasCatch) {
11708 if (this.prev < entry.catchLoc) {
11709 return handle(entry.catchLoc, true);
11710 }
11711
11712 } else if (hasFinally) {
11713 if (this.prev < entry.finallyLoc) {
11714 return handle(entry.finallyLoc);
11715 }
11716
11717 } else {
11718 throw new Error("try statement without catch or finally");
11719 }
11720 }
11721 }
11722 },
11723
11724 abrupt: function(type, arg) {
11725 for (var i = this.tryEntries.length - 1; i >= 0; --i) {
11726 var entry = this.tryEntries[i];
11727 if (entry.tryLoc <= this.prev &&
11728 hasOwn.call(entry, "finallyLoc") &&
11729 this.prev < entry.finallyLoc) {
11730 var finallyEntry = entry;
11731 break;
11732 }
11733 }
11734
11735 if (finallyEntry &&
11736 (type === "break" ||
11737 type === "continue") &&
11738 finallyEntry.tryLoc <= arg &&
11739 arg <= finallyEntry.finallyLoc) {
11740 // Ignore the finally entry if control is not jumping to a
11741 // location outside the try/catch block.
11742 finallyEntry = null;
11743 }
11744
11745 var record = finallyEntry ? finallyEntry.completion : {};
11746 record.type = type;
11747 record.arg = arg;
11748
11749 if (finallyEntry) {
11750 this.method = "next";
11751 this.next = finallyEntry.finallyLoc;
11752 return ContinueSentinel;
11753 }
11754
11755 return this.complete(record);
11756 },
11757
11758 complete: function(record, afterLoc) {
11759 if (record.type === "throw") {
11760 throw record.arg;
11761 }
11762
11763 if (record.type === "break" ||
11764 record.type === "continue") {
11765 this.next = record.arg;
11766 } else if (record.type === "return") {
11767 this.rval = this.arg = record.arg;
11768 this.method = "return";
11769 this.next = "end";
11770 } else if (record.type === "normal" && afterLoc) {
11771 this.next = afterLoc;
11772 }
11773
11774 return ContinueSentinel;
11775 },
11776
11777 finish: function(finallyLoc) {
11778 for (var i = this.tryEntries.length - 1; i >= 0; --i) {
11779 var entry = this.tryEntries[i];
11780 if (entry.finallyLoc === finallyLoc) {
11781 this.complete(entry.completion, entry.afterLoc);
11782 resetTryEntry(entry);
11783 return ContinueSentinel;
11784 }
11785 }
11786 },
11787
11788 "catch": function(tryLoc) {
11789 for (var i = this.tryEntries.length - 1; i >= 0; --i) {
11790 var entry = this.tryEntries[i];
11791 if (entry.tryLoc === tryLoc) {
11792 var record = entry.completion;
11793 if (record.type === "throw") {
11794 var thrown = record.arg;
11795 resetTryEntry(entry);
11796 }
11797 return thrown;
11798 }
11799 }
11800
11801 // The context.catch method must only be called with a location
11802 // argument that corresponds to a known catch block.
11803 throw new Error("illegal catch attempt");
11804 },
11805
11806 delegateYield: function(iterable, resultName, nextLoc) {
11807 this.delegate = {
11808 iterator: values(iterable),
11809 resultName: resultName,
11810 nextLoc: nextLoc
11811 };
11812
11813 if (this.method === "next") {
11814 // Deliberately forget the last sent value so that we don't
11815 // accidentally pass it on to the delegate.
11816 this.arg = undefined$1;
11817 }
11818
11819 return ContinueSentinel;
11820 }
11821 };
11822 })(
11823 // In sloppy mode, unbound `this` refers to the global object, fallback to
11824 // Function constructor if we're in global strict mode. That is sadly a form
11825 // of indirect eval which violates Content Security Policy.
11826 (function() {
11827 return this || (typeof self === "object" && self);
11828 })() || Function("return this")()
11829 );
11830 });
11831
11832 /**
11833 * Copyright (c) 2014-present, Facebook, Inc.
11834 *
11835 * This source code is licensed under the MIT license found in the
11836 * LICENSE file in the root directory of this source tree.
11837 */
11838
11839 // This method of obtaining a reference to the global object needs to be
11840 // kept identical to the way it is obtained in runtime.js
11841 var g = (function() {
11842 return this || (typeof self === "object" && self);
11843 })() || Function("return this")();
11844
11845 // Use `getOwnPropertyNames` because not all browsers support calling
11846 // `hasOwnProperty` on the global `self` object in a worker. See #183.
11847 var hadRuntime = g.regeneratorRuntime &&
11848 Object.getOwnPropertyNames(g).indexOf("regeneratorRuntime") >= 0;
11849
11850 // Save the old regeneratorRuntime in case it needs to be restored later.
11851 var oldRuntime = hadRuntime && g.regeneratorRuntime;
11852
11853 // Force reevalutation of runtime.js.
11854 g.regeneratorRuntime = undefined;
11855
11856 var runtimeModule = runtime;
11857
11858 if (hadRuntime) {
11859 // Restore the original runtime.
11860 g.regeneratorRuntime = oldRuntime;
11861 } else {
11862 // Remove the global property added by runtime.js.
11863 try {
11864 delete g.regeneratorRuntime;
11865 } catch(e) {
11866 g.regeneratorRuntime = undefined;
11867 }
11868 }
11869
11870 var regenerator = runtimeModule;
11871
11872 function _typeof(obj) {
11873 if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
11874 _typeof = function (obj) {
11875 return typeof obj;
11876 };
11877 } else {
11878 _typeof = function (obj) {
11879 return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
11880 };
11881 }
11882
11883 return _typeof(obj);
11884 }
11885
11886 function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
11887 try {
11888 var info = gen[key](arg);
11889 var value = info.value;
11890 } catch (error) {
11891 reject(error);
11892 return;
11893 }
11894
11895 if (info.done) {
11896 resolve(value);
11897 } else {
11898 Promise.resolve(value).then(_next, _throw);
11899 }
11900 }
11901
11902 function _asyncToGenerator(fn) {
11903 return function () {
11904 var self = this,
11905 args = arguments;
11906 return new Promise(function (resolve, reject) {
11907 var gen = fn.apply(self, args);
11908
11909 function _next(value) {
11910 asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
11911 }
11912
11913 function _throw(err) {
11914 asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
11915 }
11916
11917 _next(undefined);
11918 });
11919 };
11920 }
11921
11922 function _defineProperties(target, props) {
11923 for (var i = 0; i < props.length; i++) {
11924 var descriptor = props[i];
11925 descriptor.enumerable = descriptor.enumerable || false;
11926 descriptor.configurable = true;
11927 if ("value" in descriptor) descriptor.writable = true;
11928 Object.defineProperty(target, descriptor.key, descriptor);
11929 }
11930 }
11931
11932 function _createClass(Constructor, protoProps, staticProps) {
11933 if (protoProps) _defineProperties(Constructor.prototype, protoProps);
11934 if (staticProps) _defineProperties(Constructor, staticProps);
11935 return Constructor;
11936 }
11937
11938 function _defineProperty(obj, key, value) {
11939 if (key in obj) {
11940 Object.defineProperty(obj, key, {
11941 value: value,
11942 enumerable: true,
11943 configurable: true,
11944 writable: true
11945 });
11946 } else {
11947 obj[key] = value;
11948 }
11949
11950 return obj;
11951 }
11952
11953 function _objectSpread(target) {
11954 for (var i = 1; i < arguments.length; i++) {
11955 var source = arguments[i] != null ? arguments[i] : {};
11956 var ownKeys = Object.keys(source);
11957
11958 if (typeof Object.getOwnPropertySymbols === 'function') {
11959 ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) {
11960 return Object.getOwnPropertyDescriptor(source, sym).enumerable;
11961 }));
11962 }
11963
11964 ownKeys.forEach(function (key) {
11965 _defineProperty(target, key, source[key]);
11966 });
11967 }
11968
11969 return target;
11970 }
11971
11972 function _inheritsLoose(subClass, superClass) {
11973 subClass.prototype = Object.create(superClass.prototype);
11974 subClass.prototype.constructor = subClass;
11975 subClass.__proto__ = superClass;
11976 }
11977
11978 function _objectWithoutPropertiesLoose(source, excluded) {
11979 if (source == null) return {};
11980 var target = {};
11981 var sourceKeys = Object.keys(source);
11982 var key, i;
11983
11984 for (i = 0; i < sourceKeys.length; i++) {
11985 key = sourceKeys[i];
11986 if (excluded.indexOf(key) >= 0) continue;
11987 target[key] = source[key];
11988 }
11989
11990 return target;
11991 }
11992
11993 function _objectWithoutProperties(source, excluded) {
11994 if (source == null) return {};
11995
11996 var target = _objectWithoutPropertiesLoose(source, excluded);
11997
11998 var key, i;
11999
12000 if (Object.getOwnPropertySymbols) {
12001 var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
12002
12003 for (i = 0; i < sourceSymbolKeys.length; i++) {
12004 key = sourceSymbolKeys[i];
12005 if (excluded.indexOf(key) >= 0) continue;
12006 if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
12007 target[key] = source[key];
12008 }
12009 }
12010
12011 return target;
12012 }
12013
12014 function _assertThisInitialized(self) {
12015 if (self === void 0) {
12016 throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
12017 }
12018
12019 return self;
12020 }
12021
12022 function _toArray(arr) {
12023 return _arrayWithHoles(arr) || _iterableToArray(arr) || _nonIterableRest();
12024 }
12025
12026 function _toConsumableArray(arr) {
12027 return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread();
12028 }
12029
12030 function _arrayWithoutHoles(arr) {
12031 if (Array.isArray(arr)) {
12032 for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];
12033
12034 return arr2;
12035 }
12036 }
12037
12038 function _arrayWithHoles(arr) {
12039 if (Array.isArray(arr)) return arr;
12040 }
12041
12042 function _iterableToArray(iter) {
12043 if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter);
12044 }
12045
12046 function _nonIterableSpread() {
12047 throw new TypeError("Invalid attempt to spread non-iterable instance");
12048 }
12049
12050 function _nonIterableRest() {
12051 throw new TypeError("Invalid attempt to destructure non-iterable instance");
12052 }
12053
12054 function _applyDecoratedDescriptor(target, property, decorators, descriptor, context) {
12055 var desc = {};
12056 Object['ke' + 'ys'](descriptor).forEach(function (key) {
12057 desc[key] = descriptor[key];
12058 });
12059 desc.enumerable = !!desc.enumerable;
12060 desc.configurable = !!desc.configurable;
12061
12062 if ('value' in desc || desc.initializer) {
12063 desc.writable = true;
12064 }
12065
12066 desc = decorators.slice().reverse().reduce(function (desc, decorator) {
12067 return decorator(target, property, desc) || desc;
12068 }, desc);
12069
12070 if (context && desc.initializer !== void 0) {
12071 desc.value = desc.initializer ? desc.initializer.call(context) : void 0;
12072 desc.initializer = undefined;
12073 }
12074
12075 if (desc.initializer === void 0) {
12076 Object['define' + 'Property'](target, property, desc);
12077 desc = null;
12078 }
12079
12080 return desc;
12081 }
12082
12083 /**
12084 * Helpers.
12085 */
12086
12087 var s = 1000;
12088 var m = s * 60;
12089 var h = m * 60;
12090 var d = h * 24;
12091 var w = d * 7;
12092 var y = d * 365.25;
12093
12094 /**
12095 * Parse or format the given `val`.
12096 *
12097 * Options:
12098 *
12099 * - `long` verbose formatting [false]
12100 *
12101 * @param {String|Number} val
12102 * @param {Object} [options]
12103 * @throws {Error} throw an error if val is not a non-empty string or a number
12104 * @return {String|Number}
12105 * @api public
12106 */
12107
12108 var ms = function(val, options) {
12109 options = options || {};
12110 var type = typeof val;
12111 if (type === 'string' && val.length > 0) {
12112 return parse(val);
12113 } else if (type === 'number' && isNaN(val) === false) {
12114 return options.long ? fmtLong(val) : fmtShort(val);
12115 }
12116 throw new Error(
12117 'val is not a non-empty string or a valid number. val=' +
12118 JSON.stringify(val)
12119 );
12120 };
12121
12122 /**
12123 * Parse the given `str` and return milliseconds.
12124 *
12125 * @param {String} str
12126 * @return {Number}
12127 * @api private
12128 */
12129
12130 function parse(str) {
12131 str = String(str);
12132 if (str.length > 100) {
12133 return;
12134 }
12135 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(
12136 str
12137 );
12138 if (!match) {
12139 return;
12140 }
12141 var n = parseFloat(match[1]);
12142 var type = (match[2] || 'ms').toLowerCase();
12143 switch (type) {
12144 case 'years':
12145 case 'year':
12146 case 'yrs':
12147 case 'yr':
12148 case 'y':
12149 return n * y;
12150 case 'weeks':
12151 case 'week':
12152 case 'w':
12153 return n * w;
12154 case 'days':
12155 case 'day':
12156 case 'd':
12157 return n * d;
12158 case 'hours':
12159 case 'hour':
12160 case 'hrs':
12161 case 'hr':
12162 case 'h':
12163 return n * h;
12164 case 'minutes':
12165 case 'minute':
12166 case 'mins':
12167 case 'min':
12168 case 'm':
12169 return n * m;
12170 case 'seconds':
12171 case 'second':
12172 case 'secs':
12173 case 'sec':
12174 case 's':
12175 return n * s;
12176 case 'milliseconds':
12177 case 'millisecond':
12178 case 'msecs':
12179 case 'msec':
12180 case 'ms':
12181 return n;
12182 default:
12183 return undefined;
12184 }
12185 }
12186
12187 /**
12188 * Short format for `ms`.
12189 *
12190 * @param {Number} ms
12191 * @return {String}
12192 * @api private
12193 */
12194
12195 function fmtShort(ms) {
12196 var msAbs = Math.abs(ms);
12197 if (msAbs >= d) {
12198 return Math.round(ms / d) + 'd';
12199 }
12200 if (msAbs >= h) {
12201 return Math.round(ms / h) + 'h';
12202 }
12203 if (msAbs >= m) {
12204 return Math.round(ms / m) + 'm';
12205 }
12206 if (msAbs >= s) {
12207 return Math.round(ms / s) + 's';
12208 }
12209 return ms + 'ms';
12210 }
12211
12212 /**
12213 * Long format for `ms`.
12214 *
12215 * @param {Number} ms
12216 * @return {String}
12217 * @api private
12218 */
12219
12220 function fmtLong(ms) {
12221 var msAbs = Math.abs(ms);
12222 if (msAbs >= d) {
12223 return plural(ms, msAbs, d, 'day');
12224 }
12225 if (msAbs >= h) {
12226 return plural(ms, msAbs, h, 'hour');
12227 }
12228 if (msAbs >= m) {
12229 return plural(ms, msAbs, m, 'minute');
12230 }
12231 if (msAbs >= s) {
12232 return plural(ms, msAbs, s, 'second');
12233 }
12234 return ms + ' ms';
12235 }
12236
12237 /**
12238 * Pluralization helper.
12239 */
12240
12241 function plural(ms, msAbs, n, name) {
12242 var isPlural = msAbs >= n * 1.5;
12243 return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');
12244 }
12245
12246 /**
12247 * This is the common logic for both the Node.js and web browser
12248 * implementations of `debug()`.
12249 */
12250 function setup(env) {
12251 createDebug.debug = createDebug;
12252 createDebug.default = createDebug;
12253 createDebug.coerce = coerce;
12254 createDebug.disable = disable;
12255 createDebug.enable = enable;
12256 createDebug.enabled = enabled;
12257 createDebug.humanize = ms;
12258 Object.keys(env).forEach(function (key) {
12259 createDebug[key] = env[key];
12260 });
12261 /**
12262 * Active `debug` instances.
12263 */
12264
12265 createDebug.instances = [];
12266 /**
12267 * The currently active debug mode names, and names to skip.
12268 */
12269
12270 createDebug.names = [];
12271 createDebug.skips = [];
12272 /**
12273 * Map of special "%n" handling functions, for the debug "format" argument.
12274 *
12275 * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
12276 */
12277
12278 createDebug.formatters = {};
12279 /**
12280 * Selects a color for a debug namespace
12281 * @param {String} namespace The namespace string for the for the debug instance to be colored
12282 * @return {Number|String} An ANSI color code for the given namespace
12283 * @api private
12284 */
12285
12286 function selectColor(namespace) {
12287 var hash = 0;
12288
12289 for (var i = 0; i < namespace.length; i++) {
12290 hash = (hash << 5) - hash + namespace.charCodeAt(i);
12291 hash |= 0; // Convert to 32bit integer
12292 }
12293
12294 return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
12295 }
12296
12297 createDebug.selectColor = selectColor;
12298 /**
12299 * Create a debugger with the given `namespace`.
12300 *
12301 * @param {String} namespace
12302 * @return {Function}
12303 * @api public
12304 */
12305
12306 function createDebug(namespace) {
12307 var prevTime;
12308
12309 function debug() {
12310 // Disabled?
12311 if (!debug.enabled) {
12312 return;
12313 }
12314
12315 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
12316 args[_key] = arguments[_key];
12317 }
12318
12319 var self = debug; // Set `diff` timestamp
12320
12321 var curr = Number(new Date());
12322 var ms = curr - (prevTime || curr);
12323 self.diff = ms;
12324 self.prev = prevTime;
12325 self.curr = curr;
12326 prevTime = curr;
12327 args[0] = createDebug.coerce(args[0]);
12328
12329 if (typeof args[0] !== 'string') {
12330 // Anything else let's inspect with %O
12331 args.unshift('%O');
12332 } // Apply any `formatters` transformations
12333
12334
12335 var index = 0;
12336 args[0] = args[0].replace(/%([a-zA-Z%])/g, function (match, format) {
12337 // If we encounter an escaped % then don't increase the array index
12338 if (match === '%%') {
12339 return match;
12340 }
12341
12342 index++;
12343 var formatter = createDebug.formatters[format];
12344
12345 if (typeof formatter === 'function') {
12346 var val = args[index];
12347 match = formatter.call(self, val); // Now we need to remove `args[index]` since it's inlined in the `format`
12348
12349 args.splice(index, 1);
12350 index--;
12351 }
12352
12353 return match;
12354 }); // Apply env-specific formatting (colors, etc.)
12355
12356 createDebug.formatArgs.call(self, args);
12357 var logFn = self.log || createDebug.log;
12358 logFn.apply(self, args);
12359 }
12360
12361 debug.namespace = namespace;
12362 debug.enabled = createDebug.enabled(namespace);
12363 debug.useColors = createDebug.useColors();
12364 debug.color = selectColor(namespace);
12365 debug.destroy = destroy;
12366 debug.extend = extend; // Debug.formatArgs = formatArgs;
12367 // debug.rawLog = rawLog;
12368 // env-specific initialization logic for debug instances
12369
12370 if (typeof createDebug.init === 'function') {
12371 createDebug.init(debug);
12372 }
12373
12374 createDebug.instances.push(debug);
12375 return debug;
12376 }
12377
12378 function destroy() {
12379 var index = createDebug.instances.indexOf(this);
12380
12381 if (index !== -1) {
12382 createDebug.instances.splice(index, 1);
12383 return true;
12384 }
12385
12386 return false;
12387 }
12388
12389 function extend(namespace, delimiter) {
12390 return createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);
12391 }
12392 /**
12393 * Enables a debug mode by namespaces. This can include modes
12394 * separated by a colon and wildcards.
12395 *
12396 * @param {String} namespaces
12397 * @api public
12398 */
12399
12400
12401 function enable(namespaces) {
12402 createDebug.save(namespaces);
12403 createDebug.names = [];
12404 createDebug.skips = [];
12405 var i;
12406 var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
12407 var len = split.length;
12408
12409 for (i = 0; i < len; i++) {
12410 if (!split[i]) {
12411 // ignore empty strings
12412 continue;
12413 }
12414
12415 namespaces = split[i].replace(/\*/g, '.*?');
12416
12417 if (namespaces[0] === '-') {
12418 createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
12419 } else {
12420 createDebug.names.push(new RegExp('^' + namespaces + '$'));
12421 }
12422 }
12423
12424 for (i = 0; i < createDebug.instances.length; i++) {
12425 var instance = createDebug.instances[i];
12426 instance.enabled = createDebug.enabled(instance.namespace);
12427 }
12428 }
12429 /**
12430 * Disable debug output.
12431 *
12432 * @api public
12433 */
12434
12435
12436 function disable() {
12437 createDebug.enable('');
12438 }
12439 /**
12440 * Returns true if the given mode name is enabled, false otherwise.
12441 *
12442 * @param {String} name
12443 * @return {Boolean}
12444 * @api public
12445 */
12446
12447
12448 function enabled(name) {
12449 if (name[name.length - 1] === '*') {
12450 return true;
12451 }
12452
12453 var i;
12454 var len;
12455
12456 for (i = 0, len = createDebug.skips.length; i < len; i++) {
12457 if (createDebug.skips[i].test(name)) {
12458 return false;
12459 }
12460 }
12461
12462 for (i = 0, len = createDebug.names.length; i < len; i++) {
12463 if (createDebug.names[i].test(name)) {
12464 return true;
12465 }
12466 }
12467
12468 return false;
12469 }
12470 /**
12471 * Coerce `val`.
12472 *
12473 * @param {Mixed} val
12474 * @return {Mixed}
12475 * @api private
12476 */
12477
12478
12479 function coerce(val) {
12480 if (val instanceof Error) {
12481 return val.stack || val.message;
12482 }
12483
12484 return val;
12485 }
12486
12487 createDebug.enable(createDebug.load());
12488 return createDebug;
12489 }
12490
12491 var common = setup;
12492
12493 var browser = createCommonjsModule(function (module, exports) {
12494
12495 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); }
12496
12497 /* eslint-env browser */
12498
12499 /**
12500 * This is the web browser implementation of `debug()`.
12501 */
12502 exports.log = log;
12503 exports.formatArgs = formatArgs;
12504 exports.save = save;
12505 exports.load = load;
12506 exports.useColors = useColors;
12507 exports.storage = localstorage();
12508 /**
12509 * Colors.
12510 */
12511
12512 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'];
12513 /**
12514 * Currently only WebKit-based Web Inspectors, Firefox >= v31,
12515 * and the Firebug extension (any Firefox version) are known
12516 * to support "%c" CSS customizations.
12517 *
12518 * TODO: add a `localStorage` variable to explicitly enable/disable colors
12519 */
12520 // eslint-disable-next-line complexity
12521
12522 function useColors() {
12523 // NB: In an Electron preload script, document will be defined but not fully
12524 // initialized. Since we know we're in Chrome, we'll just detect this case
12525 // explicitly
12526 if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {
12527 return true;
12528 } // Internet Explorer and Edge do not support colors.
12529
12530
12531 if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
12532 return false;
12533 } // Is webkit? http://stackoverflow.com/a/16459606/376773
12534 // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
12535
12536
12537 return typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || // Is firebug? http://stackoverflow.com/a/398120/376773
12538 typeof window !== 'undefined' && window.console && (window.console.firebug || window.console.exception && window.console.table) || // Is firefox >= v31?
12539 // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
12540 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
12541 typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/);
12542 }
12543 /**
12544 * Colorize log arguments if enabled.
12545 *
12546 * @api public
12547 */
12548
12549
12550 function formatArgs(args) {
12551 args[0] = (this.useColors ? '%c' : '') + this.namespace + (this.useColors ? ' %c' : ' ') + args[0] + (this.useColors ? '%c ' : ' ') + '+' + module.exports.humanize(this.diff);
12552
12553 if (!this.useColors) {
12554 return;
12555 }
12556
12557 var c = 'color: ' + this.color;
12558 args.splice(1, 0, c, 'color: inherit'); // The final "%c" is somewhat tricky, because there could be other
12559 // arguments passed either before or after the %c, so we need to
12560 // figure out the correct index to insert the CSS into
12561
12562 var index = 0;
12563 var lastC = 0;
12564 args[0].replace(/%[a-zA-Z%]/g, function (match) {
12565 if (match === '%%') {
12566 return;
12567 }
12568
12569 index++;
12570
12571 if (match === '%c') {
12572 // We only are interested in the *last* %c
12573 // (the user may have provided their own)
12574 lastC = index;
12575 }
12576 });
12577 args.splice(lastC, 0, c);
12578 }
12579 /**
12580 * Invokes `console.log()` when available.
12581 * No-op when `console.log` is not a "function".
12582 *
12583 * @api public
12584 */
12585
12586
12587 function log() {
12588 var _console;
12589
12590 // This hackery is required for IE8/9, where
12591 // the `console.log` function doesn't have 'apply'
12592 return (typeof console === "undefined" ? "undefined" : _typeof(console)) === 'object' && console.log && (_console = console).log.apply(_console, arguments);
12593 }
12594 /**
12595 * Save `namespaces`.
12596 *
12597 * @param {String} namespaces
12598 * @api private
12599 */
12600
12601
12602 function save(namespaces) {
12603 try {
12604 if (namespaces) {
12605 exports.storage.setItem('debug', namespaces);
12606 } else {
12607 exports.storage.removeItem('debug');
12608 }
12609 } catch (error) {// Swallow
12610 // XXX (@Qix-) should we be logging these?
12611 }
12612 }
12613 /**
12614 * Load `namespaces`.
12615 *
12616 * @return {String} returns the previously persisted debug modes
12617 * @api private
12618 */
12619
12620
12621 function load() {
12622 var r;
12623
12624 try {
12625 r = exports.storage.getItem('debug');
12626 } catch (error) {} // Swallow
12627 // XXX (@Qix-) should we be logging these?
12628 // If debug isn't set in LS, and we're in Electron, try to load $DEBUG
12629
12630
12631 if (!r && typeof process !== 'undefined' && 'env' in process) {
12632 r = process.env.DEBUG;
12633 }
12634
12635 return r;
12636 }
12637 /**
12638 * Localstorage attempts to return the localstorage.
12639 *
12640 * This is necessary because safari throws
12641 * when a user disables cookies/localstorage
12642 * and you attempt to access it.
12643 *
12644 * @return {LocalStorage}
12645 * @api private
12646 */
12647
12648
12649 function localstorage() {
12650 try {
12651 // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context
12652 // The Browser also has localStorage in the global context.
12653 return localStorage;
12654 } catch (error) {// Swallow
12655 // XXX (@Qix-) should we be logging these?
12656 }
12657 }
12658
12659 module.exports = common(exports);
12660 var formatters = module.exports.formatters;
12661 /**
12662 * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
12663 */
12664
12665 formatters.j = function (v) {
12666 try {
12667 return JSON.stringify(v);
12668 } catch (error) {
12669 return '[UnexpectedJSONParseError]: ' + error.message;
12670 }
12671 };
12672 });
12673 var browser_1 = browser.log;
12674 var browser_2 = browser.formatArgs;
12675 var browser_3 = browser.save;
12676 var browser_4 = browser.load;
12677 var browser_5 = browser.useColors;
12678 var browser_6 = browser.storage;
12679 var browser_7 = browser.colors;
12680
12681 var componentEmitter = createCommonjsModule(function (module) {
12682 /**
12683 * Expose `Emitter`.
12684 */
12685 {
12686 module.exports = Emitter;
12687 }
12688 /**
12689 * Initialize a new `Emitter`.
12690 *
12691 * @api public
12692 */
12693
12694
12695 function Emitter(obj) {
12696 if (obj) return mixin(obj);
12697 }
12698 /**
12699 * Mixin the emitter properties.
12700 *
12701 * @param {Object} obj
12702 * @return {Object}
12703 * @api private
12704 */
12705
12706 function mixin(obj) {
12707 for (var key in Emitter.prototype) {
12708 obj[key] = Emitter.prototype[key];
12709 }
12710
12711 return obj;
12712 }
12713 /**
12714 * Listen on the given `event` with `fn`.
12715 *
12716 * @param {String} event
12717 * @param {Function} fn
12718 * @return {Emitter}
12719 * @api public
12720 */
12721
12722
12723 Emitter.prototype.on = Emitter.prototype.addEventListener = function (event, fn) {
12724 this._callbacks = this._callbacks || {};
12725 (this._callbacks['$' + event] = this._callbacks['$' + event] || []).push(fn);
12726 return this;
12727 };
12728 /**
12729 * Adds an `event` listener that will be invoked a single
12730 * time then automatically removed.
12731 *
12732 * @param {String} event
12733 * @param {Function} fn
12734 * @return {Emitter}
12735 * @api public
12736 */
12737
12738
12739 Emitter.prototype.once = function (event, fn) {
12740 function on() {
12741 this.off(event, on);
12742 fn.apply(this, arguments);
12743 }
12744
12745 on.fn = fn;
12746 this.on(event, on);
12747 return this;
12748 };
12749 /**
12750 * Remove the given callback for `event` or all
12751 * registered callbacks.
12752 *
12753 * @param {String} event
12754 * @param {Function} fn
12755 * @return {Emitter}
12756 * @api public
12757 */
12758
12759
12760 Emitter.prototype.off = Emitter.prototype.removeListener = Emitter.prototype.removeAllListeners = Emitter.prototype.removeEventListener = function (event, fn) {
12761 this._callbacks = this._callbacks || {}; // all
12762
12763 if (0 == arguments.length) {
12764 this._callbacks = {};
12765 return this;
12766 } // specific event
12767
12768
12769 var callbacks = this._callbacks['$' + event];
12770 if (!callbacks) return this; // remove all handlers
12771
12772 if (1 == arguments.length) {
12773 delete this._callbacks['$' + event];
12774 return this;
12775 } // remove specific handler
12776
12777
12778 var cb;
12779
12780 for (var i = 0; i < callbacks.length; i++) {
12781 cb = callbacks[i];
12782
12783 if (cb === fn || cb.fn === fn) {
12784 callbacks.splice(i, 1);
12785 break;
12786 }
12787 } // Remove event specific arrays for event types that no
12788 // one is subscribed for to avoid memory leak.
12789
12790
12791 if (callbacks.length === 0) {
12792 delete this._callbacks['$' + event];
12793 }
12794
12795 return this;
12796 };
12797 /**
12798 * Emit `event` with the given args.
12799 *
12800 * @param {String} event
12801 * @param {Mixed} ...
12802 * @return {Emitter}
12803 */
12804
12805
12806 Emitter.prototype.emit = function (event) {
12807 this._callbacks = this._callbacks || {};
12808 var args = new Array(arguments.length - 1),
12809 callbacks = this._callbacks['$' + event];
12810
12811 for (var i = 1; i < arguments.length; i++) {
12812 args[i - 1] = arguments[i];
12813 }
12814
12815 if (callbacks) {
12816 callbacks = callbacks.slice(0);
12817
12818 for (var i = 0, len = callbacks.length; i < len; ++i) {
12819 callbacks[i].apply(this, args);
12820 }
12821 }
12822
12823 return this;
12824 };
12825 /**
12826 * Return array of callbacks for `event`.
12827 *
12828 * @param {String} event
12829 * @return {Array}
12830 * @api public
12831 */
12832
12833
12834 Emitter.prototype.listeners = function (event) {
12835 this._callbacks = this._callbacks || {};
12836 return this._callbacks['$' + event] || [];
12837 };
12838 /**
12839 * Check if this emitter has `event` handlers.
12840 *
12841 * @param {String} event
12842 * @return {Boolean}
12843 * @api public
12844 */
12845
12846
12847 Emitter.prototype.hasListeners = function (event) {
12848 return !!this.listeners(event).length;
12849 };
12850 });
12851
12852 var fastSafeStringify = stringify;
12853 stringify.default = stringify;
12854 stringify.stable = deterministicStringify;
12855 stringify.stableStringify = deterministicStringify;
12856
12857 var arr = [];
12858 var replacerStack = [];
12859
12860 // Regular stringify
12861 function stringify (obj, replacer, spacer) {
12862 decirc(obj, '', [], undefined);
12863 var res;
12864 if (replacerStack.length === 0) {
12865 res = JSON.stringify(obj, replacer, spacer);
12866 } else {
12867 res = JSON.stringify(obj, replaceGetterValues(replacer), spacer);
12868 }
12869 while (arr.length !== 0) {
12870 var part = arr.pop();
12871 if (part.length === 4) {
12872 Object.defineProperty(part[0], part[1], part[3]);
12873 } else {
12874 part[0][part[1]] = part[2];
12875 }
12876 }
12877 return res
12878 }
12879 function decirc (val, k, stack, parent) {
12880 var i;
12881 if (typeof val === 'object' && val !== null) {
12882 for (i = 0; i < stack.length; i++) {
12883 if (stack[i] === val) {
12884 var propertyDescriptor = Object.getOwnPropertyDescriptor(parent, k);
12885 if (propertyDescriptor.get !== undefined) {
12886 if (propertyDescriptor.configurable) {
12887 Object.defineProperty(parent, k, { value: '[Circular]' });
12888 arr.push([parent, k, val, propertyDescriptor]);
12889 } else {
12890 replacerStack.push([val, k]);
12891 }
12892 } else {
12893 parent[k] = '[Circular]';
12894 arr.push([parent, k, val]);
12895 }
12896 return
12897 }
12898 }
12899 stack.push(val);
12900 // Optimize for Arrays. Big arrays could kill the performance otherwise!
12901 if (Array.isArray(val)) {
12902 for (i = 0; i < val.length; i++) {
12903 decirc(val[i], i, stack, val);
12904 }
12905 } else {
12906 var keys = Object.keys(val);
12907 for (i = 0; i < keys.length; i++) {
12908 var key = keys[i];
12909 decirc(val[key], key, stack, val);
12910 }
12911 }
12912 stack.pop();
12913 }
12914 }
12915
12916 // Stable-stringify
12917 function compareFunction (a, b) {
12918 if (a < b) {
12919 return -1
12920 }
12921 if (a > b) {
12922 return 1
12923 }
12924 return 0
12925 }
12926
12927 function deterministicStringify (obj, replacer, spacer) {
12928 var tmp = deterministicDecirc(obj, '', [], undefined) || obj;
12929 var res;
12930 if (replacerStack.length === 0) {
12931 res = JSON.stringify(tmp, replacer, spacer);
12932 } else {
12933 res = JSON.stringify(tmp, replaceGetterValues(replacer), spacer);
12934 }
12935 while (arr.length !== 0) {
12936 var part = arr.pop();
12937 if (part.length === 4) {
12938 Object.defineProperty(part[0], part[1], part[3]);
12939 } else {
12940 part[0][part[1]] = part[2];
12941 }
12942 }
12943 return res
12944 }
12945
12946 function deterministicDecirc (val, k, stack, parent) {
12947 var i;
12948 if (typeof val === 'object' && val !== null) {
12949 for (i = 0; i < stack.length; i++) {
12950 if (stack[i] === val) {
12951 var propertyDescriptor = Object.getOwnPropertyDescriptor(parent, k);
12952 if (propertyDescriptor.get !== undefined) {
12953 if (propertyDescriptor.configurable) {
12954 Object.defineProperty(parent, k, { value: '[Circular]' });
12955 arr.push([parent, k, val, propertyDescriptor]);
12956 } else {
12957 replacerStack.push([val, k]);
12958 }
12959 } else {
12960 parent[k] = '[Circular]';
12961 arr.push([parent, k, val]);
12962 }
12963 return
12964 }
12965 }
12966 if (typeof val.toJSON === 'function') {
12967 return
12968 }
12969 stack.push(val);
12970 // Optimize for Arrays. Big arrays could kill the performance otherwise!
12971 if (Array.isArray(val)) {
12972 for (i = 0; i < val.length; i++) {
12973 deterministicDecirc(val[i], i, stack, val);
12974 }
12975 } else {
12976 // Create a temporary object in the required way
12977 var tmp = {};
12978 var keys = Object.keys(val).sort(compareFunction);
12979 for (i = 0; i < keys.length; i++) {
12980 var key = keys[i];
12981 deterministicDecirc(val[key], key, stack, val);
12982 tmp[key] = val[key];
12983 }
12984 if (parent !== undefined) {
12985 arr.push([parent, k, val]);
12986 parent[k] = tmp;
12987 } else {
12988 return tmp
12989 }
12990 }
12991 stack.pop();
12992 }
12993 }
12994
12995 // wraps replacer function to handle values we couldn't replace
12996 // and mark them as [Circular]
12997 function replaceGetterValues (replacer) {
12998 replacer = replacer !== undefined ? replacer : function (k, v) { return v };
12999 return function (key, val) {
13000 if (replacerStack.length > 0) {
13001 for (var i = 0; i < replacerStack.length; i++) {
13002 var part = replacerStack[i];
13003 if (part[1] === key && part[0] === val) {
13004 val = '[Circular]';
13005 replacerStack.splice(i, 1);
13006 break
13007 }
13008 }
13009 }
13010 return replacer.call(this, key, val)
13011 }
13012 }
13013
13014 function _typeof$1(obj) {
13015 if (typeof Symbol === "function" && _typeof(Symbol.iterator) === "symbol") {
13016 _typeof$1 = function _typeof$1(obj) {
13017 return _typeof(obj);
13018 };
13019 } else {
13020 _typeof$1 = function _typeof$1(obj) {
13021 return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : _typeof(obj);
13022 };
13023 }
13024
13025 return _typeof$1(obj);
13026 }
13027 /**
13028 * Check if `obj` is an object.
13029 *
13030 * @param {Object} obj
13031 * @return {Boolean}
13032 * @api private
13033 */
13034
13035
13036 function isObject(obj) {
13037 return obj !== null && _typeof$1(obj) === 'object';
13038 }
13039
13040 var isObject_1 = isObject;
13041
13042 function _typeof$2(obj) {
13043 if (typeof Symbol === "function" && _typeof(Symbol.iterator) === "symbol") {
13044 _typeof$2 = function _typeof$1(obj) {
13045 return _typeof(obj);
13046 };
13047 } else {
13048 _typeof$2 = function _typeof$1(obj) {
13049 return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : _typeof(obj);
13050 };
13051 }
13052
13053 return _typeof$2(obj);
13054 }
13055 /**
13056 * Module of mixed-in functions shared between node and client code
13057 */
13058
13059 /**
13060 * Expose `RequestBase`.
13061 */
13062
13063
13064 var requestBase = RequestBase;
13065 /**
13066 * Initialize a new `RequestBase`.
13067 *
13068 * @api public
13069 */
13070
13071 function RequestBase(obj) {
13072 if (obj) return mixin(obj);
13073 }
13074 /**
13075 * Mixin the prototype properties.
13076 *
13077 * @param {Object} obj
13078 * @return {Object}
13079 * @api private
13080 */
13081
13082
13083 function mixin(obj) {
13084 for (var key in RequestBase.prototype) {
13085 if (Object.prototype.hasOwnProperty.call(RequestBase.prototype, key)) obj[key] = RequestBase.prototype[key];
13086 }
13087
13088 return obj;
13089 }
13090 /**
13091 * Clear previous timeout.
13092 *
13093 * @return {Request} for chaining
13094 * @api public
13095 */
13096
13097
13098 RequestBase.prototype.clearTimeout = function () {
13099 clearTimeout(this._timer);
13100 clearTimeout(this._responseTimeoutTimer);
13101 clearTimeout(this._uploadTimeoutTimer);
13102 delete this._timer;
13103 delete this._responseTimeoutTimer;
13104 delete this._uploadTimeoutTimer;
13105 return this;
13106 };
13107 /**
13108 * Override default response body parser
13109 *
13110 * This function will be called to convert incoming data into request.body
13111 *
13112 * @param {Function}
13113 * @api public
13114 */
13115
13116
13117 RequestBase.prototype.parse = function (fn) {
13118 this._parser = fn;
13119 return this;
13120 };
13121 /**
13122 * Set format of binary response body.
13123 * In browser valid formats are 'blob' and 'arraybuffer',
13124 * which return Blob and ArrayBuffer, respectively.
13125 *
13126 * In Node all values result in Buffer.
13127 *
13128 * Examples:
13129 *
13130 * req.get('/')
13131 * .responseType('blob')
13132 * .end(callback);
13133 *
13134 * @param {String} val
13135 * @return {Request} for chaining
13136 * @api public
13137 */
13138
13139
13140 RequestBase.prototype.responseType = function (val) {
13141 this._responseType = val;
13142 return this;
13143 };
13144 /**
13145 * Override default request body serializer
13146 *
13147 * This function will be called to convert data set via .send or .attach into payload to send
13148 *
13149 * @param {Function}
13150 * @api public
13151 */
13152
13153
13154 RequestBase.prototype.serialize = function (fn) {
13155 this._serializer = fn;
13156 return this;
13157 };
13158 /**
13159 * Set timeouts.
13160 *
13161 * - response timeout is time between sending request and receiving the first byte of the response. Includes DNS and connection time.
13162 * - 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.
13163 * - upload is the time since last bit of data was sent or received. This timeout works only if deadline timeout is off
13164 *
13165 * Value of 0 or false means no timeout.
13166 *
13167 * @param {Number|Object} ms or {response, deadline}
13168 * @return {Request} for chaining
13169 * @api public
13170 */
13171
13172
13173 RequestBase.prototype.timeout = function (options) {
13174 if (!options || _typeof$2(options) !== 'object') {
13175 this._timeout = options;
13176 this._responseTimeout = 0;
13177 this._uploadTimeout = 0;
13178 return this;
13179 }
13180
13181 for (var option in options) {
13182 if (Object.prototype.hasOwnProperty.call(options, option)) {
13183 switch (option) {
13184 case 'deadline':
13185 this._timeout = options.deadline;
13186 break;
13187
13188 case 'response':
13189 this._responseTimeout = options.response;
13190 break;
13191
13192 case 'upload':
13193 this._uploadTimeout = options.upload;
13194 break;
13195
13196 default:
13197 console.warn('Unknown timeout option', option);
13198 }
13199 }
13200 }
13201
13202 return this;
13203 };
13204 /**
13205 * Set number of retry attempts on error.
13206 *
13207 * Failed requests will be retried 'count' times if timeout or err.code >= 500.
13208 *
13209 * @param {Number} count
13210 * @param {Function} [fn]
13211 * @return {Request} for chaining
13212 * @api public
13213 */
13214
13215
13216 RequestBase.prototype.retry = function (count, fn) {
13217 // Default to 1 if no count passed or true
13218 if (arguments.length === 0 || count === true) count = 1;
13219 if (count <= 0) count = 0;
13220 this._maxRetries = count;
13221 this._retries = 0;
13222 this._retryCallback = fn;
13223 return this;
13224 };
13225
13226 var ERROR_CODES = ['ECONNRESET', 'ETIMEDOUT', 'EADDRINFO', 'ESOCKETTIMEDOUT'];
13227 /**
13228 * Determine if a request should be retried.
13229 * (Borrowed from segmentio/superagent-retry)
13230 *
13231 * @param {Error} err an error
13232 * @param {Response} [res] response
13233 * @returns {Boolean} if segment should be retried
13234 */
13235
13236 RequestBase.prototype._shouldRetry = function (err, res) {
13237 if (!this._maxRetries || this._retries++ >= this._maxRetries) {
13238 return false;
13239 }
13240
13241 if (this._retryCallback) {
13242 try {
13243 var override = this._retryCallback(err, res);
13244
13245 if (override === true) return true;
13246 if (override === false) return false; // undefined falls back to defaults
13247 } catch (err2) {
13248 console.error(err2);
13249 }
13250 }
13251
13252 if (res && res.status && res.status >= 500 && res.status !== 501) return true;
13253
13254 if (err) {
13255 if (err.code && ERROR_CODES.indexOf(err.code) !== -1) return true; // Superagent timeout
13256
13257 if (err.timeout && err.code === 'ECONNABORTED') return true;
13258 if (err.crossDomain) return true;
13259 }
13260
13261 return false;
13262 };
13263 /**
13264 * Retry request
13265 *
13266 * @return {Request} for chaining
13267 * @api private
13268 */
13269
13270
13271 RequestBase.prototype._retry = function () {
13272 this.clearTimeout(); // node
13273
13274 if (this.req) {
13275 this.req = null;
13276 this.req = this.request();
13277 }
13278
13279 this._aborted = false;
13280 this.timedout = false;
13281 return this._end();
13282 };
13283 /**
13284 * Promise support
13285 *
13286 * @param {Function} resolve
13287 * @param {Function} [reject]
13288 * @return {Request}
13289 */
13290
13291
13292 RequestBase.prototype.then = function (resolve, reject) {
13293 var _this = this;
13294
13295 if (!this._fullfilledPromise) {
13296 var self = this;
13297
13298 if (this._endCalled) {
13299 console.warn('Warning: superagent request was sent twice, because both .end() and .then() were called. Never call .end() if you use promises');
13300 }
13301
13302 this._fullfilledPromise = new Promise(function (resolve, reject) {
13303 self.on('abort', function () {
13304 var err = new Error('Aborted');
13305 err.code = 'ABORTED';
13306 err.status = _this.status;
13307 err.method = _this.method;
13308 err.url = _this.url;
13309 reject(err);
13310 });
13311 self.end(function (err, res) {
13312 if (err) reject(err);else resolve(res);
13313 });
13314 });
13315 }
13316
13317 return this._fullfilledPromise.then(resolve, reject);
13318 };
13319
13320 RequestBase.prototype.catch = function (cb) {
13321 return this.then(undefined, cb);
13322 };
13323 /**
13324 * Allow for extension
13325 */
13326
13327
13328 RequestBase.prototype.use = function (fn) {
13329 fn(this);
13330 return this;
13331 };
13332
13333 RequestBase.prototype.ok = function (cb) {
13334 if (typeof cb !== 'function') throw new Error('Callback required');
13335 this._okCallback = cb;
13336 return this;
13337 };
13338
13339 RequestBase.prototype._isResponseOK = function (res) {
13340 if (!res) {
13341 return false;
13342 }
13343
13344 if (this._okCallback) {
13345 return this._okCallback(res);
13346 }
13347
13348 return res.status >= 200 && res.status < 300;
13349 };
13350 /**
13351 * Get request header `field`.
13352 * Case-insensitive.
13353 *
13354 * @param {String} field
13355 * @return {String}
13356 * @api public
13357 */
13358
13359
13360 RequestBase.prototype.get = function (field) {
13361 return this._header[field.toLowerCase()];
13362 };
13363 /**
13364 * Get case-insensitive header `field` value.
13365 * This is a deprecated internal API. Use `.get(field)` instead.
13366 *
13367 * (getHeader is no longer used internally by the superagent code base)
13368 *
13369 * @param {String} field
13370 * @return {String}
13371 * @api private
13372 * @deprecated
13373 */
13374
13375
13376 RequestBase.prototype.getHeader = RequestBase.prototype.get;
13377 /**
13378 * Set header `field` to `val`, or multiple fields with one object.
13379 * Case-insensitive.
13380 *
13381 * Examples:
13382 *
13383 * req.get('/')
13384 * .set('Accept', 'application/json')
13385 * .set('X-API-Key', 'foobar')
13386 * .end(callback);
13387 *
13388 * req.get('/')
13389 * .set({ Accept: 'application/json', 'X-API-Key': 'foobar' })
13390 * .end(callback);
13391 *
13392 * @param {String|Object} field
13393 * @param {String} val
13394 * @return {Request} for chaining
13395 * @api public
13396 */
13397
13398 RequestBase.prototype.set = function (field, val) {
13399 if (isObject_1(field)) {
13400 for (var key in field) {
13401 if (Object.prototype.hasOwnProperty.call(field, key)) this.set(key, field[key]);
13402 }
13403
13404 return this;
13405 }
13406
13407 this._header[field.toLowerCase()] = val;
13408 this.header[field] = val;
13409 return this;
13410 }; // eslint-disable-next-line valid-jsdoc
13411
13412 /**
13413 * Remove header `field`.
13414 * Case-insensitive.
13415 *
13416 * Example:
13417 *
13418 * req.get('/')
13419 * .unset('User-Agent')
13420 * .end(callback);
13421 *
13422 * @param {String} field field name
13423 */
13424
13425
13426 RequestBase.prototype.unset = function (field) {
13427 delete this._header[field.toLowerCase()];
13428 delete this.header[field];
13429 return this;
13430 };
13431 /**
13432 * Write the field `name` and `val`, or multiple fields with one object
13433 * for "multipart/form-data" request bodies.
13434 *
13435 * ``` js
13436 * request.post('/upload')
13437 * .field('foo', 'bar')
13438 * .end(callback);
13439 *
13440 * request.post('/upload')
13441 * .field({ foo: 'bar', baz: 'qux' })
13442 * .end(callback);
13443 * ```
13444 *
13445 * @param {String|Object} name name of field
13446 * @param {String|Blob|File|Buffer|fs.ReadStream} val value of field
13447 * @return {Request} for chaining
13448 * @api public
13449 */
13450
13451
13452 RequestBase.prototype.field = function (name, val) {
13453 // name should be either a string or an object.
13454 if (name === null || undefined === name) {
13455 throw new Error('.field(name, val) name can not be empty');
13456 }
13457
13458 if (this._data) {
13459 throw new Error(".field() can't be used if .send() is used. Please use only .send() or only .field() & .attach()");
13460 }
13461
13462 if (isObject_1(name)) {
13463 for (var key in name) {
13464 if (Object.prototype.hasOwnProperty.call(name, key)) this.field(key, name[key]);
13465 }
13466
13467 return this;
13468 }
13469
13470 if (Array.isArray(val)) {
13471 for (var i in val) {
13472 if (Object.prototype.hasOwnProperty.call(val, i)) this.field(name, val[i]);
13473 }
13474
13475 return this;
13476 } // val should be defined now
13477
13478
13479 if (val === null || undefined === val) {
13480 throw new Error('.field(name, val) val can not be empty');
13481 }
13482
13483 if (typeof val === 'boolean') {
13484 val = String(val);
13485 }
13486
13487 this._getFormData().append(name, val);
13488
13489 return this;
13490 };
13491 /**
13492 * Abort the request, and clear potential timeout.
13493 *
13494 * @return {Request} request
13495 * @api public
13496 */
13497
13498
13499 RequestBase.prototype.abort = function () {
13500 if (this._aborted) {
13501 return this;
13502 }
13503
13504 this._aborted = true;
13505 if (this.xhr) this.xhr.abort(); // browser
13506
13507 if (this.req) this.req.abort(); // node
13508
13509 this.clearTimeout();
13510 this.emit('abort');
13511 return this;
13512 };
13513
13514 RequestBase.prototype._auth = function (user, pass, options, base64Encoder) {
13515 switch (options.type) {
13516 case 'basic':
13517 this.set('Authorization', "Basic ".concat(base64Encoder("".concat(user, ":").concat(pass))));
13518 break;
13519
13520 case 'auto':
13521 this.username = user;
13522 this.password = pass;
13523 break;
13524
13525 case 'bearer':
13526 // usage would be .auth(accessToken, { type: 'bearer' })
13527 this.set('Authorization', "Bearer ".concat(user));
13528 break;
13529
13530 default:
13531 break;
13532 }
13533
13534 return this;
13535 };
13536 /**
13537 * Enable transmission of cookies with x-domain requests.
13538 *
13539 * Note that for this to work the origin must not be
13540 * using "Access-Control-Allow-Origin" with a wildcard,
13541 * and also must set "Access-Control-Allow-Credentials"
13542 * to "true".
13543 *
13544 * @api public
13545 */
13546
13547
13548 RequestBase.prototype.withCredentials = function (on) {
13549 // This is browser-only functionality. Node side is no-op.
13550 if (on === undefined) on = true;
13551 this._withCredentials = on;
13552 return this;
13553 };
13554 /**
13555 * Set the max redirects to `n`. Does nothing in browser XHR implementation.
13556 *
13557 * @param {Number} n
13558 * @return {Request} for chaining
13559 * @api public
13560 */
13561
13562
13563 RequestBase.prototype.redirects = function (n) {
13564 this._maxRedirects = n;
13565 return this;
13566 };
13567 /**
13568 * Maximum size of buffered response body, in bytes. Counts uncompressed size.
13569 * Default 200MB.
13570 *
13571 * @param {Number} n number of bytes
13572 * @return {Request} for chaining
13573 */
13574
13575
13576 RequestBase.prototype.maxResponseSize = function (n) {
13577 if (typeof n !== 'number') {
13578 throw new TypeError('Invalid argument');
13579 }
13580
13581 this._maxResponseSize = n;
13582 return this;
13583 };
13584 /**
13585 * Convert to a plain javascript object (not JSON string) of scalar properties.
13586 * Note as this method is designed to return a useful non-this value,
13587 * it cannot be chained.
13588 *
13589 * @return {Object} describing method, url, and data of this request
13590 * @api public
13591 */
13592
13593
13594 RequestBase.prototype.toJSON = function () {
13595 return {
13596 method: this.method,
13597 url: this.url,
13598 data: this._data,
13599 headers: this._header
13600 };
13601 };
13602 /**
13603 * Send `data` as the request body, defaulting the `.type()` to "json" when
13604 * an object is given.
13605 *
13606 * Examples:
13607 *
13608 * // manual json
13609 * request.post('/user')
13610 * .type('json')
13611 * .send('{"name":"tj"}')
13612 * .end(callback)
13613 *
13614 * // auto json
13615 * request.post('/user')
13616 * .send({ name: 'tj' })
13617 * .end(callback)
13618 *
13619 * // manual x-www-form-urlencoded
13620 * request.post('/user')
13621 * .type('form')
13622 * .send('name=tj')
13623 * .end(callback)
13624 *
13625 * // auto x-www-form-urlencoded
13626 * request.post('/user')
13627 * .type('form')
13628 * .send({ name: 'tj' })
13629 * .end(callback)
13630 *
13631 * // defaults to x-www-form-urlencoded
13632 * request.post('/user')
13633 * .send('name=tobi')
13634 * .send('species=ferret')
13635 * .end(callback)
13636 *
13637 * @param {String|Object} data
13638 * @return {Request} for chaining
13639 * @api public
13640 */
13641 // eslint-disable-next-line complexity
13642
13643
13644 RequestBase.prototype.send = function (data) {
13645 var isObj = isObject_1(data);
13646 var type = this._header['content-type'];
13647
13648 if (this._formData) {
13649 throw new Error(".send() can't be used if .attach() or .field() is used. Please use only .send() or only .field() & .attach()");
13650 }
13651
13652 if (isObj && !this._data) {
13653 if (Array.isArray(data)) {
13654 this._data = [];
13655 } else if (!this._isHost(data)) {
13656 this._data = {};
13657 }
13658 } else if (data && this._data && this._isHost(this._data)) {
13659 throw new Error("Can't merge these send calls");
13660 } // merge
13661
13662
13663 if (isObj && isObject_1(this._data)) {
13664 for (var key in data) {
13665 if (Object.prototype.hasOwnProperty.call(data, key)) this._data[key] = data[key];
13666 }
13667 } else if (typeof data === 'string') {
13668 // default to x-www-form-urlencoded
13669 if (!type) this.type('form');
13670 type = this._header['content-type'];
13671
13672 if (type === 'application/x-www-form-urlencoded') {
13673 this._data = this._data ? "".concat(this._data, "&").concat(data) : data;
13674 } else {
13675 this._data = (this._data || '') + data;
13676 }
13677 } else {
13678 this._data = data;
13679 }
13680
13681 if (!isObj || this._isHost(data)) {
13682 return this;
13683 } // default to json
13684
13685
13686 if (!type) this.type('json');
13687 return this;
13688 };
13689 /**
13690 * Sort `querystring` by the sort function
13691 *
13692 *
13693 * Examples:
13694 *
13695 * // default order
13696 * request.get('/user')
13697 * .query('name=Nick')
13698 * .query('search=Manny')
13699 * .sortQuery()
13700 * .end(callback)
13701 *
13702 * // customized sort function
13703 * request.get('/user')
13704 * .query('name=Nick')
13705 * .query('search=Manny')
13706 * .sortQuery(function(a, b){
13707 * return a.length - b.length;
13708 * })
13709 * .end(callback)
13710 *
13711 *
13712 * @param {Function} sort
13713 * @return {Request} for chaining
13714 * @api public
13715 */
13716
13717
13718 RequestBase.prototype.sortQuery = function (sort) {
13719 // _sort default to true but otherwise can be a function or boolean
13720 this._sort = typeof sort === 'undefined' ? true : sort;
13721 return this;
13722 };
13723 /**
13724 * Compose querystring to append to req.url
13725 *
13726 * @api private
13727 */
13728
13729
13730 RequestBase.prototype._finalizeQueryString = function () {
13731 var query = this._query.join('&');
13732
13733 if (query) {
13734 this.url += (this.url.indexOf('?') >= 0 ? '&' : '?') + query;
13735 }
13736
13737 this._query.length = 0; // Makes the call idempotent
13738
13739 if (this._sort) {
13740 var index = this.url.indexOf('?');
13741
13742 if (index >= 0) {
13743 var queryArr = this.url.substring(index + 1).split('&');
13744
13745 if (typeof this._sort === 'function') {
13746 queryArr.sort(this._sort);
13747 } else {
13748 queryArr.sort();
13749 }
13750
13751 this.url = this.url.substring(0, index) + '?' + queryArr.join('&');
13752 }
13753 }
13754 }; // For backwards compat only
13755
13756
13757 RequestBase.prototype._appendQueryString = function () {
13758 console.warn('Unsupported');
13759 };
13760 /**
13761 * Invoke callback with timeout error.
13762 *
13763 * @api private
13764 */
13765
13766
13767 RequestBase.prototype._timeoutError = function (reason, timeout, errno) {
13768 if (this._aborted) {
13769 return;
13770 }
13771
13772 var err = new Error("".concat(reason + timeout, "ms exceeded"));
13773 err.timeout = timeout;
13774 err.code = 'ECONNABORTED';
13775 err.errno = errno;
13776 this.timedout = true;
13777 this.abort();
13778 this.callback(err);
13779 };
13780
13781 RequestBase.prototype._setTimeouts = function () {
13782 var self = this; // deadline
13783
13784 if (this._timeout && !this._timer) {
13785 this._timer = setTimeout(function () {
13786 self._timeoutError('Timeout of ', self._timeout, 'ETIME');
13787 }, this._timeout);
13788 } // response timeout
13789
13790
13791 if (this._responseTimeout && !this._responseTimeoutTimer) {
13792 this._responseTimeoutTimer = setTimeout(function () {
13793 self._timeoutError('Response timeout of ', self._responseTimeout, 'ETIMEDOUT');
13794 }, this._responseTimeout);
13795 }
13796 };
13797
13798 /**
13799 * Return the mime type for the given `str`.
13800 *
13801 * @param {String} str
13802 * @return {String}
13803 * @api private
13804 */
13805
13806 var type = function type(str) {
13807 return str.split(/ *; */).shift();
13808 };
13809 /**
13810 * Return header field parameters.
13811 *
13812 * @param {String} str
13813 * @return {Object}
13814 * @api private
13815 */
13816
13817
13818 var params = function params(str) {
13819 return str.split(/ *; */).reduce(function (obj, str) {
13820 var parts = str.split(/ *= */);
13821 var key = parts.shift();
13822 var val = parts.shift();
13823 if (key && val) obj[key] = val;
13824 return obj;
13825 }, {});
13826 };
13827 /**
13828 * Parse Link header fields.
13829 *
13830 * @param {String} str
13831 * @return {Object}
13832 * @api private
13833 */
13834
13835
13836 var parseLinks = function parseLinks(str) {
13837 return str.split(/ *, */).reduce(function (obj, str) {
13838 var parts = str.split(/ *; */);
13839 var url = parts[0].slice(1, -1);
13840 var rel = parts[1].split(/ *= */)[1].slice(1, -1);
13841 obj[rel] = url;
13842 return obj;
13843 }, {});
13844 };
13845 /**
13846 * Strip content related fields from `header`.
13847 *
13848 * @param {Object} header
13849 * @return {Object} header
13850 * @api private
13851 */
13852
13853
13854 var cleanHeader = function cleanHeader(header, changesOrigin) {
13855 delete header['content-type'];
13856 delete header['content-length'];
13857 delete header['transfer-encoding'];
13858 delete header.host; // secuirty
13859
13860 if (changesOrigin) {
13861 delete header.authorization;
13862 delete header.cookie;
13863 }
13864
13865 return header;
13866 };
13867
13868 var utils = {
13869 type: type,
13870 params: params,
13871 parseLinks: parseLinks,
13872 cleanHeader: cleanHeader
13873 };
13874
13875 /**
13876 * Module dependencies.
13877 */
13878
13879 /**
13880 * Expose `ResponseBase`.
13881 */
13882
13883
13884 var responseBase = ResponseBase;
13885 /**
13886 * Initialize a new `ResponseBase`.
13887 *
13888 * @api public
13889 */
13890
13891 function ResponseBase(obj) {
13892 if (obj) return mixin$1(obj);
13893 }
13894 /**
13895 * Mixin the prototype properties.
13896 *
13897 * @param {Object} obj
13898 * @return {Object}
13899 * @api private
13900 */
13901
13902
13903 function mixin$1(obj) {
13904 for (var key in ResponseBase.prototype) {
13905 if (Object.prototype.hasOwnProperty.call(ResponseBase.prototype, key)) obj[key] = ResponseBase.prototype[key];
13906 }
13907
13908 return obj;
13909 }
13910 /**
13911 * Get case-insensitive `field` value.
13912 *
13913 * @param {String} field
13914 * @return {String}
13915 * @api public
13916 */
13917
13918
13919 ResponseBase.prototype.get = function (field) {
13920 return this.header[field.toLowerCase()];
13921 };
13922 /**
13923 * Set header related properties:
13924 *
13925 * - `.type` the content type without params
13926 *
13927 * A response of "Content-Type: text/plain; charset=utf-8"
13928 * will provide you with a `.type` of "text/plain".
13929 *
13930 * @param {Object} header
13931 * @api private
13932 */
13933
13934
13935 ResponseBase.prototype._setHeaderProperties = function (header) {
13936 // TODO: moar!
13937 // TODO: make this a util
13938 // content-type
13939 var ct = header['content-type'] || '';
13940 this.type = utils.type(ct); // params
13941
13942 var params = utils.params(ct);
13943
13944 for (var key in params) {
13945 if (Object.prototype.hasOwnProperty.call(params, key)) this[key] = params[key];
13946 }
13947
13948 this.links = {}; // links
13949
13950 try {
13951 if (header.link) {
13952 this.links = utils.parseLinks(header.link);
13953 }
13954 } catch (err) {// ignore
13955 }
13956 };
13957 /**
13958 * Set flags such as `.ok` based on `status`.
13959 *
13960 * For example a 2xx response will give you a `.ok` of __true__
13961 * whereas 5xx will be __false__ and `.error` will be __true__. The
13962 * `.clientError` and `.serverError` are also available to be more
13963 * specific, and `.statusType` is the class of error ranging from 1..5
13964 * sometimes useful for mapping respond colors etc.
13965 *
13966 * "sugar" properties are also defined for common cases. Currently providing:
13967 *
13968 * - .noContent
13969 * - .badRequest
13970 * - .unauthorized
13971 * - .notAcceptable
13972 * - .notFound
13973 *
13974 * @param {Number} status
13975 * @api private
13976 */
13977
13978
13979 ResponseBase.prototype._setStatusProperties = function (status) {
13980 var type = status / 100 | 0; // status / class
13981
13982 this.statusCode = status;
13983 this.status = this.statusCode;
13984 this.statusType = type; // basics
13985
13986 this.info = type === 1;
13987 this.ok = type === 2;
13988 this.redirect = type === 3;
13989 this.clientError = type === 4;
13990 this.serverError = type === 5;
13991 this.error = type === 4 || type === 5 ? this.toError() : false; // sugar
13992
13993 this.created = status === 201;
13994 this.accepted = status === 202;
13995 this.noContent = status === 204;
13996 this.badRequest = status === 400;
13997 this.unauthorized = status === 401;
13998 this.notAcceptable = status === 406;
13999 this.forbidden = status === 403;
14000 this.notFound = status === 404;
14001 this.unprocessableEntity = status === 422;
14002 };
14003
14004 function _toConsumableArray$1(arr) {
14005 return _arrayWithoutHoles$1(arr) || _iterableToArray$1(arr) || _nonIterableSpread$1();
14006 }
14007
14008 function _nonIterableSpread$1() {
14009 throw new TypeError("Invalid attempt to spread non-iterable instance");
14010 }
14011
14012 function _iterableToArray$1(iter) {
14013 if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter);
14014 }
14015
14016 function _arrayWithoutHoles$1(arr) {
14017 if (Array.isArray(arr)) {
14018 for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) {
14019 arr2[i] = arr[i];
14020 }
14021
14022 return arr2;
14023 }
14024 }
14025
14026 function Agent() {
14027 this._defaults = [];
14028 }
14029
14030 ['use', 'on', 'once', 'set', 'query', 'type', 'accept', 'auth', 'withCredentials', 'sortQuery', 'retry', 'ok', 'redirects', 'timeout', 'buffer', 'serialize', 'parse', 'ca', 'key', 'pfx', 'cert'].forEach(function (fn) {
14031 // Default setting for all requests from this agent
14032 Agent.prototype[fn] = function () {
14033 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
14034 args[_key] = arguments[_key];
14035 }
14036
14037 this._defaults.push({
14038 fn: fn,
14039 args: args
14040 });
14041
14042 return this;
14043 };
14044 });
14045
14046 Agent.prototype._setDefaults = function (req) {
14047 this._defaults.forEach(function (def) {
14048 req[def.fn].apply(req, _toConsumableArray$1(def.args));
14049 });
14050 };
14051
14052 var agentBase = Agent;
14053
14054 var client = createCommonjsModule(function (module, exports) {
14055
14056 function _typeof$1(obj) {
14057 if (typeof Symbol === "function" && _typeof(Symbol.iterator) === "symbol") {
14058 _typeof$1 = function _typeof$1(obj) {
14059 return _typeof(obj);
14060 };
14061 } else {
14062 _typeof$1 = function _typeof$1(obj) {
14063 return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : _typeof(obj);
14064 };
14065 }
14066
14067 return _typeof$1(obj);
14068 }
14069 /**
14070 * Root reference for iframes.
14071 */
14072
14073
14074 var root;
14075
14076 if (typeof window !== 'undefined') {
14077 // Browser window
14078 root = window;
14079 } else if (typeof self === 'undefined') {
14080 // Other environments
14081 console.warn('Using browser-only version of superagent in non-browser environment');
14082 root = void 0;
14083 } else {
14084 // Web Worker
14085 root = self;
14086 }
14087 /**
14088 * Noop.
14089 */
14090
14091
14092 function noop() {}
14093 /**
14094 * Expose `request`.
14095 */
14096
14097
14098 module.exports = function (method, url) {
14099 // callback
14100 if (typeof url === 'function') {
14101 return new exports.Request('GET', method).end(url);
14102 } // url first
14103
14104
14105 if (arguments.length === 1) {
14106 return new exports.Request('GET', method);
14107 }
14108
14109 return new exports.Request(method, url);
14110 };
14111
14112 exports = module.exports;
14113 var request = exports;
14114 exports.Request = Request;
14115 /**
14116 * Determine XHR.
14117 */
14118
14119 request.getXHR = function () {
14120 if (root.XMLHttpRequest && (!root.location || root.location.protocol !== 'file:' || !root.ActiveXObject)) {
14121 return new XMLHttpRequest();
14122 }
14123
14124 try {
14125 return new ActiveXObject('Microsoft.XMLHTTP');
14126 } catch (err) {}
14127
14128 try {
14129 return new ActiveXObject('Msxml2.XMLHTTP.6.0');
14130 } catch (err) {}
14131
14132 try {
14133 return new ActiveXObject('Msxml2.XMLHTTP.3.0');
14134 } catch (err) {}
14135
14136 try {
14137 return new ActiveXObject('Msxml2.XMLHTTP');
14138 } catch (err) {}
14139
14140 throw new Error('Browser-only version of superagent could not find XHR');
14141 };
14142 /**
14143 * Removes leading and trailing whitespace, added to support IE.
14144 *
14145 * @param {String} s
14146 * @return {String}
14147 * @api private
14148 */
14149
14150
14151 var trim = ''.trim ? function (s) {
14152 return s.trim();
14153 } : function (s) {
14154 return s.replace(/(^\s*|\s*$)/g, '');
14155 };
14156 /**
14157 * Serialize the given `obj`.
14158 *
14159 * @param {Object} obj
14160 * @return {String}
14161 * @api private
14162 */
14163
14164 function serialize(obj) {
14165 if (!isObject_1(obj)) return obj;
14166 var pairs = [];
14167
14168 for (var key in obj) {
14169 if (Object.prototype.hasOwnProperty.call(obj, key)) pushEncodedKeyValuePair(pairs, key, obj[key]);
14170 }
14171
14172 return pairs.join('&');
14173 }
14174 /**
14175 * Helps 'serialize' with serializing arrays.
14176 * Mutates the pairs array.
14177 *
14178 * @param {Array} pairs
14179 * @param {String} key
14180 * @param {Mixed} val
14181 */
14182
14183
14184 function pushEncodedKeyValuePair(pairs, key, val) {
14185 if (val === undefined) return;
14186
14187 if (val === null) {
14188 pairs.push(encodeURIComponent(key));
14189 return;
14190 }
14191
14192 if (Array.isArray(val)) {
14193 val.forEach(function (v) {
14194 pushEncodedKeyValuePair(pairs, key, v);
14195 });
14196 } else if (isObject_1(val)) {
14197 for (var subkey in val) {
14198 if (Object.prototype.hasOwnProperty.call(val, subkey)) pushEncodedKeyValuePair(pairs, "".concat(key, "[").concat(subkey, "]"), val[subkey]);
14199 }
14200 } else {
14201 pairs.push(encodeURIComponent(key) + '=' + encodeURIComponent(val));
14202 }
14203 }
14204 /**
14205 * Expose serialization method.
14206 */
14207
14208
14209 request.serializeObject = serialize;
14210 /**
14211 * Parse the given x-www-form-urlencoded `str`.
14212 *
14213 * @param {String} str
14214 * @return {Object}
14215 * @api private
14216 */
14217
14218 function parseString(str) {
14219 var obj = {};
14220 var pairs = str.split('&');
14221 var pair;
14222 var pos;
14223
14224 for (var i = 0, len = pairs.length; i < len; ++i) {
14225 pair = pairs[i];
14226 pos = pair.indexOf('=');
14227
14228 if (pos === -1) {
14229 obj[decodeURIComponent(pair)] = '';
14230 } else {
14231 obj[decodeURIComponent(pair.slice(0, pos))] = decodeURIComponent(pair.slice(pos + 1));
14232 }
14233 }
14234
14235 return obj;
14236 }
14237 /**
14238 * Expose parser.
14239 */
14240
14241
14242 request.parseString = parseString;
14243 /**
14244 * Default MIME type map.
14245 *
14246 * superagent.types.xml = 'application/xml';
14247 *
14248 */
14249
14250 request.types = {
14251 html: 'text/html',
14252 json: 'application/json',
14253 xml: 'text/xml',
14254 urlencoded: 'application/x-www-form-urlencoded',
14255 form: 'application/x-www-form-urlencoded',
14256 'form-data': 'application/x-www-form-urlencoded'
14257 };
14258 /**
14259 * Default serialization map.
14260 *
14261 * superagent.serialize['application/xml'] = function(obj){
14262 * return 'generated xml here';
14263 * };
14264 *
14265 */
14266
14267 request.serialize = {
14268 'application/x-www-form-urlencoded': serialize,
14269 'application/json': fastSafeStringify
14270 };
14271 /**
14272 * Default parsers.
14273 *
14274 * superagent.parse['application/xml'] = function(str){
14275 * return { object parsed from str };
14276 * };
14277 *
14278 */
14279
14280 request.parse = {
14281 'application/x-www-form-urlencoded': parseString,
14282 'application/json': JSON.parse
14283 };
14284 /**
14285 * Parse the given header `str` into
14286 * an object containing the mapped fields.
14287 *
14288 * @param {String} str
14289 * @return {Object}
14290 * @api private
14291 */
14292
14293 function parseHeader(str) {
14294 var lines = str.split(/\r?\n/);
14295 var fields = {};
14296 var index;
14297 var line;
14298 var field;
14299 var val;
14300
14301 for (var i = 0, len = lines.length; i < len; ++i) {
14302 line = lines[i];
14303 index = line.indexOf(':');
14304
14305 if (index === -1) {
14306 // could be empty line, just skip it
14307 continue;
14308 }
14309
14310 field = line.slice(0, index).toLowerCase();
14311 val = trim(line.slice(index + 1));
14312 fields[field] = val;
14313 }
14314
14315 return fields;
14316 }
14317 /**
14318 * Check if `mime` is json or has +json structured syntax suffix.
14319 *
14320 * @param {String} mime
14321 * @return {Boolean}
14322 * @api private
14323 */
14324
14325
14326 function isJSON(mime) {
14327 // should match /json or +json
14328 // but not /json-seq
14329 return /[/+]json($|[^-\w])/.test(mime);
14330 }
14331 /**
14332 * Initialize a new `Response` with the given `xhr`.
14333 *
14334 * - set flags (.ok, .error, etc)
14335 * - parse header
14336 *
14337 * Examples:
14338 *
14339 * Aliasing `superagent` as `request` is nice:
14340 *
14341 * request = superagent;
14342 *
14343 * We can use the promise-like API, or pass callbacks:
14344 *
14345 * request.get('/').end(function(res){});
14346 * request.get('/', function(res){});
14347 *
14348 * Sending data can be chained:
14349 *
14350 * request
14351 * .post('/user')
14352 * .send({ name: 'tj' })
14353 * .end(function(res){});
14354 *
14355 * Or passed to `.send()`:
14356 *
14357 * request
14358 * .post('/user')
14359 * .send({ name: 'tj' }, function(res){});
14360 *
14361 * Or passed to `.post()`:
14362 *
14363 * request
14364 * .post('/user', { name: 'tj' })
14365 * .end(function(res){});
14366 *
14367 * Or further reduced to a single call for simple cases:
14368 *
14369 * request
14370 * .post('/user', { name: 'tj' }, function(res){});
14371 *
14372 * @param {XMLHTTPRequest} xhr
14373 * @param {Object} options
14374 * @api private
14375 */
14376
14377
14378 function Response(req) {
14379 this.req = req;
14380 this.xhr = this.req.xhr; // responseText is accessible only if responseType is '' or 'text' and on older browsers
14381
14382 this.text = this.req.method !== 'HEAD' && (this.xhr.responseType === '' || this.xhr.responseType === 'text') || typeof this.xhr.responseType === 'undefined' ? this.xhr.responseText : null;
14383 this.statusText = this.req.xhr.statusText;
14384 var status = this.xhr.status; // handle IE9 bug: http://stackoverflow.com/questions/10046972/msie-returns-status-code-of-1223-for-ajax-request
14385
14386 if (status === 1223) {
14387 status = 204;
14388 }
14389
14390 this._setStatusProperties(status);
14391
14392 this.headers = parseHeader(this.xhr.getAllResponseHeaders());
14393 this.header = this.headers; // getAllResponseHeaders sometimes falsely returns "" for CORS requests, but
14394 // getResponseHeader still works. so we get content-type even if getting
14395 // other headers fails.
14396
14397 this.header['content-type'] = this.xhr.getResponseHeader('content-type');
14398
14399 this._setHeaderProperties(this.header);
14400
14401 if (this.text === null && req._responseType) {
14402 this.body = this.xhr.response;
14403 } else {
14404 this.body = this.req.method === 'HEAD' ? null : this._parseBody(this.text ? this.text : this.xhr.response);
14405 }
14406 } // eslint-disable-next-line new-cap
14407
14408
14409 responseBase(Response.prototype);
14410 /**
14411 * Parse the given body `str`.
14412 *
14413 * Used for auto-parsing of bodies. Parsers
14414 * are defined on the `superagent.parse` object.
14415 *
14416 * @param {String} str
14417 * @return {Mixed}
14418 * @api private
14419 */
14420
14421 Response.prototype._parseBody = function (str) {
14422 var parse = request.parse[this.type];
14423
14424 if (this.req._parser) {
14425 return this.req._parser(this, str);
14426 }
14427
14428 if (!parse && isJSON(this.type)) {
14429 parse = request.parse['application/json'];
14430 }
14431
14432 return parse && str && (str.length > 0 || str instanceof Object) ? parse(str) : null;
14433 };
14434 /**
14435 * Return an `Error` representative of this response.
14436 *
14437 * @return {Error}
14438 * @api public
14439 */
14440
14441
14442 Response.prototype.toError = function () {
14443 var req = this.req;
14444 var method = req.method;
14445 var url = req.url;
14446 var msg = "cannot ".concat(method, " ").concat(url, " (").concat(this.status, ")");
14447 var err = new Error(msg);
14448 err.status = this.status;
14449 err.method = method;
14450 err.url = url;
14451 return err;
14452 };
14453 /**
14454 * Expose `Response`.
14455 */
14456
14457
14458 request.Response = Response;
14459 /**
14460 * Initialize a new `Request` with the given `method` and `url`.
14461 *
14462 * @param {String} method
14463 * @param {String} url
14464 * @api public
14465 */
14466
14467 function Request(method, url) {
14468 var self = this;
14469 this._query = this._query || [];
14470 this.method = method;
14471 this.url = url;
14472 this.header = {}; // preserves header name case
14473
14474 this._header = {}; // coerces header names to lowercase
14475
14476 this.on('end', function () {
14477 var err = null;
14478 var res = null;
14479
14480 try {
14481 res = new Response(self);
14482 } catch (err2) {
14483 err = new Error('Parser is unable to parse the response');
14484 err.parse = true;
14485 err.original = err2; // issue #675: return the raw response if the response parsing fails
14486
14487 if (self.xhr) {
14488 // ie9 doesn't have 'response' property
14489 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
14490
14491 err.status = self.xhr.status ? self.xhr.status : null;
14492 err.statusCode = err.status; // backwards-compat only
14493 } else {
14494 err.rawResponse = null;
14495 err.status = null;
14496 }
14497
14498 return self.callback(err);
14499 }
14500
14501 self.emit('response', res);
14502 var new_err;
14503
14504 try {
14505 if (!self._isResponseOK(res)) {
14506 new_err = new Error(res.statusText || 'Unsuccessful HTTP response');
14507 }
14508 } catch (err2) {
14509 new_err = err2; // ok() callback can throw
14510 } // #1000 don't catch errors from the callback to avoid double calling it
14511
14512
14513 if (new_err) {
14514 new_err.original = err;
14515 new_err.response = res;
14516 new_err.status = res.status;
14517 self.callback(new_err, res);
14518 } else {
14519 self.callback(null, res);
14520 }
14521 });
14522 }
14523 /**
14524 * Mixin `Emitter` and `RequestBase`.
14525 */
14526 // eslint-disable-next-line new-cap
14527
14528
14529 componentEmitter(Request.prototype); // eslint-disable-next-line new-cap
14530
14531 requestBase(Request.prototype);
14532 /**
14533 * Set Content-Type to `type`, mapping values from `request.types`.
14534 *
14535 * Examples:
14536 *
14537 * superagent.types.xml = 'application/xml';
14538 *
14539 * request.post('/')
14540 * .type('xml')
14541 * .send(xmlstring)
14542 * .end(callback);
14543 *
14544 * request.post('/')
14545 * .type('application/xml')
14546 * .send(xmlstring)
14547 * .end(callback);
14548 *
14549 * @param {String} type
14550 * @return {Request} for chaining
14551 * @api public
14552 */
14553
14554 Request.prototype.type = function (type) {
14555 this.set('Content-Type', request.types[type] || type);
14556 return this;
14557 };
14558 /**
14559 * Set Accept to `type`, mapping values from `request.types`.
14560 *
14561 * Examples:
14562 *
14563 * superagent.types.json = 'application/json';
14564 *
14565 * request.get('/agent')
14566 * .accept('json')
14567 * .end(callback);
14568 *
14569 * request.get('/agent')
14570 * .accept('application/json')
14571 * .end(callback);
14572 *
14573 * @param {String} accept
14574 * @return {Request} for chaining
14575 * @api public
14576 */
14577
14578
14579 Request.prototype.accept = function (type) {
14580 this.set('Accept', request.types[type] || type);
14581 return this;
14582 };
14583 /**
14584 * Set Authorization field value with `user` and `pass`.
14585 *
14586 * @param {String} user
14587 * @param {String} [pass] optional in case of using 'bearer' as type
14588 * @param {Object} options with 'type' property 'auto', 'basic' or 'bearer' (default 'basic')
14589 * @return {Request} for chaining
14590 * @api public
14591 */
14592
14593
14594 Request.prototype.auth = function (user, pass, options) {
14595 if (arguments.length === 1) pass = '';
14596
14597 if (_typeof$1(pass) === 'object' && pass !== null) {
14598 // pass is optional and can be replaced with options
14599 options = pass;
14600 pass = '';
14601 }
14602
14603 if (!options) {
14604 options = {
14605 type: typeof btoa === 'function' ? 'basic' : 'auto'
14606 };
14607 }
14608
14609 var encoder = function encoder(string) {
14610 if (typeof btoa === 'function') {
14611 return btoa(string);
14612 }
14613
14614 throw new Error('Cannot use basic auth, btoa is not a function');
14615 };
14616
14617 return this._auth(user, pass, options, encoder);
14618 };
14619 /**
14620 * Add query-string `val`.
14621 *
14622 * Examples:
14623 *
14624 * request.get('/shoes')
14625 * .query('size=10')
14626 * .query({ color: 'blue' })
14627 *
14628 * @param {Object|String} val
14629 * @return {Request} for chaining
14630 * @api public
14631 */
14632
14633
14634 Request.prototype.query = function (val) {
14635 if (typeof val !== 'string') val = serialize(val);
14636 if (val) this._query.push(val);
14637 return this;
14638 };
14639 /**
14640 * Queue the given `file` as an attachment to the specified `field`,
14641 * with optional `options` (or filename).
14642 *
14643 * ``` js
14644 * request.post('/upload')
14645 * .attach('content', new Blob(['<a id="a"><b id="b">hey!</b></a>'], { type: "text/html"}))
14646 * .end(callback);
14647 * ```
14648 *
14649 * @param {String} field
14650 * @param {Blob|File} file
14651 * @param {String|Object} options
14652 * @return {Request} for chaining
14653 * @api public
14654 */
14655
14656
14657 Request.prototype.attach = function (field, file, options) {
14658 if (file) {
14659 if (this._data) {
14660 throw new Error("superagent can't mix .send() and .attach()");
14661 }
14662
14663 this._getFormData().append(field, file, options || file.name);
14664 }
14665
14666 return this;
14667 };
14668
14669 Request.prototype._getFormData = function () {
14670 if (!this._formData) {
14671 this._formData = new root.FormData();
14672 }
14673
14674 return this._formData;
14675 };
14676 /**
14677 * Invoke the callback with `err` and `res`
14678 * and handle arity check.
14679 *
14680 * @param {Error} err
14681 * @param {Response} res
14682 * @api private
14683 */
14684
14685
14686 Request.prototype.callback = function (err, res) {
14687 if (this._shouldRetry(err, res)) {
14688 return this._retry();
14689 }
14690
14691 var fn = this._callback;
14692 this.clearTimeout();
14693
14694 if (err) {
14695 if (this._maxRetries) err.retries = this._retries - 1;
14696 this.emit('error', err);
14697 }
14698
14699 fn(err, res);
14700 };
14701 /**
14702 * Invoke callback with x-domain error.
14703 *
14704 * @api private
14705 */
14706
14707
14708 Request.prototype.crossDomainError = function () {
14709 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.');
14710 err.crossDomain = true;
14711 err.status = this.status;
14712 err.method = this.method;
14713 err.url = this.url;
14714 this.callback(err);
14715 }; // This only warns, because the request is still likely to work
14716
14717
14718 Request.prototype.agent = function () {
14719 console.warn('This is not supported in browser version of superagent');
14720 return this;
14721 };
14722
14723 Request.prototype.buffer = Request.prototype.ca;
14724 Request.prototype.ca = Request.prototype.agent; // This throws, because it can't send/receive data as expected
14725
14726 Request.prototype.write = function () {
14727 throw new Error('Streaming is not supported in browser version of superagent');
14728 };
14729
14730 Request.prototype.pipe = Request.prototype.write;
14731 /**
14732 * Check if `obj` is a host object,
14733 * we don't want to serialize these :)
14734 *
14735 * @param {Object} obj host object
14736 * @return {Boolean} is a host object
14737 * @api private
14738 */
14739
14740 Request.prototype._isHost = function (obj) {
14741 // Native objects stringify to [object File], [object Blob], [object FormData], etc.
14742 return obj && _typeof$1(obj) === 'object' && !Array.isArray(obj) && Object.prototype.toString.call(obj) !== '[object Object]';
14743 };
14744 /**
14745 * Initiate request, invoking callback `fn(res)`
14746 * with an instanceof `Response`.
14747 *
14748 * @param {Function} fn
14749 * @return {Request} for chaining
14750 * @api public
14751 */
14752
14753
14754 Request.prototype.end = function (fn) {
14755 if (this._endCalled) {
14756 console.warn('Warning: .end() was called twice. This is not supported in superagent');
14757 }
14758
14759 this._endCalled = true; // store callback
14760
14761 this._callback = fn || noop; // querystring
14762
14763 this._finalizeQueryString();
14764
14765 this._end();
14766 };
14767
14768 Request.prototype._setUploadTimeout = function () {
14769 var self = this; // upload timeout it's wokrs only if deadline timeout is off
14770
14771 if (this._uploadTimeout && !this._uploadTimeoutTimer) {
14772 this._uploadTimeoutTimer = setTimeout(function () {
14773 self._timeoutError('Upload timeout of ', self._uploadTimeout, 'ETIMEDOUT');
14774 }, this._uploadTimeout);
14775 }
14776 }; // eslint-disable-next-line complexity
14777
14778
14779 Request.prototype._end = function () {
14780 if (this._aborted) return this.callback(new Error('The request has been aborted even before .end() was called'));
14781 var self = this;
14782 this.xhr = request.getXHR();
14783 var xhr = this.xhr;
14784 var data = this._formData || this._data;
14785
14786 this._setTimeouts(); // state change
14787
14788
14789 xhr.onreadystatechange = function () {
14790 var readyState = xhr.readyState;
14791
14792 if (readyState >= 2 && self._responseTimeoutTimer) {
14793 clearTimeout(self._responseTimeoutTimer);
14794 }
14795
14796 if (readyState !== 4) {
14797 return;
14798 } // In IE9, reads to any property (e.g. status) off of an aborted XHR will
14799 // result in the error "Could not complete the operation due to error c00c023f"
14800
14801
14802 var status;
14803
14804 try {
14805 status = xhr.status;
14806 } catch (err) {
14807 status = 0;
14808 }
14809
14810 if (!status) {
14811 if (self.timedout || self._aborted) return;
14812 return self.crossDomainError();
14813 }
14814
14815 self.emit('end');
14816 }; // progress
14817
14818
14819 var handleProgress = function handleProgress(direction, e) {
14820 if (e.total > 0) {
14821 e.percent = e.loaded / e.total * 100;
14822
14823 if (e.percent === 100) {
14824 clearTimeout(self._uploadTimeoutTimer);
14825 }
14826 }
14827
14828 e.direction = direction;
14829 self.emit('progress', e);
14830 };
14831
14832 if (this.hasListeners('progress')) {
14833 try {
14834 xhr.addEventListener('progress', handleProgress.bind(null, 'download'));
14835
14836 if (xhr.upload) {
14837 xhr.upload.addEventListener('progress', handleProgress.bind(null, 'upload'));
14838 }
14839 } catch (err) {// Accessing xhr.upload fails in IE from a web worker, so just pretend it doesn't exist.
14840 // Reported here:
14841 // https://connect.microsoft.com/IE/feedback/details/837245/xmlhttprequest-upload-throws-invalid-argument-when-used-from-web-worker-context
14842 }
14843 }
14844
14845 if (xhr.upload) {
14846 this._setUploadTimeout();
14847 } // initiate request
14848
14849
14850 try {
14851 if (this.username && this.password) {
14852 xhr.open(this.method, this.url, true, this.username, this.password);
14853 } else {
14854 xhr.open(this.method, this.url, true);
14855 }
14856 } catch (err) {
14857 // see #1149
14858 return this.callback(err);
14859 } // CORS
14860
14861
14862 if (this._withCredentials) xhr.withCredentials = true; // body
14863
14864 if (!this._formData && this.method !== 'GET' && this.method !== 'HEAD' && typeof data !== 'string' && !this._isHost(data)) {
14865 // serialize stuff
14866 var contentType = this._header['content-type'];
14867
14868 var _serialize = this._serializer || request.serialize[contentType ? contentType.split(';')[0] : ''];
14869
14870 if (!_serialize && isJSON(contentType)) {
14871 _serialize = request.serialize['application/json'];
14872 }
14873
14874 if (_serialize) data = _serialize(data);
14875 } // set header fields
14876
14877
14878 for (var field in this.header) {
14879 if (this.header[field] === null) continue;
14880 if (Object.prototype.hasOwnProperty.call(this.header, field)) xhr.setRequestHeader(field, this.header[field]);
14881 }
14882
14883 if (this._responseType) {
14884 xhr.responseType = this._responseType;
14885 } // send stuff
14886
14887
14888 this.emit('request', this); // IE11 xhr.send(undefined) sends 'undefined' string as POST payload (instead of nothing)
14889 // We need null here if data is undefined
14890
14891 xhr.send(typeof data === 'undefined' ? null : data);
14892 };
14893
14894 request.agent = function () {
14895 return new agentBase();
14896 };
14897
14898 ['GET', 'POST', 'OPTIONS', 'PATCH', 'PUT', 'DELETE'].forEach(function (method) {
14899 agentBase.prototype[method.toLowerCase()] = function (url, fn) {
14900 var req = new request.Request(method, url);
14901
14902 this._setDefaults(req);
14903
14904 if (fn) {
14905 req.end(fn);
14906 }
14907
14908 return req;
14909 };
14910 });
14911 agentBase.prototype.del = agentBase.prototype.delete;
14912 /**
14913 * GET `url` with optional callback `fn(res)`.
14914 *
14915 * @param {String} url
14916 * @param {Mixed|Function} [data] or fn
14917 * @param {Function} [fn]
14918 * @return {Request}
14919 * @api public
14920 */
14921
14922 request.get = function (url, data, fn) {
14923 var req = request('GET', url);
14924
14925 if (typeof data === 'function') {
14926 fn = data;
14927 data = null;
14928 }
14929
14930 if (data) req.query(data);
14931 if (fn) req.end(fn);
14932 return req;
14933 };
14934 /**
14935 * HEAD `url` with optional callback `fn(res)`.
14936 *
14937 * @param {String} url
14938 * @param {Mixed|Function} [data] or fn
14939 * @param {Function} [fn]
14940 * @return {Request}
14941 * @api public
14942 */
14943
14944
14945 request.head = function (url, data, fn) {
14946 var req = request('HEAD', url);
14947
14948 if (typeof data === 'function') {
14949 fn = data;
14950 data = null;
14951 }
14952
14953 if (data) req.query(data);
14954 if (fn) req.end(fn);
14955 return req;
14956 };
14957 /**
14958 * OPTIONS query to `url` with optional callback `fn(res)`.
14959 *
14960 * @param {String} url
14961 * @param {Mixed|Function} [data] or fn
14962 * @param {Function} [fn]
14963 * @return {Request}
14964 * @api public
14965 */
14966
14967
14968 request.options = function (url, data, fn) {
14969 var req = request('OPTIONS', url);
14970
14971 if (typeof data === 'function') {
14972 fn = data;
14973 data = null;
14974 }
14975
14976 if (data) req.send(data);
14977 if (fn) req.end(fn);
14978 return req;
14979 };
14980 /**
14981 * DELETE `url` with optional `data` and callback `fn(res)`.
14982 *
14983 * @param {String} url
14984 * @param {Mixed} [data]
14985 * @param {Function} [fn]
14986 * @return {Request}
14987 * @api public
14988 */
14989
14990
14991 function del(url, data, fn) {
14992 var req = request('DELETE', url);
14993
14994 if (typeof data === 'function') {
14995 fn = data;
14996 data = null;
14997 }
14998
14999 if (data) req.send(data);
15000 if (fn) req.end(fn);
15001 return req;
15002 }
15003
15004 request.del = del;
15005 request.delete = del;
15006 /**
15007 * PATCH `url` with optional `data` and callback `fn(res)`.
15008 *
15009 * @param {String} url
15010 * @param {Mixed} [data]
15011 * @param {Function} [fn]
15012 * @return {Request}
15013 * @api public
15014 */
15015
15016 request.patch = function (url, data, fn) {
15017 var req = request('PATCH', url);
15018
15019 if (typeof data === 'function') {
15020 fn = data;
15021 data = null;
15022 }
15023
15024 if (data) req.send(data);
15025 if (fn) req.end(fn);
15026 return req;
15027 };
15028 /**
15029 * POST `url` with optional `data` and callback `fn(res)`.
15030 *
15031 * @param {String} url
15032 * @param {Mixed} [data]
15033 * @param {Function} [fn]
15034 * @return {Request}
15035 * @api public
15036 */
15037
15038
15039 request.post = function (url, data, fn) {
15040 var req = request('POST', url);
15041
15042 if (typeof data === 'function') {
15043 fn = data;
15044 data = null;
15045 }
15046
15047 if (data) req.send(data);
15048 if (fn) req.end(fn);
15049 return req;
15050 };
15051 /**
15052 * PUT `url` with optional `data` and callback `fn(res)`.
15053 *
15054 * @param {String} url
15055 * @param {Mixed|Function} [data] or fn
15056 * @param {Function} [fn]
15057 * @return {Request}
15058 * @api public
15059 */
15060
15061
15062 request.put = function (url, data, fn) {
15063 var req = request('PUT', url);
15064
15065 if (typeof data === 'function') {
15066 fn = data;
15067 data = null;
15068 }
15069
15070 if (data) req.send(data);
15071 if (fn) req.end(fn);
15072 return req;
15073 };
15074 });
15075 var client_1 = client.Request;
15076
15077 /**
15078 * Copies the values of `source` to `array`.
15079 *
15080 * @private
15081 * @param {Array} source The array to copy values from.
15082 * @param {Array} [array=[]] The array to copy values to.
15083 * @returns {Array} Returns `array`.
15084 */
15085 function copyArray(source, array) {
15086 var index = -1,
15087 length = source.length;
15088
15089 array || (array = Array(length));
15090 while (++index < length) {
15091 array[index] = source[index];
15092 }
15093 return array;
15094 }
15095
15096 var _copyArray = copyArray;
15097
15098 /* Built-in method references for those with the same name as other `lodash` methods. */
15099 var nativeFloor = Math.floor,
15100 nativeRandom = Math.random;
15101
15102 /**
15103 * The base implementation of `_.random` without support for returning
15104 * floating-point numbers.
15105 *
15106 * @private
15107 * @param {number} lower The lower bound.
15108 * @param {number} upper The upper bound.
15109 * @returns {number} Returns the random number.
15110 */
15111 function baseRandom(lower, upper) {
15112 return lower + nativeFloor(nativeRandom() * (upper - lower + 1));
15113 }
15114
15115 var _baseRandom = baseRandom;
15116
15117 /**
15118 * A specialized version of `_.shuffle` which mutates and sets the size of `array`.
15119 *
15120 * @private
15121 * @param {Array} array The array to shuffle.
15122 * @param {number} [size=array.length] The size of `array`.
15123 * @returns {Array} Returns `array`.
15124 */
15125 function shuffleSelf(array, size) {
15126 var index = -1,
15127 length = array.length,
15128 lastIndex = length - 1;
15129
15130 size = size === undefined ? length : size;
15131 while (++index < size) {
15132 var rand = _baseRandom(index, lastIndex),
15133 value = array[rand];
15134
15135 array[rand] = array[index];
15136 array[index] = value;
15137 }
15138 array.length = size;
15139 return array;
15140 }
15141
15142 var _shuffleSelf = shuffleSelf;
15143
15144 /**
15145 * A specialized version of `_.shuffle` for arrays.
15146 *
15147 * @private
15148 * @param {Array} array The array to shuffle.
15149 * @returns {Array} Returns the new shuffled array.
15150 */
15151 function arrayShuffle(array) {
15152 return _shuffleSelf(_copyArray(array));
15153 }
15154
15155 var _arrayShuffle = arrayShuffle;
15156
15157 /**
15158 * A specialized version of `_.map` for arrays without support for iteratee
15159 * shorthands.
15160 *
15161 * @private
15162 * @param {Array} [array] The array to iterate over.
15163 * @param {Function} iteratee The function invoked per iteration.
15164 * @returns {Array} Returns the new mapped array.
15165 */
15166 function arrayMap(array, iteratee) {
15167 var index = -1,
15168 length = array == null ? 0 : array.length,
15169 result = Array(length);
15170
15171 while (++index < length) {
15172 result[index] = iteratee(array[index], index, array);
15173 }
15174 return result;
15175 }
15176
15177 var _arrayMap = arrayMap;
15178
15179 /**
15180 * The base implementation of `_.values` and `_.valuesIn` which creates an
15181 * array of `object` property values corresponding to the property names
15182 * of `props`.
15183 *
15184 * @private
15185 * @param {Object} object The object to query.
15186 * @param {Array} props The property names to get values for.
15187 * @returns {Object} Returns the array of property values.
15188 */
15189 function baseValues(object, props) {
15190 return _arrayMap(props, function(key) {
15191 return object[key];
15192 });
15193 }
15194
15195 var _baseValues = baseValues;
15196
15197 /**
15198 * The base implementation of `_.times` without support for iteratee shorthands
15199 * or max array length checks.
15200 *
15201 * @private
15202 * @param {number} n The number of times to invoke `iteratee`.
15203 * @param {Function} iteratee The function invoked per iteration.
15204 * @returns {Array} Returns the array of results.
15205 */
15206 function baseTimes(n, iteratee) {
15207 var index = -1,
15208 result = Array(n);
15209
15210 while (++index < n) {
15211 result[index] = iteratee(index);
15212 }
15213 return result;
15214 }
15215
15216 var _baseTimes = baseTimes;
15217
15218 /** Detect free variable `global` from Node.js. */
15219 var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal;
15220
15221 var _freeGlobal = freeGlobal;
15222
15223 /** Detect free variable `self`. */
15224 var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
15225
15226 /** Used as a reference to the global object. */
15227 var root = _freeGlobal || freeSelf || Function('return this')();
15228
15229 var _root = root;
15230
15231 /** Built-in value references. */
15232 var Symbol$1 = _root.Symbol;
15233
15234 var _Symbol = Symbol$1;
15235
15236 /** Used for built-in method references. */
15237 var objectProto = Object.prototype;
15238
15239 /** Used to check objects for own properties. */
15240 var hasOwnProperty = objectProto.hasOwnProperty;
15241
15242 /**
15243 * Used to resolve the
15244 * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
15245 * of values.
15246 */
15247 var nativeObjectToString = objectProto.toString;
15248
15249 /** Built-in value references. */
15250 var symToStringTag = _Symbol ? _Symbol.toStringTag : undefined;
15251
15252 /**
15253 * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
15254 *
15255 * @private
15256 * @param {*} value The value to query.
15257 * @returns {string} Returns the raw `toStringTag`.
15258 */
15259 function getRawTag(value) {
15260 var isOwn = hasOwnProperty.call(value, symToStringTag),
15261 tag = value[symToStringTag];
15262
15263 try {
15264 value[symToStringTag] = undefined;
15265 var unmasked = true;
15266 } catch (e) {}
15267
15268 var result = nativeObjectToString.call(value);
15269 if (unmasked) {
15270 if (isOwn) {
15271 value[symToStringTag] = tag;
15272 } else {
15273 delete value[symToStringTag];
15274 }
15275 }
15276 return result;
15277 }
15278
15279 var _getRawTag = getRawTag;
15280
15281 /** Used for built-in method references. */
15282 var objectProto$1 = Object.prototype;
15283
15284 /**
15285 * Used to resolve the
15286 * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
15287 * of values.
15288 */
15289 var nativeObjectToString$1 = objectProto$1.toString;
15290
15291 /**
15292 * Converts `value` to a string using `Object.prototype.toString`.
15293 *
15294 * @private
15295 * @param {*} value The value to convert.
15296 * @returns {string} Returns the converted string.
15297 */
15298 function objectToString(value) {
15299 return nativeObjectToString$1.call(value);
15300 }
15301
15302 var _objectToString = objectToString;
15303
15304 /** `Object#toString` result references. */
15305 var nullTag = '[object Null]',
15306 undefinedTag = '[object Undefined]';
15307
15308 /** Built-in value references. */
15309 var symToStringTag$1 = _Symbol ? _Symbol.toStringTag : undefined;
15310
15311 /**
15312 * The base implementation of `getTag` without fallbacks for buggy environments.
15313 *
15314 * @private
15315 * @param {*} value The value to query.
15316 * @returns {string} Returns the `toStringTag`.
15317 */
15318 function baseGetTag(value) {
15319 if (value == null) {
15320 return value === undefined ? undefinedTag : nullTag;
15321 }
15322 return (symToStringTag$1 && symToStringTag$1 in Object(value))
15323 ? _getRawTag(value)
15324 : _objectToString(value);
15325 }
15326
15327 var _baseGetTag = baseGetTag;
15328
15329 /**
15330 * Checks if `value` is object-like. A value is object-like if it's not `null`
15331 * and has a `typeof` result of "object".
15332 *
15333 * @static
15334 * @memberOf _
15335 * @since 4.0.0
15336 * @category Lang
15337 * @param {*} value The value to check.
15338 * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
15339 * @example
15340 *
15341 * _.isObjectLike({});
15342 * // => true
15343 *
15344 * _.isObjectLike([1, 2, 3]);
15345 * // => true
15346 *
15347 * _.isObjectLike(_.noop);
15348 * // => false
15349 *
15350 * _.isObjectLike(null);
15351 * // => false
15352 */
15353 function isObjectLike(value) {
15354 return value != null && typeof value == 'object';
15355 }
15356
15357 var isObjectLike_1 = isObjectLike;
15358
15359 /** `Object#toString` result references. */
15360 var argsTag = '[object Arguments]';
15361
15362 /**
15363 * The base implementation of `_.isArguments`.
15364 *
15365 * @private
15366 * @param {*} value The value to check.
15367 * @returns {boolean} Returns `true` if `value` is an `arguments` object,
15368 */
15369 function baseIsArguments(value) {
15370 return isObjectLike_1(value) && _baseGetTag(value) == argsTag;
15371 }
15372
15373 var _baseIsArguments = baseIsArguments;
15374
15375 /** Used for built-in method references. */
15376 var objectProto$2 = Object.prototype;
15377
15378 /** Used to check objects for own properties. */
15379 var hasOwnProperty$1 = objectProto$2.hasOwnProperty;
15380
15381 /** Built-in value references. */
15382 var propertyIsEnumerable = objectProto$2.propertyIsEnumerable;
15383
15384 /**
15385 * Checks if `value` is likely an `arguments` object.
15386 *
15387 * @static
15388 * @memberOf _
15389 * @since 0.1.0
15390 * @category Lang
15391 * @param {*} value The value to check.
15392 * @returns {boolean} Returns `true` if `value` is an `arguments` object,
15393 * else `false`.
15394 * @example
15395 *
15396 * _.isArguments(function() { return arguments; }());
15397 * // => true
15398 *
15399 * _.isArguments([1, 2, 3]);
15400 * // => false
15401 */
15402 var isArguments = _baseIsArguments(function() { return arguments; }()) ? _baseIsArguments : function(value) {
15403 return isObjectLike_1(value) && hasOwnProperty$1.call(value, 'callee') &&
15404 !propertyIsEnumerable.call(value, 'callee');
15405 };
15406
15407 var isArguments_1 = isArguments;
15408
15409 /**
15410 * Checks if `value` is classified as an `Array` object.
15411 *
15412 * @static
15413 * @memberOf _
15414 * @since 0.1.0
15415 * @category Lang
15416 * @param {*} value The value to check.
15417 * @returns {boolean} Returns `true` if `value` is an array, else `false`.
15418 * @example
15419 *
15420 * _.isArray([1, 2, 3]);
15421 * // => true
15422 *
15423 * _.isArray(document.body.children);
15424 * // => false
15425 *
15426 * _.isArray('abc');
15427 * // => false
15428 *
15429 * _.isArray(_.noop);
15430 * // => false
15431 */
15432 var isArray = Array.isArray;
15433
15434 var isArray_1 = isArray;
15435
15436 /**
15437 * This method returns `false`.
15438 *
15439 * @static
15440 * @memberOf _
15441 * @since 4.13.0
15442 * @category Util
15443 * @returns {boolean} Returns `false`.
15444 * @example
15445 *
15446 * _.times(2, _.stubFalse);
15447 * // => [false, false]
15448 */
15449 function stubFalse() {
15450 return false;
15451 }
15452
15453 var stubFalse_1 = stubFalse;
15454
15455 var isBuffer_1 = createCommonjsModule(function (module, exports) {
15456 /** Detect free variable `exports`. */
15457 var freeExports = exports && !exports.nodeType && exports;
15458
15459 /** Detect free variable `module`. */
15460 var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module;
15461
15462 /** Detect the popular CommonJS extension `module.exports`. */
15463 var moduleExports = freeModule && freeModule.exports === freeExports;
15464
15465 /** Built-in value references. */
15466 var Buffer = moduleExports ? _root.Buffer : undefined;
15467
15468 /* Built-in method references for those with the same name as other `lodash` methods. */
15469 var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined;
15470
15471 /**
15472 * Checks if `value` is a buffer.
15473 *
15474 * @static
15475 * @memberOf _
15476 * @since 4.3.0
15477 * @category Lang
15478 * @param {*} value The value to check.
15479 * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.
15480 * @example
15481 *
15482 * _.isBuffer(new Buffer(2));
15483 * // => true
15484 *
15485 * _.isBuffer(new Uint8Array(2));
15486 * // => false
15487 */
15488 var isBuffer = nativeIsBuffer || stubFalse_1;
15489
15490 module.exports = isBuffer;
15491 });
15492
15493 /** Used as references for various `Number` constants. */
15494 var MAX_SAFE_INTEGER = 9007199254740991;
15495
15496 /** Used to detect unsigned integer values. */
15497 var reIsUint = /^(?:0|[1-9]\d*)$/;
15498
15499 /**
15500 * Checks if `value` is a valid array-like index.
15501 *
15502 * @private
15503 * @param {*} value The value to check.
15504 * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
15505 * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
15506 */
15507 function isIndex(value, length) {
15508 var type = typeof value;
15509 length = length == null ? MAX_SAFE_INTEGER : length;
15510
15511 return !!length &&
15512 (type == 'number' ||
15513 (type != 'symbol' && reIsUint.test(value))) &&
15514 (value > -1 && value % 1 == 0 && value < length);
15515 }
15516
15517 var _isIndex = isIndex;
15518
15519 /** Used as references for various `Number` constants. */
15520 var MAX_SAFE_INTEGER$1 = 9007199254740991;
15521
15522 /**
15523 * Checks if `value` is a valid array-like length.
15524 *
15525 * **Note:** This method is loosely based on
15526 * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
15527 *
15528 * @static
15529 * @memberOf _
15530 * @since 4.0.0
15531 * @category Lang
15532 * @param {*} value The value to check.
15533 * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
15534 * @example
15535 *
15536 * _.isLength(3);
15537 * // => true
15538 *
15539 * _.isLength(Number.MIN_VALUE);
15540 * // => false
15541 *
15542 * _.isLength(Infinity);
15543 * // => false
15544 *
15545 * _.isLength('3');
15546 * // => false
15547 */
15548 function isLength(value) {
15549 return typeof value == 'number' &&
15550 value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER$1;
15551 }
15552
15553 var isLength_1 = isLength;
15554
15555 /** `Object#toString` result references. */
15556 var argsTag$1 = '[object Arguments]',
15557 arrayTag = '[object Array]',
15558 boolTag = '[object Boolean]',
15559 dateTag = '[object Date]',
15560 errorTag = '[object Error]',
15561 funcTag = '[object Function]',
15562 mapTag = '[object Map]',
15563 numberTag = '[object Number]',
15564 objectTag = '[object Object]',
15565 regexpTag = '[object RegExp]',
15566 setTag = '[object Set]',
15567 stringTag = '[object String]',
15568 weakMapTag = '[object WeakMap]';
15569
15570 var arrayBufferTag = '[object ArrayBuffer]',
15571 dataViewTag = '[object DataView]',
15572 float32Tag = '[object Float32Array]',
15573 float64Tag = '[object Float64Array]',
15574 int8Tag = '[object Int8Array]',
15575 int16Tag = '[object Int16Array]',
15576 int32Tag = '[object Int32Array]',
15577 uint8Tag = '[object Uint8Array]',
15578 uint8ClampedTag = '[object Uint8ClampedArray]',
15579 uint16Tag = '[object Uint16Array]',
15580 uint32Tag = '[object Uint32Array]';
15581
15582 /** Used to identify `toStringTag` values of typed arrays. */
15583 var typedArrayTags = {};
15584 typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =
15585 typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =
15586 typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =
15587 typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =
15588 typedArrayTags[uint32Tag] = true;
15589 typedArrayTags[argsTag$1] = typedArrayTags[arrayTag] =
15590 typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =
15591 typedArrayTags[dataViewTag] = typedArrayTags[dateTag] =
15592 typedArrayTags[errorTag] = typedArrayTags[funcTag] =
15593 typedArrayTags[mapTag] = typedArrayTags[numberTag] =
15594 typedArrayTags[objectTag] = typedArrayTags[regexpTag] =
15595 typedArrayTags[setTag] = typedArrayTags[stringTag] =
15596 typedArrayTags[weakMapTag] = false;
15597
15598 /**
15599 * The base implementation of `_.isTypedArray` without Node.js optimizations.
15600 *
15601 * @private
15602 * @param {*} value The value to check.
15603 * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
15604 */
15605 function baseIsTypedArray(value) {
15606 return isObjectLike_1(value) &&
15607 isLength_1(value.length) && !!typedArrayTags[_baseGetTag(value)];
15608 }
15609
15610 var _baseIsTypedArray = baseIsTypedArray;
15611
15612 /**
15613 * The base implementation of `_.unary` without support for storing metadata.
15614 *
15615 * @private
15616 * @param {Function} func The function to cap arguments for.
15617 * @returns {Function} Returns the new capped function.
15618 */
15619 function baseUnary(func) {
15620 return function(value) {
15621 return func(value);
15622 };
15623 }
15624
15625 var _baseUnary = baseUnary;
15626
15627 var _nodeUtil = createCommonjsModule(function (module, exports) {
15628 /** Detect free variable `exports`. */
15629 var freeExports = exports && !exports.nodeType && exports;
15630
15631 /** Detect free variable `module`. */
15632 var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module;
15633
15634 /** Detect the popular CommonJS extension `module.exports`. */
15635 var moduleExports = freeModule && freeModule.exports === freeExports;
15636
15637 /** Detect free variable `process` from Node.js. */
15638 var freeProcess = moduleExports && _freeGlobal.process;
15639
15640 /** Used to access faster Node.js helpers. */
15641 var nodeUtil = (function() {
15642 try {
15643 // Use `util.types` for Node.js 10+.
15644 var types = freeModule && freeModule.require && freeModule.require('util').types;
15645
15646 if (types) {
15647 return types;
15648 }
15649
15650 // Legacy `process.binding('util')` for Node.js < 10.
15651 return freeProcess && freeProcess.binding && freeProcess.binding('util');
15652 } catch (e) {}
15653 }());
15654
15655 module.exports = nodeUtil;
15656 });
15657
15658 /* Node.js helper references. */
15659 var nodeIsTypedArray = _nodeUtil && _nodeUtil.isTypedArray;
15660
15661 /**
15662 * Checks if `value` is classified as a typed array.
15663 *
15664 * @static
15665 * @memberOf _
15666 * @since 3.0.0
15667 * @category Lang
15668 * @param {*} value The value to check.
15669 * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
15670 * @example
15671 *
15672 * _.isTypedArray(new Uint8Array);
15673 * // => true
15674 *
15675 * _.isTypedArray([]);
15676 * // => false
15677 */
15678 var isTypedArray = nodeIsTypedArray ? _baseUnary(nodeIsTypedArray) : _baseIsTypedArray;
15679
15680 var isTypedArray_1 = isTypedArray;
15681
15682 /** Used for built-in method references. */
15683 var objectProto$3 = Object.prototype;
15684
15685 /** Used to check objects for own properties. */
15686 var hasOwnProperty$2 = objectProto$3.hasOwnProperty;
15687
15688 /**
15689 * Creates an array of the enumerable property names of the array-like `value`.
15690 *
15691 * @private
15692 * @param {*} value The value to query.
15693 * @param {boolean} inherited Specify returning inherited property names.
15694 * @returns {Array} Returns the array of property names.
15695 */
15696 function arrayLikeKeys(value, inherited) {
15697 var isArr = isArray_1(value),
15698 isArg = !isArr && isArguments_1(value),
15699 isBuff = !isArr && !isArg && isBuffer_1(value),
15700 isType = !isArr && !isArg && !isBuff && isTypedArray_1(value),
15701 skipIndexes = isArr || isArg || isBuff || isType,
15702 result = skipIndexes ? _baseTimes(value.length, String) : [],
15703 length = result.length;
15704
15705 for (var key in value) {
15706 if ((inherited || hasOwnProperty$2.call(value, key)) &&
15707 !(skipIndexes && (
15708 // Safari 9 has enumerable `arguments.length` in strict mode.
15709 key == 'length' ||
15710 // Node.js 0.10 has enumerable non-index properties on buffers.
15711 (isBuff && (key == 'offset' || key == 'parent')) ||
15712 // PhantomJS 2 has enumerable non-index properties on typed arrays.
15713 (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) ||
15714 // Skip index properties.
15715 _isIndex(key, length)
15716 ))) {
15717 result.push(key);
15718 }
15719 }
15720 return result;
15721 }
15722
15723 var _arrayLikeKeys = arrayLikeKeys;
15724
15725 /** Used for built-in method references. */
15726 var objectProto$4 = Object.prototype;
15727
15728 /**
15729 * Checks if `value` is likely a prototype object.
15730 *
15731 * @private
15732 * @param {*} value The value to check.
15733 * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
15734 */
15735 function isPrototype(value) {
15736 var Ctor = value && value.constructor,
15737 proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto$4;
15738
15739 return value === proto;
15740 }
15741
15742 var _isPrototype = isPrototype;
15743
15744 /**
15745 * Creates a unary function that invokes `func` with its argument transformed.
15746 *
15747 * @private
15748 * @param {Function} func The function to wrap.
15749 * @param {Function} transform The argument transform.
15750 * @returns {Function} Returns the new function.
15751 */
15752 function overArg(func, transform) {
15753 return function(arg) {
15754 return func(transform(arg));
15755 };
15756 }
15757
15758 var _overArg = overArg;
15759
15760 /* Built-in method references for those with the same name as other `lodash` methods. */
15761 var nativeKeys = _overArg(Object.keys, Object);
15762
15763 var _nativeKeys = nativeKeys;
15764
15765 /** Used for built-in method references. */
15766 var objectProto$5 = Object.prototype;
15767
15768 /** Used to check objects for own properties. */
15769 var hasOwnProperty$3 = objectProto$5.hasOwnProperty;
15770
15771 /**
15772 * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
15773 *
15774 * @private
15775 * @param {Object} object The object to query.
15776 * @returns {Array} Returns the array of property names.
15777 */
15778 function baseKeys(object) {
15779 if (!_isPrototype(object)) {
15780 return _nativeKeys(object);
15781 }
15782 var result = [];
15783 for (var key in Object(object)) {
15784 if (hasOwnProperty$3.call(object, key) && key != 'constructor') {
15785 result.push(key);
15786 }
15787 }
15788 return result;
15789 }
15790
15791 var _baseKeys = baseKeys;
15792
15793 /**
15794 * Checks if `value` is the
15795 * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
15796 * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
15797 *
15798 * @static
15799 * @memberOf _
15800 * @since 0.1.0
15801 * @category Lang
15802 * @param {*} value The value to check.
15803 * @returns {boolean} Returns `true` if `value` is an object, else `false`.
15804 * @example
15805 *
15806 * _.isObject({});
15807 * // => true
15808 *
15809 * _.isObject([1, 2, 3]);
15810 * // => true
15811 *
15812 * _.isObject(_.noop);
15813 * // => true
15814 *
15815 * _.isObject(null);
15816 * // => false
15817 */
15818 function isObject$1(value) {
15819 var type = typeof value;
15820 return value != null && (type == 'object' || type == 'function');
15821 }
15822
15823 var isObject_1$1 = isObject$1;
15824
15825 /** `Object#toString` result references. */
15826 var asyncTag = '[object AsyncFunction]',
15827 funcTag$1 = '[object Function]',
15828 genTag = '[object GeneratorFunction]',
15829 proxyTag = '[object Proxy]';
15830
15831 /**
15832 * Checks if `value` is classified as a `Function` object.
15833 *
15834 * @static
15835 * @memberOf _
15836 * @since 0.1.0
15837 * @category Lang
15838 * @param {*} value The value to check.
15839 * @returns {boolean} Returns `true` if `value` is a function, else `false`.
15840 * @example
15841 *
15842 * _.isFunction(_);
15843 * // => true
15844 *
15845 * _.isFunction(/abc/);
15846 * // => false
15847 */
15848 function isFunction(value) {
15849 if (!isObject_1$1(value)) {
15850 return false;
15851 }
15852 // The use of `Object#toString` avoids issues with the `typeof` operator
15853 // in Safari 9 which returns 'object' for typed arrays and other constructors.
15854 var tag = _baseGetTag(value);
15855 return tag == funcTag$1 || tag == genTag || tag == asyncTag || tag == proxyTag;
15856 }
15857
15858 var isFunction_1 = isFunction;
15859
15860 /**
15861 * Checks if `value` is array-like. A value is considered array-like if it's
15862 * not a function and has a `value.length` that's an integer greater than or
15863 * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
15864 *
15865 * @static
15866 * @memberOf _
15867 * @since 4.0.0
15868 * @category Lang
15869 * @param {*} value The value to check.
15870 * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
15871 * @example
15872 *
15873 * _.isArrayLike([1, 2, 3]);
15874 * // => true
15875 *
15876 * _.isArrayLike(document.body.children);
15877 * // => true
15878 *
15879 * _.isArrayLike('abc');
15880 * // => true
15881 *
15882 * _.isArrayLike(_.noop);
15883 * // => false
15884 */
15885 function isArrayLike(value) {
15886 return value != null && isLength_1(value.length) && !isFunction_1(value);
15887 }
15888
15889 var isArrayLike_1 = isArrayLike;
15890
15891 /**
15892 * Creates an array of the own enumerable property names of `object`.
15893 *
15894 * **Note:** Non-object values are coerced to objects. See the
15895 * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
15896 * for more details.
15897 *
15898 * @static
15899 * @since 0.1.0
15900 * @memberOf _
15901 * @category Object
15902 * @param {Object} object The object to query.
15903 * @returns {Array} Returns the array of property names.
15904 * @example
15905 *
15906 * function Foo() {
15907 * this.a = 1;
15908 * this.b = 2;
15909 * }
15910 *
15911 * Foo.prototype.c = 3;
15912 *
15913 * _.keys(new Foo);
15914 * // => ['a', 'b'] (iteration order is not guaranteed)
15915 *
15916 * _.keys('hi');
15917 * // => ['0', '1']
15918 */
15919 function keys(object) {
15920 return isArrayLike_1(object) ? _arrayLikeKeys(object) : _baseKeys(object);
15921 }
15922
15923 var keys_1 = keys;
15924
15925 /**
15926 * Creates an array of the own enumerable string keyed property values of `object`.
15927 *
15928 * **Note:** Non-object values are coerced to objects.
15929 *
15930 * @static
15931 * @since 0.1.0
15932 * @memberOf _
15933 * @category Object
15934 * @param {Object} object The object to query.
15935 * @returns {Array} Returns the array of property values.
15936 * @example
15937 *
15938 * function Foo() {
15939 * this.a = 1;
15940 * this.b = 2;
15941 * }
15942 *
15943 * Foo.prototype.c = 3;
15944 *
15945 * _.values(new Foo);
15946 * // => [1, 2] (iteration order is not guaranteed)
15947 *
15948 * _.values('hi');
15949 * // => ['h', 'i']
15950 */
15951 function values(object) {
15952 return object == null ? [] : _baseValues(object, keys_1(object));
15953 }
15954
15955 var values_1 = values;
15956
15957 /**
15958 * The base implementation of `_.shuffle`.
15959 *
15960 * @private
15961 * @param {Array|Object} collection The collection to shuffle.
15962 * @returns {Array} Returns the new shuffled array.
15963 */
15964 function baseShuffle(collection) {
15965 return _shuffleSelf(values_1(collection));
15966 }
15967
15968 var _baseShuffle = baseShuffle;
15969
15970 /**
15971 * Creates an array of shuffled values, using a version of the
15972 * [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle).
15973 *
15974 * @static
15975 * @memberOf _
15976 * @since 0.1.0
15977 * @category Collection
15978 * @param {Array|Object} collection The collection to shuffle.
15979 * @returns {Array} Returns the new shuffled array.
15980 * @example
15981 *
15982 * _.shuffle([1, 2, 3, 4]);
15983 * // => [4, 1, 3, 2]
15984 */
15985 function shuffle(collection) {
15986 var func = isArray_1(collection) ? _arrayShuffle : _baseShuffle;
15987 return func(collection);
15988 }
15989
15990 var shuffle_1 = shuffle;
15991
15992 var stateMachine = createCommonjsModule(function (module, exports) {
15993 /*
15994
15995 Javascript State Machine Library - https://github.com/jakesgordon/javascript-state-machine
15996
15997 Copyright (c) 2012, 2013, 2014, 2015, Jake Gordon and contributors
15998 Released under the MIT license - https://github.com/jakesgordon/javascript-state-machine/blob/master/LICENSE
15999
16000 */
16001
16002 (function () {
16003
16004 var StateMachine = {
16005
16006 //---------------------------------------------------------------------------
16007
16008 VERSION: "2.4.0",
16009
16010 //---------------------------------------------------------------------------
16011
16012 Result: {
16013 SUCCEEDED: 1, // the event transitioned successfully from one state to another
16014 NOTRANSITION: 2, // the event was successfull but no state transition was necessary
16015 CANCELLED: 3, // the event was cancelled by the caller in a beforeEvent callback
16016 PENDING: 4 // the event is asynchronous and the caller is in control of when the transition occurs
16017 },
16018
16019 Error: {
16020 INVALID_TRANSITION: 100, // caller tried to fire an event that was innapropriate in the current state
16021 PENDING_TRANSITION: 200, // caller tried to fire an event while an async transition was still pending
16022 INVALID_CALLBACK: 300 // caller provided callback function threw an exception
16023 },
16024
16025 WILDCARD: '*',
16026 ASYNC: 'async',
16027
16028 //---------------------------------------------------------------------------
16029
16030 create: function(cfg, target) {
16031
16032 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 }
16033 var terminal = cfg.terminal || cfg['final'];
16034 var fsm = target || cfg.target || {};
16035 var events = cfg.events || [];
16036 var callbacks = cfg.callbacks || {};
16037 var map = {}; // track state transitions allowed for an event { event: { from: [ to ] } }
16038 var transitions = {}; // track events allowed from a state { state: [ event ] }
16039
16040 var add = function(e) {
16041 var from = Array.isArray(e.from) ? e.from : (e.from ? [e.from] : [StateMachine.WILDCARD]); // allow 'wildcard' transition if 'from' is not specified
16042 map[e.name] = map[e.name] || {};
16043 for (var n = 0 ; n < from.length ; n++) {
16044 transitions[from[n]] = transitions[from[n]] || [];
16045 transitions[from[n]].push(e.name);
16046
16047 map[e.name][from[n]] = e.to || from[n]; // allow no-op transition if 'to' is not specified
16048 }
16049 if (e.to)
16050 transitions[e.to] = transitions[e.to] || [];
16051 };
16052
16053 if (initial) {
16054 initial.event = initial.event || 'startup';
16055 add({ name: initial.event, from: 'none', to: initial.state });
16056 }
16057
16058 for(var n = 0 ; n < events.length ; n++)
16059 add(events[n]);
16060
16061 for(var name in map) {
16062 if (map.hasOwnProperty(name))
16063 fsm[name] = StateMachine.buildEvent(name, map[name]);
16064 }
16065
16066 for(var name in callbacks) {
16067 if (callbacks.hasOwnProperty(name))
16068 fsm[name] = callbacks[name];
16069 }
16070
16071 fsm.current = 'none';
16072 fsm.is = function(state) { return Array.isArray(state) ? (state.indexOf(this.current) >= 0) : (this.current === state); };
16073 fsm.can = function(event) { return !this.transition && (map[event] !== undefined) && (map[event].hasOwnProperty(this.current) || map[event].hasOwnProperty(StateMachine.WILDCARD)); };
16074 fsm.cannot = function(event) { return !this.can(event); };
16075 fsm.transitions = function() { return (transitions[this.current] || []).concat(transitions[StateMachine.WILDCARD] || []); };
16076 fsm.isFinished = function() { return this.is(terminal); };
16077 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)
16078 fsm.states = function() { return Object.keys(transitions).sort() };
16079
16080 if (initial && !initial.defer)
16081 fsm[initial.event]();
16082
16083 return fsm;
16084
16085 },
16086
16087 //===========================================================================
16088
16089 doCallback: function(fsm, func, name, from, to, args) {
16090 if (func) {
16091 try {
16092 return func.apply(fsm, [name, from, to].concat(args));
16093 }
16094 catch(e) {
16095 return fsm.error(name, from, to, args, StateMachine.Error.INVALID_CALLBACK, "an exception occurred in a caller-provided callback function", e);
16096 }
16097 }
16098 },
16099
16100 beforeAnyEvent: function(fsm, name, from, to, args) { return StateMachine.doCallback(fsm, fsm['onbeforeevent'], name, from, to, args); },
16101 afterAnyEvent: function(fsm, name, from, to, args) { return StateMachine.doCallback(fsm, fsm['onafterevent'] || fsm['onevent'], name, from, to, args); },
16102 leaveAnyState: function(fsm, name, from, to, args) { return StateMachine.doCallback(fsm, fsm['onleavestate'], name, from, to, args); },
16103 enterAnyState: function(fsm, name, from, to, args) { return StateMachine.doCallback(fsm, fsm['onenterstate'] || fsm['onstate'], name, from, to, args); },
16104 changeState: function(fsm, name, from, to, args) { return StateMachine.doCallback(fsm, fsm['onchangestate'], name, from, to, args); },
16105
16106 beforeThisEvent: function(fsm, name, from, to, args) { return StateMachine.doCallback(fsm, fsm['onbefore' + name], name, from, to, args); },
16107 afterThisEvent: function(fsm, name, from, to, args) { return StateMachine.doCallback(fsm, fsm['onafter' + name] || fsm['on' + name], name, from, to, args); },
16108 leaveThisState: function(fsm, name, from, to, args) { return StateMachine.doCallback(fsm, fsm['onleave' + from], name, from, to, args); },
16109 enterThisState: function(fsm, name, from, to, args) { return StateMachine.doCallback(fsm, fsm['onenter' + to] || fsm['on' + to], name, from, to, args); },
16110
16111 beforeEvent: function(fsm, name, from, to, args) {
16112 if ((false === StateMachine.beforeThisEvent(fsm, name, from, to, args)) ||
16113 (false === StateMachine.beforeAnyEvent( fsm, name, from, to, args)))
16114 return false;
16115 },
16116
16117 afterEvent: function(fsm, name, from, to, args) {
16118 StateMachine.afterThisEvent(fsm, name, from, to, args);
16119 StateMachine.afterAnyEvent( fsm, name, from, to, args);
16120 },
16121
16122 leaveState: function(fsm, name, from, to, args) {
16123 var specific = StateMachine.leaveThisState(fsm, name, from, to, args),
16124 general = StateMachine.leaveAnyState( fsm, name, from, to, args);
16125 if ((false === specific) || (false === general))
16126 return false;
16127 else if ((StateMachine.ASYNC === specific) || (StateMachine.ASYNC === general))
16128 return StateMachine.ASYNC;
16129 },
16130
16131 enterState: function(fsm, name, from, to, args) {
16132 StateMachine.enterThisState(fsm, name, from, to, args);
16133 StateMachine.enterAnyState( fsm, name, from, to, args);
16134 },
16135
16136 //===========================================================================
16137
16138 buildEvent: function(name, map) {
16139 return function() {
16140
16141 var from = this.current;
16142 var to = map[from] || (map[StateMachine.WILDCARD] != StateMachine.WILDCARD ? map[StateMachine.WILDCARD] : from) || from;
16143 var args = Array.prototype.slice.call(arguments); // turn arguments into pure array
16144
16145 if (this.transition)
16146 return this.error(name, from, to, args, StateMachine.Error.PENDING_TRANSITION, "event " + name + " inappropriate because previous transition did not complete");
16147
16148 if (this.cannot(name))
16149 return this.error(name, from, to, args, StateMachine.Error.INVALID_TRANSITION, "event " + name + " inappropriate in current state " + this.current);
16150
16151 if (false === StateMachine.beforeEvent(this, name, from, to, args))
16152 return StateMachine.Result.CANCELLED;
16153
16154 if (from === to) {
16155 StateMachine.afterEvent(this, name, from, to, args);
16156 return StateMachine.Result.NOTRANSITION;
16157 }
16158
16159 // 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)
16160 var fsm = this;
16161 this.transition = function() {
16162 fsm.transition = null; // this method should only ever be called once
16163 fsm.current = to;
16164 StateMachine.enterState( fsm, name, from, to, args);
16165 StateMachine.changeState(fsm, name, from, to, args);
16166 StateMachine.afterEvent( fsm, name, from, to, args);
16167 return StateMachine.Result.SUCCEEDED;
16168 };
16169 this.transition.cancel = function() { // provide a way for caller to cancel async transition if desired (issue #22)
16170 fsm.transition = null;
16171 StateMachine.afterEvent(fsm, name, from, to, args);
16172 };
16173
16174 var leave = StateMachine.leaveState(this, name, from, to, args);
16175 if (false === leave) {
16176 this.transition = null;
16177 return StateMachine.Result.CANCELLED;
16178 }
16179 else if (StateMachine.ASYNC === leave) {
16180 return StateMachine.Result.PENDING;
16181 }
16182 else {
16183 if (this.transition) // need to check in case user manually called transition() but forgot to return StateMachine.ASYNC
16184 return this.transition();
16185 }
16186
16187 };
16188 }
16189
16190 }; // StateMachine
16191
16192 //===========================================================================
16193
16194 //======
16195 // NODE
16196 //======
16197 {
16198 if (module.exports) {
16199 exports = module.exports = StateMachine;
16200 }
16201 exports.StateMachine = StateMachine;
16202 }
16203
16204 }());
16205 });
16206 var stateMachine_1 = stateMachine.StateMachine;
16207
16208 /** Built-in value references. */
16209 var getPrototype = _overArg(Object.getPrototypeOf, Object);
16210
16211 var _getPrototype = getPrototype;
16212
16213 /** `Object#toString` result references. */
16214 var objectTag$1 = '[object Object]';
16215
16216 /** Used for built-in method references. */
16217 var funcProto = Function.prototype,
16218 objectProto$6 = Object.prototype;
16219
16220 /** Used to resolve the decompiled source of functions. */
16221 var funcToString = funcProto.toString;
16222
16223 /** Used to check objects for own properties. */
16224 var hasOwnProperty$4 = objectProto$6.hasOwnProperty;
16225
16226 /** Used to infer the `Object` constructor. */
16227 var objectCtorString = funcToString.call(Object);
16228
16229 /**
16230 * Checks if `value` is a plain object, that is, an object created by the
16231 * `Object` constructor or one with a `[[Prototype]]` of `null`.
16232 *
16233 * @static
16234 * @memberOf _
16235 * @since 0.8.0
16236 * @category Lang
16237 * @param {*} value The value to check.
16238 * @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
16239 * @example
16240 *
16241 * function Foo() {
16242 * this.a = 1;
16243 * }
16244 *
16245 * _.isPlainObject(new Foo);
16246 * // => false
16247 *
16248 * _.isPlainObject([1, 2, 3]);
16249 * // => false
16250 *
16251 * _.isPlainObject({ 'x': 0, 'y': 0 });
16252 * // => true
16253 *
16254 * _.isPlainObject(Object.create(null));
16255 * // => true
16256 */
16257 function isPlainObject(value) {
16258 if (!isObjectLike_1(value) || _baseGetTag(value) != objectTag$1) {
16259 return false;
16260 }
16261 var proto = _getPrototype(value);
16262 if (proto === null) {
16263 return true;
16264 }
16265 var Ctor = hasOwnProperty$4.call(proto, 'constructor') && proto.constructor;
16266 return typeof Ctor == 'function' && Ctor instanceof Ctor &&
16267 funcToString.call(Ctor) == objectCtorString;
16268 }
16269
16270 var isPlainObject_1 = isPlainObject;
16271
16272 /* eslint-disable */
16273 var global$1 = typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : {};
16274
16275 var EXPIRED = Symbol('expired');
16276 var debug = browser('LC:Expirable');
16277
16278 var Expirable =
16279 /*#__PURE__*/
16280 function () {
16281 function Expirable(value, ttl) {
16282 this.originalValue = value;
16283
16284 if (typeof ttl === 'number') {
16285 this.expiredAt = Date.now() + ttl;
16286 }
16287 }
16288
16289 _createClass(Expirable, [{
16290 key: "value",
16291 get: function get() {
16292 var expired = this.expiredAt && this.expiredAt <= Date.now();
16293 if (expired) debug("expired: ".concat(this.originalValue));
16294 return expired ? EXPIRED : this.originalValue;
16295 }
16296 }]);
16297
16298 return Expirable;
16299 }();
16300 Expirable.EXPIRED = EXPIRED;
16301
16302 var debug$1 = browser('LC:Cache');
16303
16304 var Cache =
16305 /*#__PURE__*/
16306 function () {
16307 function Cache() {
16308 var name = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'anonymous';
16309 this.name = name;
16310 this._map = {};
16311 }
16312
16313 var _proto = Cache.prototype;
16314
16315 _proto.get = function get(key) {
16316 var cache = this._map[key];
16317
16318 if (cache) {
16319 var value = cache.value;
16320
16321 if (value !== Expirable.EXPIRED) {
16322 debug$1('[%s] hit: %s', this.name, key);
16323 return value;
16324 }
16325
16326 delete this._map[key];
16327 }
16328
16329 debug$1("[".concat(this.name, "] missed: ").concat(key));
16330 return null;
16331 };
16332
16333 _proto.set = function set(key, value, ttl) {
16334 debug$1('[%s] set: %s %d', this.name, key, ttl);
16335 this._map[key] = new Expirable(value, ttl);
16336 };
16337
16338 return Cache;
16339 }();
16340
16341 var debug$2 = {
16342 enable: function enable() {
16343 var namespaces = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'LC*';
16344 return browser.enable(namespaces);
16345 },
16346 disable: browser.disable
16347 };
16348 var tryAll = function tryAll(promiseConstructors) {
16349 var promise = new Promise(promiseConstructors[0]);
16350
16351 if (promiseConstructors.length === 1) {
16352 return promise;
16353 }
16354
16355 return promise.catch(function () {
16356 return tryAll(promiseConstructors.slice(1));
16357 });
16358 }; // eslint-disable-next-line no-sequences
16359
16360 var tap = function tap(interceptor) {
16361 return function (value) {
16362 return interceptor(value), value;
16363 };
16364 };
16365 var isIE10 = global$1.navigator && global$1.navigator.userAgent && global$1.navigator.userAgent.indexOf('MSIE 10.') !== -1;
16366 var map = new WeakMap(); // protected property helper
16367
16368 var internal = function internal(object) {
16369 if (!map.has(object)) {
16370 map.set(object, {});
16371 }
16372
16373 return map.get(object);
16374 };
16375 var compact = function compact(obj, filter) {
16376 if (!isPlainObject_1(obj)) return obj;
16377 var object = Object.assign({}, obj); // eslint-disable-next-line no-restricted-syntax
16378
16379 for (var prop in object) {
16380 if ({}.hasOwnProperty.call(object, prop)) {
16381 var value = object[prop];
16382
16383 if (value === filter) {
16384 delete object[prop];
16385 } else {
16386 object[prop] = compact(value, filter);
16387 }
16388 }
16389 }
16390
16391 return object;
16392 }; // debug utility
16393
16394 var removeNull = function removeNull(obj) {
16395 return compact(obj, null);
16396 };
16397
16398 var trim = function trim(message) {
16399 return removeNull(JSON.parse(JSON.stringify(message)));
16400 };
16401 var ensureArray = function ensureArray(target) {
16402 if (Array.isArray(target)) {
16403 return target;
16404 }
16405
16406 if (target === undefined || target === null) {
16407 return [];
16408 }
16409
16410 return [target];
16411 };
16412 var isWeapp = // eslint-disable-next-line no-undef
16413 (typeof wx === "undefined" ? "undefined" : _typeof(wx)) === 'object' && typeof wx.connectSocket === 'function'; // throttle decorator
16414 var isCNApp = function isCNApp(appId) {
16415 return appId.slice(-9) !== '-MdYXbMMI';
16416 };
16417
16418 var WebSocket = global$1.WebSocket || global$1.MozWebSocket;
16419
16420 var _class;
16421 var debug$3 = browser('LC:WebSocketPlus');
16422 var OPEN = 'open';
16423 var DISCONNECT = 'disconnect';
16424 var RECONNECT = 'reconnect';
16425 var RETRY = 'retry';
16426 var SCHEDULE = 'schedule';
16427 var OFFLINE = 'offline';
16428 var ONLINE = 'online';
16429 var ERROR = 'error';
16430 var MESSAGE = 'message';
16431 var HEARTBEAT_TIME = 180000;
16432 var TIMEOUT_TIME = 380000;
16433
16434 var DEFAULT_RETRY_STRATEGY = function DEFAULT_RETRY_STRATEGY(attempt) {
16435 return Math.min(1000 * Math.pow(2, attempt), 300000);
16436 };
16437
16438 var requireConnected = function requireConnected(target, name, descriptor) {
16439 return Object.assign({}, descriptor, {
16440 value: function requireConnectedWrapper() {
16441 var _descriptor$value;
16442
16443 this.checkConnectionAvailability(name);
16444
16445 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
16446 args[_key] = arguments[_key];
16447 }
16448
16449 return (_descriptor$value = descriptor.value).call.apply(_descriptor$value, [this].concat(args));
16450 }
16451 });
16452 };
16453
16454 var WebSocketPlus = (_class =
16455 /*#__PURE__*/
16456 function (_EventEmitter) {
16457 _inheritsLoose(WebSocketPlus, _EventEmitter);
16458
16459 _createClass(WebSocketPlus, [{
16460 key: "urls",
16461 get: function get() {
16462 return this._urls;
16463 },
16464 set: function set(urls) {
16465 this._urls = ensureArray(urls);
16466 }
16467 }]);
16468
16469 function WebSocketPlus(getUrls, protocol) {
16470 var _this;
16471
16472 if (typeof WebSocket === 'undefined') {
16473 throw new Error('WebSocket is undefined. Polyfill is required in this runtime.');
16474 }
16475
16476 _this = _EventEmitter.call(this) || this;
16477
16478 _this.init();
16479
16480 _this._protocol = protocol;
16481 Promise.resolve(typeof getUrls === 'function' ? getUrls() : getUrls).then(ensureArray).then(function (urls) {
16482 _this._urls = urls;
16483 return _this._open();
16484 }).then(function () {
16485 _this.__postponeTimeoutTimer = _this._postponeTimeoutTimer.bind(_assertThisInitialized(_this));
16486
16487 if (global$1.addEventListener) {
16488 _this.__pause = function () {
16489 if (_this.can('pause')) _this.pause();
16490 };
16491
16492 _this.__resume = function () {
16493 if (_this.can('resume')) _this.resume();
16494 };
16495
16496 global$1.addEventListener('offline', _this.__pause);
16497 global$1.addEventListener('online', _this.__resume);
16498 }
16499
16500 _this.open();
16501 }).catch(_this.throw.bind(_assertThisInitialized(_this)));
16502 return _this;
16503 }
16504
16505 var _proto = WebSocketPlus.prototype;
16506
16507 _proto._open = function _open() {
16508 var _this2 = this;
16509
16510 return this._createWs(this._urls, this._protocol).then(function (ws) {
16511 var _this2$_urls = _toArray(_this2._urls),
16512 first = _this2$_urls[0],
16513 reset = _this2$_urls.slice(1);
16514
16515 _this2._urls = [].concat(_toConsumableArray(reset), [first]);
16516 return ws;
16517 });
16518 };
16519
16520 _proto._createWs = function _createWs(urls, protocol) {
16521 var _this3 = this;
16522
16523 return tryAll(urls.map(function (url) {
16524 return function (resolve, reject) {
16525 debug$3("connect [".concat(url, "] ").concat(protocol));
16526 var ws = protocol ? new WebSocket(url, protocol) : new WebSocket(url);
16527 ws.binaryType = _this3.binaryType || 'arraybuffer';
16528
16529 ws.onopen = function () {
16530 return resolve(ws);
16531 };
16532
16533 ws.onclose = function (error) {
16534 if (error instanceof Error) {
16535 return reject(error);
16536 } // in browser, error event is useless
16537
16538
16539 return reject(new Error("Failed to connect [".concat(url, "]")));
16540 };
16541
16542 ws.onerror = ws.onclose;
16543 };
16544 })).then(function (ws) {
16545 _this3._ws = ws;
16546 _this3._ws.onclose = _this3._handleClose.bind(_this3);
16547 _this3._ws.onmessage = _this3._handleMessage.bind(_this3);
16548 return ws;
16549 });
16550 };
16551
16552 _proto._destroyWs = function _destroyWs() {
16553 var ws = this._ws;
16554 if (!ws) return;
16555 ws.onopen = null;
16556 ws.onclose = null;
16557 ws.onerror = null;
16558 ws.onmessage = null;
16559 this._ws = null;
16560 ws.close();
16561 } // eslint-disable-next-line class-methods-use-this
16562 ;
16563
16564 _proto.onbeforeevent = function onbeforeevent(event, from, to) {
16565 for (var _len2 = arguments.length, payload = new Array(_len2 > 3 ? _len2 - 3 : 0), _key2 = 3; _key2 < _len2; _key2++) {
16566 payload[_key2 - 3] = arguments[_key2];
16567 }
16568
16569 debug$3("".concat(event, ": ").concat(from, " -> ").concat(to, " %o"), payload);
16570 };
16571
16572 _proto.onopen = function onopen() {
16573 this.emit(OPEN);
16574 };
16575
16576 _proto.onconnected = function onconnected() {
16577 this._startConnectionKeeper();
16578 };
16579
16580 _proto.onleaveconnected = function onleaveconnected(event, from, to) {
16581 this._stopConnectionKeeper();
16582
16583 this._destroyWs();
16584
16585 if (to === 'offline' || to === 'disconnected') {
16586 this.emit(DISCONNECT);
16587 }
16588 };
16589
16590 _proto.onpause = function onpause() {
16591 this.emit(OFFLINE);
16592 };
16593
16594 _proto.onbeforeresume = function onbeforeresume() {
16595 this.emit(ONLINE);
16596 };
16597
16598 _proto.onreconnect = function onreconnect() {
16599 this.emit(RECONNECT);
16600 };
16601
16602 _proto.ondisconnected = function ondisconnected(event, from, to) {
16603 var _this4 = this;
16604
16605 var attempt = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;
16606 var delay = DEFAULT_RETRY_STRATEGY.call(null, attempt);
16607 debug$3("schedule attempt=".concat(attempt, " delay=").concat(delay));
16608 this.emit(SCHEDULE, attempt, delay);
16609
16610 if (this.__scheduledRetry) {
16611 clearTimeout(this.__scheduledRetry);
16612 }
16613
16614 this.__scheduledRetry = setTimeout(function () {
16615 if (_this4.is('disconnected')) {
16616 _this4.retry(attempt);
16617 }
16618 }, delay);
16619 };
16620
16621 _proto.onretry = function onretry(event, from, to) {
16622 var _this5 = this;
16623
16624 var attempt = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;
16625 this.emit(RETRY, attempt);
16626
16627 this._open().then(function () {
16628 return _this5.can('reconnect') ? _this5.reconnect() : _this5._destroyWs();
16629 }, function () {
16630 return _this5.can('fail') && _this5.fail(attempt + 1);
16631 });
16632 };
16633
16634 _proto.onerror = function onerror(event, from, to, error) {
16635 this.emit(ERROR, error);
16636 };
16637
16638 _proto.onclose = function onclose() {
16639 if (global$1.removeEventListener) {
16640 if (this.__pause) global$1.removeEventListener('offline', this.__pause);
16641 if (this.__resume) global$1.removeEventListener('online', this.__resume);
16642 }
16643 };
16644
16645 _proto.checkConnectionAvailability = function checkConnectionAvailability() {
16646 var name = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'API';
16647
16648 if (!this.is('connected')) {
16649 var currentState = this.current;
16650 console.warn("".concat(name, " should not be called when the connection is ").concat(currentState));
16651
16652 if (this.is('disconnected') || this.is('reconnecting')) {
16653 console.warn('disconnect and reconnect event should be handled to avoid such calls.');
16654 }
16655
16656 throw new Error('Connection unavailable');
16657 }
16658 } // jsdoc-ignore-start
16659 ;
16660
16661 _proto. // jsdoc-ignore-end
16662 _ping = function _ping() {
16663 debug$3('ping');
16664
16665 try {
16666 this.ping();
16667 } catch (error) {
16668 console.warn("websocket ping error: ".concat(error.message));
16669 }
16670 };
16671
16672 _proto.ping = function ping() {
16673 if (this._ws.ping) {
16674 this._ws.ping();
16675 } else {
16676 console.warn("The WebSocket implement does not support sending ping frame.\n Override ping method to use application defined ping/pong mechanism.");
16677 }
16678 };
16679
16680 _proto._postponeTimeoutTimer = function _postponeTimeoutTimer() {
16681 var _this6 = this;
16682
16683 debug$3('_postponeTimeoutTimer');
16684
16685 this._clearTimeoutTimers();
16686
16687 this._timeoutTimer = setTimeout(function () {
16688 debug$3('timeout');
16689
16690 _this6.disconnect();
16691 }, TIMEOUT_TIME);
16692 };
16693
16694 _proto._clearTimeoutTimers = function _clearTimeoutTimers() {
16695 if (this._timeoutTimer) {
16696 clearTimeout(this._timeoutTimer);
16697 }
16698 };
16699
16700 _proto._startConnectionKeeper = function _startConnectionKeeper() {
16701 debug$3('start connection keeper');
16702 this._heartbeatTimer = setInterval(this._ping.bind(this), HEARTBEAT_TIME);
16703 var addListener = this._ws.addListener || this._ws.addEventListener;
16704
16705 if (!addListener) {
16706 debug$3('connection keeper disabled due to the lack of #addEventListener.');
16707 return;
16708 }
16709
16710 addListener.call(this._ws, 'message', this.__postponeTimeoutTimer);
16711 addListener.call(this._ws, 'pong', this.__postponeTimeoutTimer);
16712
16713 this._postponeTimeoutTimer();
16714 };
16715
16716 _proto._stopConnectionKeeper = function _stopConnectionKeeper() {
16717 debug$3('stop connection keeper'); // websockets/ws#489
16718
16719 var removeListener = this._ws.removeListener || this._ws.removeEventListener;
16720
16721 if (removeListener) {
16722 removeListener.call(this._ws, 'message', this.__postponeTimeoutTimer);
16723 removeListener.call(this._ws, 'pong', this.__postponeTimeoutTimer);
16724
16725 this._clearTimeoutTimers();
16726 }
16727
16728 if (this._heartbeatTimer) {
16729 clearInterval(this._heartbeatTimer);
16730 }
16731 };
16732
16733 _proto._handleClose = function _handleClose(event) {
16734 debug$3("ws closed [".concat(event.code, "] ").concat(event.reason)); // socket closed manually, ignore close event.
16735
16736 if (this.isFinished()) return;
16737 this.handleClose(event);
16738 };
16739
16740 _proto.handleClose = function handleClose() {
16741 // reconnect
16742 this.disconnect();
16743 } // jsdoc-ignore-start
16744 ;
16745
16746 _proto. // jsdoc-ignore-end
16747 send = function send(data) {
16748 debug$3('send', data);
16749
16750 this._ws.send(data);
16751 };
16752
16753 _proto._handleMessage = function _handleMessage(event) {
16754 debug$3('message', event.data);
16755 this.handleMessage(event.data);
16756 };
16757
16758 _proto.handleMessage = function handleMessage(message) {
16759 this.emit(MESSAGE, message);
16760 };
16761
16762 return WebSocketPlus;
16763 }(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);
16764 stateMachine.create({
16765 target: WebSocketPlus.prototype,
16766 initial: {
16767 state: 'initialized',
16768 event: 'init',
16769 defer: true
16770 },
16771 terminal: 'closed',
16772 events: [{
16773 name: 'open',
16774 from: 'initialized',
16775 to: 'connected'
16776 }, {
16777 name: 'disconnect',
16778 from: 'connected',
16779 to: 'disconnected'
16780 }, {
16781 name: 'retry',
16782 from: 'disconnected',
16783 to: 'reconnecting'
16784 }, {
16785 name: 'fail',
16786 from: 'reconnecting',
16787 to: 'disconnected'
16788 }, {
16789 name: 'reconnect',
16790 from: 'reconnecting',
16791 to: 'connected'
16792 }, {
16793 name: 'pause',
16794 from: ['connected', 'disconnected', 'reconnecting'],
16795 to: 'offline'
16796 }, {}, {
16797 name: 'resume',
16798 from: 'offline',
16799 to: 'disconnected'
16800 }, {
16801 name: 'close',
16802 from: ['connected', 'disconnected', 'reconnecting', 'offline'],
16803 to: 'closed'
16804 }, {
16805 name: 'throw',
16806 from: '*',
16807 to: 'error'
16808 }]
16809 });
16810
16811 var error = Object.freeze({
16812 1000: {
16813 name: 'CLOSE_NORMAL'
16814 },
16815 1006: {
16816 name: 'CLOSE_ABNORMAL'
16817 },
16818 4100: {
16819 name: 'APP_NOT_AVAILABLE',
16820 message: 'App not exists or realtime message service is disabled.'
16821 },
16822 4102: {
16823 name: 'SIGNATURE_FAILED',
16824 message: 'Login signature mismatch.'
16825 },
16826 4103: {
16827 name: 'INVALID_LOGIN',
16828 message: 'Malformed clientId.'
16829 },
16830 4105: {
16831 name: 'SESSION_REQUIRED',
16832 message: 'Message sent before session opened.'
16833 },
16834 4107: {
16835 name: 'READ_TIMEOUT'
16836 },
16837 4108: {
16838 name: 'LOGIN_TIMEOUT'
16839 },
16840 4109: {
16841 name: 'FRAME_TOO_LONG'
16842 },
16843 4110: {
16844 name: 'INVALID_ORIGIN',
16845 message: 'Access denied by domain whitelist.'
16846 },
16847 4111: {
16848 name: 'SESSION_CONFLICT'
16849 },
16850 4112: {
16851 name: 'SESSION_TOKEN_EXPIRED'
16852 },
16853 4113: {
16854 name: 'APP_QUOTA_EXCEEDED',
16855 message: 'The daily active users limit exceeded.'
16856 },
16857 4116: {
16858 name: 'MESSAGE_SENT_QUOTA_EXCEEDED',
16859 message: 'Command sent too fast.'
16860 },
16861 4200: {
16862 name: 'INTERNAL_ERROR',
16863 message: 'Internal error, please contact LeanCloud for support.'
16864 },
16865 4301: {
16866 name: 'CONVERSATION_API_FAILED',
16867 message: 'Upstream Conversatoin API failed, see error.detail for details.'
16868 },
16869 4302: {
16870 name: 'CONVERSATION_SIGNATURE_FAILED',
16871 message: 'Conversation action signature mismatch.'
16872 },
16873 4303: {
16874 name: 'CONVERSATION_NOT_FOUND'
16875 },
16876 4304: {
16877 name: 'CONVERSATION_FULL'
16878 },
16879 4305: {
16880 name: 'CONVERSATION_REJECTED_BY_APP',
16881 message: 'Conversation action rejected by hook.'
16882 },
16883 4306: {
16884 name: 'CONVERSATION_UPDATE_FAILED'
16885 },
16886 4307: {
16887 name: 'CONVERSATION_READ_ONLY'
16888 },
16889 4308: {
16890 name: 'CONVERSATION_NOT_ALLOWED'
16891 },
16892 4309: {
16893 name: 'CONVERSATION_UPDATE_REJECTED',
16894 message: 'Conversation update rejected because the client is not a member.'
16895 },
16896 4310: {
16897 name: 'CONVERSATION_QUERY_FAILED',
16898 message: 'Conversation query failed because it is too expansive.'
16899 },
16900 4311: {
16901 name: 'CONVERSATION_LOG_FAILED'
16902 },
16903 4312: {
16904 name: 'CONVERSATION_LOG_REJECTED',
16905 message: 'Message query rejected because the client is not a member of the conversation.'
16906 },
16907 4313: {
16908 name: 'SYSTEM_CONVERSATION_REQUIRED'
16909 },
16910 4314: {
16911 name: 'NORMAL_CONVERSATION_REQUIRED'
16912 },
16913 4315: {
16914 name: 'CONVERSATION_BLACKLISTED',
16915 message: 'Blacklisted in the conversation.'
16916 },
16917 4316: {
16918 name: 'TRANSIENT_CONVERSATION_REQUIRED'
16919 },
16920 4317: {
16921 name: 'CONVERSATION_MEMBERSHIP_REQUIRED'
16922 },
16923 4318: {
16924 name: 'CONVERSATION_API_QUOTA_EXCEEDED',
16925 message: 'LeanCloud API quota exceeded. You may upgrade your plan.'
16926 },
16927 4323: {
16928 name: 'TEMPORARY_CONVERSATION_EXPIRED',
16929 message: 'Temporary conversation expired or does not exist.'
16930 },
16931 4401: {
16932 name: 'INVALID_MESSAGING_TARGET',
16933 message: 'Conversation does not exist or client is not a member.'
16934 },
16935 4402: {
16936 name: 'MESSAGE_REJECTED_BY_APP',
16937 message: 'Message rejected by hook.'
16938 },
16939 4403: {
16940 name: 'MESSAGE_OWNERSHIP_REQUIRED'
16941 },
16942 4404: {
16943 name: 'MESSAGE_NOT_FOUND'
16944 },
16945 4405: {
16946 name: 'MESSAGE_UPDATE_REJECTED_BY_APP',
16947 message: 'Message update rejected by hook.'
16948 },
16949 4406: {
16950 name: 'MESSAGE_EDIT_DISABLED'
16951 },
16952 4407: {
16953 name: 'MESSAGE_RECALL_DISABLED'
16954 },
16955 5130: {
16956 name: 'OWNER_PROMOTION_NOT_ALLOWED',
16957 message: "Updating a member's role to owner is not allowed."
16958 }
16959 });
16960 var ErrorCode = Object.freeze(Object.keys(error).reduce(function (result, code) {
16961 return Object.assign(result, _defineProperty({}, error[code].name, Number(code)));
16962 }, {}));
16963 var createError = function createError(_ref) {
16964 var code = _ref.code,
16965 reason = _ref.reason,
16966 appCode = _ref.appCode,
16967 detail = _ref.detail,
16968 errorMessage = _ref.error;
16969 var message = reason || detail || errorMessage;
16970 var name = reason;
16971
16972 if (!message && error[code]) {
16973 name = error[code].name;
16974 message = error[code].message || name;
16975 }
16976
16977 if (!message) {
16978 message = "Unknow Error: ".concat(code);
16979 }
16980
16981 var err = new Error(message);
16982 return Object.assign(err, {
16983 code: code,
16984 appCode: appCode,
16985 detail: detail,
16986 name: name
16987 });
16988 };
16989
16990 var debug$4 = browser('LC:Connection');
16991 var COMMAND_TIMEOUT = 20000;
16992 var EXPIRE = Symbol('expire');
16993
16994 var Connection =
16995 /*#__PURE__*/
16996 function (_WebSocketPlus) {
16997 _inheritsLoose(Connection, _WebSocketPlus);
16998
16999 function Connection(getUrl, _ref) {
17000 var _this;
17001
17002 var format = _ref.format,
17003 version = _ref.version;
17004 debug$4('initializing Connection');
17005 var protocolString = "lc.".concat(format, ".").concat(version);
17006
17007 if (!isWeapp) {
17008 _this = _WebSocketPlus.call(this, getUrl, protocolString) || this;
17009 } else {
17010 _this = _WebSocketPlus.call(this, getUrl().then(function (urls) {
17011 return urls.map(function (url) {
17012 return "".concat(url).concat(url.indexOf('?') === -1 ? '?' : '&', "subprotocol=").concat(encodeURIComponent(protocolString));
17013 });
17014 })) || this;
17015 }
17016
17017 _this._protocalFormat = format;
17018 _this._commands = {};
17019 _this._serialId = 0;
17020 return _assertThisInitialized(_this);
17021 }
17022
17023 var _proto = Connection.prototype;
17024
17025 _proto.send =
17026 /*#__PURE__*/
17027 function () {
17028 var _send = _asyncToGenerator(
17029 /*#__PURE__*/
17030 regenerator.mark(function _callee(command) {
17031 var _this2 = this;
17032
17033 var waitingForRespond,
17034 serialId,
17035 message,
17036 _args = arguments;
17037 return regenerator.wrap(function _callee$(_context) {
17038 while (1) {
17039 switch (_context.prev = _context.next) {
17040 case 0:
17041 waitingForRespond = _args.length > 1 && _args[1] !== undefined ? _args[1] : true;
17042
17043 if (waitingForRespond) {
17044 this._serialId += 1;
17045 serialId = this._serialId;
17046 command.i = serialId; // eslint-disable-line no-param-reassign
17047 }
17048
17049 if (debug$4.enabled) debug$4('↑ %O sent', trim(command));
17050
17051 if (this._protocalFormat === 'proto2base64') {
17052 message = command.toBase64();
17053 } else if (command.toArrayBuffer) {
17054 message = command.toArrayBuffer();
17055 }
17056
17057 if (message) {
17058 _context.next = 6;
17059 break;
17060 }
17061
17062 throw new TypeError("".concat(command, " is not a GenericCommand"));
17063
17064 case 6:
17065 _WebSocketPlus.prototype.send.call(this, message);
17066
17067 if (waitingForRespond) {
17068 _context.next = 9;
17069 break;
17070 }
17071
17072 return _context.abrupt("return", undefined);
17073
17074 case 9:
17075 return _context.abrupt("return", new Promise(function (resolve, reject) {
17076 _this2._commands[serialId] = {
17077 resolve: resolve,
17078 reject: reject,
17079 timeout: setTimeout(function () {
17080 if (_this2._commands[serialId]) {
17081 if (debug$4.enabled) debug$4('✗ %O timeout', trim(command));
17082 reject(createError({
17083 error: "Command Timeout [cmd:".concat(command.cmd, " op:").concat(command.op, "]"),
17084 name: 'COMMAND_TIMEOUT'
17085 }));
17086 delete _this2._commands[serialId];
17087 }
17088 }, COMMAND_TIMEOUT)
17089 };
17090 }));
17091
17092 case 10:
17093 case "end":
17094 return _context.stop();
17095 }
17096 }
17097 }, _callee, this);
17098 }));
17099
17100 function send(_x) {
17101 return _send.apply(this, arguments);
17102 }
17103
17104 return send;
17105 }();
17106
17107 _proto.handleMessage = function handleMessage(msg) {
17108 var message;
17109
17110 try {
17111 message = GenericCommand.decode(msg);
17112 if (debug$4.enabled) debug$4('↓ %O received', trim(message));
17113 } catch (e) {
17114 console.warn('Decode message failed:', e.message, msg);
17115 return;
17116 }
17117
17118 var serialId = message.i;
17119
17120 if (serialId) {
17121 if (this._commands[serialId]) {
17122 clearTimeout(this._commands[serialId].timeout);
17123
17124 if (message.cmd === CommandType.error) {
17125 this._commands[serialId].reject(createError(message.errorMessage));
17126 } else {
17127 this._commands[serialId].resolve(message);
17128 }
17129
17130 delete this._commands[serialId];
17131 } else {
17132 console.warn("Unexpected command received with serialId [".concat(serialId, "],\n which have timed out or never been requested."));
17133 }
17134 } else {
17135 switch (message.cmd) {
17136 case CommandType.error:
17137 {
17138 this.emit(ERROR, createError(message.errorMessage));
17139 return;
17140 }
17141
17142 case CommandType.goaway:
17143 {
17144 this.emit(EXPIRE);
17145 return;
17146 }
17147
17148 default:
17149 {
17150 this.emit(MESSAGE, message);
17151 }
17152 }
17153 }
17154 };
17155
17156 _proto.ping = function ping() {
17157 return this.send(new GenericCommand({
17158 cmd: CommandType.echo
17159 })).catch(function (error) {
17160 return debug$4('ping failed:', error);
17161 });
17162 };
17163
17164 return Connection;
17165 }(WebSocketPlus);
17166
17167 var applyDecorators = function applyDecorators(decorators, target) {
17168 if (decorators) {
17169 decorators.forEach(function (decorator) {
17170 try {
17171 decorator(target);
17172 } catch (error) {
17173 if (decorator._pluginName) {
17174 error.message += "[".concat(decorator._pluginName, "]");
17175 }
17176
17177 throw error;
17178 }
17179 });
17180 }
17181 };
17182 var applyDispatcher = function applyDispatcher(dispatchers, payload) {
17183 return ensureArray(dispatchers).reduce(function (resultPromise, dispatcher) {
17184 return resultPromise.then(function (shouldDispatch) {
17185 return shouldDispatch === false ? false : dispatcher.apply(void 0, _toConsumableArray(payload));
17186 }).catch(function (error) {
17187 if (dispatcher._pluginName) {
17188 // eslint-disable-next-line no-param-reassign
17189 error.message += "[".concat(dispatcher._pluginName, "]");
17190 }
17191
17192 throw error;
17193 });
17194 }, Promise.resolve(true));
17195 };
17196
17197 var version = "5.0.0-beta.0";
17198
17199 var debug$5 = browser('LC:Realtime');
17200 var debugRequest = browser('LC:request');
17201 var routerCache = new Cache('push-router');
17202
17203 var Realtime =
17204 /*#__PURE__*/
17205 function (_EventEmitter) {
17206 _inheritsLoose(Realtime, _EventEmitter);
17207
17208 /**
17209 * @extends EventEmitter
17210 * @param {Object} options
17211 * @param {String} options.appId
17212 * @param {String} options.appKey (since 4.0.0)
17213 * @param {String|Object} [options.server] 指定服务器域名,中国节点应用此参数必填(since 4.0.0)
17214 * @param {Boolean} [options.pushOfflineMessages=false] 启用推送离线消息模式(默认为发送未读消息通知模式)
17215 * @param {Boolean} [options.noBinary=false] 设置 WebSocket 使用字符串格式收发消息(默认为二进制格式)。
17216 * 适用于 WebSocket 实现不支持二进制数据格式的情况
17217 * @param {Boolean} [options.ssl=true] 使用 wss 进行连接
17218 * @param {String|String[]} [options.RTMServers] 指定私有部署的 RTM 服务器地址(since 4.0.0)
17219 * @param {Plugin[]} [options.plugins] 加载插件(since 3.1.0)
17220 */
17221 function Realtime(_ref) {
17222 var _this2;
17223
17224 var plugins = _ref.plugins,
17225 options = _objectWithoutProperties(_ref, ["plugins"]);
17226
17227 debug$5('initializing Realtime %s %O', version, options);
17228 _this2 = _EventEmitter.call(this) || this;
17229
17230 if (typeof options.appId !== 'string') {
17231 throw new TypeError("appId [".concat(options.appId, "] is not a string"));
17232 }
17233
17234 if (typeof options.appKey !== 'string') {
17235 throw new TypeError("appKey [".concat(options.appKey, "] is not a string"));
17236 }
17237
17238 if (isCNApp(options.appId)) {
17239 if (!options.server) {
17240 throw new TypeError("server option is required for apps from CN region");
17241 }
17242 }
17243
17244 _this2._options = Object.assign({
17245 appId: undefined,
17246 appKey: undefined,
17247 pushOfflineMessages: false,
17248 noBinary: false,
17249 ssl: true,
17250 RTMServerName: process.env.RTM_SERVER_NAME // undocumented on purpose, internal use only
17251
17252 }, options);
17253 _this2._cache = new Cache('endpoints');
17254
17255 var _this = internal(_assertThisInitialized(_this2));
17256
17257 _this.clients = new Set();
17258 _this.pendingClients = new Set();
17259 var mergedPlugins = [].concat(_toConsumableArray(ensureArray(Realtime.__preRegisteredPlugins)), _toConsumableArray(ensureArray(plugins)));
17260 debug$5('Using plugins %o', mergedPlugins.map(function (plugin) {
17261 return plugin.name;
17262 }));
17263 _this2._plugins = mergedPlugins.reduce(function (result, plugin) {
17264 // eslint-disable-next-line no-restricted-syntax
17265 for (var hook in plugin) {
17266 if ({}.hasOwnProperty.call(plugin, hook) && hook !== 'name') {
17267 if (plugin.name) {
17268 ensureArray(plugin[hook]).forEach(function (value) {
17269 // eslint-disable-next-line no-param-reassign
17270 value._pluginName = plugin.name;
17271 });
17272 } // eslint-disable-next-line no-param-reassign
17273
17274
17275 result[hook] = ensureArray(result[hook]).concat(plugin[hook]);
17276 }
17277 }
17278
17279 return result;
17280 }, {}); // onRealtimeCreate hook
17281
17282 applyDecorators(_this2._plugins.onRealtimeCreate, _assertThisInitialized(_this2));
17283 return _this2;
17284 }
17285
17286 var _proto = Realtime.prototype;
17287
17288 _proto._request =
17289 /*#__PURE__*/
17290 function () {
17291 var _request2 = _asyncToGenerator(
17292 /*#__PURE__*/
17293 regenerator.mark(function _callee(_ref2) {
17294 var method, _ref2$version, version, path, query, headers, _ref2$data, data, _this$_options, appId, server, _ref3, api, url;
17295
17296 return regenerator.wrap(function _callee$(_context) {
17297 while (1) {
17298 switch (_context.prev = _context.next) {
17299 case 0:
17300 method = _ref2.method, _ref2$version = _ref2.version, version = _ref2$version === void 0 ? '1.1' : _ref2$version, path = _ref2.path, query = _ref2.query, headers = _ref2.headers, _ref2$data = _ref2.data, data = _ref2$data === void 0 ? {} : _ref2$data;
17301 _this$_options = this._options, appId = _this$_options.appId, server = _this$_options.server;
17302 _context.next = 4;
17303 return this.constructor._getServerUrls({
17304 appId: appId,
17305 server: server
17306 });
17307
17308 case 4:
17309 _ref3 = _context.sent;
17310 api = _ref3.api;
17311 url = "".concat(api, "/").concat(version).concat(path);
17312 debugRequest('Req: %O %O %O', method, url, {
17313 query: query,
17314 headers: headers,
17315 data: data
17316 });
17317 return _context.abrupt("return", client(method, url).set(_objectSpread({
17318 'X-LC-Id': this._options.appId,
17319 'X-LC-Key': this._options.appKey
17320 }, headers)).query(query).send(data).then(function (response) {
17321 debugRequest('Res: %O %O %O', url, response.status, response.body);
17322 return response.body;
17323 }, function (error) {
17324 debugRequest('Error: %O %O %O', url, error.response.status, error.response.body);
17325
17326 if (error.response && error.response.body && error.response.body.code) {
17327 throw createError(error.response.body);
17328 }
17329
17330 throw error;
17331 }));
17332
17333 case 9:
17334 case "end":
17335 return _context.stop();
17336 }
17337 }
17338 }, _callee, this);
17339 }));
17340
17341 function _request(_x) {
17342 return _request2.apply(this, arguments);
17343 }
17344
17345 return _request;
17346 }();
17347
17348 _proto._open = function _open() {
17349 var _this3 = this;
17350
17351 if (this._openPromise) return this._openPromise;
17352 var format = 'protobuf2';
17353
17354 if (this._options.noBinary) {
17355 // 不发送 binary data,fallback to base64 string
17356 format = 'proto2base64';
17357 }
17358
17359 var version = 3;
17360
17361 if (this._options.pushOfflineMessages) {
17362 // 不推送离线消息,而是发送对话的未读通知
17363 version = 1;
17364 }
17365
17366 var protocol = {
17367 format: format,
17368 version: version
17369 };
17370 this._openPromise = new Promise(function (resolve, reject) {
17371 debug$5('No connection established, create a new one.');
17372 var connection = new Connection(function () {
17373 return _this3._getRTMServers(_this3._options);
17374 }, protocol);
17375 connection.on(OPEN, function () {
17376 return resolve(connection);
17377 }).on(ERROR, reject).on(EXPIRE,
17378 /*#__PURE__*/
17379 _asyncToGenerator(
17380 /*#__PURE__*/
17381 regenerator.mark(function _callee2() {
17382 return regenerator.wrap(function _callee2$(_context2) {
17383 while (1) {
17384 switch (_context2.prev = _context2.next) {
17385 case 0:
17386 debug$5('Connection expired. Refresh endpoints.');
17387
17388 _this3._cache.set('endpoints', null, 0);
17389
17390 _context2.next = 4;
17391 return _this3._getRTMServers(_this3._options);
17392
17393 case 4:
17394 connection.urls = _context2.sent;
17395 connection.disconnect();
17396
17397 case 6:
17398 case "end":
17399 return _context2.stop();
17400 }
17401 }
17402 }, _callee2, this);
17403 }))).on(MESSAGE, _this3._dispatchCommand.bind(_this3));
17404 /**
17405 * 连接断开。
17406 * 连接断开可能是因为 SDK 进入了离线状态(see {@link Realtime#event:OFFLINE}),或长时间没有收到服务器心跳。
17407 * 连接断开后所有的网络操作都会失败,请在连接断开后禁用相关的 UI 元素。
17408 * @event Realtime#DISCONNECT
17409 */
17410
17411 /**
17412 * 计划在一段时间后尝试重新连接
17413 * @event Realtime#SCHEDULE
17414 * @param {Number} attempt 尝试重连的次数
17415 * @param {Number} delay 延迟的毫秒数
17416 */
17417
17418 /**
17419 * 正在尝试重新连接
17420 * @event Realtime#RETRY
17421 * @param {Number} attempt 尝试重连的次数
17422 */
17423
17424 /**
17425 * 连接恢复正常。
17426 * 请重新启用在 {@link Realtime#event:DISCONNECT} 事件中禁用的相关 UI 元素
17427 * @event Realtime#RECONNECT
17428 */
17429
17430 /**
17431 * 客户端连接断开
17432 * @event IMClient#DISCONNECT
17433 * @see Realtime#event:DISCONNECT
17434 * @since 3.2.0
17435 */
17436
17437 /**
17438 * 计划在一段时间后尝试重新连接
17439 * @event IMClient#SCHEDULE
17440 * @param {Number} attempt 尝试重连的次数
17441 * @param {Number} delay 延迟的毫秒数
17442 * @since 3.2.0
17443 */
17444
17445 /**
17446 * 正在尝试重新连接
17447 * @event IMClient#RETRY
17448 * @param {Number} attempt 尝试重连的次数
17449 * @since 3.2.0
17450 */
17451
17452 /**
17453 * 客户端进入离线状态。
17454 * 这通常意味着网络已断开,或者 {@link Realtime#pause} 被调用
17455 * @event Realtime#OFFLINE
17456 * @since 3.4.0
17457 */
17458
17459 /**
17460 * 客户端恢复在线状态
17461 * 这通常意味着网络已恢复,或者 {@link Realtime#resume} 被调用
17462 * @event Realtime#ONLINE
17463 * @since 3.4.0
17464 */
17465
17466 /**
17467 * 进入离线状态。
17468 * 这通常意味着网络已断开,或者 {@link Realtime#pause} 被调用
17469 * @event IMClient#OFFLINE
17470 * @since 3.4.0
17471 */
17472
17473 /**
17474 * 恢复在线状态
17475 * 这通常意味着网络已恢复,或者 {@link Realtime#resume} 被调用
17476 * @event IMClient#ONLINE
17477 * @since 3.4.0
17478 */
17479 // event proxy
17480
17481 [DISCONNECT, RECONNECT, RETRY, SCHEDULE, OFFLINE, ONLINE].forEach(function (event) {
17482 return connection.on(event, function () {
17483 for (var _len = arguments.length, payload = new Array(_len), _key = 0; _key < _len; _key++) {
17484 payload[_key] = arguments[_key];
17485 }
17486
17487 debug$5("".concat(event, " event emitted. %o"), payload);
17488
17489 _this3.emit.apply(_this3, [event].concat(payload));
17490
17491 if (event !== RECONNECT) {
17492 internal(_this3).clients.forEach(function (client) {
17493 client.emit.apply(client, [event].concat(payload));
17494 });
17495 }
17496 });
17497 }); // override handleClose
17498
17499 connection.handleClose = function handleClose(event) {
17500 var isFatal = [ErrorCode.APP_NOT_AVAILABLE, ErrorCode.INVALID_LOGIN, ErrorCode.INVALID_ORIGIN].some(function (errorCode) {
17501 return errorCode === event.code;
17502 });
17503
17504 if (isFatal) {
17505 // in these cases, SDK should throw.
17506 this.throw(createError(event));
17507 } else {
17508 // reconnect
17509 this.disconnect();
17510 }
17511 };
17512
17513 internal(_this3).connection = connection;
17514 });
17515 return this._openPromise;
17516 };
17517
17518 _proto._getRTMServers =
17519 /*#__PURE__*/
17520 function () {
17521 var _getRTMServers2 = _asyncToGenerator(
17522 /*#__PURE__*/
17523 regenerator.mark(function _callee3(options) {
17524 var info, cachedEndPoints;
17525 return regenerator.wrap(function _callee3$(_context3) {
17526 while (1) {
17527 switch (_context3.prev = _context3.next) {
17528 case 0:
17529 if (!options.RTMServers) {
17530 _context3.next = 2;
17531 break;
17532 }
17533
17534 return _context3.abrupt("return", shuffle_1(ensureArray(options.RTMServers)));
17535
17536 case 2:
17537 cachedEndPoints = this._cache.get('endpoints');
17538
17539 if (!cachedEndPoints) {
17540 _context3.next = 9;
17541 break;
17542 }
17543
17544 _context3.next = 6;
17545 return cachedEndPoints;
17546
17547 case 6:
17548 info = _context3.sent;
17549 _context3.next = 13;
17550 break;
17551
17552 case 9:
17553 _context3.next = 11;
17554 return this.constructor._fetchRTMServers(options);
17555
17556 case 11:
17557 info = _context3.sent;
17558
17559 this._cache.set('endpoints', info, info.ttl * 1000);
17560
17561 case 13:
17562 debug$5('endpoint info: %O', info);
17563 return _context3.abrupt("return", [info.server, info.secondary]);
17564
17565 case 15:
17566 case "end":
17567 return _context3.stop();
17568 }
17569 }
17570 }, _callee3, this);
17571 }));
17572
17573 function _getRTMServers(_x2) {
17574 return _getRTMServers2.apply(this, arguments);
17575 }
17576
17577 return _getRTMServers;
17578 }();
17579
17580 Realtime._getServerUrls =
17581 /*#__PURE__*/
17582 function () {
17583 var _getServerUrls2 = _asyncToGenerator(
17584 /*#__PURE__*/
17585 regenerator.mark(function _callee4(_ref5) {
17586 var appId, server, cachedRouter, defaultProtocol;
17587 return regenerator.wrap(function _callee4$(_context4) {
17588 while (1) {
17589 switch (_context4.prev = _context4.next) {
17590 case 0:
17591 appId = _ref5.appId, server = _ref5.server;
17592 debug$5('fetch server urls');
17593
17594 if (!server) {
17595 _context4.next = 6;
17596 break;
17597 }
17598
17599 if (!(typeof server !== 'string')) {
17600 _context4.next = 5;
17601 break;
17602 }
17603
17604 return _context4.abrupt("return", server);
17605
17606 case 5:
17607 return _context4.abrupt("return", {
17608 RTMRouter: server,
17609 api: server
17610 });
17611
17612 case 6:
17613 cachedRouter = routerCache.get(appId);
17614
17615 if (!cachedRouter) {
17616 _context4.next = 9;
17617 break;
17618 }
17619
17620 return _context4.abrupt("return", cachedRouter);
17621
17622 case 9:
17623 defaultProtocol = 'https://';
17624 return _context4.abrupt("return", client.get('https://app-router.com/2/route').query({
17625 appId: appId
17626 }).timeout(20000).then(function (res) {
17627 return res.body;
17628 }).then(tap(debug$5)).then(function (_ref6) {
17629 var RTMRouterServer = _ref6.rtm_router_server,
17630 APIServer = _ref6.api_server,
17631 _ref6$ttl = _ref6.ttl,
17632 ttl = _ref6$ttl === void 0 ? 3600 : _ref6$ttl;
17633
17634 if (!RTMRouterServer) {
17635 throw new Error('rtm router not exists');
17636 }
17637
17638 var serverUrls = {
17639 RTMRouter: "".concat(defaultProtocol).concat(RTMRouterServer),
17640 api: "".concat(defaultProtocol).concat(APIServer)
17641 };
17642 routerCache.set(appId, serverUrls, ttl * 1000);
17643 return serverUrls;
17644 }).catch(function () {
17645 var id = appId.slice(0, 8).toLowerCase();
17646 var domain = 'lncldglobal.com';
17647 return {
17648 RTMRouter: "".concat(defaultProtocol).concat(id, ".rtm.").concat(domain),
17649 api: "".concat(defaultProtocol).concat(id, ".api.").concat(domain)
17650 };
17651 }));
17652
17653 case 11:
17654 case "end":
17655 return _context4.stop();
17656 }
17657 }
17658 }, _callee4, this);
17659 }));
17660
17661 function _getServerUrls(_x3) {
17662 return _getServerUrls2.apply(this, arguments);
17663 }
17664
17665 return _getServerUrls;
17666 }();
17667
17668 Realtime._fetchRTMServers = function _fetchRTMServers(_ref7) {
17669 var appId = _ref7.appId,
17670 ssl = _ref7.ssl,
17671 server = _ref7.server,
17672 RTMServerName = _ref7.RTMServerName;
17673 debug$5('fetch endpoint info');
17674 return this._getServerUrls({
17675 appId: appId,
17676 server: server
17677 }).then(tap(debug$5)).then(function (_ref8) {
17678 var RTMRouter = _ref8.RTMRouter;
17679 return client.get("".concat(RTMRouter, "/v1/route")).query({
17680 appId: appId,
17681 secure: ssl,
17682 features: isWeapp ? 'wechat' : undefined,
17683 server: RTMServerName,
17684 _t: Date.now()
17685 }).timeout(20000).then(function (res) {
17686 return res.body;
17687 }).then(tap(debug$5));
17688 });
17689 };
17690
17691 _proto._close = function _close() {
17692 if (this._openPromise) {
17693 this._openPromise.then(function (connection) {
17694 return connection.close();
17695 });
17696 }
17697
17698 delete this._openPromise;
17699 }
17700 /**
17701 * 手动进行重连。
17702 * SDK 在网络出现异常时会自动按照一定的时间间隔尝试重连,调用该方法会立即尝试重连并重置重连尝试计数器。
17703 * 只能在 `SCHEDULE` 事件之后,`RETRY` 事件之前调用,如果当前网络正常或者正在进行重连,调用该方法会抛异常。
17704 */
17705 ;
17706
17707 _proto.retry = function retry() {
17708 var _internal = internal(this),
17709 connection = _internal.connection;
17710
17711 if (!connection) {
17712 throw new Error('no connection established');
17713 }
17714
17715 if (connection.cannot('retry')) {
17716 throw new Error("retrying not allowed when not disconnected. the connection is now ".concat(connection.current));
17717 }
17718
17719 return connection.retry();
17720 }
17721 /**
17722 * 暂停,使 SDK 进入离线状态。
17723 * 你可以在网络断开、应用进入后台等时刻调用该方法让 SDK 进入离线状态,离线状态下不会尝试重连。
17724 * 在浏览器中 SDK 会自动监听网络变化,因此无需手动调用该方法。
17725 *
17726 * @since 3.4.0
17727 * @see Realtime#event:OFFLINE
17728 */
17729 ;
17730
17731 _proto.pause = function pause() {
17732 // 这个方法常常在网络断开、进入后台时被调用,此时 connection 可能没有建立或者已经 close。
17733 // 因此不像 retry,这个方法应该尽可能 loose
17734 var _internal2 = internal(this),
17735 connection = _internal2.connection;
17736
17737 if (!connection) return;
17738 if (connection.can('pause')) connection.pause();
17739 }
17740 /**
17741 * 恢复在线状态。
17742 * 你可以在网络恢复、应用回到前台等时刻调用该方法让 SDK 恢复在线状态,恢复在线状态后 SDK 会开始尝试重连。
17743 *
17744 * @since 3.4.0
17745 * @see Realtime#event:ONLINE
17746 */
17747 ;
17748
17749 _proto.resume = function resume() {
17750 // 与 pause 一样,这个方法应该尽可能 loose
17751 var _internal3 = internal(this),
17752 connection = _internal3.connection;
17753
17754 if (!connection) return;
17755 if (connection.can('resume')) connection.resume();
17756 };
17757
17758 _proto._registerPending = function _registerPending(value) {
17759 internal(this).pendingClients.add(value);
17760 };
17761
17762 _proto._deregisterPending = function _deregisterPending(client) {
17763 internal(this).pendingClients.delete(client);
17764 };
17765
17766 _proto._register = function _register(client) {
17767 internal(this).clients.add(client);
17768 };
17769
17770 _proto._deregister = function _deregister(client) {
17771 var _this = internal(this);
17772
17773 _this.clients.delete(client);
17774
17775 if (_this.clients.size + _this.pendingClients.size === 0) {
17776 this._close();
17777 }
17778 };
17779
17780 _proto._dispatchCommand = function _dispatchCommand(command) {
17781 return applyDispatcher(this._plugins.beforeCommandDispatch, [command, this]).then(function (shouldDispatch) {
17782 // no plugin handled this command
17783 if (shouldDispatch) return debug$5('[WARN] Unexpected message received: %O', trim(command));
17784 return false;
17785 });
17786 };
17787
17788 return Realtime;
17789 }(eventemitter3);
17790
17791 var polyfilledPromise = Promise;
17792
17793 exports.Protocals = message;
17794 exports.Promise = polyfilledPromise;
17795 exports.EventEmitter = eventemitter3;
17796 exports.Realtime = Realtime;
17797 exports.debug = debug$2;
17798
17799 Object.defineProperty(exports, '__esModule', { value: true });
17800
17801}));
17802//# sourceMappingURL=realtime-core-browser.js.map