UNPKG

662 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 XMLHttpRequest;
16
17 function _typeof(obj) {
18 if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
19 _typeof = function (obj) {
20 return typeof obj;
21 };
22 } else {
23 _typeof = function (obj) {
24 return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
25 };
26 }
27
28 return _typeof(obj);
29 }
30
31 function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
32 try {
33 var info = gen[key](arg);
34 var value = info.value;
35 } catch (error) {
36 reject(error);
37 return;
38 }
39
40 if (info.done) {
41 resolve(value);
42 } else {
43 Promise.resolve(value).then(_next, _throw);
44 }
45 }
46
47 function _asyncToGenerator(fn) {
48 return function () {
49 var self = this,
50 args = arguments;
51 return new Promise(function (resolve, reject) {
52 var gen = fn.apply(self, args);
53
54 function _next(value) {
55 asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
56 }
57
58 function _throw(err) {
59 asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
60 }
61
62 _next(undefined);
63 });
64 };
65 }
66
67 function _defineProperties(target, props) {
68 for (var i = 0; i < props.length; i++) {
69 var descriptor = props[i];
70 descriptor.enumerable = descriptor.enumerable || false;
71 descriptor.configurable = true;
72 if ("value" in descriptor) descriptor.writable = true;
73 Object.defineProperty(target, descriptor.key, descriptor);
74 }
75 }
76
77 function _createClass(Constructor, protoProps, staticProps) {
78 if (protoProps) _defineProperties(Constructor.prototype, protoProps);
79 if (staticProps) _defineProperties(Constructor, staticProps);
80 return Constructor;
81 }
82
83 function _defineProperty(obj, key, value) {
84 if (key in obj) {
85 Object.defineProperty(obj, key, {
86 value: value,
87 enumerable: true,
88 configurable: true,
89 writable: true
90 });
91 } else {
92 obj[key] = value;
93 }
94
95 return obj;
96 }
97
98 function _objectSpread(target) {
99 for (var i = 1; i < arguments.length; i++) {
100 var source = arguments[i] != null ? arguments[i] : {};
101 var ownKeys = Object.keys(source);
102
103 if (typeof Object.getOwnPropertySymbols === 'function') {
104 ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) {
105 return Object.getOwnPropertyDescriptor(source, sym).enumerable;
106 }));
107 }
108
109 ownKeys.forEach(function (key) {
110 _defineProperty(target, key, source[key]);
111 });
112 }
113
114 return target;
115 }
116
117 function _inheritsLoose(subClass, superClass) {
118 subClass.prototype = Object.create(superClass.prototype);
119 subClass.prototype.constructor = subClass;
120 subClass.__proto__ = superClass;
121 }
122
123 function _objectWithoutPropertiesLoose(source, excluded) {
124 if (source == null) return {};
125 var target = {};
126 var sourceKeys = Object.keys(source);
127 var key, i;
128
129 for (i = 0; i < sourceKeys.length; i++) {
130 key = sourceKeys[i];
131 if (excluded.indexOf(key) >= 0) continue;
132 target[key] = source[key];
133 }
134
135 return target;
136 }
137
138 function _objectWithoutProperties(source, excluded) {
139 if (source == null) return {};
140
141 var target = _objectWithoutPropertiesLoose(source, excluded);
142
143 var key, i;
144
145 if (Object.getOwnPropertySymbols) {
146 var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
147
148 for (i = 0; i < sourceSymbolKeys.length; i++) {
149 key = sourceSymbolKeys[i];
150 if (excluded.indexOf(key) >= 0) continue;
151 if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
152 target[key] = source[key];
153 }
154 }
155
156 return target;
157 }
158
159 function _assertThisInitialized(self) {
160 if (self === void 0) {
161 throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
162 }
163
164 return self;
165 }
166
167 function _toArray(arr) {
168 return _arrayWithHoles(arr) || _iterableToArray(arr) || _nonIterableRest();
169 }
170
171 function _toConsumableArray(arr) {
172 return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread();
173 }
174
175 function _arrayWithoutHoles(arr) {
176 if (Array.isArray(arr)) {
177 for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];
178
179 return arr2;
180 }
181 }
182
183 function _arrayWithHoles(arr) {
184 if (Array.isArray(arr)) return arr;
185 }
186
187 function _iterableToArray(iter) {
188 if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter);
189 }
190
191 function _nonIterableSpread() {
192 throw new TypeError("Invalid attempt to spread non-iterable instance");
193 }
194
195 function _nonIterableRest() {
196 throw new TypeError("Invalid attempt to destructure non-iterable instance");
197 }
198
199 function _applyDecoratedDescriptor(target, property, decorators, descriptor, context) {
200 var desc = {};
201 Object['ke' + 'ys'](descriptor).forEach(function (key) {
202 desc[key] = descriptor[key];
203 });
204 desc.enumerable = !!desc.enumerable;
205 desc.configurable = !!desc.configurable;
206
207 if ('value' in desc || desc.initializer) {
208 desc.writable = true;
209 }
210
211 desc = decorators.slice().reverse().reduce(function (desc, decorator) {
212 return decorator(target, property, desc) || desc;
213 }, desc);
214
215 if (context && desc.initializer !== void 0) {
216 desc.value = desc.initializer ? desc.initializer.call(context) : void 0;
217 desc.initializer = undefined;
218 }
219
220 if (desc.initializer === void 0) {
221 Object['define' + 'Property'](target, property, desc);
222 desc = null;
223 }
224
225 return desc;
226 }
227
228 var commonjsGlobal = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
229
230 function commonjsRequire () {
231 throw new Error('Dynamic requires are not currently supported by rollup-plugin-commonjs');
232 }
233
234 function createCommonjsModule(fn, module) {
235 return module = { exports: {} }, fn(module, module.exports), module.exports;
236 }
237
238 var Storage =
239 /*#__PURE__*/
240 function () {
241 function Storage() {}
242
243 var _proto = Storage.prototype;
244
245 _proto.getItem = function getItem(key) {
246 return wx.getStorageSync(key);
247 };
248
249 _proto.setItem = function setItem(key, value) {
250 return wx.setStorageSync(key, value);
251 };
252
253 _proto.removeItem = function removeItem(key) {
254 return this.setItem(key, '');
255 };
256
257 _proto.clear = function clear() {
258 return wx.clearStorageSync();
259 };
260
261 return Storage;
262 }();
263
264 var localstorage = new Storage();
265
266 /*
267 object-assign
268 (c) Sindre Sorhus
269 @license MIT
270 */
271 /* eslint-disable no-unused-vars */
272 var getOwnPropertySymbols = Object.getOwnPropertySymbols;
273 var hasOwnProperty = Object.prototype.hasOwnProperty;
274 var propIsEnumerable = Object.prototype.propertyIsEnumerable;
275
276 function toObject(val) {
277 if (val === null || val === undefined) {
278 throw new TypeError('Object.assign cannot be called with null or undefined');
279 }
280
281 return Object(val);
282 }
283
284 function shouldUseNative() {
285 try {
286 if (!Object.assign) {
287 return false;
288 }
289
290 // Detect buggy property enumeration order in older V8 versions.
291
292 // https://bugs.chromium.org/p/v8/issues/detail?id=4118
293 var test1 = new String('abc'); // eslint-disable-line no-new-wrappers
294 test1[5] = 'de';
295 if (Object.getOwnPropertyNames(test1)[0] === '5') {
296 return false;
297 }
298
299 // https://bugs.chromium.org/p/v8/issues/detail?id=3056
300 var test2 = {};
301 for (var i = 0; i < 10; i++) {
302 test2['_' + String.fromCharCode(i)] = i;
303 }
304 var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
305 return test2[n];
306 });
307 if (order2.join('') !== '0123456789') {
308 return false;
309 }
310
311 // https://bugs.chromium.org/p/v8/issues/detail?id=3056
312 var test3 = {};
313 'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
314 test3[letter] = letter;
315 });
316 if (Object.keys(Object.assign({}, test3)).join('') !==
317 'abcdefghijklmnopqrst') {
318 return false;
319 }
320
321 return true;
322 } catch (err) {
323 // We don't expect any of the above to throw, but better to be safe.
324 return false;
325 }
326 }
327
328 var objectAssign = shouldUseNative() ? Object.assign : function (target, source) {
329 var from;
330 var to = toObject(target);
331 var symbols;
332
333 for (var s = 1; s < arguments.length; s++) {
334 from = Object(arguments[s]);
335
336 for (var key in from) {
337 if (hasOwnProperty.call(from, key)) {
338 to[key] = from[key];
339 }
340 }
341
342 if (getOwnPropertySymbols) {
343 symbols = getOwnPropertySymbols(from);
344 for (var i = 0; i < symbols.length; i++) {
345 if (propIsEnumerable.call(from, symbols[i])) {
346 to[symbols[i]] = from[symbols[i]];
347 }
348 }
349 }
350 }
351
352 return to;
353 };
354
355 var commons = createCommonjsModule(function (module, exports) {
356
357 /**
358 * Creates a unique key.
359 *
360 * @param {string} name - A name to create.
361 * @returns {symbol|string}
362 * @private
363 */
364 var createUniqueKey = exports.createUniqueKey = (typeof Symbol !== "undefined" ?
365 Symbol :
366 function createUniqueKey(name) {
367 return "[[" + name + "_" + Math.random().toFixed(8).slice(2) + "]]";
368 });
369
370 /**
371 * The key of listeners.
372 *
373 * @type {symbol|string}
374 * @private
375 */
376 exports.LISTENERS = createUniqueKey("listeners");
377
378 /**
379 * A value of kind for listeners which are registered in the capturing phase.
380 *
381 * @type {number}
382 * @private
383 */
384 exports.CAPTURE = 1;
385
386 /**
387 * A value of kind for listeners which are registered in the bubbling phase.
388 *
389 * @type {number}
390 * @private
391 */
392 exports.BUBBLE = 2;
393
394 /**
395 * A value of kind for listeners which are registered as an attribute.
396 *
397 * @type {number}
398 * @private
399 */
400 exports.ATTRIBUTE = 3;
401
402 /**
403 * @typedef object ListenerNode
404 * @property {function} listener - A listener function.
405 * @property {number} kind - The kind of the listener.
406 * @property {ListenerNode|null} next - The next node.
407 * If this node is the last, this is `null`.
408 */
409
410 /**
411 * Creates a node of singly linked list for a list of listeners.
412 *
413 * @param {function} listener - A listener function.
414 * @param {number} kind - The kind of the listener.
415 * @returns {ListenerNode} The created listener node.
416 */
417 exports.newNode = function newNode(listener, kind) {
418 return {listener: listener, kind: kind, next: null};
419 };
420 });
421 var commons_1 = commons.createUniqueKey;
422 var commons_2 = commons.LISTENERS;
423 var commons_3 = commons.CAPTURE;
424 var commons_4 = commons.BUBBLE;
425 var commons_5 = commons.ATTRIBUTE;
426 var commons_6 = commons.newNode;
427
428 //-----------------------------------------------------------------------------
429 // Requirements
430 //-----------------------------------------------------------------------------
431
432
433 var LISTENERS = commons.LISTENERS;
434 var ATTRIBUTE = commons.ATTRIBUTE;
435 var newNode = commons.newNode;
436
437 //-----------------------------------------------------------------------------
438 // Helpers
439 //-----------------------------------------------------------------------------
440
441 /**
442 * Gets a specified attribute listener from a given EventTarget object.
443 *
444 * @param {EventTarget} eventTarget - An EventTarget object to get.
445 * @param {string} type - An event type to get.
446 * @returns {function|null} The found attribute listener.
447 */
448 function getAttributeListener(eventTarget, type) {
449 var node = eventTarget[LISTENERS][type];
450 while (node != null) {
451 if (node.kind === ATTRIBUTE) {
452 return node.listener;
453 }
454 node = node.next;
455 }
456 return null;
457 }
458
459 /**
460 * Sets a specified attribute listener to a given EventTarget object.
461 *
462 * @param {EventTarget} eventTarget - An EventTarget object to set.
463 * @param {string} type - An event type to set.
464 * @param {function|null} listener - A listener to be set.
465 * @returns {void}
466 */
467 function setAttributeListener(eventTarget, type, listener) {
468 if (typeof listener !== "function" && typeof listener !== "object") {
469 listener = null; // eslint-disable-line no-param-reassign
470 }
471
472 var prev = null;
473 var node = eventTarget[LISTENERS][type];
474 while (node != null) {
475 if (node.kind === ATTRIBUTE) {
476 // Remove old value.
477 if (prev == null) {
478 eventTarget[LISTENERS][type] = node.next;
479 }
480 else {
481 prev.next = node.next;
482 }
483 }
484 else {
485 prev = node;
486 }
487
488 node = node.next;
489 }
490
491 // Add new value.
492 if (listener != null) {
493 if (prev == null) {
494 eventTarget[LISTENERS][type] = newNode(listener, ATTRIBUTE);
495 }
496 else {
497 prev.next = newNode(listener, ATTRIBUTE);
498 }
499 }
500 }
501
502 //-----------------------------------------------------------------------------
503 // Public Interface
504 //-----------------------------------------------------------------------------
505
506 /**
507 * Defines an `EventTarget` implementation which has `onfoobar` attributes.
508 *
509 * @param {EventTarget} EventTargetBase - A base implementation of EventTarget.
510 * @param {string[]} types - A list of event types which are defined as attribute listeners.
511 * @returns {EventTarget} The defined `EventTarget` implementation which has attribute listeners.
512 */
513 var defineCustomEventTarget = function(EventTargetBase, types) {
514 function EventTarget() {
515 EventTargetBase.call(this);
516 }
517
518 var descripter = {
519 constructor: {
520 value: EventTarget,
521 configurable: true,
522 writable: true
523 }
524 };
525
526 types.forEach(function(type) {
527 descripter["on" + type] = {
528 get: function() { return getAttributeListener(this, type); },
529 set: function(listener) { setAttributeListener(this, type, listener); },
530 configurable: true,
531 enumerable: true
532 };
533 });
534
535 EventTarget.prototype = Object.create(EventTargetBase.prototype, descripter);
536
537 return EventTarget;
538 };
539
540 var customEventTarget = {
541 defineCustomEventTarget: defineCustomEventTarget
542 };
543
544 //-----------------------------------------------------------------------------
545 // Requirements
546 //-----------------------------------------------------------------------------
547
548 var createUniqueKey = commons.createUniqueKey;
549
550 //-----------------------------------------------------------------------------
551 // Constsnts
552 //-----------------------------------------------------------------------------
553
554 /**
555 * The key of the flag which is turned on by `stopImmediatePropagation` method.
556 *
557 * @type {symbol|string}
558 * @private
559 */
560 var STOP_IMMEDIATE_PROPAGATION_FLAG =
561 createUniqueKey("stop_immediate_propagation_flag");
562
563 /**
564 * The key of the flag which is turned on by `preventDefault` method.
565 *
566 * @type {symbol|string}
567 * @private
568 */
569 var CANCELED_FLAG = createUniqueKey("canceled_flag");
570
571 /**
572 * The key of the original event object.
573 *
574 * @type {symbol|string}
575 * @private
576 */
577 var ORIGINAL_EVENT = createUniqueKey("original_event");
578
579 /**
580 * Method definitions for the event wrapper.
581 *
582 * @type {object}
583 * @private
584 */
585 var wrapperPrototypeDefinition = Object.freeze({
586 stopPropagation: Object.freeze({
587 value: function stopPropagation() {
588 var e = this[ORIGINAL_EVENT];
589 if (typeof e.stopPropagation === "function") {
590 e.stopPropagation();
591 }
592 },
593 writable: true,
594 configurable: true
595 }),
596
597 stopImmediatePropagation: Object.freeze({
598 value: function stopImmediatePropagation() {
599 this[STOP_IMMEDIATE_PROPAGATION_FLAG] = true;
600
601 var e = this[ORIGINAL_EVENT];
602 if (typeof e.stopImmediatePropagation === "function") {
603 e.stopImmediatePropagation();
604 }
605 },
606 writable: true,
607 configurable: true
608 }),
609
610 preventDefault: Object.freeze({
611 value: function preventDefault() {
612 if (this.cancelable === true) {
613 this[CANCELED_FLAG] = true;
614 }
615
616 var e = this[ORIGINAL_EVENT];
617 if (typeof e.preventDefault === "function") {
618 e.preventDefault();
619 }
620 },
621 writable: true,
622 configurable: true
623 }),
624
625 defaultPrevented: Object.freeze({
626 get: function defaultPrevented() { return this[CANCELED_FLAG]; },
627 enumerable: true,
628 configurable: true
629 })
630 });
631
632 //-----------------------------------------------------------------------------
633 // Public Interface
634 //-----------------------------------------------------------------------------
635
636 var STOP_IMMEDIATE_PROPAGATION_FLAG_1 = STOP_IMMEDIATE_PROPAGATION_FLAG;
637
638 /**
639 * Creates an event wrapper.
640 *
641 * We cannot modify several properties of `Event` object, so we need to create the wrapper.
642 * Plus, this wrapper supports non `Event` objects.
643 *
644 * @param {Event|{type: string}} event - An original event to create the wrapper.
645 * @param {EventTarget} eventTarget - The event target of the event.
646 * @returns {Event} The created wrapper. This object is implemented `Event` interface.
647 * @private
648 */
649 var createEventWrapper = function createEventWrapper(event, eventTarget) {
650 var timeStamp = (
651 typeof event.timeStamp === "number" ? event.timeStamp : Date.now()
652 );
653 var propertyDefinition = {
654 type: {value: event.type, enumerable: true},
655 target: {value: eventTarget, enumerable: true},
656 currentTarget: {value: eventTarget, enumerable: true},
657 eventPhase: {value: 2, enumerable: true},
658 bubbles: {value: Boolean(event.bubbles), enumerable: true},
659 cancelable: {value: Boolean(event.cancelable), enumerable: true},
660 timeStamp: {value: timeStamp, enumerable: true},
661 isTrusted: {value: false, enumerable: true}
662 };
663 propertyDefinition[STOP_IMMEDIATE_PROPAGATION_FLAG] = {value: false, writable: true};
664 propertyDefinition[CANCELED_FLAG] = {value: false, writable: true};
665 propertyDefinition[ORIGINAL_EVENT] = {value: event};
666
667 // For CustomEvent.
668 if (typeof event.detail !== "undefined") {
669 propertyDefinition.detail = {value: event.detail, enumerable: true};
670 }
671
672 return Object.create(
673 Object.create(event, wrapperPrototypeDefinition),
674 propertyDefinition
675 );
676 };
677
678 var eventWrapper = {
679 STOP_IMMEDIATE_PROPAGATION_FLAG: STOP_IMMEDIATE_PROPAGATION_FLAG_1,
680 createEventWrapper: createEventWrapper
681 };
682
683 var eventTarget = createCommonjsModule(function (module) {
684
685 //-----------------------------------------------------------------------------
686 // Requirements
687 //-----------------------------------------------------------------------------
688
689
690
691
692 var LISTENERS = commons.LISTENERS;
693 var CAPTURE = commons.CAPTURE;
694 var BUBBLE = commons.BUBBLE;
695 var ATTRIBUTE = commons.ATTRIBUTE;
696 var newNode = commons.newNode;
697 var defineCustomEventTarget = customEventTarget.defineCustomEventTarget;
698 var createEventWrapper = eventWrapper.createEventWrapper;
699 var STOP_IMMEDIATE_PROPAGATION_FLAG =
700 eventWrapper.STOP_IMMEDIATE_PROPAGATION_FLAG;
701
702 //-----------------------------------------------------------------------------
703 // Constants
704 //-----------------------------------------------------------------------------
705
706 /**
707 * A flag which shows there is the native `EventTarget` interface object.
708 *
709 * @type {boolean}
710 * @private
711 */
712 var HAS_EVENTTARGET_INTERFACE = (
713 typeof window !== "undefined" &&
714 typeof window.EventTarget !== "undefined"
715 );
716
717 //-----------------------------------------------------------------------------
718 // Public Interface
719 //-----------------------------------------------------------------------------
720
721 /**
722 * An implementation for `EventTarget` interface.
723 *
724 * @constructor
725 * @public
726 */
727 var EventTarget = module.exports = function EventTarget() {
728 if (this instanceof EventTarget) {
729 // this[LISTENERS] is a Map.
730 // Its key is event type.
731 // Its value is ListenerNode object or null.
732 //
733 // interface ListenerNode {
734 // var listener: Function
735 // var kind: CAPTURE|BUBBLE|ATTRIBUTE
736 // var next: ListenerNode|null
737 // }
738 Object.defineProperty(this, LISTENERS, {value: Object.create(null)});
739 }
740 else if (arguments.length === 1 && Array.isArray(arguments[0])) {
741 return defineCustomEventTarget(EventTarget, arguments[0]);
742 }
743 else if (arguments.length > 0) {
744 var types = Array(arguments.length);
745 for (var i = 0; i < arguments.length; ++i) {
746 types[i] = arguments[i];
747 }
748
749 // To use to extend with attribute listener properties.
750 // e.g.
751 // class MyCustomObject extends EventTarget("message", "error") {
752 // //...
753 // }
754 return defineCustomEventTarget(EventTarget, types);
755 }
756 else {
757 throw new TypeError("Cannot call a class as a function");
758 }
759 };
760
761 EventTarget.prototype = Object.create(
762 (HAS_EVENTTARGET_INTERFACE ? window.EventTarget : Object).prototype,
763 {
764 constructor: {
765 value: EventTarget,
766 writable: true,
767 configurable: true
768 },
769
770 addEventListener: {
771 value: function addEventListener(type, listener, capture) {
772 if (listener == null) {
773 return false;
774 }
775 if (typeof listener !== "function" && typeof listener !== "object") {
776 throw new TypeError("\"listener\" is not an object.");
777 }
778
779 var kind = (capture ? CAPTURE : BUBBLE);
780 var node = this[LISTENERS][type];
781 if (node == null) {
782 this[LISTENERS][type] = newNode(listener, kind);
783 return true;
784 }
785
786 var prev = null;
787 while (node != null) {
788 if (node.listener === listener && node.kind === kind) {
789 // Should ignore a duplicated listener.
790 return false;
791 }
792 prev = node;
793 node = node.next;
794 }
795
796 prev.next = newNode(listener, kind);
797 return true;
798 },
799 configurable: true,
800 writable: true
801 },
802
803 removeEventListener: {
804 value: function removeEventListener(type, listener, capture) {
805 if (listener == null) {
806 return false;
807 }
808
809 var kind = (capture ? CAPTURE : BUBBLE);
810 var prev = null;
811 var node = this[LISTENERS][type];
812 while (node != null) {
813 if (node.listener === listener && node.kind === kind) {
814 if (prev == null) {
815 this[LISTENERS][type] = node.next;
816 }
817 else {
818 prev.next = node.next;
819 }
820 return true;
821 }
822
823 prev = node;
824 node = node.next;
825 }
826
827 return false;
828 },
829 configurable: true,
830 writable: true
831 },
832
833 dispatchEvent: {
834 value: function dispatchEvent(event) {
835 // If listeners aren't registered, terminate.
836 var node = this[LISTENERS][event.type];
837 if (node == null) {
838 return true;
839 }
840
841 // Since we cannot rewrite several properties, so wrap object.
842 var wrapped = createEventWrapper(event, this);
843
844 // This doesn't process capturing phase and bubbling phase.
845 // This isn't participating in a tree.
846 while (node != null) {
847 if (typeof node.listener === "function") {
848 node.listener.call(this, wrapped);
849 }
850 else if (node.kind !== ATTRIBUTE && typeof node.listener.handleEvent === "function") {
851 node.listener.handleEvent(wrapped);
852 }
853
854 if (wrapped[STOP_IMMEDIATE_PROPAGATION_FLAG]) {
855 break;
856 }
857 node = node.next;
858 }
859
860 return !wrapped.defaultPrevented;
861 },
862 configurable: true,
863 writable: true
864 }
865 }
866 );
867 });
868
869 var FormData$1 =
870 /*#__PURE__*/
871 function () {
872 function FormData() {
873 this._entries = [];
874 }
875
876 var _proto = FormData.prototype;
877
878 _proto.append = function append(name, value) {
879 if (typeof name !== 'string') {
880 throw new TypeError('FormData name must be a string');
881 }
882
883 if (typeof value !== 'string') {
884 if (_typeof(value) !== 'object' || typeof value.uri !== 'string') {
885 throw new TypeError('FormData value must be a string or { uri: tempFilePath }');
886 }
887 }
888
889 this._entries.push([name, value]);
890 };
891
892 _proto.set = function set(name, value) {
893 var entry = this.get(name);
894
895 if (entry) {
896 entry[1] = value;
897 } else {
898 this.append(name, value);
899 }
900 };
901
902 _proto.delete = function _delete(name) {
903 this._entries = this._entries.filter(function (entry) {
904 return entry[0] !== name;
905 });
906 };
907
908 _proto.entries = function entries() {
909 return this._entries;
910 };
911
912 _proto.get = function get(name) {
913 return this._entries.find(function (entry) {
914 return entry[0] === name;
915 });
916 };
917
918 _proto.getAll = function getAll(name) {
919 return this._entries.filter(function (entry) {
920 return entry[0] === name;
921 });
922 };
923
924 _proto.has = function has(name) {
925 return this._entries.some(function (entry) {
926 return entry[0] === name;
927 });
928 };
929
930 _proto.keys = function keys() {
931 return this._entries.map(function (entry) {
932 return entry[0];
933 });
934 };
935
936 _proto.values = function values() {
937 return this._entries.map(function (entry) {
938 return entry[1];
939 });
940 };
941
942 return FormData;
943 }();
944
945 var formdata = FormData$1;
946
947 var UNSENT = 0;
948 var OPENED = 1;
949 var HEADERS_RECEIVED = 2;
950 var LOADING = 3;
951 var DONE = 4;
952 var REQUEST_EVENTS = ['abort', 'error', 'load', 'loadstart', 'progress', 'timeout', 'loadend', 'readystatechange'];
953 var REQUEST_UPLOAD_EVENTS = ['abort', 'error', 'load', 'loadstart', 'progress', 'timeout', 'loadend'];
954
955 function successCallback(response) {
956 this.status = response.statusCode;
957 this.statusText = response.statusCode; // 基础库 1.2.0 开始支持
958
959 if (response.header) {
960 this._responseHeaders = Object.keys(response.header).reduce(function (headers, key) {
961 headers[key.toLowerCase()] = response.header[key];
962 return headers;
963 }, {});
964 }
965
966 var text = response.data;
967
968 if (typeof text !== 'string') {
969 text = JSON.stringify(text);
970 }
971
972 this.responseText = this.response = text;
973 this.readyState = DONE;
974 this.dispatchEvent({
975 type: 'readystatechange'
976 });
977 }
978
979 var XMLHttpRequestUpload =
980 /*#__PURE__*/
981 function (_EventTarget) {
982 _inheritsLoose(XMLHttpRequestUpload, _EventTarget);
983
984 function XMLHttpRequestUpload() {
985 return _EventTarget.apply(this, arguments) || this;
986 }
987
988 return XMLHttpRequestUpload;
989 }(eventTarget(REQUEST_UPLOAD_EVENTS));
990
991 var XMLHttpRequest$1 =
992 /*#__PURE__*/
993 function (_EventTarget2) {
994 _inheritsLoose(XMLHttpRequest, _EventTarget2);
995
996 function XMLHttpRequest() {
997 var _this;
998
999 _this = _EventTarget2.call(this) || this;
1000 _this.readyState = UNSENT;
1001 _this._headers = {};
1002 _this.upload = new XMLHttpRequestUpload();
1003 return _this;
1004 }
1005
1006 var _proto = XMLHttpRequest.prototype;
1007
1008 _proto.abort = function abort() {
1009 // 基础库 1.4.0 开始支持
1010 if (!this._request || this._request.abort) {
1011 this.status = 0;
1012 this.readyState = DONE;
1013 return this._request.abort();
1014 }
1015
1016 throw new Error('该版本基础库不支持 abort request');
1017 };
1018
1019 _proto.getAllResponseHeaders = function getAllResponseHeaders() {
1020 var _this2 = this;
1021
1022 return this._responseHeaders ? Object.keys(this._responseHeaders).map(function (key) {
1023 return "".concat(key, ": ").concat(_this2._responseHeaders[key]);
1024 }).join('\r\n') : '';
1025 };
1026
1027 _proto.getResponseHeader = function getResponseHeader(key) {
1028 var lowserCasedKey = key.toLowerCase();
1029
1030 if (this._responseHeaders && this._responseHeaders[lowserCasedKey]) {
1031 return this._responseHeaders[lowserCasedKey];
1032 }
1033
1034 return null;
1035 };
1036
1037 _proto.overrideMimeType = function overrideMimeType() {
1038 throw new Error('not supported in weapp');
1039 };
1040
1041 _proto.open = function open(method, url) {
1042 var async = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
1043
1044 if (this.readyState !== UNSENT) {
1045 throw new Error('request is already opened');
1046 }
1047
1048 if (!async) {
1049 throw new Error('sync request is not supported');
1050 }
1051
1052 this._method = method;
1053 this._url = url;
1054 this.readyState = OPENED;
1055 this.dispatchEvent({
1056 type: 'readystatechange'
1057 });
1058 };
1059
1060 _proto.setRequestHeader = function setRequestHeader(header, value) {
1061 if (this.readyState !== OPENED) {
1062 throw new Error('request is not opened');
1063 }
1064
1065 this._headers[header.toLowerCase()] = value;
1066 };
1067
1068 _proto.send = function send(data) {
1069 var _this3 = this;
1070
1071 if (this.readyState !== OPENED) {
1072 throw new Error('request is not opened');
1073 }
1074
1075 if (data instanceof formdata) {
1076 var entries = data.entries();
1077 var blobs = entries.filter(function (entry) {
1078 return typeof entry[1] !== 'string';
1079 });
1080
1081 if (blobs.length === 0) {
1082 throw new Error('Must specify a Blob field in FormData');
1083 }
1084
1085 if (blobs.length > 1) {
1086 console.warn('Only the first Blob will be send in Weapp');
1087 }
1088
1089 var restData = entries.filter(function (entry) {
1090 return typeof entry[1] === 'string';
1091 }).reduce(function (result, entry) {
1092 return objectAssign(result, _defineProperty({}, entry[0], entry[1]));
1093 }, {});
1094 this._request = wx.uploadFile({
1095 url: this._url,
1096 name: blobs[0][0],
1097 filePath: blobs[0][1].uri,
1098 formData: restData,
1099 header: this._headers,
1100 success: successCallback.bind(this),
1101 fail: function fail(error) {
1102 _this3.status = 0;
1103 _this3.readyState = DONE;
1104
1105 _this3.dispatchEvent({
1106 type: 'readystatechange'
1107 });
1108
1109 _this3.dispatchEvent({
1110 type: 'error'
1111 });
1112 }
1113 }); // 基础库 1.4.0 开始支持
1114
1115 if (this._request && this._request.onProgressUpdate) {
1116 this._request.onProgressUpdate(function (_ref) {
1117 var totalBytesSent = _ref.totalBytesSent,
1118 totalBytesExpectedToSend = _ref.totalBytesExpectedToSend;
1119
1120 _this3.upload.dispatchEvent({
1121 type: 'progress',
1122 loaded: totalBytesSent,
1123 total: totalBytesExpectedToSend
1124 });
1125 });
1126 }
1127 } else {
1128 this._request = wx.request({
1129 url: this._url,
1130 data: data || '',
1131 // method 的 value 居然必须为大写
1132 method: this._method.toUpperCase(),
1133 header: this._headers,
1134 success: successCallback.bind(this),
1135 fail: function fail(error) {
1136 _this3.status = 0;
1137 _this3.readyState = DONE;
1138
1139 _this3.dispatchEvent({
1140 type: 'readystatechange'
1141 });
1142
1143 _this3.dispatchEvent({
1144 type: 'error'
1145 });
1146 }
1147 });
1148 }
1149 };
1150
1151 return XMLHttpRequest;
1152 }(eventTarget(REQUEST_EVENTS));
1153
1154 objectAssign(XMLHttpRequest$1, {
1155 UNSENT: UNSENT,
1156 OPENED: OPENED,
1157 HEADERS_RECEIVED: HEADERS_RECEIVED,
1158 LOADING: LOADING,
1159 DONE: DONE
1160 });
1161 var xmlhttprequest = XMLHttpRequest$1;
1162
1163 var CONNECTING = 0;
1164 var OPEN = 1;
1165 var CLOSING = 2;
1166 var CLOSED = 3;
1167 var EVENTS = ['open', 'error', 'message', 'close'];
1168
1169 var WebSocket$1 =
1170 /*#__PURE__*/
1171 function (_EventTarget) {
1172 _inheritsLoose(WebSocket, _EventTarget);
1173
1174 function WebSocket(url, protocal) {
1175 var _this;
1176
1177 if (!url) {
1178 throw new TypeError('Failed to construct \'WebSocket\': url required');
1179 }
1180
1181 if (protocal && !(wx.canIUse && wx.canIUse('connectSocket.object.protocols'))) {
1182 throw new Error('subprotocal not supported in weapp');
1183 }
1184
1185 _this = _EventTarget.call(this) || this;
1186 _this._url = url;
1187 _this._protocal = protocal || ''; // default value according to specs
1188
1189 _this._readyState = CONNECTING;
1190
1191 var errorHandler = function errorHandler(event) {
1192 _this._readyState = CLOSED;
1193
1194 _this.dispatchEvent({
1195 type: 'error',
1196 message: event.errMsg
1197 });
1198 };
1199
1200 var socketTask = wx.connectSocket({
1201 url: url,
1202 protocals: _this._protocal,
1203 fail: function fail(error) {
1204 return setTimeout(function () {
1205 return errorHandler(error);
1206 }, 0);
1207 }
1208 });
1209 _this._socketTask = socketTask;
1210 socketTask.onOpen(function (event) {
1211 _this._readyState = OPEN;
1212
1213 _this.dispatchEvent({
1214 type: 'open'
1215 });
1216 });
1217 socketTask.onError(errorHandler);
1218 socketTask.onMessage(function (event) {
1219 var data = event.data,
1220 origin = event.origin,
1221 ports = event.ports,
1222 source = event.source;
1223
1224 _this.dispatchEvent({
1225 data: data,
1226 origin: origin,
1227 ports: ports,
1228 source: source,
1229 type: 'message'
1230 });
1231 });
1232 socketTask.onClose(function (event) {
1233 _this._readyState = CLOSED;
1234 var code = event.code,
1235 reason = event.reason,
1236 wasClean = event.wasClean;
1237
1238 _this.dispatchEvent({
1239 code: code,
1240 reason: reason,
1241 wasClean: wasClean,
1242 type: 'close'
1243 });
1244 });
1245 return _this;
1246 }
1247
1248 var _proto = WebSocket.prototype;
1249
1250 _proto.close = function close() {
1251 if (this.readyState === CLOSED) return;
1252
1253 if (this.readyState === CONNECTING) {
1254 console.warn('close WebSocket which is connecting might not work');
1255 }
1256
1257 this._socketTask.close();
1258 };
1259
1260 _proto.send = function send(data) {
1261 if (this.readyState !== OPEN) {
1262 throw new Error('INVALID_STATE_ERR');
1263 }
1264
1265 if (!(typeof data === 'string' || data instanceof ArrayBuffer)) {
1266 throw new TypeError('only String/ArrayBuffer supported');
1267 }
1268
1269 this._socketTask.send({
1270 data: data
1271 });
1272 };
1273
1274 _createClass(WebSocket, [{
1275 key: "url",
1276 get: function get() {
1277 return this._url;
1278 }
1279 }, {
1280 key: "protocal",
1281 get: function get() {
1282 return this._protocal;
1283 }
1284 }, {
1285 key: "readyState",
1286 get: function get() {
1287 return this._readyState;
1288 }
1289 }]);
1290
1291 return WebSocket;
1292 }(eventTarget(EVENTS));
1293
1294 objectAssign(WebSocket$1, {
1295 CONNECTING: CONNECTING,
1296 OPEN: OPEN,
1297 CLOSING: CLOSING,
1298 CLOSED: CLOSED
1299 });
1300 var websocket = WebSocket$1;
1301
1302 var polyfill = function polyfill(target) {
1303 if (!wx.onNetworkStatusChange) return;
1304 if (target.__onlineOfflinePolyfilled) return;
1305 target.__onlineOfflinePolyfilled = true;
1306 var internalEventTarget = new eventTarget();
1307
1308 if (!target.dispatchEvent) {
1309 target.addEventListener = internalEventTarget.addEventListener.bind(internalEventTarget);
1310 target.removeEventListener = internalEventTarget.removeEventListener.bind(internalEventTarget);
1311 target.dispatchEvent = internalEventTarget.dispatchEvent.bind(internalEventTarget); // avoid this condition to be true:
1312 // https://github.com/zloirock/core-js/blob/9f051803760c02b306aae2595621bb7ef698fc29/library/modules/_task.js#L61
1313
1314 if (typeof postMessage == 'function' && !target.importScripts) {
1315 target.importScripts = function () {
1316 throw new Error('mocked');
1317 };
1318 }
1319 }
1320
1321 wx.getNetworkType({
1322 success: function success(_ref) {
1323 var networkType = _ref.networkType;
1324 target.onLine = networkType !== 'none';
1325 wx.onNetworkStatusChange(function (_ref2) {
1326 var isConnected = _ref2.isConnected;
1327 if (target.onLine === isConnected) return;
1328 target.onLine = isConnected;
1329 target.dispatchEvent({
1330 type: isConnected ? 'online' : 'offline'
1331 });
1332 });
1333 }
1334 });
1335 };
1336
1337 var onlineOfflineEvents = {
1338 polyfill: polyfill
1339 };
1340
1341 var navigator$1 = {};
1342
1343 var weappPolyfill = {
1344 polyfill: function polyfill() {
1345 var target = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : commonjsGlobal || window;
1346
1347 if (_typeof(target) !== 'object') {
1348 throw new Error('polyfill target is not an Object');
1349 }
1350
1351 var polyfills = {
1352 localStorage: localstorage,
1353 XMLHttpRequest: xmlhttprequest,
1354 FormData: formdata,
1355 WebSocket: websocket,
1356 Object: Object,
1357 navigator: navigator$1
1358 };
1359
1360 for (var k in polyfills) {
1361 if (!target[k]) target[k] = polyfills[k];
1362 }
1363
1364 onlineOfflineEvents.polyfill(target); // 假扮为 React Native,让 axios 认为这是一个 nonStandardBrowserEnv
1365
1366 target.navigator.product = 'ReactNative';
1367 },
1368 localStorage: localstorage,
1369 XMLHttpRequest: xmlhttprequest,
1370 FormData: formdata,
1371 WebSocket: websocket
1372 };
1373
1374 var polyfill$1 = weappPolyfill.polyfill;
1375
1376 try {
1377 polyfill$1();
1378 } catch (e) {}
1379
1380 try {
1381 polyfill$1(GameGlobal);
1382 } catch (e) {}
1383
1384 try {
1385 window = window || {};
1386 polyfill$1(window);
1387 } catch (e) {}
1388
1389 try {
1390 localStorage = localStorage || localstorage;
1391 } catch (e) {}
1392
1393 try {
1394 XMLHttpRequest = XMLHttpRequest || xmlhttprequest;
1395 } catch (e) {}
1396
1397 try {
1398 FormData = FormData || formdata;
1399 } catch (e) {}
1400
1401 try {
1402 WebSocket = WebSocket || websocket;
1403 } catch (e) {}
1404
1405 try {
1406 navigator = navigator || navigator$1;
1407 } catch (e) {}
1408
1409 // eslint-disable-next-line import/no-extraneous-dependencies
1410
1411 var long_1 = createCommonjsModule(function (module) {
1412 /*
1413 Copyright 2013 Daniel Wirtz <dcode@dcode.io>
1414 Copyright 2009 The Closure Library Authors. All Rights Reserved.
1415
1416 Licensed under the Apache License, Version 2.0 (the "License");
1417 you may not use this file except in compliance with the License.
1418 You may obtain a copy of the License at
1419
1420 http://www.apache.org/licenses/LICENSE-2.0
1421
1422 Unless required by applicable law or agreed to in writing, software
1423 distributed under the License is distributed on an "AS-IS" BASIS,
1424 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1425 See the License for the specific language governing permissions and
1426 limitations under the License.
1427 */
1428
1429 /**
1430 * @license long.js (c) 2013 Daniel Wirtz <dcode@dcode.io>
1431 * Released under the Apache License, Version 2.0
1432 * see: https://github.com/dcodeIO/long.js for details
1433 */
1434 (function(global, factory) {
1435
1436 /* AMD */ if (typeof commonjsRequire === 'function' && 'object' === "object" && module && module["exports"])
1437 module["exports"] = factory();
1438 /* Global */ else
1439 (global["dcodeIO"] = global["dcodeIO"] || {})["Long"] = factory();
1440
1441 })(commonjsGlobal, function() {
1442
1443 /**
1444 * Constructs a 64 bit two's-complement integer, given its low and high 32 bit values as *signed* integers.
1445 * See the from* functions below for more convenient ways of constructing Longs.
1446 * @exports Long
1447 * @class A Long class for representing a 64 bit two's-complement integer value.
1448 * @param {number} low The low (signed) 32 bits of the long
1449 * @param {number} high The high (signed) 32 bits of the long
1450 * @param {boolean=} unsigned Whether unsigned or not, defaults to `false` for signed
1451 * @constructor
1452 */
1453 function Long(low, high, unsigned) {
1454
1455 /**
1456 * The low 32 bits as a signed value.
1457 * @type {number}
1458 */
1459 this.low = low | 0;
1460
1461 /**
1462 * The high 32 bits as a signed value.
1463 * @type {number}
1464 */
1465 this.high = high | 0;
1466
1467 /**
1468 * Whether unsigned or not.
1469 * @type {boolean}
1470 */
1471 this.unsigned = !!unsigned;
1472 }
1473
1474 // The internal representation of a long is the two given signed, 32-bit values.
1475 // We use 32-bit pieces because these are the size of integers on which
1476 // Javascript performs bit-operations. For operations like addition and
1477 // multiplication, we split each number into 16 bit pieces, which can easily be
1478 // multiplied within Javascript's floating-point representation without overflow
1479 // or change in sign.
1480 //
1481 // In the algorithms below, we frequently reduce the negative case to the
1482 // positive case by negating the input(s) and then post-processing the result.
1483 // Note that we must ALWAYS check specially whether those values are MIN_VALUE
1484 // (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as
1485 // a positive number, it overflows back into a negative). Not handling this
1486 // case would often result in infinite recursion.
1487 //
1488 // Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the from*
1489 // methods on which they depend.
1490
1491 /**
1492 * An indicator used to reliably determine if an object is a Long or not.
1493 * @type {boolean}
1494 * @const
1495 * @private
1496 */
1497 Long.prototype.__isLong__;
1498
1499 Object.defineProperty(Long.prototype, "__isLong__", {
1500 value: true,
1501 enumerable: false,
1502 configurable: false
1503 });
1504
1505 /**
1506 * @function
1507 * @param {*} obj Object
1508 * @returns {boolean}
1509 * @inner
1510 */
1511 function isLong(obj) {
1512 return (obj && obj["__isLong__"]) === true;
1513 }
1514
1515 /**
1516 * Tests if the specified object is a Long.
1517 * @function
1518 * @param {*} obj Object
1519 * @returns {boolean}
1520 */
1521 Long.isLong = isLong;
1522
1523 /**
1524 * A cache of the Long representations of small integer values.
1525 * @type {!Object}
1526 * @inner
1527 */
1528 var INT_CACHE = {};
1529
1530 /**
1531 * A cache of the Long representations of small unsigned integer values.
1532 * @type {!Object}
1533 * @inner
1534 */
1535 var UINT_CACHE = {};
1536
1537 /**
1538 * @param {number} value
1539 * @param {boolean=} unsigned
1540 * @returns {!Long}
1541 * @inner
1542 */
1543 function fromInt(value, unsigned) {
1544 var obj, cachedObj, cache;
1545 if (unsigned) {
1546 value >>>= 0;
1547 if (cache = (0 <= value && value < 256)) {
1548 cachedObj = UINT_CACHE[value];
1549 if (cachedObj)
1550 return cachedObj;
1551 }
1552 obj = fromBits(value, (value | 0) < 0 ? -1 : 0, true);
1553 if (cache)
1554 UINT_CACHE[value] = obj;
1555 return obj;
1556 } else {
1557 value |= 0;
1558 if (cache = (-128 <= value && value < 128)) {
1559 cachedObj = INT_CACHE[value];
1560 if (cachedObj)
1561 return cachedObj;
1562 }
1563 obj = fromBits(value, value < 0 ? -1 : 0, false);
1564 if (cache)
1565 INT_CACHE[value] = obj;
1566 return obj;
1567 }
1568 }
1569
1570 /**
1571 * Returns a Long representing the given 32 bit integer value.
1572 * @function
1573 * @param {number} value The 32 bit integer in question
1574 * @param {boolean=} unsigned Whether unsigned or not, defaults to `false` for signed
1575 * @returns {!Long} The corresponding Long value
1576 */
1577 Long.fromInt = fromInt;
1578
1579 /**
1580 * @param {number} value
1581 * @param {boolean=} unsigned
1582 * @returns {!Long}
1583 * @inner
1584 */
1585 function fromNumber(value, unsigned) {
1586 if (isNaN(value) || !isFinite(value))
1587 return unsigned ? UZERO : ZERO;
1588 if (unsigned) {
1589 if (value < 0)
1590 return UZERO;
1591 if (value >= TWO_PWR_64_DBL)
1592 return MAX_UNSIGNED_VALUE;
1593 } else {
1594 if (value <= -TWO_PWR_63_DBL)
1595 return MIN_VALUE;
1596 if (value + 1 >= TWO_PWR_63_DBL)
1597 return MAX_VALUE;
1598 }
1599 if (value < 0)
1600 return fromNumber(-value, unsigned).neg();
1601 return fromBits((value % TWO_PWR_32_DBL) | 0, (value / TWO_PWR_32_DBL) | 0, unsigned);
1602 }
1603
1604 /**
1605 * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned.
1606 * @function
1607 * @param {number} value The number in question
1608 * @param {boolean=} unsigned Whether unsigned or not, defaults to `false` for signed
1609 * @returns {!Long} The corresponding Long value
1610 */
1611 Long.fromNumber = fromNumber;
1612
1613 /**
1614 * @param {number} lowBits
1615 * @param {number} highBits
1616 * @param {boolean=} unsigned
1617 * @returns {!Long}
1618 * @inner
1619 */
1620 function fromBits(lowBits, highBits, unsigned) {
1621 return new Long(lowBits, highBits, unsigned);
1622 }
1623
1624 /**
1625 * Returns a Long representing the 64 bit integer that comes by concatenating the given low and high bits. Each is
1626 * assumed to use 32 bits.
1627 * @function
1628 * @param {number} lowBits The low 32 bits
1629 * @param {number} highBits The high 32 bits
1630 * @param {boolean=} unsigned Whether unsigned or not, defaults to `false` for signed
1631 * @returns {!Long} The corresponding Long value
1632 */
1633 Long.fromBits = fromBits;
1634
1635 /**
1636 * @function
1637 * @param {number} base
1638 * @param {number} exponent
1639 * @returns {number}
1640 * @inner
1641 */
1642 var pow_dbl = Math.pow; // Used 4 times (4*8 to 15+4)
1643
1644 /**
1645 * @param {string} str
1646 * @param {(boolean|number)=} unsigned
1647 * @param {number=} radix
1648 * @returns {!Long}
1649 * @inner
1650 */
1651 function fromString(str, unsigned, radix) {
1652 if (str.length === 0)
1653 throw Error('empty string');
1654 if (str === "NaN" || str === "Infinity" || str === "+Infinity" || str === "-Infinity")
1655 return ZERO;
1656 if (typeof unsigned === 'number') {
1657 // For goog.math.long compatibility
1658 radix = unsigned,
1659 unsigned = false;
1660 } else {
1661 unsigned = !! unsigned;
1662 }
1663 radix = radix || 10;
1664 if (radix < 2 || 36 < radix)
1665 throw RangeError('radix');
1666
1667 var p;
1668 if ((p = str.indexOf('-')) > 0)
1669 throw Error('interior hyphen');
1670 else if (p === 0) {
1671 return fromString(str.substring(1), unsigned, radix).neg();
1672 }
1673
1674 // Do several (8) digits each time through the loop, so as to
1675 // minimize the calls to the very expensive emulated div.
1676 var radixToPower = fromNumber(pow_dbl(radix, 8));
1677
1678 var result = ZERO;
1679 for (var i = 0; i < str.length; i += 8) {
1680 var size = Math.min(8, str.length - i),
1681 value = parseInt(str.substring(i, i + size), radix);
1682 if (size < 8) {
1683 var power = fromNumber(pow_dbl(radix, size));
1684 result = result.mul(power).add(fromNumber(value));
1685 } else {
1686 result = result.mul(radixToPower);
1687 result = result.add(fromNumber(value));
1688 }
1689 }
1690 result.unsigned = unsigned;
1691 return result;
1692 }
1693
1694 /**
1695 * Returns a Long representation of the given string, written using the specified radix.
1696 * @function
1697 * @param {string} str The textual representation of the Long
1698 * @param {(boolean|number)=} unsigned Whether unsigned or not, defaults to `false` for signed
1699 * @param {number=} radix The radix in which the text is written (2-36), defaults to 10
1700 * @returns {!Long} The corresponding Long value
1701 */
1702 Long.fromString = fromString;
1703
1704 /**
1705 * @function
1706 * @param {!Long|number|string|!{low: number, high: number, unsigned: boolean}} val
1707 * @returns {!Long}
1708 * @inner
1709 */
1710 function fromValue(val) {
1711 if (val /* is compatible */ instanceof Long)
1712 return val;
1713 if (typeof val === 'number')
1714 return fromNumber(val);
1715 if (typeof val === 'string')
1716 return fromString(val);
1717 // Throws for non-objects, converts non-instanceof Long:
1718 return fromBits(val.low, val.high, val.unsigned);
1719 }
1720
1721 /**
1722 * Converts the specified value to a Long.
1723 * @function
1724 * @param {!Long|number|string|!{low: number, high: number, unsigned: boolean}} val Value
1725 * @returns {!Long}
1726 */
1727 Long.fromValue = fromValue;
1728
1729 // NOTE: the compiler should inline these constant values below and then remove these variables, so there should be
1730 // no runtime penalty for these.
1731
1732 /**
1733 * @type {number}
1734 * @const
1735 * @inner
1736 */
1737 var TWO_PWR_16_DBL = 1 << 16;
1738
1739 /**
1740 * @type {number}
1741 * @const
1742 * @inner
1743 */
1744 var TWO_PWR_24_DBL = 1 << 24;
1745
1746 /**
1747 * @type {number}
1748 * @const
1749 * @inner
1750 */
1751 var TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL;
1752
1753 /**
1754 * @type {number}
1755 * @const
1756 * @inner
1757 */
1758 var TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL;
1759
1760 /**
1761 * @type {number}
1762 * @const
1763 * @inner
1764 */
1765 var TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2;
1766
1767 /**
1768 * @type {!Long}
1769 * @const
1770 * @inner
1771 */
1772 var TWO_PWR_24 = fromInt(TWO_PWR_24_DBL);
1773
1774 /**
1775 * @type {!Long}
1776 * @inner
1777 */
1778 var ZERO = fromInt(0);
1779
1780 /**
1781 * Signed zero.
1782 * @type {!Long}
1783 */
1784 Long.ZERO = ZERO;
1785
1786 /**
1787 * @type {!Long}
1788 * @inner
1789 */
1790 var UZERO = fromInt(0, true);
1791
1792 /**
1793 * Unsigned zero.
1794 * @type {!Long}
1795 */
1796 Long.UZERO = UZERO;
1797
1798 /**
1799 * @type {!Long}
1800 * @inner
1801 */
1802 var ONE = fromInt(1);
1803
1804 /**
1805 * Signed one.
1806 * @type {!Long}
1807 */
1808 Long.ONE = ONE;
1809
1810 /**
1811 * @type {!Long}
1812 * @inner
1813 */
1814 var UONE = fromInt(1, true);
1815
1816 /**
1817 * Unsigned one.
1818 * @type {!Long}
1819 */
1820 Long.UONE = UONE;
1821
1822 /**
1823 * @type {!Long}
1824 * @inner
1825 */
1826 var NEG_ONE = fromInt(-1);
1827
1828 /**
1829 * Signed negative one.
1830 * @type {!Long}
1831 */
1832 Long.NEG_ONE = NEG_ONE;
1833
1834 /**
1835 * @type {!Long}
1836 * @inner
1837 */
1838 var MAX_VALUE = fromBits(0xFFFFFFFF|0, 0x7FFFFFFF|0, false);
1839
1840 /**
1841 * Maximum signed value.
1842 * @type {!Long}
1843 */
1844 Long.MAX_VALUE = MAX_VALUE;
1845
1846 /**
1847 * @type {!Long}
1848 * @inner
1849 */
1850 var MAX_UNSIGNED_VALUE = fromBits(0xFFFFFFFF|0, 0xFFFFFFFF|0, true);
1851
1852 /**
1853 * Maximum unsigned value.
1854 * @type {!Long}
1855 */
1856 Long.MAX_UNSIGNED_VALUE = MAX_UNSIGNED_VALUE;
1857
1858 /**
1859 * @type {!Long}
1860 * @inner
1861 */
1862 var MIN_VALUE = fromBits(0, 0x80000000|0, false);
1863
1864 /**
1865 * Minimum signed value.
1866 * @type {!Long}
1867 */
1868 Long.MIN_VALUE = MIN_VALUE;
1869
1870 /**
1871 * @alias Long.prototype
1872 * @inner
1873 */
1874 var LongPrototype = Long.prototype;
1875
1876 /**
1877 * Converts the Long to a 32 bit integer, assuming it is a 32 bit integer.
1878 * @returns {number}
1879 */
1880 LongPrototype.toInt = function toInt() {
1881 return this.unsigned ? this.low >>> 0 : this.low;
1882 };
1883
1884 /**
1885 * Converts the Long to a the nearest floating-point representation of this value (double, 53 bit mantissa).
1886 * @returns {number}
1887 */
1888 LongPrototype.toNumber = function toNumber() {
1889 if (this.unsigned)
1890 return ((this.high >>> 0) * TWO_PWR_32_DBL) + (this.low >>> 0);
1891 return this.high * TWO_PWR_32_DBL + (this.low >>> 0);
1892 };
1893
1894 /**
1895 * Converts the Long to a string written in the specified radix.
1896 * @param {number=} radix Radix (2-36), defaults to 10
1897 * @returns {string}
1898 * @override
1899 * @throws {RangeError} If `radix` is out of range
1900 */
1901 LongPrototype.toString = function toString(radix) {
1902 radix = radix || 10;
1903 if (radix < 2 || 36 < radix)
1904 throw RangeError('radix');
1905 if (this.isZero())
1906 return '0';
1907 if (this.isNegative()) { // Unsigned Longs are never negative
1908 if (this.eq(MIN_VALUE)) {
1909 // We need to change the Long value before it can be negated, so we remove
1910 // the bottom-most digit in this base and then recurse to do the rest.
1911 var radixLong = fromNumber(radix),
1912 div = this.div(radixLong),
1913 rem1 = div.mul(radixLong).sub(this);
1914 return div.toString(radix) + rem1.toInt().toString(radix);
1915 } else
1916 return '-' + this.neg().toString(radix);
1917 }
1918
1919 // Do several (6) digits each time through the loop, so as to
1920 // minimize the calls to the very expensive emulated div.
1921 var radixToPower = fromNumber(pow_dbl(radix, 6), this.unsigned),
1922 rem = this;
1923 var result = '';
1924 while (true) {
1925 var remDiv = rem.div(radixToPower),
1926 intval = rem.sub(remDiv.mul(radixToPower)).toInt() >>> 0,
1927 digits = intval.toString(radix);
1928 rem = remDiv;
1929 if (rem.isZero())
1930 return digits + result;
1931 else {
1932 while (digits.length < 6)
1933 digits = '0' + digits;
1934 result = '' + digits + result;
1935 }
1936 }
1937 };
1938
1939 /**
1940 * Gets the high 32 bits as a signed integer.
1941 * @returns {number} Signed high bits
1942 */
1943 LongPrototype.getHighBits = function getHighBits() {
1944 return this.high;
1945 };
1946
1947 /**
1948 * Gets the high 32 bits as an unsigned integer.
1949 * @returns {number} Unsigned high bits
1950 */
1951 LongPrototype.getHighBitsUnsigned = function getHighBitsUnsigned() {
1952 return this.high >>> 0;
1953 };
1954
1955 /**
1956 * Gets the low 32 bits as a signed integer.
1957 * @returns {number} Signed low bits
1958 */
1959 LongPrototype.getLowBits = function getLowBits() {
1960 return this.low;
1961 };
1962
1963 /**
1964 * Gets the low 32 bits as an unsigned integer.
1965 * @returns {number} Unsigned low bits
1966 */
1967 LongPrototype.getLowBitsUnsigned = function getLowBitsUnsigned() {
1968 return this.low >>> 0;
1969 };
1970
1971 /**
1972 * Gets the number of bits needed to represent the absolute value of this Long.
1973 * @returns {number}
1974 */
1975 LongPrototype.getNumBitsAbs = function getNumBitsAbs() {
1976 if (this.isNegative()) // Unsigned Longs are never negative
1977 return this.eq(MIN_VALUE) ? 64 : this.neg().getNumBitsAbs();
1978 var val = this.high != 0 ? this.high : this.low;
1979 for (var bit = 31; bit > 0; bit--)
1980 if ((val & (1 << bit)) != 0)
1981 break;
1982 return this.high != 0 ? bit + 33 : bit + 1;
1983 };
1984
1985 /**
1986 * Tests if this Long's value equals zero.
1987 * @returns {boolean}
1988 */
1989 LongPrototype.isZero = function isZero() {
1990 return this.high === 0 && this.low === 0;
1991 };
1992
1993 /**
1994 * Tests if this Long's value is negative.
1995 * @returns {boolean}
1996 */
1997 LongPrototype.isNegative = function isNegative() {
1998 return !this.unsigned && this.high < 0;
1999 };
2000
2001 /**
2002 * Tests if this Long's value is positive.
2003 * @returns {boolean}
2004 */
2005 LongPrototype.isPositive = function isPositive() {
2006 return this.unsigned || this.high >= 0;
2007 };
2008
2009 /**
2010 * Tests if this Long's value is odd.
2011 * @returns {boolean}
2012 */
2013 LongPrototype.isOdd = function isOdd() {
2014 return (this.low & 1) === 1;
2015 };
2016
2017 /**
2018 * Tests if this Long's value is even.
2019 * @returns {boolean}
2020 */
2021 LongPrototype.isEven = function isEven() {
2022 return (this.low & 1) === 0;
2023 };
2024
2025 /**
2026 * Tests if this Long's value equals the specified's.
2027 * @param {!Long|number|string} other Other value
2028 * @returns {boolean}
2029 */
2030 LongPrototype.equals = function equals(other) {
2031 if (!isLong(other))
2032 other = fromValue(other);
2033 if (this.unsigned !== other.unsigned && (this.high >>> 31) === 1 && (other.high >>> 31) === 1)
2034 return false;
2035 return this.high === other.high && this.low === other.low;
2036 };
2037
2038 /**
2039 * Tests if this Long's value equals the specified's. This is an alias of {@link Long#equals}.
2040 * @function
2041 * @param {!Long|number|string} other Other value
2042 * @returns {boolean}
2043 */
2044 LongPrototype.eq = LongPrototype.equals;
2045
2046 /**
2047 * Tests if this Long's value differs from the specified's.
2048 * @param {!Long|number|string} other Other value
2049 * @returns {boolean}
2050 */
2051 LongPrototype.notEquals = function notEquals(other) {
2052 return !this.eq(/* validates */ other);
2053 };
2054
2055 /**
2056 * Tests if this Long's value differs from the specified's. This is an alias of {@link Long#notEquals}.
2057 * @function
2058 * @param {!Long|number|string} other Other value
2059 * @returns {boolean}
2060 */
2061 LongPrototype.neq = LongPrototype.notEquals;
2062
2063 /**
2064 * Tests if this Long's value is less than the specified's.
2065 * @param {!Long|number|string} other Other value
2066 * @returns {boolean}
2067 */
2068 LongPrototype.lessThan = function lessThan(other) {
2069 return this.comp(/* validates */ other) < 0;
2070 };
2071
2072 /**
2073 * Tests if this Long's value is less than the specified's. This is an alias of {@link Long#lessThan}.
2074 * @function
2075 * @param {!Long|number|string} other Other value
2076 * @returns {boolean}
2077 */
2078 LongPrototype.lt = LongPrototype.lessThan;
2079
2080 /**
2081 * Tests if this Long's value is less than or equal the specified's.
2082 * @param {!Long|number|string} other Other value
2083 * @returns {boolean}
2084 */
2085 LongPrototype.lessThanOrEqual = function lessThanOrEqual(other) {
2086 return this.comp(/* validates */ other) <= 0;
2087 };
2088
2089 /**
2090 * Tests if this Long's value is less than or equal the specified's. This is an alias of {@link Long#lessThanOrEqual}.
2091 * @function
2092 * @param {!Long|number|string} other Other value
2093 * @returns {boolean}
2094 */
2095 LongPrototype.lte = LongPrototype.lessThanOrEqual;
2096
2097 /**
2098 * Tests if this Long's value is greater than the specified's.
2099 * @param {!Long|number|string} other Other value
2100 * @returns {boolean}
2101 */
2102 LongPrototype.greaterThan = function greaterThan(other) {
2103 return this.comp(/* validates */ other) > 0;
2104 };
2105
2106 /**
2107 * Tests if this Long's value is greater than the specified's. This is an alias of {@link Long#greaterThan}.
2108 * @function
2109 * @param {!Long|number|string} other Other value
2110 * @returns {boolean}
2111 */
2112 LongPrototype.gt = LongPrototype.greaterThan;
2113
2114 /**
2115 * Tests if this Long's value is greater than or equal the specified's.
2116 * @param {!Long|number|string} other Other value
2117 * @returns {boolean}
2118 */
2119 LongPrototype.greaterThanOrEqual = function greaterThanOrEqual(other) {
2120 return this.comp(/* validates */ other) >= 0;
2121 };
2122
2123 /**
2124 * Tests if this Long's value is greater than or equal the specified's. This is an alias of {@link Long#greaterThanOrEqual}.
2125 * @function
2126 * @param {!Long|number|string} other Other value
2127 * @returns {boolean}
2128 */
2129 LongPrototype.gte = LongPrototype.greaterThanOrEqual;
2130
2131 /**
2132 * Compares this Long's value with the specified's.
2133 * @param {!Long|number|string} other Other value
2134 * @returns {number} 0 if they are the same, 1 if the this is greater and -1
2135 * if the given one is greater
2136 */
2137 LongPrototype.compare = function compare(other) {
2138 if (!isLong(other))
2139 other = fromValue(other);
2140 if (this.eq(other))
2141 return 0;
2142 var thisNeg = this.isNegative(),
2143 otherNeg = other.isNegative();
2144 if (thisNeg && !otherNeg)
2145 return -1;
2146 if (!thisNeg && otherNeg)
2147 return 1;
2148 // At this point the sign bits are the same
2149 if (!this.unsigned)
2150 return this.sub(other).isNegative() ? -1 : 1;
2151 // Both are positive if at least one is unsigned
2152 return (other.high >>> 0) > (this.high >>> 0) || (other.high === this.high && (other.low >>> 0) > (this.low >>> 0)) ? -1 : 1;
2153 };
2154
2155 /**
2156 * Compares this Long's value with the specified's. This is an alias of {@link Long#compare}.
2157 * @function
2158 * @param {!Long|number|string} other Other value
2159 * @returns {number} 0 if they are the same, 1 if the this is greater and -1
2160 * if the given one is greater
2161 */
2162 LongPrototype.comp = LongPrototype.compare;
2163
2164 /**
2165 * Negates this Long's value.
2166 * @returns {!Long} Negated Long
2167 */
2168 LongPrototype.negate = function negate() {
2169 if (!this.unsigned && this.eq(MIN_VALUE))
2170 return MIN_VALUE;
2171 return this.not().add(ONE);
2172 };
2173
2174 /**
2175 * Negates this Long's value. This is an alias of {@link Long#negate}.
2176 * @function
2177 * @returns {!Long} Negated Long
2178 */
2179 LongPrototype.neg = LongPrototype.negate;
2180
2181 /**
2182 * Returns the sum of this and the specified Long.
2183 * @param {!Long|number|string} addend Addend
2184 * @returns {!Long} Sum
2185 */
2186 LongPrototype.add = function add(addend) {
2187 if (!isLong(addend))
2188 addend = fromValue(addend);
2189
2190 // Divide each number into 4 chunks of 16 bits, and then sum the chunks.
2191
2192 var a48 = this.high >>> 16;
2193 var a32 = this.high & 0xFFFF;
2194 var a16 = this.low >>> 16;
2195 var a00 = this.low & 0xFFFF;
2196
2197 var b48 = addend.high >>> 16;
2198 var b32 = addend.high & 0xFFFF;
2199 var b16 = addend.low >>> 16;
2200 var b00 = addend.low & 0xFFFF;
2201
2202 var c48 = 0, c32 = 0, c16 = 0, c00 = 0;
2203 c00 += a00 + b00;
2204 c16 += c00 >>> 16;
2205 c00 &= 0xFFFF;
2206 c16 += a16 + b16;
2207 c32 += c16 >>> 16;
2208 c16 &= 0xFFFF;
2209 c32 += a32 + b32;
2210 c48 += c32 >>> 16;
2211 c32 &= 0xFFFF;
2212 c48 += a48 + b48;
2213 c48 &= 0xFFFF;
2214 return fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned);
2215 };
2216
2217 /**
2218 * Returns the difference of this and the specified Long.
2219 * @param {!Long|number|string} subtrahend Subtrahend
2220 * @returns {!Long} Difference
2221 */
2222 LongPrototype.subtract = function subtract(subtrahend) {
2223 if (!isLong(subtrahend))
2224 subtrahend = fromValue(subtrahend);
2225 return this.add(subtrahend.neg());
2226 };
2227
2228 /**
2229 * Returns the difference of this and the specified Long. This is an alias of {@link Long#subtract}.
2230 * @function
2231 * @param {!Long|number|string} subtrahend Subtrahend
2232 * @returns {!Long} Difference
2233 */
2234 LongPrototype.sub = LongPrototype.subtract;
2235
2236 /**
2237 * Returns the product of this and the specified Long.
2238 * @param {!Long|number|string} multiplier Multiplier
2239 * @returns {!Long} Product
2240 */
2241 LongPrototype.multiply = function multiply(multiplier) {
2242 if (this.isZero())
2243 return ZERO;
2244 if (!isLong(multiplier))
2245 multiplier = fromValue(multiplier);
2246 if (multiplier.isZero())
2247 return ZERO;
2248 if (this.eq(MIN_VALUE))
2249 return multiplier.isOdd() ? MIN_VALUE : ZERO;
2250 if (multiplier.eq(MIN_VALUE))
2251 return this.isOdd() ? MIN_VALUE : ZERO;
2252
2253 if (this.isNegative()) {
2254 if (multiplier.isNegative())
2255 return this.neg().mul(multiplier.neg());
2256 else
2257 return this.neg().mul(multiplier).neg();
2258 } else if (multiplier.isNegative())
2259 return this.mul(multiplier.neg()).neg();
2260
2261 // If both longs are small, use float multiplication
2262 if (this.lt(TWO_PWR_24) && multiplier.lt(TWO_PWR_24))
2263 return fromNumber(this.toNumber() * multiplier.toNumber(), this.unsigned);
2264
2265 // Divide each long into 4 chunks of 16 bits, and then add up 4x4 products.
2266 // We can skip products that would overflow.
2267
2268 var a48 = this.high >>> 16;
2269 var a32 = this.high & 0xFFFF;
2270 var a16 = this.low >>> 16;
2271 var a00 = this.low & 0xFFFF;
2272
2273 var b48 = multiplier.high >>> 16;
2274 var b32 = multiplier.high & 0xFFFF;
2275 var b16 = multiplier.low >>> 16;
2276 var b00 = multiplier.low & 0xFFFF;
2277
2278 var c48 = 0, c32 = 0, c16 = 0, c00 = 0;
2279 c00 += a00 * b00;
2280 c16 += c00 >>> 16;
2281 c00 &= 0xFFFF;
2282 c16 += a16 * b00;
2283 c32 += c16 >>> 16;
2284 c16 &= 0xFFFF;
2285 c16 += a00 * b16;
2286 c32 += c16 >>> 16;
2287 c16 &= 0xFFFF;
2288 c32 += a32 * b00;
2289 c48 += c32 >>> 16;
2290 c32 &= 0xFFFF;
2291 c32 += a16 * b16;
2292 c48 += c32 >>> 16;
2293 c32 &= 0xFFFF;
2294 c32 += a00 * b32;
2295 c48 += c32 >>> 16;
2296 c32 &= 0xFFFF;
2297 c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48;
2298 c48 &= 0xFFFF;
2299 return fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned);
2300 };
2301
2302 /**
2303 * Returns the product of this and the specified Long. This is an alias of {@link Long#multiply}.
2304 * @function
2305 * @param {!Long|number|string} multiplier Multiplier
2306 * @returns {!Long} Product
2307 */
2308 LongPrototype.mul = LongPrototype.multiply;
2309
2310 /**
2311 * Returns this Long divided by the specified. The result is signed if this Long is signed or
2312 * unsigned if this Long is unsigned.
2313 * @param {!Long|number|string} divisor Divisor
2314 * @returns {!Long} Quotient
2315 */
2316 LongPrototype.divide = function divide(divisor) {
2317 if (!isLong(divisor))
2318 divisor = fromValue(divisor);
2319 if (divisor.isZero())
2320 throw Error('division by zero');
2321 if (this.isZero())
2322 return this.unsigned ? UZERO : ZERO;
2323 var approx, rem, res;
2324 if (!this.unsigned) {
2325 // This section is only relevant for signed longs and is derived from the
2326 // closure library as a whole.
2327 if (this.eq(MIN_VALUE)) {
2328 if (divisor.eq(ONE) || divisor.eq(NEG_ONE))
2329 return MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE
2330 else if (divisor.eq(MIN_VALUE))
2331 return ONE;
2332 else {
2333 // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|.
2334 var halfThis = this.shr(1);
2335 approx = halfThis.div(divisor).shl(1);
2336 if (approx.eq(ZERO)) {
2337 return divisor.isNegative() ? ONE : NEG_ONE;
2338 } else {
2339 rem = this.sub(divisor.mul(approx));
2340 res = approx.add(rem.div(divisor));
2341 return res;
2342 }
2343 }
2344 } else if (divisor.eq(MIN_VALUE))
2345 return this.unsigned ? UZERO : ZERO;
2346 if (this.isNegative()) {
2347 if (divisor.isNegative())
2348 return this.neg().div(divisor.neg());
2349 return this.neg().div(divisor).neg();
2350 } else if (divisor.isNegative())
2351 return this.div(divisor.neg()).neg();
2352 res = ZERO;
2353 } else {
2354 // The algorithm below has not been made for unsigned longs. It's therefore
2355 // required to take special care of the MSB prior to running it.
2356 if (!divisor.unsigned)
2357 divisor = divisor.toUnsigned();
2358 if (divisor.gt(this))
2359 return UZERO;
2360 if (divisor.gt(this.shru(1))) // 15 >>> 1 = 7 ; with divisor = 8 ; true
2361 return UONE;
2362 res = UZERO;
2363 }
2364
2365 // Repeat the following until the remainder is less than other: find a
2366 // floating-point that approximates remainder / other *from below*, add this
2367 // into the result, and subtract it from the remainder. It is critical that
2368 // the approximate value is less than or equal to the real value so that the
2369 // remainder never becomes negative.
2370 rem = this;
2371 while (rem.gte(divisor)) {
2372 // Approximate the result of division. This may be a little greater or
2373 // smaller than the actual value.
2374 approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber()));
2375
2376 // We will tweak the approximate result by changing it in the 48-th digit or
2377 // the smallest non-fractional digit, whichever is larger.
2378 var log2 = Math.ceil(Math.log(approx) / Math.LN2),
2379 delta = (log2 <= 48) ? 1 : pow_dbl(2, log2 - 48),
2380
2381 // Decrease the approximation until it is smaller than the remainder. Note
2382 // that if it is too large, the product overflows and is negative.
2383 approxRes = fromNumber(approx),
2384 approxRem = approxRes.mul(divisor);
2385 while (approxRem.isNegative() || approxRem.gt(rem)) {
2386 approx -= delta;
2387 approxRes = fromNumber(approx, this.unsigned);
2388 approxRem = approxRes.mul(divisor);
2389 }
2390
2391 // We know the answer can't be zero... and actually, zero would cause
2392 // infinite recursion since we would make no progress.
2393 if (approxRes.isZero())
2394 approxRes = ONE;
2395
2396 res = res.add(approxRes);
2397 rem = rem.sub(approxRem);
2398 }
2399 return res;
2400 };
2401
2402 /**
2403 * Returns this Long divided by the specified. This is an alias of {@link Long#divide}.
2404 * @function
2405 * @param {!Long|number|string} divisor Divisor
2406 * @returns {!Long} Quotient
2407 */
2408 LongPrototype.div = LongPrototype.divide;
2409
2410 /**
2411 * Returns this Long modulo the specified.
2412 * @param {!Long|number|string} divisor Divisor
2413 * @returns {!Long} Remainder
2414 */
2415 LongPrototype.modulo = function modulo(divisor) {
2416 if (!isLong(divisor))
2417 divisor = fromValue(divisor);
2418 return this.sub(this.div(divisor).mul(divisor));
2419 };
2420
2421 /**
2422 * Returns this Long modulo the specified. This is an alias of {@link Long#modulo}.
2423 * @function
2424 * @param {!Long|number|string} divisor Divisor
2425 * @returns {!Long} Remainder
2426 */
2427 LongPrototype.mod = LongPrototype.modulo;
2428
2429 /**
2430 * Returns the bitwise NOT of this Long.
2431 * @returns {!Long}
2432 */
2433 LongPrototype.not = function not() {
2434 return fromBits(~this.low, ~this.high, this.unsigned);
2435 };
2436
2437 /**
2438 * Returns the bitwise AND of this Long and the specified.
2439 * @param {!Long|number|string} other Other Long
2440 * @returns {!Long}
2441 */
2442 LongPrototype.and = function and(other) {
2443 if (!isLong(other))
2444 other = fromValue(other);
2445 return fromBits(this.low & other.low, this.high & other.high, this.unsigned);
2446 };
2447
2448 /**
2449 * Returns the bitwise OR of this Long and the specified.
2450 * @param {!Long|number|string} other Other Long
2451 * @returns {!Long}
2452 */
2453 LongPrototype.or = function or(other) {
2454 if (!isLong(other))
2455 other = fromValue(other);
2456 return fromBits(this.low | other.low, this.high | other.high, this.unsigned);
2457 };
2458
2459 /**
2460 * Returns the bitwise XOR of this Long and the given one.
2461 * @param {!Long|number|string} other Other Long
2462 * @returns {!Long}
2463 */
2464 LongPrototype.xor = function xor(other) {
2465 if (!isLong(other))
2466 other = fromValue(other);
2467 return fromBits(this.low ^ other.low, this.high ^ other.high, this.unsigned);
2468 };
2469
2470 /**
2471 * Returns this Long with bits shifted to the left by the given amount.
2472 * @param {number|!Long} numBits Number of bits
2473 * @returns {!Long} Shifted Long
2474 */
2475 LongPrototype.shiftLeft = function shiftLeft(numBits) {
2476 if (isLong(numBits))
2477 numBits = numBits.toInt();
2478 if ((numBits &= 63) === 0)
2479 return this;
2480 else if (numBits < 32)
2481 return fromBits(this.low << numBits, (this.high << numBits) | (this.low >>> (32 - numBits)), this.unsigned);
2482 else
2483 return fromBits(0, this.low << (numBits - 32), this.unsigned);
2484 };
2485
2486 /**
2487 * Returns this Long with bits shifted to the left by the given amount. This is an alias of {@link Long#shiftLeft}.
2488 * @function
2489 * @param {number|!Long} numBits Number of bits
2490 * @returns {!Long} Shifted Long
2491 */
2492 LongPrototype.shl = LongPrototype.shiftLeft;
2493
2494 /**
2495 * Returns this Long with bits arithmetically shifted to the right by the given amount.
2496 * @param {number|!Long} numBits Number of bits
2497 * @returns {!Long} Shifted Long
2498 */
2499 LongPrototype.shiftRight = function shiftRight(numBits) {
2500 if (isLong(numBits))
2501 numBits = numBits.toInt();
2502 if ((numBits &= 63) === 0)
2503 return this;
2504 else if (numBits < 32)
2505 return fromBits((this.low >>> numBits) | (this.high << (32 - numBits)), this.high >> numBits, this.unsigned);
2506 else
2507 return fromBits(this.high >> (numBits - 32), this.high >= 0 ? 0 : -1, this.unsigned);
2508 };
2509
2510 /**
2511 * Returns this Long with bits arithmetically shifted to the right by the given amount. This is an alias of {@link Long#shiftRight}.
2512 * @function
2513 * @param {number|!Long} numBits Number of bits
2514 * @returns {!Long} Shifted Long
2515 */
2516 LongPrototype.shr = LongPrototype.shiftRight;
2517
2518 /**
2519 * Returns this Long with bits logically shifted to the right by the given amount.
2520 * @param {number|!Long} numBits Number of bits
2521 * @returns {!Long} Shifted Long
2522 */
2523 LongPrototype.shiftRightUnsigned = function shiftRightUnsigned(numBits) {
2524 if (isLong(numBits))
2525 numBits = numBits.toInt();
2526 numBits &= 63;
2527 if (numBits === 0)
2528 return this;
2529 else {
2530 var high = this.high;
2531 if (numBits < 32) {
2532 var low = this.low;
2533 return fromBits((low >>> numBits) | (high << (32 - numBits)), high >>> numBits, this.unsigned);
2534 } else if (numBits === 32)
2535 return fromBits(high, 0, this.unsigned);
2536 else
2537 return fromBits(high >>> (numBits - 32), 0, this.unsigned);
2538 }
2539 };
2540
2541 /**
2542 * Returns this Long with bits logically shifted to the right by the given amount. This is an alias of {@link Long#shiftRightUnsigned}.
2543 * @function
2544 * @param {number|!Long} numBits Number of bits
2545 * @returns {!Long} Shifted Long
2546 */
2547 LongPrototype.shru = LongPrototype.shiftRightUnsigned;
2548
2549 /**
2550 * Converts this Long to signed.
2551 * @returns {!Long} Signed long
2552 */
2553 LongPrototype.toSigned = function toSigned() {
2554 if (!this.unsigned)
2555 return this;
2556 return fromBits(this.low, this.high, false);
2557 };
2558
2559 /**
2560 * Converts this Long to unsigned.
2561 * @returns {!Long} Unsigned long
2562 */
2563 LongPrototype.toUnsigned = function toUnsigned() {
2564 if (this.unsigned)
2565 return this;
2566 return fromBits(this.low, this.high, true);
2567 };
2568
2569 /**
2570 * Converts this Long to its byte representation.
2571 * @param {boolean=} le Whether little or big endian, defaults to big endian
2572 * @returns {!Array.<number>} Byte representation
2573 */
2574 LongPrototype.toBytes = function(le) {
2575 return le ? this.toBytesLE() : this.toBytesBE();
2576 };
2577
2578 /**
2579 * Converts this Long to its little endian byte representation.
2580 * @returns {!Array.<number>} Little endian byte representation
2581 */
2582 LongPrototype.toBytesLE = function() {
2583 var hi = this.high,
2584 lo = this.low;
2585 return [
2586 lo & 0xff,
2587 (lo >>> 8) & 0xff,
2588 (lo >>> 16) & 0xff,
2589 (lo >>> 24) & 0xff,
2590 hi & 0xff,
2591 (hi >>> 8) & 0xff,
2592 (hi >>> 16) & 0xff,
2593 (hi >>> 24) & 0xff
2594 ];
2595 };
2596
2597 /**
2598 * Converts this Long to its big endian byte representation.
2599 * @returns {!Array.<number>} Big endian byte representation
2600 */
2601 LongPrototype.toBytesBE = function() {
2602 var hi = this.high,
2603 lo = this.low;
2604 return [
2605 (hi >>> 24) & 0xff,
2606 (hi >>> 16) & 0xff,
2607 (hi >>> 8) & 0xff,
2608 hi & 0xff,
2609 (lo >>> 24) & 0xff,
2610 (lo >>> 16) & 0xff,
2611 (lo >>> 8) & 0xff,
2612 lo & 0xff
2613 ];
2614 };
2615
2616 return Long;
2617 });
2618 });
2619
2620 var bytebuffer = createCommonjsModule(function (module) {
2621 /*
2622 Copyright 2013-2014 Daniel Wirtz <dcode@dcode.io>
2623
2624 Licensed under the Apache License, Version 2.0 (the "License");
2625 you may not use this file except in compliance with the License.
2626 You may obtain a copy of the License at
2627
2628 http://www.apache.org/licenses/LICENSE-2.0
2629
2630 Unless required by applicable law or agreed to in writing, software
2631 distributed under the License is distributed on an "AS IS" BASIS,
2632 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2633 See the License for the specific language governing permissions and
2634 limitations under the License.
2635 */
2636
2637 /**
2638 * @license bytebuffer.js (c) 2015 Daniel Wirtz <dcode@dcode.io>
2639 * Backing buffer: ArrayBuffer, Accessor: Uint8Array
2640 * Released under the Apache License, Version 2.0
2641 * see: https://github.com/dcodeIO/bytebuffer.js for details
2642 */
2643 (function(global, factory) {
2644
2645 /* AMD */ if (typeof commonjsRequire === 'function' && 'object' === "object" && module && module["exports"])
2646 module['exports'] = (function() {
2647 var Long; try { Long = long_1; } catch (e) {}
2648 return factory(Long);
2649 })();
2650 /* Global */ else
2651 (global["dcodeIO"] = global["dcodeIO"] || {})["ByteBuffer"] = factory(global["dcodeIO"]["Long"]);
2652
2653 })(commonjsGlobal, function(Long) {
2654
2655 /**
2656 * Constructs a new ByteBuffer.
2657 * @class The swiss army knife for binary data in JavaScript.
2658 * @exports ByteBuffer
2659 * @constructor
2660 * @param {number=} capacity Initial capacity. Defaults to {@link ByteBuffer.DEFAULT_CAPACITY}.
2661 * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
2662 * {@link ByteBuffer.DEFAULT_ENDIAN}.
2663 * @param {boolean=} noAssert Whether to skip assertions of offsets and values. Defaults to
2664 * {@link ByteBuffer.DEFAULT_NOASSERT}.
2665 * @expose
2666 */
2667 var ByteBuffer = function(capacity, littleEndian, noAssert) {
2668 if (typeof capacity === 'undefined')
2669 capacity = ByteBuffer.DEFAULT_CAPACITY;
2670 if (typeof littleEndian === 'undefined')
2671 littleEndian = ByteBuffer.DEFAULT_ENDIAN;
2672 if (typeof noAssert === 'undefined')
2673 noAssert = ByteBuffer.DEFAULT_NOASSERT;
2674 if (!noAssert) {
2675 capacity = capacity | 0;
2676 if (capacity < 0)
2677 throw RangeError("Illegal capacity");
2678 littleEndian = !!littleEndian;
2679 noAssert = !!noAssert;
2680 }
2681
2682 /**
2683 * Backing ArrayBuffer.
2684 * @type {!ArrayBuffer}
2685 * @expose
2686 */
2687 this.buffer = capacity === 0 ? EMPTY_BUFFER : new ArrayBuffer(capacity);
2688
2689 /**
2690 * Uint8Array utilized to manipulate the backing buffer. Becomes `null` if the backing buffer has a capacity of `0`.
2691 * @type {?Uint8Array}
2692 * @expose
2693 */
2694 this.view = capacity === 0 ? null : new Uint8Array(this.buffer);
2695
2696 /**
2697 * Absolute read/write offset.
2698 * @type {number}
2699 * @expose
2700 * @see ByteBuffer#flip
2701 * @see ByteBuffer#clear
2702 */
2703 this.offset = 0;
2704
2705 /**
2706 * Marked offset.
2707 * @type {number}
2708 * @expose
2709 * @see ByteBuffer#mark
2710 * @see ByteBuffer#reset
2711 */
2712 this.markedOffset = -1;
2713
2714 /**
2715 * Absolute limit of the contained data. Set to the backing buffer's capacity upon allocation.
2716 * @type {number}
2717 * @expose
2718 * @see ByteBuffer#flip
2719 * @see ByteBuffer#clear
2720 */
2721 this.limit = capacity;
2722
2723 /**
2724 * Whether to use little endian byte order, defaults to `false` for big endian.
2725 * @type {boolean}
2726 * @expose
2727 */
2728 this.littleEndian = littleEndian;
2729
2730 /**
2731 * Whether to skip assertions of offsets and values, defaults to `false`.
2732 * @type {boolean}
2733 * @expose
2734 */
2735 this.noAssert = noAssert;
2736 };
2737
2738 /**
2739 * ByteBuffer version.
2740 * @type {string}
2741 * @const
2742 * @expose
2743 */
2744 ByteBuffer.VERSION = "5.0.1";
2745
2746 /**
2747 * Little endian constant that can be used instead of its boolean value. Evaluates to `true`.
2748 * @type {boolean}
2749 * @const
2750 * @expose
2751 */
2752 ByteBuffer.LITTLE_ENDIAN = true;
2753
2754 /**
2755 * Big endian constant that can be used instead of its boolean value. Evaluates to `false`.
2756 * @type {boolean}
2757 * @const
2758 * @expose
2759 */
2760 ByteBuffer.BIG_ENDIAN = false;
2761
2762 /**
2763 * Default initial capacity of `16`.
2764 * @type {number}
2765 * @expose
2766 */
2767 ByteBuffer.DEFAULT_CAPACITY = 16;
2768
2769 /**
2770 * Default endianess of `false` for big endian.
2771 * @type {boolean}
2772 * @expose
2773 */
2774 ByteBuffer.DEFAULT_ENDIAN = ByteBuffer.BIG_ENDIAN;
2775
2776 /**
2777 * Default no assertions flag of `false`.
2778 * @type {boolean}
2779 * @expose
2780 */
2781 ByteBuffer.DEFAULT_NOASSERT = false;
2782
2783 /**
2784 * A `Long` class for representing a 64-bit two's-complement integer value. May be `null` if Long.js has not been loaded
2785 * and int64 support is not available.
2786 * @type {?Long}
2787 * @const
2788 * @see https://github.com/dcodeIO/long.js
2789 * @expose
2790 */
2791 ByteBuffer.Long = Long || null;
2792
2793 /**
2794 * @alias ByteBuffer.prototype
2795 * @inner
2796 */
2797 var ByteBufferPrototype = ByteBuffer.prototype;
2798
2799 /**
2800 * An indicator used to reliably determine if an object is a ByteBuffer or not.
2801 * @type {boolean}
2802 * @const
2803 * @expose
2804 * @private
2805 */
2806 ByteBufferPrototype.__isByteBuffer__;
2807
2808 Object.defineProperty(ByteBufferPrototype, "__isByteBuffer__", {
2809 value: true,
2810 enumerable: false,
2811 configurable: false
2812 });
2813
2814 // helpers
2815
2816 /**
2817 * @type {!ArrayBuffer}
2818 * @inner
2819 */
2820 var EMPTY_BUFFER = new ArrayBuffer(0);
2821
2822 /**
2823 * String.fromCharCode reference for compile-time renaming.
2824 * @type {function(...number):string}
2825 * @inner
2826 */
2827 var stringFromCharCode = String.fromCharCode;
2828
2829 /**
2830 * Creates a source function for a string.
2831 * @param {string} s String to read from
2832 * @returns {function():number|null} Source function returning the next char code respectively `null` if there are
2833 * no more characters left.
2834 * @throws {TypeError} If the argument is invalid
2835 * @inner
2836 */
2837 function stringSource(s) {
2838 var i=0; return function() {
2839 return i < s.length ? s.charCodeAt(i++) : null;
2840 };
2841 }
2842
2843 /**
2844 * Creates a destination function for a string.
2845 * @returns {function(number=):undefined|string} Destination function successively called with the next char code.
2846 * Returns the final string when called without arguments.
2847 * @inner
2848 */
2849 function stringDestination() {
2850 var cs = [], ps = []; return function() {
2851 if (arguments.length === 0)
2852 return ps.join('')+stringFromCharCode.apply(String, cs);
2853 if (cs.length + arguments.length > 1024)
2854 ps.push(stringFromCharCode.apply(String, cs)),
2855 cs.length = 0;
2856 Array.prototype.push.apply(cs, arguments);
2857 };
2858 }
2859
2860 /**
2861 * Gets the accessor type.
2862 * @returns {Function} `Buffer` under node.js, `Uint8Array` respectively `DataView` in the browser (classes)
2863 * @expose
2864 */
2865 ByteBuffer.accessor = function() {
2866 return Uint8Array;
2867 };
2868 /**
2869 * Allocates a new ByteBuffer backed by a buffer of the specified capacity.
2870 * @param {number=} capacity Initial capacity. Defaults to {@link ByteBuffer.DEFAULT_CAPACITY}.
2871 * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
2872 * {@link ByteBuffer.DEFAULT_ENDIAN}.
2873 * @param {boolean=} noAssert Whether to skip assertions of offsets and values. Defaults to
2874 * {@link ByteBuffer.DEFAULT_NOASSERT}.
2875 * @returns {!ByteBuffer}
2876 * @expose
2877 */
2878 ByteBuffer.allocate = function(capacity, littleEndian, noAssert) {
2879 return new ByteBuffer(capacity, littleEndian, noAssert);
2880 };
2881
2882 /**
2883 * Concatenates multiple ByteBuffers into one.
2884 * @param {!Array.<!ByteBuffer|!ArrayBuffer|!Uint8Array|string>} buffers Buffers to concatenate
2885 * @param {(string|boolean)=} encoding String encoding if `buffers` contains a string ("base64", "hex", "binary",
2886 * defaults to "utf8")
2887 * @param {boolean=} littleEndian Whether to use little or big endian byte order for the resulting ByteBuffer. Defaults
2888 * to {@link ByteBuffer.DEFAULT_ENDIAN}.
2889 * @param {boolean=} noAssert Whether to skip assertions of offsets and values for the resulting ByteBuffer. Defaults to
2890 * {@link ByteBuffer.DEFAULT_NOASSERT}.
2891 * @returns {!ByteBuffer} Concatenated ByteBuffer
2892 * @expose
2893 */
2894 ByteBuffer.concat = function(buffers, encoding, littleEndian, noAssert) {
2895 if (typeof encoding === 'boolean' || typeof encoding !== 'string') {
2896 noAssert = littleEndian;
2897 littleEndian = encoding;
2898 encoding = undefined;
2899 }
2900 var capacity = 0;
2901 for (var i=0, k=buffers.length, length; i<k; ++i) {
2902 if (!ByteBuffer.isByteBuffer(buffers[i]))
2903 buffers[i] = ByteBuffer.wrap(buffers[i], encoding);
2904 length = buffers[i].limit - buffers[i].offset;
2905 if (length > 0) capacity += length;
2906 }
2907 if (capacity === 0)
2908 return new ByteBuffer(0, littleEndian, noAssert);
2909 var bb = new ByteBuffer(capacity, littleEndian, noAssert),
2910 bi;
2911 i=0; while (i<k) {
2912 bi = buffers[i++];
2913 length = bi.limit - bi.offset;
2914 if (length <= 0) continue;
2915 bb.view.set(bi.view.subarray(bi.offset, bi.limit), bb.offset);
2916 bb.offset += length;
2917 }
2918 bb.limit = bb.offset;
2919 bb.offset = 0;
2920 return bb;
2921 };
2922
2923 /**
2924 * Tests if the specified type is a ByteBuffer.
2925 * @param {*} bb ByteBuffer to test
2926 * @returns {boolean} `true` if it is a ByteBuffer, otherwise `false`
2927 * @expose
2928 */
2929 ByteBuffer.isByteBuffer = function(bb) {
2930 return (bb && bb["__isByteBuffer__"]) === true;
2931 };
2932 /**
2933 * Gets the backing buffer type.
2934 * @returns {Function} `Buffer` under node.js, `ArrayBuffer` in the browser (classes)
2935 * @expose
2936 */
2937 ByteBuffer.type = function() {
2938 return ArrayBuffer;
2939 };
2940 /**
2941 * Wraps a buffer or a string. Sets the allocated ByteBuffer's {@link ByteBuffer#offset} to `0` and its
2942 * {@link ByteBuffer#limit} to the length of the wrapped data.
2943 * @param {!ByteBuffer|!ArrayBuffer|!Uint8Array|string|!Array.<number>} buffer Anything that can be wrapped
2944 * @param {(string|boolean)=} encoding String encoding if `buffer` is a string ("base64", "hex", "binary", defaults to
2945 * "utf8")
2946 * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
2947 * {@link ByteBuffer.DEFAULT_ENDIAN}.
2948 * @param {boolean=} noAssert Whether to skip assertions of offsets and values. Defaults to
2949 * {@link ByteBuffer.DEFAULT_NOASSERT}.
2950 * @returns {!ByteBuffer} A ByteBuffer wrapping `buffer`
2951 * @expose
2952 */
2953 ByteBuffer.wrap = function(buffer, encoding, littleEndian, noAssert) {
2954 if (typeof encoding !== 'string') {
2955 noAssert = littleEndian;
2956 littleEndian = encoding;
2957 encoding = undefined;
2958 }
2959 if (typeof buffer === 'string') {
2960 if (typeof encoding === 'undefined')
2961 encoding = "utf8";
2962 switch (encoding) {
2963 case "base64":
2964 return ByteBuffer.fromBase64(buffer, littleEndian);
2965 case "hex":
2966 return ByteBuffer.fromHex(buffer, littleEndian);
2967 case "binary":
2968 return ByteBuffer.fromBinary(buffer, littleEndian);
2969 case "utf8":
2970 return ByteBuffer.fromUTF8(buffer, littleEndian);
2971 case "debug":
2972 return ByteBuffer.fromDebug(buffer, littleEndian);
2973 default:
2974 throw Error("Unsupported encoding: "+encoding);
2975 }
2976 }
2977 if (buffer === null || typeof buffer !== 'object')
2978 throw TypeError("Illegal buffer");
2979 var bb;
2980 if (ByteBuffer.isByteBuffer(buffer)) {
2981 bb = ByteBufferPrototype.clone.call(buffer);
2982 bb.markedOffset = -1;
2983 return bb;
2984 }
2985 if (buffer instanceof Uint8Array) { // Extract ArrayBuffer from Uint8Array
2986 bb = new ByteBuffer(0, littleEndian, noAssert);
2987 if (buffer.length > 0) { // Avoid references to more than one EMPTY_BUFFER
2988 bb.buffer = buffer.buffer;
2989 bb.offset = buffer.byteOffset;
2990 bb.limit = buffer.byteOffset + buffer.byteLength;
2991 bb.view = new Uint8Array(buffer.buffer);
2992 }
2993 } else if (buffer instanceof ArrayBuffer) { // Reuse ArrayBuffer
2994 bb = new ByteBuffer(0, littleEndian, noAssert);
2995 if (buffer.byteLength > 0) {
2996 bb.buffer = buffer;
2997 bb.offset = 0;
2998 bb.limit = buffer.byteLength;
2999 bb.view = buffer.byteLength > 0 ? new Uint8Array(buffer) : null;
3000 }
3001 } else if (Object.prototype.toString.call(buffer) === "[object Array]") { // Create from octets
3002 bb = new ByteBuffer(buffer.length, littleEndian, noAssert);
3003 bb.limit = buffer.length;
3004 for (var i=0; i<buffer.length; ++i)
3005 bb.view[i] = buffer[i];
3006 } else
3007 throw TypeError("Illegal buffer"); // Otherwise fail
3008 return bb;
3009 };
3010
3011 /**
3012 * Writes the array as a bitset.
3013 * @param {Array<boolean>} value Array of booleans to write
3014 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `length` if omitted.
3015 * @returns {!ByteBuffer}
3016 * @expose
3017 */
3018 ByteBufferPrototype.writeBitSet = function(value, offset) {
3019 var relative = typeof offset === 'undefined';
3020 if (relative) offset = this.offset;
3021 if (!this.noAssert) {
3022 if (!(value instanceof Array))
3023 throw TypeError("Illegal BitSet: Not an array");
3024 if (typeof offset !== 'number' || offset % 1 !== 0)
3025 throw TypeError("Illegal offset: "+offset+" (not an integer)");
3026 offset >>>= 0;
3027 if (offset < 0 || offset + 0 > this.buffer.byteLength)
3028 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
3029 }
3030
3031 var start = offset,
3032 bits = value.length,
3033 bytes = (bits >> 3),
3034 bit = 0,
3035 k;
3036
3037 offset += this.writeVarint32(bits,offset);
3038
3039 while(bytes--) {
3040 k = (!!value[bit++] & 1) |
3041 ((!!value[bit++] & 1) << 1) |
3042 ((!!value[bit++] & 1) << 2) |
3043 ((!!value[bit++] & 1) << 3) |
3044 ((!!value[bit++] & 1) << 4) |
3045 ((!!value[bit++] & 1) << 5) |
3046 ((!!value[bit++] & 1) << 6) |
3047 ((!!value[bit++] & 1) << 7);
3048 this.writeByte(k,offset++);
3049 }
3050
3051 if(bit < bits) {
3052 var m = 0; k = 0;
3053 while(bit < bits) k = k | ((!!value[bit++] & 1) << (m++));
3054 this.writeByte(k,offset++);
3055 }
3056
3057 if (relative) {
3058 this.offset = offset;
3059 return this;
3060 }
3061 return offset - start;
3062 };
3063
3064 /**
3065 * Reads a BitSet as an array of booleans.
3066 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `length` if omitted.
3067 * @returns {Array<boolean>
3068 * @expose
3069 */
3070 ByteBufferPrototype.readBitSet = function(offset) {
3071 var relative = typeof offset === 'undefined';
3072 if (relative) offset = this.offset;
3073
3074 var ret = this.readVarint32(offset),
3075 bits = ret.value,
3076 bytes = (bits >> 3),
3077 bit = 0,
3078 value = [],
3079 k;
3080
3081 offset += ret.length;
3082
3083 while(bytes--) {
3084 k = this.readByte(offset++);
3085 value[bit++] = !!(k & 0x01);
3086 value[bit++] = !!(k & 0x02);
3087 value[bit++] = !!(k & 0x04);
3088 value[bit++] = !!(k & 0x08);
3089 value[bit++] = !!(k & 0x10);
3090 value[bit++] = !!(k & 0x20);
3091 value[bit++] = !!(k & 0x40);
3092 value[bit++] = !!(k & 0x80);
3093 }
3094
3095 if(bit < bits) {
3096 var m = 0;
3097 k = this.readByte(offset++);
3098 while(bit < bits) value[bit++] = !!((k >> (m++)) & 1);
3099 }
3100
3101 if (relative) {
3102 this.offset = offset;
3103 }
3104 return value;
3105 };
3106 /**
3107 * Reads the specified number of bytes.
3108 * @param {number} length Number of bytes to read
3109 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `length` if omitted.
3110 * @returns {!ByteBuffer}
3111 * @expose
3112 */
3113 ByteBufferPrototype.readBytes = function(length, offset) {
3114 var relative = typeof offset === 'undefined';
3115 if (relative) offset = this.offset;
3116 if (!this.noAssert) {
3117 if (typeof offset !== 'number' || offset % 1 !== 0)
3118 throw TypeError("Illegal offset: "+offset+" (not an integer)");
3119 offset >>>= 0;
3120 if (offset < 0 || offset + length > this.buffer.byteLength)
3121 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+length+") <= "+this.buffer.byteLength);
3122 }
3123 var slice = this.slice(offset, offset + length);
3124 if (relative) this.offset += length;
3125 return slice;
3126 };
3127
3128 /**
3129 * Writes a payload of bytes. This is an alias of {@link ByteBuffer#append}.
3130 * @function
3131 * @param {!ByteBuffer|!ArrayBuffer|!Uint8Array|string} source Data to write. If `source` is a ByteBuffer, its offsets
3132 * will be modified according to the performed read operation.
3133 * @param {(string|number)=} encoding Encoding if `data` is a string ("base64", "hex", "binary", defaults to "utf8")
3134 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
3135 * written if omitted.
3136 * @returns {!ByteBuffer} this
3137 * @expose
3138 */
3139 ByteBufferPrototype.writeBytes = ByteBufferPrototype.append;
3140
3141 // types/ints/int8
3142
3143 /**
3144 * Writes an 8bit signed integer.
3145 * @param {number} value Value to write
3146 * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `1` if omitted.
3147 * @returns {!ByteBuffer} this
3148 * @expose
3149 */
3150 ByteBufferPrototype.writeInt8 = function(value, offset) {
3151 var relative = typeof offset === 'undefined';
3152 if (relative) offset = this.offset;
3153 if (!this.noAssert) {
3154 if (typeof value !== 'number' || value % 1 !== 0)
3155 throw TypeError("Illegal value: "+value+" (not an integer)");
3156 value |= 0;
3157 if (typeof offset !== 'number' || offset % 1 !== 0)
3158 throw TypeError("Illegal offset: "+offset+" (not an integer)");
3159 offset >>>= 0;
3160 if (offset < 0 || offset + 0 > this.buffer.byteLength)
3161 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
3162 }
3163 offset += 1;
3164 var capacity0 = this.buffer.byteLength;
3165 if (offset > capacity0)
3166 this.resize((capacity0 *= 2) > offset ? capacity0 : offset);
3167 offset -= 1;
3168 this.view[offset] = value;
3169 if (relative) this.offset += 1;
3170 return this;
3171 };
3172
3173 /**
3174 * Writes an 8bit signed integer. This is an alias of {@link ByteBuffer#writeInt8}.
3175 * @function
3176 * @param {number} value Value to write
3177 * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `1` if omitted.
3178 * @returns {!ByteBuffer} this
3179 * @expose
3180 */
3181 ByteBufferPrototype.writeByte = ByteBufferPrototype.writeInt8;
3182
3183 /**
3184 * Reads an 8bit signed integer.
3185 * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `1` if omitted.
3186 * @returns {number} Value read
3187 * @expose
3188 */
3189 ByteBufferPrototype.readInt8 = function(offset) {
3190 var relative = typeof offset === 'undefined';
3191 if (relative) offset = this.offset;
3192 if (!this.noAssert) {
3193 if (typeof offset !== 'number' || offset % 1 !== 0)
3194 throw TypeError("Illegal offset: "+offset+" (not an integer)");
3195 offset >>>= 0;
3196 if (offset < 0 || offset + 1 > this.buffer.byteLength)
3197 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+1+") <= "+this.buffer.byteLength);
3198 }
3199 var value = this.view[offset];
3200 if ((value & 0x80) === 0x80) value = -(0xFF - value + 1); // Cast to signed
3201 if (relative) this.offset += 1;
3202 return value;
3203 };
3204
3205 /**
3206 * Reads an 8bit signed integer. This is an alias of {@link ByteBuffer#readInt8}.
3207 * @function
3208 * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `1` if omitted.
3209 * @returns {number} Value read
3210 * @expose
3211 */
3212 ByteBufferPrototype.readByte = ByteBufferPrototype.readInt8;
3213
3214 /**
3215 * Writes an 8bit unsigned integer.
3216 * @param {number} value Value to write
3217 * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `1` if omitted.
3218 * @returns {!ByteBuffer} this
3219 * @expose
3220 */
3221 ByteBufferPrototype.writeUint8 = function(value, offset) {
3222 var relative = typeof offset === 'undefined';
3223 if (relative) offset = this.offset;
3224 if (!this.noAssert) {
3225 if (typeof value !== 'number' || value % 1 !== 0)
3226 throw TypeError("Illegal value: "+value+" (not an integer)");
3227 value >>>= 0;
3228 if (typeof offset !== 'number' || offset % 1 !== 0)
3229 throw TypeError("Illegal offset: "+offset+" (not an integer)");
3230 offset >>>= 0;
3231 if (offset < 0 || offset + 0 > this.buffer.byteLength)
3232 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
3233 }
3234 offset += 1;
3235 var capacity1 = this.buffer.byteLength;
3236 if (offset > capacity1)
3237 this.resize((capacity1 *= 2) > offset ? capacity1 : offset);
3238 offset -= 1;
3239 this.view[offset] = value;
3240 if (relative) this.offset += 1;
3241 return this;
3242 };
3243
3244 /**
3245 * Writes an 8bit unsigned integer. This is an alias of {@link ByteBuffer#writeUint8}.
3246 * @function
3247 * @param {number} value Value to write
3248 * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `1` if omitted.
3249 * @returns {!ByteBuffer} this
3250 * @expose
3251 */
3252 ByteBufferPrototype.writeUInt8 = ByteBufferPrototype.writeUint8;
3253
3254 /**
3255 * Reads an 8bit unsigned integer.
3256 * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `1` if omitted.
3257 * @returns {number} Value read
3258 * @expose
3259 */
3260 ByteBufferPrototype.readUint8 = function(offset) {
3261 var relative = typeof offset === 'undefined';
3262 if (relative) offset = this.offset;
3263 if (!this.noAssert) {
3264 if (typeof offset !== 'number' || offset % 1 !== 0)
3265 throw TypeError("Illegal offset: "+offset+" (not an integer)");
3266 offset >>>= 0;
3267 if (offset < 0 || offset + 1 > this.buffer.byteLength)
3268 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+1+") <= "+this.buffer.byteLength);
3269 }
3270 var value = this.view[offset];
3271 if (relative) this.offset += 1;
3272 return value;
3273 };
3274
3275 /**
3276 * Reads an 8bit unsigned integer. This is an alias of {@link ByteBuffer#readUint8}.
3277 * @function
3278 * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `1` if omitted.
3279 * @returns {number} Value read
3280 * @expose
3281 */
3282 ByteBufferPrototype.readUInt8 = ByteBufferPrototype.readUint8;
3283
3284 // types/ints/int16
3285
3286 /**
3287 * Writes a 16bit signed integer.
3288 * @param {number} value Value to write
3289 * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `2` if omitted.
3290 * @throws {TypeError} If `offset` or `value` is not a valid number
3291 * @throws {RangeError} If `offset` is out of bounds
3292 * @expose
3293 */
3294 ByteBufferPrototype.writeInt16 = function(value, offset) {
3295 var relative = typeof offset === 'undefined';
3296 if (relative) offset = this.offset;
3297 if (!this.noAssert) {
3298 if (typeof value !== 'number' || value % 1 !== 0)
3299 throw TypeError("Illegal value: "+value+" (not an integer)");
3300 value |= 0;
3301 if (typeof offset !== 'number' || offset % 1 !== 0)
3302 throw TypeError("Illegal offset: "+offset+" (not an integer)");
3303 offset >>>= 0;
3304 if (offset < 0 || offset + 0 > this.buffer.byteLength)
3305 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
3306 }
3307 offset += 2;
3308 var capacity2 = this.buffer.byteLength;
3309 if (offset > capacity2)
3310 this.resize((capacity2 *= 2) > offset ? capacity2 : offset);
3311 offset -= 2;
3312 if (this.littleEndian) {
3313 this.view[offset+1] = (value & 0xFF00) >>> 8;
3314 this.view[offset ] = value & 0x00FF;
3315 } else {
3316 this.view[offset] = (value & 0xFF00) >>> 8;
3317 this.view[offset+1] = value & 0x00FF;
3318 }
3319 if (relative) this.offset += 2;
3320 return this;
3321 };
3322
3323 /**
3324 * Writes a 16bit signed integer. This is an alias of {@link ByteBuffer#writeInt16}.
3325 * @function
3326 * @param {number} value Value to write
3327 * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `2` if omitted.
3328 * @throws {TypeError} If `offset` or `value` is not a valid number
3329 * @throws {RangeError} If `offset` is out of bounds
3330 * @expose
3331 */
3332 ByteBufferPrototype.writeShort = ByteBufferPrototype.writeInt16;
3333
3334 /**
3335 * Reads a 16bit signed integer.
3336 * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `2` if omitted.
3337 * @returns {number} Value read
3338 * @throws {TypeError} If `offset` is not a valid number
3339 * @throws {RangeError} If `offset` is out of bounds
3340 * @expose
3341 */
3342 ByteBufferPrototype.readInt16 = function(offset) {
3343 var relative = typeof offset === 'undefined';
3344 if (relative) offset = this.offset;
3345 if (!this.noAssert) {
3346 if (typeof offset !== 'number' || offset % 1 !== 0)
3347 throw TypeError("Illegal offset: "+offset+" (not an integer)");
3348 offset >>>= 0;
3349 if (offset < 0 || offset + 2 > this.buffer.byteLength)
3350 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+2+") <= "+this.buffer.byteLength);
3351 }
3352 var value = 0;
3353 if (this.littleEndian) {
3354 value = this.view[offset ];
3355 value |= this.view[offset+1] << 8;
3356 } else {
3357 value = this.view[offset ] << 8;
3358 value |= this.view[offset+1];
3359 }
3360 if ((value & 0x8000) === 0x8000) value = -(0xFFFF - value + 1); // Cast to signed
3361 if (relative) this.offset += 2;
3362 return value;
3363 };
3364
3365 /**
3366 * Reads a 16bit signed integer. This is an alias of {@link ByteBuffer#readInt16}.
3367 * @function
3368 * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `2` if omitted.
3369 * @returns {number} Value read
3370 * @throws {TypeError} If `offset` is not a valid number
3371 * @throws {RangeError} If `offset` is out of bounds
3372 * @expose
3373 */
3374 ByteBufferPrototype.readShort = ByteBufferPrototype.readInt16;
3375
3376 /**
3377 * Writes a 16bit unsigned integer.
3378 * @param {number} value Value to write
3379 * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `2` if omitted.
3380 * @throws {TypeError} If `offset` or `value` is not a valid number
3381 * @throws {RangeError} If `offset` is out of bounds
3382 * @expose
3383 */
3384 ByteBufferPrototype.writeUint16 = function(value, offset) {
3385 var relative = typeof offset === 'undefined';
3386 if (relative) offset = this.offset;
3387 if (!this.noAssert) {
3388 if (typeof value !== 'number' || value % 1 !== 0)
3389 throw TypeError("Illegal value: "+value+" (not an integer)");
3390 value >>>= 0;
3391 if (typeof offset !== 'number' || offset % 1 !== 0)
3392 throw TypeError("Illegal offset: "+offset+" (not an integer)");
3393 offset >>>= 0;
3394 if (offset < 0 || offset + 0 > this.buffer.byteLength)
3395 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
3396 }
3397 offset += 2;
3398 var capacity3 = this.buffer.byteLength;
3399 if (offset > capacity3)
3400 this.resize((capacity3 *= 2) > offset ? capacity3 : offset);
3401 offset -= 2;
3402 if (this.littleEndian) {
3403 this.view[offset+1] = (value & 0xFF00) >>> 8;
3404 this.view[offset ] = value & 0x00FF;
3405 } else {
3406 this.view[offset] = (value & 0xFF00) >>> 8;
3407 this.view[offset+1] = value & 0x00FF;
3408 }
3409 if (relative) this.offset += 2;
3410 return this;
3411 };
3412
3413 /**
3414 * Writes a 16bit unsigned integer. This is an alias of {@link ByteBuffer#writeUint16}.
3415 * @function
3416 * @param {number} value Value to write
3417 * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `2` if omitted.
3418 * @throws {TypeError} If `offset` or `value` is not a valid number
3419 * @throws {RangeError} If `offset` is out of bounds
3420 * @expose
3421 */
3422 ByteBufferPrototype.writeUInt16 = ByteBufferPrototype.writeUint16;
3423
3424 /**
3425 * Reads a 16bit unsigned integer.
3426 * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `2` if omitted.
3427 * @returns {number} Value read
3428 * @throws {TypeError} If `offset` is not a valid number
3429 * @throws {RangeError} If `offset` is out of bounds
3430 * @expose
3431 */
3432 ByteBufferPrototype.readUint16 = function(offset) {
3433 var relative = typeof offset === 'undefined';
3434 if (relative) offset = this.offset;
3435 if (!this.noAssert) {
3436 if (typeof offset !== 'number' || offset % 1 !== 0)
3437 throw TypeError("Illegal offset: "+offset+" (not an integer)");
3438 offset >>>= 0;
3439 if (offset < 0 || offset + 2 > this.buffer.byteLength)
3440 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+2+") <= "+this.buffer.byteLength);
3441 }
3442 var value = 0;
3443 if (this.littleEndian) {
3444 value = this.view[offset ];
3445 value |= this.view[offset+1] << 8;
3446 } else {
3447 value = this.view[offset ] << 8;
3448 value |= this.view[offset+1];
3449 }
3450 if (relative) this.offset += 2;
3451 return value;
3452 };
3453
3454 /**
3455 * Reads a 16bit unsigned integer. This is an alias of {@link ByteBuffer#readUint16}.
3456 * @function
3457 * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `2` if omitted.
3458 * @returns {number} Value read
3459 * @throws {TypeError} If `offset` is not a valid number
3460 * @throws {RangeError} If `offset` is out of bounds
3461 * @expose
3462 */
3463 ByteBufferPrototype.readUInt16 = ByteBufferPrototype.readUint16;
3464
3465 // types/ints/int32
3466
3467 /**
3468 * Writes a 32bit signed integer.
3469 * @param {number} value Value to write
3470 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
3471 * @expose
3472 */
3473 ByteBufferPrototype.writeInt32 = function(value, offset) {
3474 var relative = typeof offset === 'undefined';
3475 if (relative) offset = this.offset;
3476 if (!this.noAssert) {
3477 if (typeof value !== 'number' || value % 1 !== 0)
3478 throw TypeError("Illegal value: "+value+" (not an integer)");
3479 value |= 0;
3480 if (typeof offset !== 'number' || offset % 1 !== 0)
3481 throw TypeError("Illegal offset: "+offset+" (not an integer)");
3482 offset >>>= 0;
3483 if (offset < 0 || offset + 0 > this.buffer.byteLength)
3484 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
3485 }
3486 offset += 4;
3487 var capacity4 = this.buffer.byteLength;
3488 if (offset > capacity4)
3489 this.resize((capacity4 *= 2) > offset ? capacity4 : offset);
3490 offset -= 4;
3491 if (this.littleEndian) {
3492 this.view[offset+3] = (value >>> 24) & 0xFF;
3493 this.view[offset+2] = (value >>> 16) & 0xFF;
3494 this.view[offset+1] = (value >>> 8) & 0xFF;
3495 this.view[offset ] = value & 0xFF;
3496 } else {
3497 this.view[offset ] = (value >>> 24) & 0xFF;
3498 this.view[offset+1] = (value >>> 16) & 0xFF;
3499 this.view[offset+2] = (value >>> 8) & 0xFF;
3500 this.view[offset+3] = value & 0xFF;
3501 }
3502 if (relative) this.offset += 4;
3503 return this;
3504 };
3505
3506 /**
3507 * Writes a 32bit signed integer. This is an alias of {@link ByteBuffer#writeInt32}.
3508 * @param {number} value Value to write
3509 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
3510 * @expose
3511 */
3512 ByteBufferPrototype.writeInt = ByteBufferPrototype.writeInt32;
3513
3514 /**
3515 * Reads a 32bit signed integer.
3516 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
3517 * @returns {number} Value read
3518 * @expose
3519 */
3520 ByteBufferPrototype.readInt32 = function(offset) {
3521 var relative = typeof offset === 'undefined';
3522 if (relative) offset = this.offset;
3523 if (!this.noAssert) {
3524 if (typeof offset !== 'number' || offset % 1 !== 0)
3525 throw TypeError("Illegal offset: "+offset+" (not an integer)");
3526 offset >>>= 0;
3527 if (offset < 0 || offset + 4 > this.buffer.byteLength)
3528 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+4+") <= "+this.buffer.byteLength);
3529 }
3530 var value = 0;
3531 if (this.littleEndian) {
3532 value = this.view[offset+2] << 16;
3533 value |= this.view[offset+1] << 8;
3534 value |= this.view[offset ];
3535 value += this.view[offset+3] << 24 >>> 0;
3536 } else {
3537 value = this.view[offset+1] << 16;
3538 value |= this.view[offset+2] << 8;
3539 value |= this.view[offset+3];
3540 value += this.view[offset ] << 24 >>> 0;
3541 }
3542 value |= 0; // Cast to signed
3543 if (relative) this.offset += 4;
3544 return value;
3545 };
3546
3547 /**
3548 * Reads a 32bit signed integer. This is an alias of {@link ByteBuffer#readInt32}.
3549 * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `4` if omitted.
3550 * @returns {number} Value read
3551 * @expose
3552 */
3553 ByteBufferPrototype.readInt = ByteBufferPrototype.readInt32;
3554
3555 /**
3556 * Writes a 32bit unsigned integer.
3557 * @param {number} value Value to write
3558 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
3559 * @expose
3560 */
3561 ByteBufferPrototype.writeUint32 = function(value, offset) {
3562 var relative = typeof offset === 'undefined';
3563 if (relative) offset = this.offset;
3564 if (!this.noAssert) {
3565 if (typeof value !== 'number' || value % 1 !== 0)
3566 throw TypeError("Illegal value: "+value+" (not an integer)");
3567 value >>>= 0;
3568 if (typeof offset !== 'number' || offset % 1 !== 0)
3569 throw TypeError("Illegal offset: "+offset+" (not an integer)");
3570 offset >>>= 0;
3571 if (offset < 0 || offset + 0 > this.buffer.byteLength)
3572 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
3573 }
3574 offset += 4;
3575 var capacity5 = this.buffer.byteLength;
3576 if (offset > capacity5)
3577 this.resize((capacity5 *= 2) > offset ? capacity5 : offset);
3578 offset -= 4;
3579 if (this.littleEndian) {
3580 this.view[offset+3] = (value >>> 24) & 0xFF;
3581 this.view[offset+2] = (value >>> 16) & 0xFF;
3582 this.view[offset+1] = (value >>> 8) & 0xFF;
3583 this.view[offset ] = value & 0xFF;
3584 } else {
3585 this.view[offset ] = (value >>> 24) & 0xFF;
3586 this.view[offset+1] = (value >>> 16) & 0xFF;
3587 this.view[offset+2] = (value >>> 8) & 0xFF;
3588 this.view[offset+3] = value & 0xFF;
3589 }
3590 if (relative) this.offset += 4;
3591 return this;
3592 };
3593
3594 /**
3595 * Writes a 32bit unsigned integer. This is an alias of {@link ByteBuffer#writeUint32}.
3596 * @function
3597 * @param {number} value Value to write
3598 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
3599 * @expose
3600 */
3601 ByteBufferPrototype.writeUInt32 = ByteBufferPrototype.writeUint32;
3602
3603 /**
3604 * Reads a 32bit unsigned integer.
3605 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
3606 * @returns {number} Value read
3607 * @expose
3608 */
3609 ByteBufferPrototype.readUint32 = function(offset) {
3610 var relative = typeof offset === 'undefined';
3611 if (relative) offset = this.offset;
3612 if (!this.noAssert) {
3613 if (typeof offset !== 'number' || offset % 1 !== 0)
3614 throw TypeError("Illegal offset: "+offset+" (not an integer)");
3615 offset >>>= 0;
3616 if (offset < 0 || offset + 4 > this.buffer.byteLength)
3617 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+4+") <= "+this.buffer.byteLength);
3618 }
3619 var value = 0;
3620 if (this.littleEndian) {
3621 value = this.view[offset+2] << 16;
3622 value |= this.view[offset+1] << 8;
3623 value |= this.view[offset ];
3624 value += this.view[offset+3] << 24 >>> 0;
3625 } else {
3626 value = this.view[offset+1] << 16;
3627 value |= this.view[offset+2] << 8;
3628 value |= this.view[offset+3];
3629 value += this.view[offset ] << 24 >>> 0;
3630 }
3631 if (relative) this.offset += 4;
3632 return value;
3633 };
3634
3635 /**
3636 * Reads a 32bit unsigned integer. This is an alias of {@link ByteBuffer#readUint32}.
3637 * @function
3638 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
3639 * @returns {number} Value read
3640 * @expose
3641 */
3642 ByteBufferPrototype.readUInt32 = ByteBufferPrototype.readUint32;
3643
3644 // types/ints/int64
3645
3646 if (Long) {
3647
3648 /**
3649 * Writes a 64bit signed integer.
3650 * @param {number|!Long} value Value to write
3651 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
3652 * @returns {!ByteBuffer} this
3653 * @expose
3654 */
3655 ByteBufferPrototype.writeInt64 = function(value, offset) {
3656 var relative = typeof offset === 'undefined';
3657 if (relative) offset = this.offset;
3658 if (!this.noAssert) {
3659 if (typeof value === 'number')
3660 value = Long.fromNumber(value);
3661 else if (typeof value === 'string')
3662 value = Long.fromString(value);
3663 else if (!(value && value instanceof Long))
3664 throw TypeError("Illegal value: "+value+" (not an integer or Long)");
3665 if (typeof offset !== 'number' || offset % 1 !== 0)
3666 throw TypeError("Illegal offset: "+offset+" (not an integer)");
3667 offset >>>= 0;
3668 if (offset < 0 || offset + 0 > this.buffer.byteLength)
3669 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
3670 }
3671 if (typeof value === 'number')
3672 value = Long.fromNumber(value);
3673 else if (typeof value === 'string')
3674 value = Long.fromString(value);
3675 offset += 8;
3676 var capacity6 = this.buffer.byteLength;
3677 if (offset > capacity6)
3678 this.resize((capacity6 *= 2) > offset ? capacity6 : offset);
3679 offset -= 8;
3680 var lo = value.low,
3681 hi = value.high;
3682 if (this.littleEndian) {
3683 this.view[offset+3] = (lo >>> 24) & 0xFF;
3684 this.view[offset+2] = (lo >>> 16) & 0xFF;
3685 this.view[offset+1] = (lo >>> 8) & 0xFF;
3686 this.view[offset ] = lo & 0xFF;
3687 offset += 4;
3688 this.view[offset+3] = (hi >>> 24) & 0xFF;
3689 this.view[offset+2] = (hi >>> 16) & 0xFF;
3690 this.view[offset+1] = (hi >>> 8) & 0xFF;
3691 this.view[offset ] = hi & 0xFF;
3692 } else {
3693 this.view[offset ] = (hi >>> 24) & 0xFF;
3694 this.view[offset+1] = (hi >>> 16) & 0xFF;
3695 this.view[offset+2] = (hi >>> 8) & 0xFF;
3696 this.view[offset+3] = hi & 0xFF;
3697 offset += 4;
3698 this.view[offset ] = (lo >>> 24) & 0xFF;
3699 this.view[offset+1] = (lo >>> 16) & 0xFF;
3700 this.view[offset+2] = (lo >>> 8) & 0xFF;
3701 this.view[offset+3] = lo & 0xFF;
3702 }
3703 if (relative) this.offset += 8;
3704 return this;
3705 };
3706
3707 /**
3708 * Writes a 64bit signed integer. This is an alias of {@link ByteBuffer#writeInt64}.
3709 * @param {number|!Long} value Value to write
3710 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
3711 * @returns {!ByteBuffer} this
3712 * @expose
3713 */
3714 ByteBufferPrototype.writeLong = ByteBufferPrototype.writeInt64;
3715
3716 /**
3717 * Reads a 64bit signed integer.
3718 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
3719 * @returns {!Long}
3720 * @expose
3721 */
3722 ByteBufferPrototype.readInt64 = function(offset) {
3723 var relative = typeof offset === 'undefined';
3724 if (relative) offset = this.offset;
3725 if (!this.noAssert) {
3726 if (typeof offset !== 'number' || offset % 1 !== 0)
3727 throw TypeError("Illegal offset: "+offset+" (not an integer)");
3728 offset >>>= 0;
3729 if (offset < 0 || offset + 8 > this.buffer.byteLength)
3730 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+8+") <= "+this.buffer.byteLength);
3731 }
3732 var lo = 0,
3733 hi = 0;
3734 if (this.littleEndian) {
3735 lo = this.view[offset+2] << 16;
3736 lo |= this.view[offset+1] << 8;
3737 lo |= this.view[offset ];
3738 lo += this.view[offset+3] << 24 >>> 0;
3739 offset += 4;
3740 hi = this.view[offset+2] << 16;
3741 hi |= this.view[offset+1] << 8;
3742 hi |= this.view[offset ];
3743 hi += this.view[offset+3] << 24 >>> 0;
3744 } else {
3745 hi = this.view[offset+1] << 16;
3746 hi |= this.view[offset+2] << 8;
3747 hi |= this.view[offset+3];
3748 hi += this.view[offset ] << 24 >>> 0;
3749 offset += 4;
3750 lo = this.view[offset+1] << 16;
3751 lo |= this.view[offset+2] << 8;
3752 lo |= this.view[offset+3];
3753 lo += this.view[offset ] << 24 >>> 0;
3754 }
3755 var value = new Long(lo, hi, false);
3756 if (relative) this.offset += 8;
3757 return value;
3758 };
3759
3760 /**
3761 * Reads a 64bit signed integer. This is an alias of {@link ByteBuffer#readInt64}.
3762 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
3763 * @returns {!Long}
3764 * @expose
3765 */
3766 ByteBufferPrototype.readLong = ByteBufferPrototype.readInt64;
3767
3768 /**
3769 * Writes a 64bit unsigned integer.
3770 * @param {number|!Long} value Value to write
3771 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
3772 * @returns {!ByteBuffer} this
3773 * @expose
3774 */
3775 ByteBufferPrototype.writeUint64 = function(value, offset) {
3776 var relative = typeof offset === 'undefined';
3777 if (relative) offset = this.offset;
3778 if (!this.noAssert) {
3779 if (typeof value === 'number')
3780 value = Long.fromNumber(value);
3781 else if (typeof value === 'string')
3782 value = Long.fromString(value);
3783 else if (!(value && value instanceof Long))
3784 throw TypeError("Illegal value: "+value+" (not an integer or Long)");
3785 if (typeof offset !== 'number' || offset % 1 !== 0)
3786 throw TypeError("Illegal offset: "+offset+" (not an integer)");
3787 offset >>>= 0;
3788 if (offset < 0 || offset + 0 > this.buffer.byteLength)
3789 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
3790 }
3791 if (typeof value === 'number')
3792 value = Long.fromNumber(value);
3793 else if (typeof value === 'string')
3794 value = Long.fromString(value);
3795 offset += 8;
3796 var capacity7 = this.buffer.byteLength;
3797 if (offset > capacity7)
3798 this.resize((capacity7 *= 2) > offset ? capacity7 : offset);
3799 offset -= 8;
3800 var lo = value.low,
3801 hi = value.high;
3802 if (this.littleEndian) {
3803 this.view[offset+3] = (lo >>> 24) & 0xFF;
3804 this.view[offset+2] = (lo >>> 16) & 0xFF;
3805 this.view[offset+1] = (lo >>> 8) & 0xFF;
3806 this.view[offset ] = lo & 0xFF;
3807 offset += 4;
3808 this.view[offset+3] = (hi >>> 24) & 0xFF;
3809 this.view[offset+2] = (hi >>> 16) & 0xFF;
3810 this.view[offset+1] = (hi >>> 8) & 0xFF;
3811 this.view[offset ] = hi & 0xFF;
3812 } else {
3813 this.view[offset ] = (hi >>> 24) & 0xFF;
3814 this.view[offset+1] = (hi >>> 16) & 0xFF;
3815 this.view[offset+2] = (hi >>> 8) & 0xFF;
3816 this.view[offset+3] = hi & 0xFF;
3817 offset += 4;
3818 this.view[offset ] = (lo >>> 24) & 0xFF;
3819 this.view[offset+1] = (lo >>> 16) & 0xFF;
3820 this.view[offset+2] = (lo >>> 8) & 0xFF;
3821 this.view[offset+3] = lo & 0xFF;
3822 }
3823 if (relative) this.offset += 8;
3824 return this;
3825 };
3826
3827 /**
3828 * Writes a 64bit unsigned integer. This is an alias of {@link ByteBuffer#writeUint64}.
3829 * @function
3830 * @param {number|!Long} value Value to write
3831 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
3832 * @returns {!ByteBuffer} this
3833 * @expose
3834 */
3835 ByteBufferPrototype.writeUInt64 = ByteBufferPrototype.writeUint64;
3836
3837 /**
3838 * Reads a 64bit unsigned integer.
3839 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
3840 * @returns {!Long}
3841 * @expose
3842 */
3843 ByteBufferPrototype.readUint64 = function(offset) {
3844 var relative = typeof offset === 'undefined';
3845 if (relative) offset = this.offset;
3846 if (!this.noAssert) {
3847 if (typeof offset !== 'number' || offset % 1 !== 0)
3848 throw TypeError("Illegal offset: "+offset+" (not an integer)");
3849 offset >>>= 0;
3850 if (offset < 0 || offset + 8 > this.buffer.byteLength)
3851 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+8+") <= "+this.buffer.byteLength);
3852 }
3853 var lo = 0,
3854 hi = 0;
3855 if (this.littleEndian) {
3856 lo = this.view[offset+2] << 16;
3857 lo |= this.view[offset+1] << 8;
3858 lo |= this.view[offset ];
3859 lo += this.view[offset+3] << 24 >>> 0;
3860 offset += 4;
3861 hi = this.view[offset+2] << 16;
3862 hi |= this.view[offset+1] << 8;
3863 hi |= this.view[offset ];
3864 hi += this.view[offset+3] << 24 >>> 0;
3865 } else {
3866 hi = this.view[offset+1] << 16;
3867 hi |= this.view[offset+2] << 8;
3868 hi |= this.view[offset+3];
3869 hi += this.view[offset ] << 24 >>> 0;
3870 offset += 4;
3871 lo = this.view[offset+1] << 16;
3872 lo |= this.view[offset+2] << 8;
3873 lo |= this.view[offset+3];
3874 lo += this.view[offset ] << 24 >>> 0;
3875 }
3876 var value = new Long(lo, hi, true);
3877 if (relative) this.offset += 8;
3878 return value;
3879 };
3880
3881 /**
3882 * Reads a 64bit unsigned integer. This is an alias of {@link ByteBuffer#readUint64}.
3883 * @function
3884 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
3885 * @returns {!Long}
3886 * @expose
3887 */
3888 ByteBufferPrototype.readUInt64 = ByteBufferPrototype.readUint64;
3889
3890 } // Long
3891
3892
3893 // types/floats/float32
3894
3895 /*
3896 ieee754 - https://github.com/feross/ieee754
3897
3898 The MIT License (MIT)
3899
3900 Copyright (c) Feross Aboukhadijeh
3901
3902 Permission is hereby granted, free of charge, to any person obtaining a copy
3903 of this software and associated documentation files (the "Software"), to deal
3904 in the Software without restriction, including without limitation the rights
3905 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
3906 copies of the Software, and to permit persons to whom the Software is
3907 furnished to do so, subject to the following conditions:
3908
3909 The above copyright notice and this permission notice shall be included in
3910 all copies or substantial portions of the Software.
3911
3912 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
3913 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
3914 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
3915 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
3916 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
3917 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
3918 THE SOFTWARE.
3919 */
3920
3921 /**
3922 * Reads an IEEE754 float from a byte array.
3923 * @param {!Array} buffer
3924 * @param {number} offset
3925 * @param {boolean} isLE
3926 * @param {number} mLen
3927 * @param {number} nBytes
3928 * @returns {number}
3929 * @inner
3930 */
3931 function ieee754_read(buffer, offset, isLE, mLen, nBytes) {
3932 var e, m,
3933 eLen = nBytes * 8 - mLen - 1,
3934 eMax = (1 << eLen) - 1,
3935 eBias = eMax >> 1,
3936 nBits = -7,
3937 i = isLE ? (nBytes - 1) : 0,
3938 d = isLE ? -1 : 1,
3939 s = buffer[offset + i];
3940
3941 i += d;
3942
3943 e = s & ((1 << (-nBits)) - 1);
3944 s >>= (-nBits);
3945 nBits += eLen;
3946 for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
3947
3948 m = e & ((1 << (-nBits)) - 1);
3949 e >>= (-nBits);
3950 nBits += mLen;
3951 for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
3952
3953 if (e === 0) {
3954 e = 1 - eBias;
3955 } else if (e === eMax) {
3956 return m ? NaN : ((s ? -1 : 1) * Infinity);
3957 } else {
3958 m = m + Math.pow(2, mLen);
3959 e = e - eBias;
3960 }
3961 return (s ? -1 : 1) * m * Math.pow(2, e - mLen);
3962 }
3963
3964 /**
3965 * Writes an IEEE754 float to a byte array.
3966 * @param {!Array} buffer
3967 * @param {number} value
3968 * @param {number} offset
3969 * @param {boolean} isLE
3970 * @param {number} mLen
3971 * @param {number} nBytes
3972 * @inner
3973 */
3974 function ieee754_write(buffer, value, offset, isLE, mLen, nBytes) {
3975 var e, m, c,
3976 eLen = nBytes * 8 - mLen - 1,
3977 eMax = (1 << eLen) - 1,
3978 eBias = eMax >> 1,
3979 rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0),
3980 i = isLE ? 0 : (nBytes - 1),
3981 d = isLE ? 1 : -1,
3982 s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0;
3983
3984 value = Math.abs(value);
3985
3986 if (isNaN(value) || value === Infinity) {
3987 m = isNaN(value) ? 1 : 0;
3988 e = eMax;
3989 } else {
3990 e = Math.floor(Math.log(value) / Math.LN2);
3991 if (value * (c = Math.pow(2, -e)) < 1) {
3992 e--;
3993 c *= 2;
3994 }
3995 if (e + eBias >= 1) {
3996 value += rt / c;
3997 } else {
3998 value += rt * Math.pow(2, 1 - eBias);
3999 }
4000 if (value * c >= 2) {
4001 e++;
4002 c /= 2;
4003 }
4004
4005 if (e + eBias >= eMax) {
4006 m = 0;
4007 e = eMax;
4008 } else if (e + eBias >= 1) {
4009 m = (value * c - 1) * Math.pow(2, mLen);
4010 e = e + eBias;
4011 } else {
4012 m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
4013 e = 0;
4014 }
4015 }
4016
4017 for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
4018
4019 e = (e << mLen) | m;
4020 eLen += mLen;
4021 for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
4022
4023 buffer[offset + i - d] |= s * 128;
4024 }
4025
4026 /**
4027 * Writes a 32bit float.
4028 * @param {number} value Value to write
4029 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
4030 * @returns {!ByteBuffer} this
4031 * @expose
4032 */
4033 ByteBufferPrototype.writeFloat32 = function(value, offset) {
4034 var relative = typeof offset === 'undefined';
4035 if (relative) offset = this.offset;
4036 if (!this.noAssert) {
4037 if (typeof value !== 'number')
4038 throw TypeError("Illegal value: "+value+" (not a number)");
4039 if (typeof offset !== 'number' || offset % 1 !== 0)
4040 throw TypeError("Illegal offset: "+offset+" (not an integer)");
4041 offset >>>= 0;
4042 if (offset < 0 || offset + 0 > this.buffer.byteLength)
4043 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
4044 }
4045 offset += 4;
4046 var capacity8 = this.buffer.byteLength;
4047 if (offset > capacity8)
4048 this.resize((capacity8 *= 2) > offset ? capacity8 : offset);
4049 offset -= 4;
4050 ieee754_write(this.view, value, offset, this.littleEndian, 23, 4);
4051 if (relative) this.offset += 4;
4052 return this;
4053 };
4054
4055 /**
4056 * Writes a 32bit float. This is an alias of {@link ByteBuffer#writeFloat32}.
4057 * @function
4058 * @param {number} value Value to write
4059 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
4060 * @returns {!ByteBuffer} this
4061 * @expose
4062 */
4063 ByteBufferPrototype.writeFloat = ByteBufferPrototype.writeFloat32;
4064
4065 /**
4066 * Reads a 32bit float.
4067 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
4068 * @returns {number}
4069 * @expose
4070 */
4071 ByteBufferPrototype.readFloat32 = function(offset) {
4072 var relative = typeof offset === 'undefined';
4073 if (relative) offset = this.offset;
4074 if (!this.noAssert) {
4075 if (typeof offset !== 'number' || offset % 1 !== 0)
4076 throw TypeError("Illegal offset: "+offset+" (not an integer)");
4077 offset >>>= 0;
4078 if (offset < 0 || offset + 4 > this.buffer.byteLength)
4079 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+4+") <= "+this.buffer.byteLength);
4080 }
4081 var value = ieee754_read(this.view, offset, this.littleEndian, 23, 4);
4082 if (relative) this.offset += 4;
4083 return value;
4084 };
4085
4086 /**
4087 * Reads a 32bit float. This is an alias of {@link ByteBuffer#readFloat32}.
4088 * @function
4089 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
4090 * @returns {number}
4091 * @expose
4092 */
4093 ByteBufferPrototype.readFloat = ByteBufferPrototype.readFloat32;
4094
4095 // types/floats/float64
4096
4097 /**
4098 * Writes a 64bit float.
4099 * @param {number} value Value to write
4100 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
4101 * @returns {!ByteBuffer} this
4102 * @expose
4103 */
4104 ByteBufferPrototype.writeFloat64 = function(value, offset) {
4105 var relative = typeof offset === 'undefined';
4106 if (relative) offset = this.offset;
4107 if (!this.noAssert) {
4108 if (typeof value !== 'number')
4109 throw TypeError("Illegal value: "+value+" (not a number)");
4110 if (typeof offset !== 'number' || offset % 1 !== 0)
4111 throw TypeError("Illegal offset: "+offset+" (not an integer)");
4112 offset >>>= 0;
4113 if (offset < 0 || offset + 0 > this.buffer.byteLength)
4114 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
4115 }
4116 offset += 8;
4117 var capacity9 = this.buffer.byteLength;
4118 if (offset > capacity9)
4119 this.resize((capacity9 *= 2) > offset ? capacity9 : offset);
4120 offset -= 8;
4121 ieee754_write(this.view, value, offset, this.littleEndian, 52, 8);
4122 if (relative) this.offset += 8;
4123 return this;
4124 };
4125
4126 /**
4127 * Writes a 64bit float. This is an alias of {@link ByteBuffer#writeFloat64}.
4128 * @function
4129 * @param {number} value Value to write
4130 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
4131 * @returns {!ByteBuffer} this
4132 * @expose
4133 */
4134 ByteBufferPrototype.writeDouble = ByteBufferPrototype.writeFloat64;
4135
4136 /**
4137 * Reads a 64bit float.
4138 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
4139 * @returns {number}
4140 * @expose
4141 */
4142 ByteBufferPrototype.readFloat64 = function(offset) {
4143 var relative = typeof offset === 'undefined';
4144 if (relative) offset = this.offset;
4145 if (!this.noAssert) {
4146 if (typeof offset !== 'number' || offset % 1 !== 0)
4147 throw TypeError("Illegal offset: "+offset+" (not an integer)");
4148 offset >>>= 0;
4149 if (offset < 0 || offset + 8 > this.buffer.byteLength)
4150 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+8+") <= "+this.buffer.byteLength);
4151 }
4152 var value = ieee754_read(this.view, offset, this.littleEndian, 52, 8);
4153 if (relative) this.offset += 8;
4154 return value;
4155 };
4156
4157 /**
4158 * Reads a 64bit float. This is an alias of {@link ByteBuffer#readFloat64}.
4159 * @function
4160 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
4161 * @returns {number}
4162 * @expose
4163 */
4164 ByteBufferPrototype.readDouble = ByteBufferPrototype.readFloat64;
4165
4166
4167 // types/varints/varint32
4168
4169 /**
4170 * Maximum number of bytes required to store a 32bit base 128 variable-length integer.
4171 * @type {number}
4172 * @const
4173 * @expose
4174 */
4175 ByteBuffer.MAX_VARINT32_BYTES = 5;
4176
4177 /**
4178 * Calculates the actual number of bytes required to store a 32bit base 128 variable-length integer.
4179 * @param {number} value Value to encode
4180 * @returns {number} Number of bytes required. Capped to {@link ByteBuffer.MAX_VARINT32_BYTES}
4181 * @expose
4182 */
4183 ByteBuffer.calculateVarint32 = function(value) {
4184 // ref: src/google/protobuf/io/coded_stream.cc
4185 value = value >>> 0;
4186 if (value < 1 << 7 ) return 1;
4187 else if (value < 1 << 14) return 2;
4188 else if (value < 1 << 21) return 3;
4189 else if (value < 1 << 28) return 4;
4190 else return 5;
4191 };
4192
4193 /**
4194 * Zigzag encodes a signed 32bit integer so that it can be effectively used with varint encoding.
4195 * @param {number} n Signed 32bit integer
4196 * @returns {number} Unsigned zigzag encoded 32bit integer
4197 * @expose
4198 */
4199 ByteBuffer.zigZagEncode32 = function(n) {
4200 return (((n |= 0) << 1) ^ (n >> 31)) >>> 0; // ref: src/google/protobuf/wire_format_lite.h
4201 };
4202
4203 /**
4204 * Decodes a zigzag encoded signed 32bit integer.
4205 * @param {number} n Unsigned zigzag encoded 32bit integer
4206 * @returns {number} Signed 32bit integer
4207 * @expose
4208 */
4209 ByteBuffer.zigZagDecode32 = function(n) {
4210 return ((n >>> 1) ^ -(n & 1)) | 0; // // ref: src/google/protobuf/wire_format_lite.h
4211 };
4212
4213 /**
4214 * Writes a 32bit base 128 variable-length integer.
4215 * @param {number} value Value to write
4216 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
4217 * written if omitted.
4218 * @returns {!ByteBuffer|number} this if `offset` is omitted, else the actual number of bytes written
4219 * @expose
4220 */
4221 ByteBufferPrototype.writeVarint32 = function(value, offset) {
4222 var relative = typeof offset === 'undefined';
4223 if (relative) offset = this.offset;
4224 if (!this.noAssert) {
4225 if (typeof value !== 'number' || value % 1 !== 0)
4226 throw TypeError("Illegal value: "+value+" (not an integer)");
4227 value |= 0;
4228 if (typeof offset !== 'number' || offset % 1 !== 0)
4229 throw TypeError("Illegal offset: "+offset+" (not an integer)");
4230 offset >>>= 0;
4231 if (offset < 0 || offset + 0 > this.buffer.byteLength)
4232 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
4233 }
4234 var size = ByteBuffer.calculateVarint32(value),
4235 b;
4236 offset += size;
4237 var capacity10 = this.buffer.byteLength;
4238 if (offset > capacity10)
4239 this.resize((capacity10 *= 2) > offset ? capacity10 : offset);
4240 offset -= size;
4241 value >>>= 0;
4242 while (value >= 0x80) {
4243 b = (value & 0x7f) | 0x80;
4244 this.view[offset++] = b;
4245 value >>>= 7;
4246 }
4247 this.view[offset++] = value;
4248 if (relative) {
4249 this.offset = offset;
4250 return this;
4251 }
4252 return size;
4253 };
4254
4255 /**
4256 * Writes a zig-zag encoded (signed) 32bit base 128 variable-length integer.
4257 * @param {number} value Value to write
4258 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
4259 * written if omitted.
4260 * @returns {!ByteBuffer|number} this if `offset` is omitted, else the actual number of bytes written
4261 * @expose
4262 */
4263 ByteBufferPrototype.writeVarint32ZigZag = function(value, offset) {
4264 return this.writeVarint32(ByteBuffer.zigZagEncode32(value), offset);
4265 };
4266
4267 /**
4268 * Reads a 32bit base 128 variable-length integer.
4269 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
4270 * written if omitted.
4271 * @returns {number|!{value: number, length: number}} The value read if offset is omitted, else the value read
4272 * and the actual number of bytes read.
4273 * @throws {Error} If it's not a valid varint. Has a property `truncated = true` if there is not enough data available
4274 * to fully decode the varint.
4275 * @expose
4276 */
4277 ByteBufferPrototype.readVarint32 = function(offset) {
4278 var relative = typeof offset === 'undefined';
4279 if (relative) offset = this.offset;
4280 if (!this.noAssert) {
4281 if (typeof offset !== 'number' || offset % 1 !== 0)
4282 throw TypeError("Illegal offset: "+offset+" (not an integer)");
4283 offset >>>= 0;
4284 if (offset < 0 || offset + 1 > this.buffer.byteLength)
4285 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+1+") <= "+this.buffer.byteLength);
4286 }
4287 var c = 0,
4288 value = 0 >>> 0,
4289 b;
4290 do {
4291 if (!this.noAssert && offset > this.limit) {
4292 var err = Error("Truncated");
4293 err['truncated'] = true;
4294 throw err;
4295 }
4296 b = this.view[offset++];
4297 if (c < 5)
4298 value |= (b & 0x7f) << (7*c);
4299 ++c;
4300 } while ((b & 0x80) !== 0);
4301 value |= 0;
4302 if (relative) {
4303 this.offset = offset;
4304 return value;
4305 }
4306 return {
4307 "value": value,
4308 "length": c
4309 };
4310 };
4311
4312 /**
4313 * Reads a zig-zag encoded (signed) 32bit base 128 variable-length integer.
4314 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
4315 * written if omitted.
4316 * @returns {number|!{value: number, length: number}} The value read if offset is omitted, else the value read
4317 * and the actual number of bytes read.
4318 * @throws {Error} If it's not a valid varint
4319 * @expose
4320 */
4321 ByteBufferPrototype.readVarint32ZigZag = function(offset) {
4322 var val = this.readVarint32(offset);
4323 if (typeof val === 'object')
4324 val["value"] = ByteBuffer.zigZagDecode32(val["value"]);
4325 else
4326 val = ByteBuffer.zigZagDecode32(val);
4327 return val;
4328 };
4329
4330 // types/varints/varint64
4331
4332 if (Long) {
4333
4334 /**
4335 * Maximum number of bytes required to store a 64bit base 128 variable-length integer.
4336 * @type {number}
4337 * @const
4338 * @expose
4339 */
4340 ByteBuffer.MAX_VARINT64_BYTES = 10;
4341
4342 /**
4343 * Calculates the actual number of bytes required to store a 64bit base 128 variable-length integer.
4344 * @param {number|!Long} value Value to encode
4345 * @returns {number} Number of bytes required. Capped to {@link ByteBuffer.MAX_VARINT64_BYTES}
4346 * @expose
4347 */
4348 ByteBuffer.calculateVarint64 = function(value) {
4349 if (typeof value === 'number')
4350 value = Long.fromNumber(value);
4351 else if (typeof value === 'string')
4352 value = Long.fromString(value);
4353 // ref: src/google/protobuf/io/coded_stream.cc
4354 var part0 = value.toInt() >>> 0,
4355 part1 = value.shiftRightUnsigned(28).toInt() >>> 0,
4356 part2 = value.shiftRightUnsigned(56).toInt() >>> 0;
4357 if (part2 == 0) {
4358 if (part1 == 0) {
4359 if (part0 < 1 << 14)
4360 return part0 < 1 << 7 ? 1 : 2;
4361 else
4362 return part0 < 1 << 21 ? 3 : 4;
4363 } else {
4364 if (part1 < 1 << 14)
4365 return part1 < 1 << 7 ? 5 : 6;
4366 else
4367 return part1 < 1 << 21 ? 7 : 8;
4368 }
4369 } else
4370 return part2 < 1 << 7 ? 9 : 10;
4371 };
4372
4373 /**
4374 * Zigzag encodes a signed 64bit integer so that it can be effectively used with varint encoding.
4375 * @param {number|!Long} value Signed long
4376 * @returns {!Long} Unsigned zigzag encoded long
4377 * @expose
4378 */
4379 ByteBuffer.zigZagEncode64 = function(value) {
4380 if (typeof value === 'number')
4381 value = Long.fromNumber(value, false);
4382 else if (typeof value === 'string')
4383 value = Long.fromString(value, false);
4384 else if (value.unsigned !== false) value = value.toSigned();
4385 // ref: src/google/protobuf/wire_format_lite.h
4386 return value.shiftLeft(1).xor(value.shiftRight(63)).toUnsigned();
4387 };
4388
4389 /**
4390 * Decodes a zigzag encoded signed 64bit integer.
4391 * @param {!Long|number} value Unsigned zigzag encoded long or JavaScript number
4392 * @returns {!Long} Signed long
4393 * @expose
4394 */
4395 ByteBuffer.zigZagDecode64 = function(value) {
4396 if (typeof value === 'number')
4397 value = Long.fromNumber(value, false);
4398 else if (typeof value === 'string')
4399 value = Long.fromString(value, false);
4400 else if (value.unsigned !== false) value = value.toSigned();
4401 // ref: src/google/protobuf/wire_format_lite.h
4402 return value.shiftRightUnsigned(1).xor(value.and(Long.ONE).toSigned().negate()).toSigned();
4403 };
4404
4405 /**
4406 * Writes a 64bit base 128 variable-length integer.
4407 * @param {number|Long} value Value to write
4408 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
4409 * written if omitted.
4410 * @returns {!ByteBuffer|number} `this` if offset is omitted, else the actual number of bytes written.
4411 * @expose
4412 */
4413 ByteBufferPrototype.writeVarint64 = function(value, offset) {
4414 var relative = typeof offset === 'undefined';
4415 if (relative) offset = this.offset;
4416 if (!this.noAssert) {
4417 if (typeof value === 'number')
4418 value = Long.fromNumber(value);
4419 else if (typeof value === 'string')
4420 value = Long.fromString(value);
4421 else if (!(value && value instanceof Long))
4422 throw TypeError("Illegal value: "+value+" (not an integer or Long)");
4423 if (typeof offset !== 'number' || offset % 1 !== 0)
4424 throw TypeError("Illegal offset: "+offset+" (not an integer)");
4425 offset >>>= 0;
4426 if (offset < 0 || offset + 0 > this.buffer.byteLength)
4427 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
4428 }
4429 if (typeof value === 'number')
4430 value = Long.fromNumber(value, false);
4431 else if (typeof value === 'string')
4432 value = Long.fromString(value, false);
4433 else if (value.unsigned !== false) value = value.toSigned();
4434 var size = ByteBuffer.calculateVarint64(value),
4435 part0 = value.toInt() >>> 0,
4436 part1 = value.shiftRightUnsigned(28).toInt() >>> 0,
4437 part2 = value.shiftRightUnsigned(56).toInt() >>> 0;
4438 offset += size;
4439 var capacity11 = this.buffer.byteLength;
4440 if (offset > capacity11)
4441 this.resize((capacity11 *= 2) > offset ? capacity11 : offset);
4442 offset -= size;
4443 switch (size) {
4444 case 10: this.view[offset+9] = (part2 >>> 7) & 0x01;
4445 case 9 : this.view[offset+8] = size !== 9 ? (part2 ) | 0x80 : (part2 ) & 0x7F;
4446 case 8 : this.view[offset+7] = size !== 8 ? (part1 >>> 21) | 0x80 : (part1 >>> 21) & 0x7F;
4447 case 7 : this.view[offset+6] = size !== 7 ? (part1 >>> 14) | 0x80 : (part1 >>> 14) & 0x7F;
4448 case 6 : this.view[offset+5] = size !== 6 ? (part1 >>> 7) | 0x80 : (part1 >>> 7) & 0x7F;
4449 case 5 : this.view[offset+4] = size !== 5 ? (part1 ) | 0x80 : (part1 ) & 0x7F;
4450 case 4 : this.view[offset+3] = size !== 4 ? (part0 >>> 21) | 0x80 : (part0 >>> 21) & 0x7F;
4451 case 3 : this.view[offset+2] = size !== 3 ? (part0 >>> 14) | 0x80 : (part0 >>> 14) & 0x7F;
4452 case 2 : this.view[offset+1] = size !== 2 ? (part0 >>> 7) | 0x80 : (part0 >>> 7) & 0x7F;
4453 case 1 : this.view[offset ] = size !== 1 ? (part0 ) | 0x80 : (part0 ) & 0x7F;
4454 }
4455 if (relative) {
4456 this.offset += size;
4457 return this;
4458 } else {
4459 return size;
4460 }
4461 };
4462
4463 /**
4464 * Writes a zig-zag encoded 64bit base 128 variable-length integer.
4465 * @param {number|Long} value Value to write
4466 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
4467 * written if omitted.
4468 * @returns {!ByteBuffer|number} `this` if offset is omitted, else the actual number of bytes written.
4469 * @expose
4470 */
4471 ByteBufferPrototype.writeVarint64ZigZag = function(value, offset) {
4472 return this.writeVarint64(ByteBuffer.zigZagEncode64(value), offset);
4473 };
4474
4475 /**
4476 * Reads a 64bit base 128 variable-length integer. Requires Long.js.
4477 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
4478 * read if omitted.
4479 * @returns {!Long|!{value: Long, length: number}} The value read if offset is omitted, else the value read and
4480 * the actual number of bytes read.
4481 * @throws {Error} If it's not a valid varint
4482 * @expose
4483 */
4484 ByteBufferPrototype.readVarint64 = function(offset) {
4485 var relative = typeof offset === 'undefined';
4486 if (relative) offset = this.offset;
4487 if (!this.noAssert) {
4488 if (typeof offset !== 'number' || offset % 1 !== 0)
4489 throw TypeError("Illegal offset: "+offset+" (not an integer)");
4490 offset >>>= 0;
4491 if (offset < 0 || offset + 1 > this.buffer.byteLength)
4492 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+1+") <= "+this.buffer.byteLength);
4493 }
4494 // ref: src/google/protobuf/io/coded_stream.cc
4495 var start = offset,
4496 part0 = 0,
4497 part1 = 0,
4498 part2 = 0,
4499 b = 0;
4500 b = this.view[offset++]; part0 = (b & 0x7F) ; if ( b & 0x80 ) {
4501 b = this.view[offset++]; part0 |= (b & 0x7F) << 7; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
4502 b = this.view[offset++]; part0 |= (b & 0x7F) << 14; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
4503 b = this.view[offset++]; part0 |= (b & 0x7F) << 21; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
4504 b = this.view[offset++]; part1 = (b & 0x7F) ; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
4505 b = this.view[offset++]; part1 |= (b & 0x7F) << 7; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
4506 b = this.view[offset++]; part1 |= (b & 0x7F) << 14; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
4507 b = this.view[offset++]; part1 |= (b & 0x7F) << 21; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
4508 b = this.view[offset++]; part2 = (b & 0x7F) ; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
4509 b = this.view[offset++]; part2 |= (b & 0x7F) << 7; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
4510 throw Error("Buffer overrun"); }}}}}}}}}}
4511 var value = Long.fromBits(part0 | (part1 << 28), (part1 >>> 4) | (part2) << 24, false);
4512 if (relative) {
4513 this.offset = offset;
4514 return value;
4515 } else {
4516 return {
4517 'value': value,
4518 'length': offset-start
4519 };
4520 }
4521 };
4522
4523 /**
4524 * Reads a zig-zag encoded 64bit base 128 variable-length integer. Requires Long.js.
4525 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
4526 * read if omitted.
4527 * @returns {!Long|!{value: Long, length: number}} The value read if offset is omitted, else the value read and
4528 * the actual number of bytes read.
4529 * @throws {Error} If it's not a valid varint
4530 * @expose
4531 */
4532 ByteBufferPrototype.readVarint64ZigZag = function(offset) {
4533 var val = this.readVarint64(offset);
4534 if (val && val['value'] instanceof Long)
4535 val["value"] = ByteBuffer.zigZagDecode64(val["value"]);
4536 else
4537 val = ByteBuffer.zigZagDecode64(val);
4538 return val;
4539 };
4540
4541 } // Long
4542
4543
4544 // types/strings/cstring
4545
4546 /**
4547 * Writes a NULL-terminated UTF8 encoded string. For this to work the specified string must not contain any NULL
4548 * characters itself.
4549 * @param {string} str String to write
4550 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
4551 * contained in `str` + 1 if omitted.
4552 * @returns {!ByteBuffer|number} this if offset is omitted, else the actual number of bytes written
4553 * @expose
4554 */
4555 ByteBufferPrototype.writeCString = function(str, offset) {
4556 var relative = typeof offset === 'undefined';
4557 if (relative) offset = this.offset;
4558 var i,
4559 k = str.length;
4560 if (!this.noAssert) {
4561 if (typeof str !== 'string')
4562 throw TypeError("Illegal str: Not a string");
4563 for (i=0; i<k; ++i) {
4564 if (str.charCodeAt(i) === 0)
4565 throw RangeError("Illegal str: Contains NULL-characters");
4566 }
4567 if (typeof offset !== 'number' || offset % 1 !== 0)
4568 throw TypeError("Illegal offset: "+offset+" (not an integer)");
4569 offset >>>= 0;
4570 if (offset < 0 || offset + 0 > this.buffer.byteLength)
4571 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
4572 }
4573 // UTF8 strings do not contain zero bytes in between except for the zero character, so:
4574 k = utfx.calculateUTF16asUTF8(stringSource(str))[1];
4575 offset += k+1;
4576 var capacity12 = this.buffer.byteLength;
4577 if (offset > capacity12)
4578 this.resize((capacity12 *= 2) > offset ? capacity12 : offset);
4579 offset -= k+1;
4580 utfx.encodeUTF16toUTF8(stringSource(str), function(b) {
4581 this.view[offset++] = b;
4582 }.bind(this));
4583 this.view[offset++] = 0;
4584 if (relative) {
4585 this.offset = offset;
4586 return this;
4587 }
4588 return k;
4589 };
4590
4591 /**
4592 * Reads a NULL-terminated UTF8 encoded string. For this to work the string read must not contain any NULL characters
4593 * itself.
4594 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
4595 * read if omitted.
4596 * @returns {string|!{string: string, length: number}} The string read if offset is omitted, else the string
4597 * read and the actual number of bytes read.
4598 * @expose
4599 */
4600 ByteBufferPrototype.readCString = function(offset) {
4601 var relative = typeof offset === 'undefined';
4602 if (relative) offset = this.offset;
4603 if (!this.noAssert) {
4604 if (typeof offset !== 'number' || offset % 1 !== 0)
4605 throw TypeError("Illegal offset: "+offset+" (not an integer)");
4606 offset >>>= 0;
4607 if (offset < 0 || offset + 1 > this.buffer.byteLength)
4608 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+1+") <= "+this.buffer.byteLength);
4609 }
4610 var start = offset;
4611 // UTF8 strings do not contain zero bytes in between except for the zero character itself, so:
4612 var sd, b = -1;
4613 utfx.decodeUTF8toUTF16(function() {
4614 if (b === 0) return null;
4615 if (offset >= this.limit)
4616 throw RangeError("Illegal range: Truncated data, "+offset+" < "+this.limit);
4617 b = this.view[offset++];
4618 return b === 0 ? null : b;
4619 }.bind(this), sd = stringDestination(), true);
4620 if (relative) {
4621 this.offset = offset;
4622 return sd();
4623 } else {
4624 return {
4625 "string": sd(),
4626 "length": offset - start
4627 };
4628 }
4629 };
4630
4631 // types/strings/istring
4632
4633 /**
4634 * Writes a length as uint32 prefixed UTF8 encoded string.
4635 * @param {string} str String to write
4636 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
4637 * written if omitted.
4638 * @returns {!ByteBuffer|number} `this` if `offset` is omitted, else the actual number of bytes written
4639 * @expose
4640 * @see ByteBuffer#writeVarint32
4641 */
4642 ByteBufferPrototype.writeIString = function(str, offset) {
4643 var relative = typeof offset === 'undefined';
4644 if (relative) offset = this.offset;
4645 if (!this.noAssert) {
4646 if (typeof str !== 'string')
4647 throw TypeError("Illegal str: Not a string");
4648 if (typeof offset !== 'number' || offset % 1 !== 0)
4649 throw TypeError("Illegal offset: "+offset+" (not an integer)");
4650 offset >>>= 0;
4651 if (offset < 0 || offset + 0 > this.buffer.byteLength)
4652 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
4653 }
4654 var start = offset,
4655 k;
4656 k = utfx.calculateUTF16asUTF8(stringSource(str), this.noAssert)[1];
4657 offset += 4+k;
4658 var capacity13 = this.buffer.byteLength;
4659 if (offset > capacity13)
4660 this.resize((capacity13 *= 2) > offset ? capacity13 : offset);
4661 offset -= 4+k;
4662 if (this.littleEndian) {
4663 this.view[offset+3] = (k >>> 24) & 0xFF;
4664 this.view[offset+2] = (k >>> 16) & 0xFF;
4665 this.view[offset+1] = (k >>> 8) & 0xFF;
4666 this.view[offset ] = k & 0xFF;
4667 } else {
4668 this.view[offset ] = (k >>> 24) & 0xFF;
4669 this.view[offset+1] = (k >>> 16) & 0xFF;
4670 this.view[offset+2] = (k >>> 8) & 0xFF;
4671 this.view[offset+3] = k & 0xFF;
4672 }
4673 offset += 4;
4674 utfx.encodeUTF16toUTF8(stringSource(str), function(b) {
4675 this.view[offset++] = b;
4676 }.bind(this));
4677 if (offset !== start + 4 + k)
4678 throw RangeError("Illegal range: Truncated data, "+offset+" == "+(offset+4+k));
4679 if (relative) {
4680 this.offset = offset;
4681 return this;
4682 }
4683 return offset - start;
4684 };
4685
4686 /**
4687 * Reads a length as uint32 prefixed UTF8 encoded string.
4688 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
4689 * read if omitted.
4690 * @returns {string|!{string: string, length: number}} The string read if offset is omitted, else the string
4691 * read and the actual number of bytes read.
4692 * @expose
4693 * @see ByteBuffer#readVarint32
4694 */
4695 ByteBufferPrototype.readIString = function(offset) {
4696 var relative = typeof offset === 'undefined';
4697 if (relative) offset = this.offset;
4698 if (!this.noAssert) {
4699 if (typeof offset !== 'number' || offset % 1 !== 0)
4700 throw TypeError("Illegal offset: "+offset+" (not an integer)");
4701 offset >>>= 0;
4702 if (offset < 0 || offset + 4 > this.buffer.byteLength)
4703 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+4+") <= "+this.buffer.byteLength);
4704 }
4705 var start = offset;
4706 var len = this.readUint32(offset);
4707 var str = this.readUTF8String(len, ByteBuffer.METRICS_BYTES, offset += 4);
4708 offset += str['length'];
4709 if (relative) {
4710 this.offset = offset;
4711 return str['string'];
4712 } else {
4713 return {
4714 'string': str['string'],
4715 'length': offset - start
4716 };
4717 }
4718 };
4719
4720 // types/strings/utf8string
4721
4722 /**
4723 * Metrics representing number of UTF8 characters. Evaluates to `c`.
4724 * @type {string}
4725 * @const
4726 * @expose
4727 */
4728 ByteBuffer.METRICS_CHARS = 'c';
4729
4730 /**
4731 * Metrics representing number of bytes. Evaluates to `b`.
4732 * @type {string}
4733 * @const
4734 * @expose
4735 */
4736 ByteBuffer.METRICS_BYTES = 'b';
4737
4738 /**
4739 * Writes an UTF8 encoded string.
4740 * @param {string} str String to write
4741 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} if omitted.
4742 * @returns {!ByteBuffer|number} this if offset is omitted, else the actual number of bytes written.
4743 * @expose
4744 */
4745 ByteBufferPrototype.writeUTF8String = function(str, offset) {
4746 var relative = typeof offset === 'undefined';
4747 if (relative) offset = this.offset;
4748 if (!this.noAssert) {
4749 if (typeof offset !== 'number' || offset % 1 !== 0)
4750 throw TypeError("Illegal offset: "+offset+" (not an integer)");
4751 offset >>>= 0;
4752 if (offset < 0 || offset + 0 > this.buffer.byteLength)
4753 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
4754 }
4755 var k;
4756 var start = offset;
4757 k = utfx.calculateUTF16asUTF8(stringSource(str))[1];
4758 offset += k;
4759 var capacity14 = this.buffer.byteLength;
4760 if (offset > capacity14)
4761 this.resize((capacity14 *= 2) > offset ? capacity14 : offset);
4762 offset -= k;
4763 utfx.encodeUTF16toUTF8(stringSource(str), function(b) {
4764 this.view[offset++] = b;
4765 }.bind(this));
4766 if (relative) {
4767 this.offset = offset;
4768 return this;
4769 }
4770 return offset - start;
4771 };
4772
4773 /**
4774 * Writes an UTF8 encoded string. This is an alias of {@link ByteBuffer#writeUTF8String}.
4775 * @function
4776 * @param {string} str String to write
4777 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} if omitted.
4778 * @returns {!ByteBuffer|number} this if offset is omitted, else the actual number of bytes written.
4779 * @expose
4780 */
4781 ByteBufferPrototype.writeString = ByteBufferPrototype.writeUTF8String;
4782
4783 /**
4784 * Calculates the number of UTF8 characters of a string. JavaScript itself uses UTF-16, so that a string's
4785 * `length` property does not reflect its actual UTF8 size if it contains code points larger than 0xFFFF.
4786 * @param {string} str String to calculate
4787 * @returns {number} Number of UTF8 characters
4788 * @expose
4789 */
4790 ByteBuffer.calculateUTF8Chars = function(str) {
4791 return utfx.calculateUTF16asUTF8(stringSource(str))[0];
4792 };
4793
4794 /**
4795 * Calculates the number of UTF8 bytes of a string.
4796 * @param {string} str String to calculate
4797 * @returns {number} Number of UTF8 bytes
4798 * @expose
4799 */
4800 ByteBuffer.calculateUTF8Bytes = function(str) {
4801 return utfx.calculateUTF16asUTF8(stringSource(str))[1];
4802 };
4803
4804 /**
4805 * Calculates the number of UTF8 bytes of a string. This is an alias of {@link ByteBuffer.calculateUTF8Bytes}.
4806 * @function
4807 * @param {string} str String to calculate
4808 * @returns {number} Number of UTF8 bytes
4809 * @expose
4810 */
4811 ByteBuffer.calculateString = ByteBuffer.calculateUTF8Bytes;
4812
4813 /**
4814 * Reads an UTF8 encoded string.
4815 * @param {number} length Number of characters or bytes to read.
4816 * @param {string=} metrics Metrics specifying what `length` is meant to count. Defaults to
4817 * {@link ByteBuffer.METRICS_CHARS}.
4818 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
4819 * read if omitted.
4820 * @returns {string|!{string: string, length: number}} The string read if offset is omitted, else the string
4821 * read and the actual number of bytes read.
4822 * @expose
4823 */
4824 ByteBufferPrototype.readUTF8String = function(length, metrics, offset) {
4825 if (typeof metrics === 'number') {
4826 offset = metrics;
4827 metrics = undefined;
4828 }
4829 var relative = typeof offset === 'undefined';
4830 if (relative) offset = this.offset;
4831 if (typeof metrics === 'undefined') metrics = ByteBuffer.METRICS_CHARS;
4832 if (!this.noAssert) {
4833 if (typeof length !== 'number' || length % 1 !== 0)
4834 throw TypeError("Illegal length: "+length+" (not an integer)");
4835 length |= 0;
4836 if (typeof offset !== 'number' || offset % 1 !== 0)
4837 throw TypeError("Illegal offset: "+offset+" (not an integer)");
4838 offset >>>= 0;
4839 if (offset < 0 || offset + 0 > this.buffer.byteLength)
4840 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
4841 }
4842 var i = 0,
4843 start = offset,
4844 sd;
4845 if (metrics === ByteBuffer.METRICS_CHARS) { // The same for node and the browser
4846 sd = stringDestination();
4847 utfx.decodeUTF8(function() {
4848 return i < length && offset < this.limit ? this.view[offset++] : null;
4849 }.bind(this), function(cp) {
4850 ++i; utfx.UTF8toUTF16(cp, sd);
4851 });
4852 if (i !== length)
4853 throw RangeError("Illegal range: Truncated data, "+i+" == "+length);
4854 if (relative) {
4855 this.offset = offset;
4856 return sd();
4857 } else {
4858 return {
4859 "string": sd(),
4860 "length": offset - start
4861 };
4862 }
4863 } else if (metrics === ByteBuffer.METRICS_BYTES) {
4864 if (!this.noAssert) {
4865 if (typeof offset !== 'number' || offset % 1 !== 0)
4866 throw TypeError("Illegal offset: "+offset+" (not an integer)");
4867 offset >>>= 0;
4868 if (offset < 0 || offset + length > this.buffer.byteLength)
4869 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+length+") <= "+this.buffer.byteLength);
4870 }
4871 var k = offset + length;
4872 utfx.decodeUTF8toUTF16(function() {
4873 return offset < k ? this.view[offset++] : null;
4874 }.bind(this), sd = stringDestination(), this.noAssert);
4875 if (offset !== k)
4876 throw RangeError("Illegal range: Truncated data, "+offset+" == "+k);
4877 if (relative) {
4878 this.offset = offset;
4879 return sd();
4880 } else {
4881 return {
4882 'string': sd(),
4883 'length': offset - start
4884 };
4885 }
4886 } else
4887 throw TypeError("Unsupported metrics: "+metrics);
4888 };
4889
4890 /**
4891 * Reads an UTF8 encoded string. This is an alias of {@link ByteBuffer#readUTF8String}.
4892 * @function
4893 * @param {number} length Number of characters or bytes to read
4894 * @param {number=} metrics Metrics specifying what `n` is meant to count. Defaults to
4895 * {@link ByteBuffer.METRICS_CHARS}.
4896 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
4897 * read if omitted.
4898 * @returns {string|!{string: string, length: number}} The string read if offset is omitted, else the string
4899 * read and the actual number of bytes read.
4900 * @expose
4901 */
4902 ByteBufferPrototype.readString = ByteBufferPrototype.readUTF8String;
4903
4904 // types/strings/vstring
4905
4906 /**
4907 * Writes a length as varint32 prefixed UTF8 encoded string.
4908 * @param {string} str String to write
4909 * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
4910 * written if omitted.
4911 * @returns {!ByteBuffer|number} `this` if `offset` is omitted, else the actual number of bytes written
4912 * @expose
4913 * @see ByteBuffer#writeVarint32
4914 */
4915 ByteBufferPrototype.writeVString = function(str, offset) {
4916 var relative = typeof offset === 'undefined';
4917 if (relative) offset = this.offset;
4918 if (!this.noAssert) {
4919 if (typeof str !== 'string')
4920 throw TypeError("Illegal str: Not a string");
4921 if (typeof offset !== 'number' || offset % 1 !== 0)
4922 throw TypeError("Illegal offset: "+offset+" (not an integer)");
4923 offset >>>= 0;
4924 if (offset < 0 || offset + 0 > this.buffer.byteLength)
4925 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
4926 }
4927 var start = offset,
4928 k, l;
4929 k = utfx.calculateUTF16asUTF8(stringSource(str), this.noAssert)[1];
4930 l = ByteBuffer.calculateVarint32(k);
4931 offset += l+k;
4932 var capacity15 = this.buffer.byteLength;
4933 if (offset > capacity15)
4934 this.resize((capacity15 *= 2) > offset ? capacity15 : offset);
4935 offset -= l+k;
4936 offset += this.writeVarint32(k, offset);
4937 utfx.encodeUTF16toUTF8(stringSource(str), function(b) {
4938 this.view[offset++] = b;
4939 }.bind(this));
4940 if (offset !== start+k+l)
4941 throw RangeError("Illegal range: Truncated data, "+offset+" == "+(offset+k+l));
4942 if (relative) {
4943 this.offset = offset;
4944 return this;
4945 }
4946 return offset - start;
4947 };
4948
4949 /**
4950 * Reads a length as varint32 prefixed UTF8 encoded string.
4951 * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
4952 * read if omitted.
4953 * @returns {string|!{string: string, length: number}} The string read if offset is omitted, else the string
4954 * read and the actual number of bytes read.
4955 * @expose
4956 * @see ByteBuffer#readVarint32
4957 */
4958 ByteBufferPrototype.readVString = function(offset) {
4959 var relative = typeof offset === 'undefined';
4960 if (relative) offset = this.offset;
4961 if (!this.noAssert) {
4962 if (typeof offset !== 'number' || offset % 1 !== 0)
4963 throw TypeError("Illegal offset: "+offset+" (not an integer)");
4964 offset >>>= 0;
4965 if (offset < 0 || offset + 1 > this.buffer.byteLength)
4966 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+1+") <= "+this.buffer.byteLength);
4967 }
4968 var start = offset;
4969 var len = this.readVarint32(offset);
4970 var str = this.readUTF8String(len['value'], ByteBuffer.METRICS_BYTES, offset += len['length']);
4971 offset += str['length'];
4972 if (relative) {
4973 this.offset = offset;
4974 return str['string'];
4975 } else {
4976 return {
4977 'string': str['string'],
4978 'length': offset - start
4979 };
4980 }
4981 };
4982
4983
4984 /**
4985 * Appends some data to this ByteBuffer. This will overwrite any contents behind the specified offset up to the appended
4986 * data's length.
4987 * @param {!ByteBuffer|!ArrayBuffer|!Uint8Array|string} source Data to append. If `source` is a ByteBuffer, its offsets
4988 * will be modified according to the performed read operation.
4989 * @param {(string|number)=} encoding Encoding if `data` is a string ("base64", "hex", "binary", defaults to "utf8")
4990 * @param {number=} offset Offset to append at. Will use and increase {@link ByteBuffer#offset} by the number of bytes
4991 * written if omitted.
4992 * @returns {!ByteBuffer} this
4993 * @expose
4994 * @example A relative `<01 02>03.append(<04 05>)` will result in `<01 02 04 05>, 04 05|`
4995 * @example An absolute `<01 02>03.append(04 05>, 1)` will result in `<01 04>05, 04 05|`
4996 */
4997 ByteBufferPrototype.append = function(source, encoding, offset) {
4998 if (typeof encoding === 'number' || typeof encoding !== 'string') {
4999 offset = encoding;
5000 encoding = undefined;
5001 }
5002 var relative = typeof offset === 'undefined';
5003 if (relative) offset = this.offset;
5004 if (!this.noAssert) {
5005 if (typeof offset !== 'number' || offset % 1 !== 0)
5006 throw TypeError("Illegal offset: "+offset+" (not an integer)");
5007 offset >>>= 0;
5008 if (offset < 0 || offset + 0 > this.buffer.byteLength)
5009 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
5010 }
5011 if (!(source instanceof ByteBuffer))
5012 source = ByteBuffer.wrap(source, encoding);
5013 var length = source.limit - source.offset;
5014 if (length <= 0) return this; // Nothing to append
5015 offset += length;
5016 var capacity16 = this.buffer.byteLength;
5017 if (offset > capacity16)
5018 this.resize((capacity16 *= 2) > offset ? capacity16 : offset);
5019 offset -= length;
5020 this.view.set(source.view.subarray(source.offset, source.limit), offset);
5021 source.offset += length;
5022 if (relative) this.offset += length;
5023 return this;
5024 };
5025
5026 /**
5027 * Appends this ByteBuffer's contents to another ByteBuffer. This will overwrite any contents at and after the
5028 specified offset up to the length of this ByteBuffer's data.
5029 * @param {!ByteBuffer} target Target ByteBuffer
5030 * @param {number=} offset Offset to append to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
5031 * read if omitted.
5032 * @returns {!ByteBuffer} this
5033 * @expose
5034 * @see ByteBuffer#append
5035 */
5036 ByteBufferPrototype.appendTo = function(target, offset) {
5037 target.append(this, offset);
5038 return this;
5039 };
5040
5041 /**
5042 * Enables or disables assertions of argument types and offsets. Assertions are enabled by default but you can opt to
5043 * disable them if your code already makes sure that everything is valid.
5044 * @param {boolean} assert `true` to enable assertions, otherwise `false`
5045 * @returns {!ByteBuffer} this
5046 * @expose
5047 */
5048 ByteBufferPrototype.assert = function(assert) {
5049 this.noAssert = !assert;
5050 return this;
5051 };
5052
5053 /**
5054 * Gets the capacity of this ByteBuffer's backing buffer.
5055 * @returns {number} Capacity of the backing buffer
5056 * @expose
5057 */
5058 ByteBufferPrototype.capacity = function() {
5059 return this.buffer.byteLength;
5060 };
5061 /**
5062 * Clears this ByteBuffer's offsets by setting {@link ByteBuffer#offset} to `0` and {@link ByteBuffer#limit} to the
5063 * backing buffer's capacity. Discards {@link ByteBuffer#markedOffset}.
5064 * @returns {!ByteBuffer} this
5065 * @expose
5066 */
5067 ByteBufferPrototype.clear = function() {
5068 this.offset = 0;
5069 this.limit = this.buffer.byteLength;
5070 this.markedOffset = -1;
5071 return this;
5072 };
5073
5074 /**
5075 * Creates a cloned instance of this ByteBuffer, preset with this ByteBuffer's values for {@link ByteBuffer#offset},
5076 * {@link ByteBuffer#markedOffset} and {@link ByteBuffer#limit}.
5077 * @param {boolean=} copy Whether to copy the backing buffer or to return another view on the same, defaults to `false`
5078 * @returns {!ByteBuffer} Cloned instance
5079 * @expose
5080 */
5081 ByteBufferPrototype.clone = function(copy) {
5082 var bb = new ByteBuffer(0, this.littleEndian, this.noAssert);
5083 if (copy) {
5084 bb.buffer = new ArrayBuffer(this.buffer.byteLength);
5085 bb.view = new Uint8Array(bb.buffer);
5086 } else {
5087 bb.buffer = this.buffer;
5088 bb.view = this.view;
5089 }
5090 bb.offset = this.offset;
5091 bb.markedOffset = this.markedOffset;
5092 bb.limit = this.limit;
5093 return bb;
5094 };
5095
5096 /**
5097 * Compacts this ByteBuffer to be backed by a {@link ByteBuffer#buffer} of its contents' length. Contents are the bytes
5098 * between {@link ByteBuffer#offset} and {@link ByteBuffer#limit}. Will set `offset = 0` and `limit = capacity` and
5099 * adapt {@link ByteBuffer#markedOffset} to the same relative position if set.
5100 * @param {number=} begin Offset to start at, defaults to {@link ByteBuffer#offset}
5101 * @param {number=} end Offset to end at, defaults to {@link ByteBuffer#limit}
5102 * @returns {!ByteBuffer} this
5103 * @expose
5104 */
5105 ByteBufferPrototype.compact = function(begin, end) {
5106 if (typeof begin === 'undefined') begin = this.offset;
5107 if (typeof end === 'undefined') end = this.limit;
5108 if (!this.noAssert) {
5109 if (typeof begin !== 'number' || begin % 1 !== 0)
5110 throw TypeError("Illegal begin: Not an integer");
5111 begin >>>= 0;
5112 if (typeof end !== 'number' || end % 1 !== 0)
5113 throw TypeError("Illegal end: Not an integer");
5114 end >>>= 0;
5115 if (begin < 0 || begin > end || end > this.buffer.byteLength)
5116 throw RangeError("Illegal range: 0 <= "+begin+" <= "+end+" <= "+this.buffer.byteLength);
5117 }
5118 if (begin === 0 && end === this.buffer.byteLength)
5119 return this; // Already compacted
5120 var len = end - begin;
5121 if (len === 0) {
5122 this.buffer = EMPTY_BUFFER;
5123 this.view = null;
5124 if (this.markedOffset >= 0) this.markedOffset -= begin;
5125 this.offset = 0;
5126 this.limit = 0;
5127 return this;
5128 }
5129 var buffer = new ArrayBuffer(len);
5130 var view = new Uint8Array(buffer);
5131 view.set(this.view.subarray(begin, end));
5132 this.buffer = buffer;
5133 this.view = view;
5134 if (this.markedOffset >= 0) this.markedOffset -= begin;
5135 this.offset = 0;
5136 this.limit = len;
5137 return this;
5138 };
5139
5140 /**
5141 * Creates a copy of this ByteBuffer's contents. Contents are the bytes between {@link ByteBuffer#offset} and
5142 * {@link ByteBuffer#limit}.
5143 * @param {number=} begin Begin offset, defaults to {@link ByteBuffer#offset}.
5144 * @param {number=} end End offset, defaults to {@link ByteBuffer#limit}.
5145 * @returns {!ByteBuffer} Copy
5146 * @expose
5147 */
5148 ByteBufferPrototype.copy = function(begin, end) {
5149 if (typeof begin === 'undefined') begin = this.offset;
5150 if (typeof end === 'undefined') end = this.limit;
5151 if (!this.noAssert) {
5152 if (typeof begin !== 'number' || begin % 1 !== 0)
5153 throw TypeError("Illegal begin: Not an integer");
5154 begin >>>= 0;
5155 if (typeof end !== 'number' || end % 1 !== 0)
5156 throw TypeError("Illegal end: Not an integer");
5157 end >>>= 0;
5158 if (begin < 0 || begin > end || end > this.buffer.byteLength)
5159 throw RangeError("Illegal range: 0 <= "+begin+" <= "+end+" <= "+this.buffer.byteLength);
5160 }
5161 if (begin === end)
5162 return new ByteBuffer(0, this.littleEndian, this.noAssert);
5163 var capacity = end - begin,
5164 bb = new ByteBuffer(capacity, this.littleEndian, this.noAssert);
5165 bb.offset = 0;
5166 bb.limit = capacity;
5167 if (bb.markedOffset >= 0) bb.markedOffset -= begin;
5168 this.copyTo(bb, 0, begin, end);
5169 return bb;
5170 };
5171
5172 /**
5173 * Copies this ByteBuffer's contents to another ByteBuffer. Contents are the bytes between {@link ByteBuffer#offset} and
5174 * {@link ByteBuffer#limit}.
5175 * @param {!ByteBuffer} target Target ByteBuffer
5176 * @param {number=} targetOffset Offset to copy to. Will use and increase the target's {@link ByteBuffer#offset}
5177 * by the number of bytes copied if omitted.
5178 * @param {number=} sourceOffset Offset to start copying from. Will use and increase {@link ByteBuffer#offset} by the
5179 * number of bytes copied if omitted.
5180 * @param {number=} sourceLimit Offset to end copying from, defaults to {@link ByteBuffer#limit}
5181 * @returns {!ByteBuffer} this
5182 * @expose
5183 */
5184 ByteBufferPrototype.copyTo = function(target, targetOffset, sourceOffset, sourceLimit) {
5185 var relative,
5186 targetRelative;
5187 if (!this.noAssert) {
5188 if (!ByteBuffer.isByteBuffer(target))
5189 throw TypeError("Illegal target: Not a ByteBuffer");
5190 }
5191 targetOffset = (targetRelative = typeof targetOffset === 'undefined') ? target.offset : targetOffset | 0;
5192 sourceOffset = (relative = typeof sourceOffset === 'undefined') ? this.offset : sourceOffset | 0;
5193 sourceLimit = typeof sourceLimit === 'undefined' ? this.limit : sourceLimit | 0;
5194
5195 if (targetOffset < 0 || targetOffset > target.buffer.byteLength)
5196 throw RangeError("Illegal target range: 0 <= "+targetOffset+" <= "+target.buffer.byteLength);
5197 if (sourceOffset < 0 || sourceLimit > this.buffer.byteLength)
5198 throw RangeError("Illegal source range: 0 <= "+sourceOffset+" <= "+this.buffer.byteLength);
5199
5200 var len = sourceLimit - sourceOffset;
5201 if (len === 0)
5202 return target; // Nothing to copy
5203
5204 target.ensureCapacity(targetOffset + len);
5205
5206 target.view.set(this.view.subarray(sourceOffset, sourceLimit), targetOffset);
5207
5208 if (relative) this.offset += len;
5209 if (targetRelative) target.offset += len;
5210
5211 return this;
5212 };
5213
5214 /**
5215 * Makes sure that this ByteBuffer is backed by a {@link ByteBuffer#buffer} of at least the specified capacity. If the
5216 * current capacity is exceeded, it will be doubled. If double the current capacity is less than the required capacity,
5217 * the required capacity will be used instead.
5218 * @param {number} capacity Required capacity
5219 * @returns {!ByteBuffer} this
5220 * @expose
5221 */
5222 ByteBufferPrototype.ensureCapacity = function(capacity) {
5223 var current = this.buffer.byteLength;
5224 if (current < capacity)
5225 return this.resize((current *= 2) > capacity ? current : capacity);
5226 return this;
5227 };
5228
5229 /**
5230 * Overwrites this ByteBuffer's contents with the specified value. Contents are the bytes between
5231 * {@link ByteBuffer#offset} and {@link ByteBuffer#limit}.
5232 * @param {number|string} value Byte value to fill with. If given as a string, the first character is used.
5233 * @param {number=} begin Begin offset. Will use and increase {@link ByteBuffer#offset} by the number of bytes
5234 * written if omitted. defaults to {@link ByteBuffer#offset}.
5235 * @param {number=} end End offset, defaults to {@link ByteBuffer#limit}.
5236 * @returns {!ByteBuffer} this
5237 * @expose
5238 * @example `someByteBuffer.clear().fill(0)` fills the entire backing buffer with zeroes
5239 */
5240 ByteBufferPrototype.fill = function(value, begin, end) {
5241 var relative = typeof begin === 'undefined';
5242 if (relative) begin = this.offset;
5243 if (typeof value === 'string' && value.length > 0)
5244 value = value.charCodeAt(0);
5245 if (typeof begin === 'undefined') begin = this.offset;
5246 if (typeof end === 'undefined') end = this.limit;
5247 if (!this.noAssert) {
5248 if (typeof value !== 'number' || value % 1 !== 0)
5249 throw TypeError("Illegal value: "+value+" (not an integer)");
5250 value |= 0;
5251 if (typeof begin !== 'number' || begin % 1 !== 0)
5252 throw TypeError("Illegal begin: Not an integer");
5253 begin >>>= 0;
5254 if (typeof end !== 'number' || end % 1 !== 0)
5255 throw TypeError("Illegal end: Not an integer");
5256 end >>>= 0;
5257 if (begin < 0 || begin > end || end > this.buffer.byteLength)
5258 throw RangeError("Illegal range: 0 <= "+begin+" <= "+end+" <= "+this.buffer.byteLength);
5259 }
5260 if (begin >= end)
5261 return this; // Nothing to fill
5262 while (begin < end) this.view[begin++] = value;
5263 if (relative) this.offset = begin;
5264 return this;
5265 };
5266
5267 /**
5268 * Makes this ByteBuffer ready for a new sequence of write or relative read operations. Sets `limit = offset` and
5269 * `offset = 0`. Make sure always to flip a ByteBuffer when all relative read or write operations are complete.
5270 * @returns {!ByteBuffer} this
5271 * @expose
5272 */
5273 ByteBufferPrototype.flip = function() {
5274 this.limit = this.offset;
5275 this.offset = 0;
5276 return this;
5277 };
5278 /**
5279 * Marks an offset on this ByteBuffer to be used later.
5280 * @param {number=} offset Offset to mark. Defaults to {@link ByteBuffer#offset}.
5281 * @returns {!ByteBuffer} this
5282 * @throws {TypeError} If `offset` is not a valid number
5283 * @throws {RangeError} If `offset` is out of bounds
5284 * @see ByteBuffer#reset
5285 * @expose
5286 */
5287 ByteBufferPrototype.mark = function(offset) {
5288 offset = typeof offset === 'undefined' ? this.offset : offset;
5289 if (!this.noAssert) {
5290 if (typeof offset !== 'number' || offset % 1 !== 0)
5291 throw TypeError("Illegal offset: "+offset+" (not an integer)");
5292 offset >>>= 0;
5293 if (offset < 0 || offset + 0 > this.buffer.byteLength)
5294 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
5295 }
5296 this.markedOffset = offset;
5297 return this;
5298 };
5299 /**
5300 * Sets the byte order.
5301 * @param {boolean} littleEndian `true` for little endian byte order, `false` for big endian
5302 * @returns {!ByteBuffer} this
5303 * @expose
5304 */
5305 ByteBufferPrototype.order = function(littleEndian) {
5306 if (!this.noAssert) {
5307 if (typeof littleEndian !== 'boolean')
5308 throw TypeError("Illegal littleEndian: Not a boolean");
5309 }
5310 this.littleEndian = !!littleEndian;
5311 return this;
5312 };
5313
5314 /**
5315 * Switches (to) little endian byte order.
5316 * @param {boolean=} littleEndian Defaults to `true`, otherwise uses big endian
5317 * @returns {!ByteBuffer} this
5318 * @expose
5319 */
5320 ByteBufferPrototype.LE = function(littleEndian) {
5321 this.littleEndian = typeof littleEndian !== 'undefined' ? !!littleEndian : true;
5322 return this;
5323 };
5324
5325 /**
5326 * Switches (to) big endian byte order.
5327 * @param {boolean=} bigEndian Defaults to `true`, otherwise uses little endian
5328 * @returns {!ByteBuffer} this
5329 * @expose
5330 */
5331 ByteBufferPrototype.BE = function(bigEndian) {
5332 this.littleEndian = typeof bigEndian !== 'undefined' ? !bigEndian : false;
5333 return this;
5334 };
5335 /**
5336 * Prepends some data to this ByteBuffer. This will overwrite any contents before the specified offset up to the
5337 * prepended data's length. If there is not enough space available before the specified `offset`, the backing buffer
5338 * will be resized and its contents moved accordingly.
5339 * @param {!ByteBuffer|string|!ArrayBuffer} source Data to prepend. If `source` is a ByteBuffer, its offset will be
5340 * modified according to the performed read operation.
5341 * @param {(string|number)=} encoding Encoding if `data` is a string ("base64", "hex", "binary", defaults to "utf8")
5342 * @param {number=} offset Offset to prepend at. Will use and decrease {@link ByteBuffer#offset} by the number of bytes
5343 * prepended if omitted.
5344 * @returns {!ByteBuffer} this
5345 * @expose
5346 * @example A relative `00<01 02 03>.prepend(<04 05>)` results in `<04 05 01 02 03>, 04 05|`
5347 * @example An absolute `00<01 02 03>.prepend(<04 05>, 2)` results in `04<05 02 03>, 04 05|`
5348 */
5349 ByteBufferPrototype.prepend = function(source, encoding, offset) {
5350 if (typeof encoding === 'number' || typeof encoding !== 'string') {
5351 offset = encoding;
5352 encoding = undefined;
5353 }
5354 var relative = typeof offset === 'undefined';
5355 if (relative) offset = this.offset;
5356 if (!this.noAssert) {
5357 if (typeof offset !== 'number' || offset % 1 !== 0)
5358 throw TypeError("Illegal offset: "+offset+" (not an integer)");
5359 offset >>>= 0;
5360 if (offset < 0 || offset + 0 > this.buffer.byteLength)
5361 throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
5362 }
5363 if (!(source instanceof ByteBuffer))
5364 source = ByteBuffer.wrap(source, encoding);
5365 var len = source.limit - source.offset;
5366 if (len <= 0) return this; // Nothing to prepend
5367 var diff = len - offset;
5368 if (diff > 0) { // Not enough space before offset, so resize + move
5369 var buffer = new ArrayBuffer(this.buffer.byteLength + diff);
5370 var view = new Uint8Array(buffer);
5371 view.set(this.view.subarray(offset, this.buffer.byteLength), len);
5372 this.buffer = buffer;
5373 this.view = view;
5374 this.offset += diff;
5375 if (this.markedOffset >= 0) this.markedOffset += diff;
5376 this.limit += diff;
5377 offset += diff;
5378 } else {
5379 var arrayView = new Uint8Array(this.buffer);
5380 }
5381 this.view.set(source.view.subarray(source.offset, source.limit), offset - len);
5382
5383 source.offset = source.limit;
5384 if (relative)
5385 this.offset -= len;
5386 return this;
5387 };
5388
5389 /**
5390 * Prepends this ByteBuffer to another ByteBuffer. This will overwrite any contents before the specified offset up to the
5391 * prepended data's length. If there is not enough space available before the specified `offset`, the backing buffer
5392 * will be resized and its contents moved accordingly.
5393 * @param {!ByteBuffer} target Target ByteBuffer
5394 * @param {number=} offset Offset to prepend at. Will use and decrease {@link ByteBuffer#offset} by the number of bytes
5395 * prepended if omitted.
5396 * @returns {!ByteBuffer} this
5397 * @expose
5398 * @see ByteBuffer#prepend
5399 */
5400 ByteBufferPrototype.prependTo = function(target, offset) {
5401 target.prepend(this, offset);
5402 return this;
5403 };
5404 /**
5405 * Prints debug information about this ByteBuffer's contents.
5406 * @param {function(string)=} out Output function to call, defaults to console.log
5407 * @expose
5408 */
5409 ByteBufferPrototype.printDebug = function(out) {
5410 if (typeof out !== 'function') out = console.log.bind(console);
5411 out(
5412 this.toString()+"\n"+
5413 "-------------------------------------------------------------------\n"+
5414 this.toDebug(/* columns */ true)
5415 );
5416 };
5417
5418 /**
5419 * Gets the number of remaining readable bytes. Contents are the bytes between {@link ByteBuffer#offset} and
5420 * {@link ByteBuffer#limit}, so this returns `limit - offset`.
5421 * @returns {number} Remaining readable bytes. May be negative if `offset > limit`.
5422 * @expose
5423 */
5424 ByteBufferPrototype.remaining = function() {
5425 return this.limit - this.offset;
5426 };
5427 /**
5428 * Resets this ByteBuffer's {@link ByteBuffer#offset}. If an offset has been marked through {@link ByteBuffer#mark}
5429 * before, `offset` will be set to {@link ByteBuffer#markedOffset}, which will then be discarded. If no offset has been
5430 * marked, sets `offset = 0`.
5431 * @returns {!ByteBuffer} this
5432 * @see ByteBuffer#mark
5433 * @expose
5434 */
5435 ByteBufferPrototype.reset = function() {
5436 if (this.markedOffset >= 0) {
5437 this.offset = this.markedOffset;
5438 this.markedOffset = -1;
5439 } else {
5440 this.offset = 0;
5441 }
5442 return this;
5443 };
5444 /**
5445 * Resizes this ByteBuffer to be backed by a buffer of at least the given capacity. Will do nothing if already that
5446 * large or larger.
5447 * @param {number} capacity Capacity required
5448 * @returns {!ByteBuffer} this
5449 * @throws {TypeError} If `capacity` is not a number
5450 * @throws {RangeError} If `capacity < 0`
5451 * @expose
5452 */
5453 ByteBufferPrototype.resize = function(capacity) {
5454 if (!this.noAssert) {
5455 if (typeof capacity !== 'number' || capacity % 1 !== 0)
5456 throw TypeError("Illegal capacity: "+capacity+" (not an integer)");
5457 capacity |= 0;
5458 if (capacity < 0)
5459 throw RangeError("Illegal capacity: 0 <= "+capacity);
5460 }
5461 if (this.buffer.byteLength < capacity) {
5462 var buffer = new ArrayBuffer(capacity);
5463 var view = new Uint8Array(buffer);
5464 view.set(this.view);
5465 this.buffer = buffer;
5466 this.view = view;
5467 }
5468 return this;
5469 };
5470 /**
5471 * Reverses this ByteBuffer's contents.
5472 * @param {number=} begin Offset to start at, defaults to {@link ByteBuffer#offset}
5473 * @param {number=} end Offset to end at, defaults to {@link ByteBuffer#limit}
5474 * @returns {!ByteBuffer} this
5475 * @expose
5476 */
5477 ByteBufferPrototype.reverse = function(begin, end) {
5478 if (typeof begin === 'undefined') begin = this.offset;
5479 if (typeof end === 'undefined') end = this.limit;
5480 if (!this.noAssert) {
5481 if (typeof begin !== 'number' || begin % 1 !== 0)
5482 throw TypeError("Illegal begin: Not an integer");
5483 begin >>>= 0;
5484 if (typeof end !== 'number' || end % 1 !== 0)
5485 throw TypeError("Illegal end: Not an integer");
5486 end >>>= 0;
5487 if (begin < 0 || begin > end || end > this.buffer.byteLength)
5488 throw RangeError("Illegal range: 0 <= "+begin+" <= "+end+" <= "+this.buffer.byteLength);
5489 }
5490 if (begin === end)
5491 return this; // Nothing to reverse
5492 Array.prototype.reverse.call(this.view.subarray(begin, end));
5493 return this;
5494 };
5495 /**
5496 * Skips the next `length` bytes. This will just advance
5497 * @param {number} length Number of bytes to skip. May also be negative to move the offset back.
5498 * @returns {!ByteBuffer} this
5499 * @expose
5500 */
5501 ByteBufferPrototype.skip = function(length) {
5502 if (!this.noAssert) {
5503 if (typeof length !== 'number' || length % 1 !== 0)
5504 throw TypeError("Illegal length: "+length+" (not an integer)");
5505 length |= 0;
5506 }
5507 var offset = this.offset + length;
5508 if (!this.noAssert) {
5509 if (offset < 0 || offset > this.buffer.byteLength)
5510 throw RangeError("Illegal length: 0 <= "+this.offset+" + "+length+" <= "+this.buffer.byteLength);
5511 }
5512 this.offset = offset;
5513 return this;
5514 };
5515
5516 /**
5517 * Slices this ByteBuffer by creating a cloned instance with `offset = begin` and `limit = end`.
5518 * @param {number=} begin Begin offset, defaults to {@link ByteBuffer#offset}.
5519 * @param {number=} end End offset, defaults to {@link ByteBuffer#limit}.
5520 * @returns {!ByteBuffer} Clone of this ByteBuffer with slicing applied, backed by the same {@link ByteBuffer#buffer}
5521 * @expose
5522 */
5523 ByteBufferPrototype.slice = function(begin, end) {
5524 if (typeof begin === 'undefined') begin = this.offset;
5525 if (typeof end === 'undefined') end = this.limit;
5526 if (!this.noAssert) {
5527 if (typeof begin !== 'number' || begin % 1 !== 0)
5528 throw TypeError("Illegal begin: Not an integer");
5529 begin >>>= 0;
5530 if (typeof end !== 'number' || end % 1 !== 0)
5531 throw TypeError("Illegal end: Not an integer");
5532 end >>>= 0;
5533 if (begin < 0 || begin > end || end > this.buffer.byteLength)
5534 throw RangeError("Illegal range: 0 <= "+begin+" <= "+end+" <= "+this.buffer.byteLength);
5535 }
5536 var bb = this.clone();
5537 bb.offset = begin;
5538 bb.limit = end;
5539 return bb;
5540 };
5541 /**
5542 * Returns a copy of the backing buffer that contains this ByteBuffer's contents. Contents are the bytes between
5543 * {@link ByteBuffer#offset} and {@link ByteBuffer#limit}.
5544 * @param {boolean=} forceCopy If `true` returns a copy, otherwise returns a view referencing the same memory if
5545 * possible. Defaults to `false`
5546 * @returns {!ArrayBuffer} Contents as an ArrayBuffer
5547 * @expose
5548 */
5549 ByteBufferPrototype.toBuffer = function(forceCopy) {
5550 var offset = this.offset,
5551 limit = this.limit;
5552 if (!this.noAssert) {
5553 if (typeof offset !== 'number' || offset % 1 !== 0)
5554 throw TypeError("Illegal offset: Not an integer");
5555 offset >>>= 0;
5556 if (typeof limit !== 'number' || limit % 1 !== 0)
5557 throw TypeError("Illegal limit: Not an integer");
5558 limit >>>= 0;
5559 if (offset < 0 || offset > limit || limit > this.buffer.byteLength)
5560 throw RangeError("Illegal range: 0 <= "+offset+" <= "+limit+" <= "+this.buffer.byteLength);
5561 }
5562 // NOTE: It's not possible to have another ArrayBuffer reference the same memory as the backing buffer. This is
5563 // possible with Uint8Array#subarray only, but we have to return an ArrayBuffer by contract. So:
5564 if (!forceCopy && offset === 0 && limit === this.buffer.byteLength)
5565 return this.buffer;
5566 if (offset === limit)
5567 return EMPTY_BUFFER;
5568 var buffer = new ArrayBuffer(limit - offset);
5569 new Uint8Array(buffer).set(new Uint8Array(this.buffer).subarray(offset, limit), 0);
5570 return buffer;
5571 };
5572
5573 /**
5574 * Returns a raw buffer compacted to contain this ByteBuffer's contents. Contents are the bytes between
5575 * {@link ByteBuffer#offset} and {@link ByteBuffer#limit}. This is an alias of {@link ByteBuffer#toBuffer}.
5576 * @function
5577 * @param {boolean=} forceCopy If `true` returns a copy, otherwise returns a view referencing the same memory.
5578 * Defaults to `false`
5579 * @returns {!ArrayBuffer} Contents as an ArrayBuffer
5580 * @expose
5581 */
5582 ByteBufferPrototype.toArrayBuffer = ByteBufferPrototype.toBuffer;
5583
5584 /**
5585 * Converts the ByteBuffer's contents to a string.
5586 * @param {string=} encoding Output encoding. Returns an informative string representation if omitted but also allows
5587 * direct conversion to "utf8", "hex", "base64" and "binary" encoding. "debug" returns a hex representation with
5588 * highlighted offsets.
5589 * @param {number=} begin Offset to begin at, defaults to {@link ByteBuffer#offset}
5590 * @param {number=} end Offset to end at, defaults to {@link ByteBuffer#limit}
5591 * @returns {string} String representation
5592 * @throws {Error} If `encoding` is invalid
5593 * @expose
5594 */
5595 ByteBufferPrototype.toString = function(encoding, begin, end) {
5596 if (typeof encoding === 'undefined')
5597 return "ByteBufferAB(offset="+this.offset+",markedOffset="+this.markedOffset+",limit="+this.limit+",capacity="+this.capacity()+")";
5598 if (typeof encoding === 'number')
5599 encoding = "utf8",
5600 begin = encoding,
5601 end = begin;
5602 switch (encoding) {
5603 case "utf8":
5604 return this.toUTF8(begin, end);
5605 case "base64":
5606 return this.toBase64(begin, end);
5607 case "hex":
5608 return this.toHex(begin, end);
5609 case "binary":
5610 return this.toBinary(begin, end);
5611 case "debug":
5612 return this.toDebug();
5613 case "columns":
5614 return this.toColumns();
5615 default:
5616 throw Error("Unsupported encoding: "+encoding);
5617 }
5618 };
5619
5620 // lxiv-embeddable
5621
5622 /**
5623 * lxiv-embeddable (c) 2014 Daniel Wirtz <dcode@dcode.io>
5624 * Released under the Apache License, Version 2.0
5625 * see: https://github.com/dcodeIO/lxiv for details
5626 */
5627 var lxiv = function() {
5628
5629 /**
5630 * lxiv namespace.
5631 * @type {!Object.<string,*>}
5632 * @exports lxiv
5633 */
5634 var lxiv = {};
5635
5636 /**
5637 * Character codes for output.
5638 * @type {!Array.<number>}
5639 * @inner
5640 */
5641 var aout = [
5642 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80,
5643 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 97, 98, 99, 100, 101, 102,
5644 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118,
5645 119, 120, 121, 122, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 43, 47
5646 ];
5647
5648 /**
5649 * Character codes for input.
5650 * @type {!Array.<number>}
5651 * @inner
5652 */
5653 var ain = [];
5654 for (var i=0, k=aout.length; i<k; ++i)
5655 ain[aout[i]] = i;
5656
5657 /**
5658 * Encodes bytes to base64 char codes.
5659 * @param {!function():number|null} src Bytes source as a function returning the next byte respectively `null` if
5660 * there are no more bytes left.
5661 * @param {!function(number)} dst Characters destination as a function successively called with each encoded char
5662 * code.
5663 */
5664 lxiv.encode = function(src, dst) {
5665 var b, t;
5666 while ((b = src()) !== null) {
5667 dst(aout[(b>>2)&0x3f]);
5668 t = (b&0x3)<<4;
5669 if ((b = src()) !== null) {
5670 t |= (b>>4)&0xf;
5671 dst(aout[(t|((b>>4)&0xf))&0x3f]);
5672 t = (b&0xf)<<2;
5673 if ((b = src()) !== null)
5674 dst(aout[(t|((b>>6)&0x3))&0x3f]),
5675 dst(aout[b&0x3f]);
5676 else
5677 dst(aout[t&0x3f]),
5678 dst(61);
5679 } else
5680 dst(aout[t&0x3f]),
5681 dst(61),
5682 dst(61);
5683 }
5684 };
5685
5686 /**
5687 * Decodes base64 char codes to bytes.
5688 * @param {!function():number|null} src Characters source as a function returning the next char code respectively
5689 * `null` if there are no more characters left.
5690 * @param {!function(number)} dst Bytes destination as a function successively called with the next byte.
5691 * @throws {Error} If a character code is invalid
5692 */
5693 lxiv.decode = function(src, dst) {
5694 var c, t1, t2;
5695 function fail(c) {
5696 throw Error("Illegal character code: "+c);
5697 }
5698 while ((c = src()) !== null) {
5699 t1 = ain[c];
5700 if (typeof t1 === 'undefined') fail(c);
5701 if ((c = src()) !== null) {
5702 t2 = ain[c];
5703 if (typeof t2 === 'undefined') fail(c);
5704 dst((t1<<2)>>>0|(t2&0x30)>>4);
5705 if ((c = src()) !== null) {
5706 t1 = ain[c];
5707 if (typeof t1 === 'undefined')
5708 if (c === 61) break; else fail(c);
5709 dst(((t2&0xf)<<4)>>>0|(t1&0x3c)>>2);
5710 if ((c = src()) !== null) {
5711 t2 = ain[c];
5712 if (typeof t2 === 'undefined')
5713 if (c === 61) break; else fail(c);
5714 dst(((t1&0x3)<<6)>>>0|t2);
5715 }
5716 }
5717 }
5718 }
5719 };
5720
5721 /**
5722 * Tests if a string is valid base64.
5723 * @param {string} str String to test
5724 * @returns {boolean} `true` if valid, otherwise `false`
5725 */
5726 lxiv.test = function(str) {
5727 return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(str);
5728 };
5729
5730 return lxiv;
5731 }();
5732
5733 // encodings/base64
5734
5735 /**
5736 * Encodes this ByteBuffer's contents to a base64 encoded string.
5737 * @param {number=} begin Offset to begin at, defaults to {@link ByteBuffer#offset}.
5738 * @param {number=} end Offset to end at, defaults to {@link ByteBuffer#limit}.
5739 * @returns {string} Base64 encoded string
5740 * @throws {RangeError} If `begin` or `end` is out of bounds
5741 * @expose
5742 */
5743 ByteBufferPrototype.toBase64 = function(begin, end) {
5744 if (typeof begin === 'undefined')
5745 begin = this.offset;
5746 if (typeof end === 'undefined')
5747 end = this.limit;
5748 begin = begin | 0; end = end | 0;
5749 if (begin < 0 || end > this.capacity || begin > end)
5750 throw RangeError("begin, end");
5751 var sd; lxiv.encode(function() {
5752 return begin < end ? this.view[begin++] : null;
5753 }.bind(this), sd = stringDestination());
5754 return sd();
5755 };
5756
5757 /**
5758 * Decodes a base64 encoded string to a ByteBuffer.
5759 * @param {string} str String to decode
5760 * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
5761 * {@link ByteBuffer.DEFAULT_ENDIAN}.
5762 * @returns {!ByteBuffer} ByteBuffer
5763 * @expose
5764 */
5765 ByteBuffer.fromBase64 = function(str, littleEndian) {
5766 if (typeof str !== 'string')
5767 throw TypeError("str");
5768 var bb = new ByteBuffer(str.length/4*3, littleEndian),
5769 i = 0;
5770 lxiv.decode(stringSource(str), function(b) {
5771 bb.view[i++] = b;
5772 });
5773 bb.limit = i;
5774 return bb;
5775 };
5776
5777 /**
5778 * Encodes a binary string to base64 like `window.btoa` does.
5779 * @param {string} str Binary string
5780 * @returns {string} Base64 encoded string
5781 * @see https://developer.mozilla.org/en-US/docs/Web/API/Window.btoa
5782 * @expose
5783 */
5784 ByteBuffer.btoa = function(str) {
5785 return ByteBuffer.fromBinary(str).toBase64();
5786 };
5787
5788 /**
5789 * Decodes a base64 encoded string to binary like `window.atob` does.
5790 * @param {string} b64 Base64 encoded string
5791 * @returns {string} Binary string
5792 * @see https://developer.mozilla.org/en-US/docs/Web/API/Window.atob
5793 * @expose
5794 */
5795 ByteBuffer.atob = function(b64) {
5796 return ByteBuffer.fromBase64(b64).toBinary();
5797 };
5798
5799 // encodings/binary
5800
5801 /**
5802 * Encodes this ByteBuffer to a binary encoded string, that is using only characters 0x00-0xFF as bytes.
5803 * @param {number=} begin Offset to begin at. Defaults to {@link ByteBuffer#offset}.
5804 * @param {number=} end Offset to end at. Defaults to {@link ByteBuffer#limit}.
5805 * @returns {string} Binary encoded string
5806 * @throws {RangeError} If `offset > limit`
5807 * @expose
5808 */
5809 ByteBufferPrototype.toBinary = function(begin, end) {
5810 if (typeof begin === 'undefined')
5811 begin = this.offset;
5812 if (typeof end === 'undefined')
5813 end = this.limit;
5814 begin |= 0; end |= 0;
5815 if (begin < 0 || end > this.capacity() || begin > end)
5816 throw RangeError("begin, end");
5817 if (begin === end)
5818 return "";
5819 var chars = [],
5820 parts = [];
5821 while (begin < end) {
5822 chars.push(this.view[begin++]);
5823 if (chars.length >= 1024)
5824 parts.push(String.fromCharCode.apply(String, chars)),
5825 chars = [];
5826 }
5827 return parts.join('') + String.fromCharCode.apply(String, chars);
5828 };
5829
5830 /**
5831 * Decodes a binary encoded string, that is using only characters 0x00-0xFF as bytes, to a ByteBuffer.
5832 * @param {string} str String to decode
5833 * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
5834 * {@link ByteBuffer.DEFAULT_ENDIAN}.
5835 * @returns {!ByteBuffer} ByteBuffer
5836 * @expose
5837 */
5838 ByteBuffer.fromBinary = function(str, littleEndian) {
5839 if (typeof str !== 'string')
5840 throw TypeError("str");
5841 var i = 0,
5842 k = str.length,
5843 charCode,
5844 bb = new ByteBuffer(k, littleEndian);
5845 while (i<k) {
5846 charCode = str.charCodeAt(i);
5847 if (charCode > 0xff)
5848 throw RangeError("illegal char code: "+charCode);
5849 bb.view[i++] = charCode;
5850 }
5851 bb.limit = k;
5852 return bb;
5853 };
5854
5855 // encodings/debug
5856
5857 /**
5858 * Encodes this ByteBuffer to a hex encoded string with marked offsets. Offset symbols are:
5859 * * `<` : offset,
5860 * * `'` : markedOffset,
5861 * * `>` : limit,
5862 * * `|` : offset and limit,
5863 * * `[` : offset and markedOffset,
5864 * * `]` : markedOffset and limit,
5865 * * `!` : offset, markedOffset and limit
5866 * @param {boolean=} columns If `true` returns two columns hex + ascii, defaults to `false`
5867 * @returns {string|!Array.<string>} Debug string or array of lines if `asArray = true`
5868 * @expose
5869 * @example `>00'01 02<03` contains four bytes with `limit=0, markedOffset=1, offset=3`
5870 * @example `00[01 02 03>` contains four bytes with `offset=markedOffset=1, limit=4`
5871 * @example `00|01 02 03` contains four bytes with `offset=limit=1, markedOffset=-1`
5872 * @example `|` contains zero bytes with `offset=limit=0, markedOffset=-1`
5873 */
5874 ByteBufferPrototype.toDebug = function(columns) {
5875 var i = -1,
5876 k = this.buffer.byteLength,
5877 b,
5878 hex = "",
5879 asc = "",
5880 out = "";
5881 while (i<k) {
5882 if (i !== -1) {
5883 b = this.view[i];
5884 if (b < 0x10) hex += "0"+b.toString(16).toUpperCase();
5885 else hex += b.toString(16).toUpperCase();
5886 if (columns)
5887 asc += b > 32 && b < 127 ? String.fromCharCode(b) : '.';
5888 }
5889 ++i;
5890 if (columns) {
5891 if (i > 0 && i % 16 === 0 && i !== k) {
5892 while (hex.length < 3*16+3) hex += " ";
5893 out += hex+asc+"\n";
5894 hex = asc = "";
5895 }
5896 }
5897 if (i === this.offset && i === this.limit)
5898 hex += i === this.markedOffset ? "!" : "|";
5899 else if (i === this.offset)
5900 hex += i === this.markedOffset ? "[" : "<";
5901 else if (i === this.limit)
5902 hex += i === this.markedOffset ? "]" : ">";
5903 else
5904 hex += i === this.markedOffset ? "'" : (columns || (i !== 0 && i !== k) ? " " : "");
5905 }
5906 if (columns && hex !== " ") {
5907 while (hex.length < 3*16+3)
5908 hex += " ";
5909 out += hex + asc + "\n";
5910 }
5911 return columns ? out : hex;
5912 };
5913
5914 /**
5915 * Decodes a hex encoded string with marked offsets to a ByteBuffer.
5916 * @param {string} str Debug string to decode (not be generated with `columns = true`)
5917 * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
5918 * {@link ByteBuffer.DEFAULT_ENDIAN}.
5919 * @param {boolean=} noAssert Whether to skip assertions of offsets and values. Defaults to
5920 * {@link ByteBuffer.DEFAULT_NOASSERT}.
5921 * @returns {!ByteBuffer} ByteBuffer
5922 * @expose
5923 * @see ByteBuffer#toDebug
5924 */
5925 ByteBuffer.fromDebug = function(str, littleEndian, noAssert) {
5926 var k = str.length,
5927 bb = new ByteBuffer(((k+1)/3)|0, littleEndian, noAssert);
5928 var i = 0, j = 0, ch, b,
5929 rs = false, // Require symbol next
5930 ho = false, hm = false, hl = false, // Already has offset (ho), markedOffset (hm), limit (hl)?
5931 fail = false;
5932 while (i<k) {
5933 switch (ch = str.charAt(i++)) {
5934 case '!':
5935 if (!noAssert) {
5936 if (ho || hm || hl) {
5937 fail = true;
5938 break;
5939 }
5940 ho = hm = hl = true;
5941 }
5942 bb.offset = bb.markedOffset = bb.limit = j;
5943 rs = false;
5944 break;
5945 case '|':
5946 if (!noAssert) {
5947 if (ho || hl) {
5948 fail = true;
5949 break;
5950 }
5951 ho = hl = true;
5952 }
5953 bb.offset = bb.limit = j;
5954 rs = false;
5955 break;
5956 case '[':
5957 if (!noAssert) {
5958 if (ho || hm) {
5959 fail = true;
5960 break;
5961 }
5962 ho = hm = true;
5963 }
5964 bb.offset = bb.markedOffset = j;
5965 rs = false;
5966 break;
5967 case '<':
5968 if (!noAssert) {
5969 if (ho) {
5970 fail = true;
5971 break;
5972 }
5973 ho = true;
5974 }
5975 bb.offset = j;
5976 rs = false;
5977 break;
5978 case ']':
5979 if (!noAssert) {
5980 if (hl || hm) {
5981 fail = true;
5982 break;
5983 }
5984 hl = hm = true;
5985 }
5986 bb.limit = bb.markedOffset = j;
5987 rs = false;
5988 break;
5989 case '>':
5990 if (!noAssert) {
5991 if (hl) {
5992 fail = true;
5993 break;
5994 }
5995 hl = true;
5996 }
5997 bb.limit = j;
5998 rs = false;
5999 break;
6000 case "'":
6001 if (!noAssert) {
6002 if (hm) {
6003 fail = true;
6004 break;
6005 }
6006 hm = true;
6007 }
6008 bb.markedOffset = j;
6009 rs = false;
6010 break;
6011 case ' ':
6012 rs = false;
6013 break;
6014 default:
6015 if (!noAssert) {
6016 if (rs) {
6017 fail = true;
6018 break;
6019 }
6020 }
6021 b = parseInt(ch+str.charAt(i++), 16);
6022 if (!noAssert) {
6023 if (isNaN(b) || b < 0 || b > 255)
6024 throw TypeError("Illegal str: Not a debug encoded string");
6025 }
6026 bb.view[j++] = b;
6027 rs = true;
6028 }
6029 if (fail)
6030 throw TypeError("Illegal str: Invalid symbol at "+i);
6031 }
6032 if (!noAssert) {
6033 if (!ho || !hl)
6034 throw TypeError("Illegal str: Missing offset or limit");
6035 if (j<bb.buffer.byteLength)
6036 throw TypeError("Illegal str: Not a debug encoded string (is it hex?) "+j+" < "+k);
6037 }
6038 return bb;
6039 };
6040
6041 // encodings/hex
6042
6043 /**
6044 * Encodes this ByteBuffer's contents to a hex encoded string.
6045 * @param {number=} begin Offset to begin at. Defaults to {@link ByteBuffer#offset}.
6046 * @param {number=} end Offset to end at. Defaults to {@link ByteBuffer#limit}.
6047 * @returns {string} Hex encoded string
6048 * @expose
6049 */
6050 ByteBufferPrototype.toHex = function(begin, end) {
6051 begin = typeof begin === 'undefined' ? this.offset : begin;
6052 end = typeof end === 'undefined' ? this.limit : end;
6053 if (!this.noAssert) {
6054 if (typeof begin !== 'number' || begin % 1 !== 0)
6055 throw TypeError("Illegal begin: Not an integer");
6056 begin >>>= 0;
6057 if (typeof end !== 'number' || end % 1 !== 0)
6058 throw TypeError("Illegal end: Not an integer");
6059 end >>>= 0;
6060 if (begin < 0 || begin > end || end > this.buffer.byteLength)
6061 throw RangeError("Illegal range: 0 <= "+begin+" <= "+end+" <= "+this.buffer.byteLength);
6062 }
6063 var out = new Array(end - begin),
6064 b;
6065 while (begin < end) {
6066 b = this.view[begin++];
6067 if (b < 0x10)
6068 out.push("0", b.toString(16));
6069 else out.push(b.toString(16));
6070 }
6071 return out.join('');
6072 };
6073
6074 /**
6075 * Decodes a hex encoded string to a ByteBuffer.
6076 * @param {string} str String to decode
6077 * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
6078 * {@link ByteBuffer.DEFAULT_ENDIAN}.
6079 * @param {boolean=} noAssert Whether to skip assertions of offsets and values. Defaults to
6080 * {@link ByteBuffer.DEFAULT_NOASSERT}.
6081 * @returns {!ByteBuffer} ByteBuffer
6082 * @expose
6083 */
6084 ByteBuffer.fromHex = function(str, littleEndian, noAssert) {
6085 if (!noAssert) {
6086 if (typeof str !== 'string')
6087 throw TypeError("Illegal str: Not a string");
6088 if (str.length % 2 !== 0)
6089 throw TypeError("Illegal str: Length not a multiple of 2");
6090 }
6091 var k = str.length,
6092 bb = new ByteBuffer((k / 2) | 0, littleEndian),
6093 b;
6094 for (var i=0, j=0; i<k; i+=2) {
6095 b = parseInt(str.substring(i, i+2), 16);
6096 if (!noAssert)
6097 if (!isFinite(b) || b < 0 || b > 255)
6098 throw TypeError("Illegal str: Contains non-hex characters");
6099 bb.view[j++] = b;
6100 }
6101 bb.limit = j;
6102 return bb;
6103 };
6104
6105 // utfx-embeddable
6106
6107 /**
6108 * utfx-embeddable (c) 2014 Daniel Wirtz <dcode@dcode.io>
6109 * Released under the Apache License, Version 2.0
6110 * see: https://github.com/dcodeIO/utfx for details
6111 */
6112 var utfx = function() {
6113
6114 /**
6115 * utfx namespace.
6116 * @inner
6117 * @type {!Object.<string,*>}
6118 */
6119 var utfx = {};
6120
6121 /**
6122 * Maximum valid code point.
6123 * @type {number}
6124 * @const
6125 */
6126 utfx.MAX_CODEPOINT = 0x10FFFF;
6127
6128 /**
6129 * Encodes UTF8 code points to UTF8 bytes.
6130 * @param {(!function():number|null) | number} src Code points source, either as a function returning the next code point
6131 * respectively `null` if there are no more code points left or a single numeric code point.
6132 * @param {!function(number)} dst Bytes destination as a function successively called with the next byte
6133 */
6134 utfx.encodeUTF8 = function(src, dst) {
6135 var cp = null;
6136 if (typeof src === 'number')
6137 cp = src,
6138 src = function() { return null; };
6139 while (cp !== null || (cp = src()) !== null) {
6140 if (cp < 0x80)
6141 dst(cp&0x7F);
6142 else if (cp < 0x800)
6143 dst(((cp>>6)&0x1F)|0xC0),
6144 dst((cp&0x3F)|0x80);
6145 else if (cp < 0x10000)
6146 dst(((cp>>12)&0x0F)|0xE0),
6147 dst(((cp>>6)&0x3F)|0x80),
6148 dst((cp&0x3F)|0x80);
6149 else
6150 dst(((cp>>18)&0x07)|0xF0),
6151 dst(((cp>>12)&0x3F)|0x80),
6152 dst(((cp>>6)&0x3F)|0x80),
6153 dst((cp&0x3F)|0x80);
6154 cp = null;
6155 }
6156 };
6157
6158 /**
6159 * Decodes UTF8 bytes to UTF8 code points.
6160 * @param {!function():number|null} src Bytes source as a function returning the next byte respectively `null` if there
6161 * are no more bytes left.
6162 * @param {!function(number)} dst Code points destination as a function successively called with each decoded code point.
6163 * @throws {RangeError} If a starting byte is invalid in UTF8
6164 * @throws {Error} If the last sequence is truncated. Has an array property `bytes` holding the
6165 * remaining bytes.
6166 */
6167 utfx.decodeUTF8 = function(src, dst) {
6168 var a, b, c, d, fail = function(b) {
6169 b = b.slice(0, b.indexOf(null));
6170 var err = Error(b.toString());
6171 err.name = "TruncatedError";
6172 err['bytes'] = b;
6173 throw err;
6174 };
6175 while ((a = src()) !== null) {
6176 if ((a&0x80) === 0)
6177 dst(a);
6178 else if ((a&0xE0) === 0xC0)
6179 ((b = src()) === null) && fail([a, b]),
6180 dst(((a&0x1F)<<6) | (b&0x3F));
6181 else if ((a&0xF0) === 0xE0)
6182 ((b=src()) === null || (c=src()) === null) && fail([a, b, c]),
6183 dst(((a&0x0F)<<12) | ((b&0x3F)<<6) | (c&0x3F));
6184 else if ((a&0xF8) === 0xF0)
6185 ((b=src()) === null || (c=src()) === null || (d=src()) === null) && fail([a, b, c ,d]),
6186 dst(((a&0x07)<<18) | ((b&0x3F)<<12) | ((c&0x3F)<<6) | (d&0x3F));
6187 else throw RangeError("Illegal starting byte: "+a);
6188 }
6189 };
6190
6191 /**
6192 * Converts UTF16 characters to UTF8 code points.
6193 * @param {!function():number|null} src Characters source as a function returning the next char code respectively
6194 * `null` if there are no more characters left.
6195 * @param {!function(number)} dst Code points destination as a function successively called with each converted code
6196 * point.
6197 */
6198 utfx.UTF16toUTF8 = function(src, dst) {
6199 var c1, c2 = null;
6200 while (true) {
6201 if ((c1 = c2 !== null ? c2 : src()) === null)
6202 break;
6203 if (c1 >= 0xD800 && c1 <= 0xDFFF) {
6204 if ((c2 = src()) !== null) {
6205 if (c2 >= 0xDC00 && c2 <= 0xDFFF) {
6206 dst((c1-0xD800)*0x400+c2-0xDC00+0x10000);
6207 c2 = null; continue;
6208 }
6209 }
6210 }
6211 dst(c1);
6212 }
6213 if (c2 !== null) dst(c2);
6214 };
6215
6216 /**
6217 * Converts UTF8 code points to UTF16 characters.
6218 * @param {(!function():number|null) | number} src Code points source, either as a function returning the next code point
6219 * respectively `null` if there are no more code points left or a single numeric code point.
6220 * @param {!function(number)} dst Characters destination as a function successively called with each converted char code.
6221 * @throws {RangeError} If a code point is out of range
6222 */
6223 utfx.UTF8toUTF16 = function(src, dst) {
6224 var cp = null;
6225 if (typeof src === 'number')
6226 cp = src, src = function() { return null; };
6227 while (cp !== null || (cp = src()) !== null) {
6228 if (cp <= 0xFFFF)
6229 dst(cp);
6230 else
6231 cp -= 0x10000,
6232 dst((cp>>10)+0xD800),
6233 dst((cp%0x400)+0xDC00);
6234 cp = null;
6235 }
6236 };
6237
6238 /**
6239 * Converts and encodes UTF16 characters to UTF8 bytes.
6240 * @param {!function():number|null} src Characters source as a function returning the next char code respectively `null`
6241 * if there are no more characters left.
6242 * @param {!function(number)} dst Bytes destination as a function successively called with the next byte.
6243 */
6244 utfx.encodeUTF16toUTF8 = function(src, dst) {
6245 utfx.UTF16toUTF8(src, function(cp) {
6246 utfx.encodeUTF8(cp, dst);
6247 });
6248 };
6249
6250 /**
6251 * Decodes and converts UTF8 bytes to UTF16 characters.
6252 * @param {!function():number|null} src Bytes source as a function returning the next byte respectively `null` if there
6253 * are no more bytes left.
6254 * @param {!function(number)} dst Characters destination as a function successively called with each converted char code.
6255 * @throws {RangeError} If a starting byte is invalid in UTF8
6256 * @throws {Error} If the last sequence is truncated. Has an array property `bytes` holding the remaining bytes.
6257 */
6258 utfx.decodeUTF8toUTF16 = function(src, dst) {
6259 utfx.decodeUTF8(src, function(cp) {
6260 utfx.UTF8toUTF16(cp, dst);
6261 });
6262 };
6263
6264 /**
6265 * Calculates the byte length of an UTF8 code point.
6266 * @param {number} cp UTF8 code point
6267 * @returns {number} Byte length
6268 */
6269 utfx.calculateCodePoint = function(cp) {
6270 return (cp < 0x80) ? 1 : (cp < 0x800) ? 2 : (cp < 0x10000) ? 3 : 4;
6271 };
6272
6273 /**
6274 * Calculates the number of UTF8 bytes required to store UTF8 code points.
6275 * @param {(!function():number|null)} src Code points source as a function returning the next code point respectively
6276 * `null` if there are no more code points left.
6277 * @returns {number} The number of UTF8 bytes required
6278 */
6279 utfx.calculateUTF8 = function(src) {
6280 var cp, l=0;
6281 while ((cp = src()) !== null)
6282 l += (cp < 0x80) ? 1 : (cp < 0x800) ? 2 : (cp < 0x10000) ? 3 : 4;
6283 return l;
6284 };
6285
6286 /**
6287 * Calculates the number of UTF8 code points respectively UTF8 bytes required to store UTF16 char codes.
6288 * @param {(!function():number|null)} src Characters source as a function returning the next char code respectively
6289 * `null` if there are no more characters left.
6290 * @returns {!Array.<number>} The number of UTF8 code points at index 0 and the number of UTF8 bytes required at index 1.
6291 */
6292 utfx.calculateUTF16asUTF8 = function(src) {
6293 var n=0, l=0;
6294 utfx.UTF16toUTF8(src, function(cp) {
6295 ++n; l += (cp < 0x80) ? 1 : (cp < 0x800) ? 2 : (cp < 0x10000) ? 3 : 4;
6296 });
6297 return [n,l];
6298 };
6299
6300 return utfx;
6301 }();
6302
6303 // encodings/utf8
6304
6305 /**
6306 * Encodes this ByteBuffer's contents between {@link ByteBuffer#offset} and {@link ByteBuffer#limit} to an UTF8 encoded
6307 * string.
6308 * @returns {string} Hex encoded string
6309 * @throws {RangeError} If `offset > limit`
6310 * @expose
6311 */
6312 ByteBufferPrototype.toUTF8 = function(begin, end) {
6313 if (typeof begin === 'undefined') begin = this.offset;
6314 if (typeof end === 'undefined') end = this.limit;
6315 if (!this.noAssert) {
6316 if (typeof begin !== 'number' || begin % 1 !== 0)
6317 throw TypeError("Illegal begin: Not an integer");
6318 begin >>>= 0;
6319 if (typeof end !== 'number' || end % 1 !== 0)
6320 throw TypeError("Illegal end: Not an integer");
6321 end >>>= 0;
6322 if (begin < 0 || begin > end || end > this.buffer.byteLength)
6323 throw RangeError("Illegal range: 0 <= "+begin+" <= "+end+" <= "+this.buffer.byteLength);
6324 }
6325 var sd; try {
6326 utfx.decodeUTF8toUTF16(function() {
6327 return begin < end ? this.view[begin++] : null;
6328 }.bind(this), sd = stringDestination());
6329 } catch (e) {
6330 if (begin !== end)
6331 throw RangeError("Illegal range: Truncated data, "+begin+" != "+end);
6332 }
6333 return sd();
6334 };
6335
6336 /**
6337 * Decodes an UTF8 encoded string to a ByteBuffer.
6338 * @param {string} str String to decode
6339 * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
6340 * {@link ByteBuffer.DEFAULT_ENDIAN}.
6341 * @param {boolean=} noAssert Whether to skip assertions of offsets and values. Defaults to
6342 * {@link ByteBuffer.DEFAULT_NOASSERT}.
6343 * @returns {!ByteBuffer} ByteBuffer
6344 * @expose
6345 */
6346 ByteBuffer.fromUTF8 = function(str, littleEndian, noAssert) {
6347 if (!noAssert)
6348 if (typeof str !== 'string')
6349 throw TypeError("Illegal str: Not a string");
6350 var bb = new ByteBuffer(utfx.calculateUTF16asUTF8(stringSource(str), true)[1], littleEndian, noAssert),
6351 i = 0;
6352 utfx.encodeUTF16toUTF8(stringSource(str), function(b) {
6353 bb.view[i++] = b;
6354 });
6355 bb.limit = i;
6356 return bb;
6357 };
6358
6359 return ByteBuffer;
6360 });
6361 });
6362
6363 var require$$2 = {};
6364
6365 var protobufLight = createCommonjsModule(function (module) {
6366 /*
6367 Copyright 2013 Daniel Wirtz <dcode@dcode.io>
6368
6369 Licensed under the Apache License, Version 2.0 (the "License");
6370 you may not use this file except in compliance with the License.
6371 You may obtain a copy of the License at
6372
6373 http://www.apache.org/licenses/LICENSE-2.0
6374
6375 Unless required by applicable law or agreed to in writing, software
6376 distributed under the License is distributed on an "AS IS" BASIS,
6377 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
6378 See the License for the specific language governing permissions and
6379 limitations under the License.
6380 */
6381
6382 /**
6383 * @license protobuf.js (c) 2013 Daniel Wirtz <dcode@dcode.io>
6384 * Released under the Apache License, Version 2.0
6385 * see: https://github.com/dcodeIO/protobuf.js for details
6386 */
6387 (function(global, factory) {
6388
6389 /* AMD */ if (typeof commonjsRequire === "function" && 'object' === "object" && module && module["exports"])
6390 module["exports"] = factory(bytebuffer, true);
6391 /* Global */ else
6392 (global["dcodeIO"] = global["dcodeIO"] || {})["ProtoBuf"] = factory(global["dcodeIO"]["ByteBuffer"]);
6393
6394 })(commonjsGlobal, function(ByteBuffer, isCommonJS) {
6395
6396 /**
6397 * The ProtoBuf namespace.
6398 * @exports ProtoBuf
6399 * @namespace
6400 * @expose
6401 */
6402 var ProtoBuf = {};
6403
6404 /**
6405 * @type {!function(new: ByteBuffer, ...[*])}
6406 * @expose
6407 */
6408 ProtoBuf.ByteBuffer = ByteBuffer;
6409
6410 /**
6411 * @type {?function(new: Long, ...[*])}
6412 * @expose
6413 */
6414 ProtoBuf.Long = ByteBuffer.Long || null;
6415
6416 /**
6417 * ProtoBuf.js version.
6418 * @type {string}
6419 * @const
6420 * @expose
6421 */
6422 ProtoBuf.VERSION = "5.0.3";
6423
6424 /**
6425 * Wire types.
6426 * @type {Object.<string,number>}
6427 * @const
6428 * @expose
6429 */
6430 ProtoBuf.WIRE_TYPES = {};
6431
6432 /**
6433 * Varint wire type.
6434 * @type {number}
6435 * @expose
6436 */
6437 ProtoBuf.WIRE_TYPES.VARINT = 0;
6438
6439 /**
6440 * Fixed 64 bits wire type.
6441 * @type {number}
6442 * @const
6443 * @expose
6444 */
6445 ProtoBuf.WIRE_TYPES.BITS64 = 1;
6446
6447 /**
6448 * Length delimited wire type.
6449 * @type {number}
6450 * @const
6451 * @expose
6452 */
6453 ProtoBuf.WIRE_TYPES.LDELIM = 2;
6454
6455 /**
6456 * Start group wire type.
6457 * @type {number}
6458 * @const
6459 * @expose
6460 */
6461 ProtoBuf.WIRE_TYPES.STARTGROUP = 3;
6462
6463 /**
6464 * End group wire type.
6465 * @type {number}
6466 * @const
6467 * @expose
6468 */
6469 ProtoBuf.WIRE_TYPES.ENDGROUP = 4;
6470
6471 /**
6472 * Fixed 32 bits wire type.
6473 * @type {number}
6474 * @const
6475 * @expose
6476 */
6477 ProtoBuf.WIRE_TYPES.BITS32 = 5;
6478
6479 /**
6480 * Packable wire types.
6481 * @type {!Array.<number>}
6482 * @const
6483 * @expose
6484 */
6485 ProtoBuf.PACKABLE_WIRE_TYPES = [
6486 ProtoBuf.WIRE_TYPES.VARINT,
6487 ProtoBuf.WIRE_TYPES.BITS64,
6488 ProtoBuf.WIRE_TYPES.BITS32
6489 ];
6490
6491 /**
6492 * Types.
6493 * @dict
6494 * @type {!Object.<string,{name: string, wireType: number, defaultValue: *}>}
6495 * @const
6496 * @expose
6497 */
6498 ProtoBuf.TYPES = {
6499 // According to the protobuf spec.
6500 "int32": {
6501 name: "int32",
6502 wireType: ProtoBuf.WIRE_TYPES.VARINT,
6503 defaultValue: 0
6504 },
6505 "uint32": {
6506 name: "uint32",
6507 wireType: ProtoBuf.WIRE_TYPES.VARINT,
6508 defaultValue: 0
6509 },
6510 "sint32": {
6511 name: "sint32",
6512 wireType: ProtoBuf.WIRE_TYPES.VARINT,
6513 defaultValue: 0
6514 },
6515 "int64": {
6516 name: "int64",
6517 wireType: ProtoBuf.WIRE_TYPES.VARINT,
6518 defaultValue: ProtoBuf.Long ? ProtoBuf.Long.ZERO : undefined
6519 },
6520 "uint64": {
6521 name: "uint64",
6522 wireType: ProtoBuf.WIRE_TYPES.VARINT,
6523 defaultValue: ProtoBuf.Long ? ProtoBuf.Long.UZERO : undefined
6524 },
6525 "sint64": {
6526 name: "sint64",
6527 wireType: ProtoBuf.WIRE_TYPES.VARINT,
6528 defaultValue: ProtoBuf.Long ? ProtoBuf.Long.ZERO : undefined
6529 },
6530 "bool": {
6531 name: "bool",
6532 wireType: ProtoBuf.WIRE_TYPES.VARINT,
6533 defaultValue: false
6534 },
6535 "double": {
6536 name: "double",
6537 wireType: ProtoBuf.WIRE_TYPES.BITS64,
6538 defaultValue: 0
6539 },
6540 "string": {
6541 name: "string",
6542 wireType: ProtoBuf.WIRE_TYPES.LDELIM,
6543 defaultValue: ""
6544 },
6545 "bytes": {
6546 name: "bytes",
6547 wireType: ProtoBuf.WIRE_TYPES.LDELIM,
6548 defaultValue: null // overridden in the code, must be a unique instance
6549 },
6550 "fixed32": {
6551 name: "fixed32",
6552 wireType: ProtoBuf.WIRE_TYPES.BITS32,
6553 defaultValue: 0
6554 },
6555 "sfixed32": {
6556 name: "sfixed32",
6557 wireType: ProtoBuf.WIRE_TYPES.BITS32,
6558 defaultValue: 0
6559 },
6560 "fixed64": {
6561 name: "fixed64",
6562 wireType: ProtoBuf.WIRE_TYPES.BITS64,
6563 defaultValue: ProtoBuf.Long ? ProtoBuf.Long.UZERO : undefined
6564 },
6565 "sfixed64": {
6566 name: "sfixed64",
6567 wireType: ProtoBuf.WIRE_TYPES.BITS64,
6568 defaultValue: ProtoBuf.Long ? ProtoBuf.Long.ZERO : undefined
6569 },
6570 "float": {
6571 name: "float",
6572 wireType: ProtoBuf.WIRE_TYPES.BITS32,
6573 defaultValue: 0
6574 },
6575 "enum": {
6576 name: "enum",
6577 wireType: ProtoBuf.WIRE_TYPES.VARINT,
6578 defaultValue: 0
6579 },
6580 "message": {
6581 name: "message",
6582 wireType: ProtoBuf.WIRE_TYPES.LDELIM,
6583 defaultValue: null
6584 },
6585 "group": {
6586 name: "group",
6587 wireType: ProtoBuf.WIRE_TYPES.STARTGROUP,
6588 defaultValue: null
6589 }
6590 };
6591
6592 /**
6593 * Valid map key types.
6594 * @type {!Array.<!Object.<string,{name: string, wireType: number, defaultValue: *}>>}
6595 * @const
6596 * @expose
6597 */
6598 ProtoBuf.MAP_KEY_TYPES = [
6599 ProtoBuf.TYPES["int32"],
6600 ProtoBuf.TYPES["sint32"],
6601 ProtoBuf.TYPES["sfixed32"],
6602 ProtoBuf.TYPES["uint32"],
6603 ProtoBuf.TYPES["fixed32"],
6604 ProtoBuf.TYPES["int64"],
6605 ProtoBuf.TYPES["sint64"],
6606 ProtoBuf.TYPES["sfixed64"],
6607 ProtoBuf.TYPES["uint64"],
6608 ProtoBuf.TYPES["fixed64"],
6609 ProtoBuf.TYPES["bool"],
6610 ProtoBuf.TYPES["string"],
6611 ProtoBuf.TYPES["bytes"]
6612 ];
6613
6614 /**
6615 * Minimum field id.
6616 * @type {number}
6617 * @const
6618 * @expose
6619 */
6620 ProtoBuf.ID_MIN = 1;
6621
6622 /**
6623 * Maximum field id.
6624 * @type {number}
6625 * @const
6626 * @expose
6627 */
6628 ProtoBuf.ID_MAX = 0x1FFFFFFF;
6629
6630 /**
6631 * If set to `true`, field names will be converted from underscore notation to camel case. Defaults to `false`.
6632 * Must be set prior to parsing.
6633 * @type {boolean}
6634 * @expose
6635 */
6636 ProtoBuf.convertFieldsToCamelCase = false;
6637
6638 /**
6639 * By default, messages are populated with (setX, set_x) accessors for each field. This can be disabled by
6640 * setting this to `false` prior to building messages.
6641 * @type {boolean}
6642 * @expose
6643 */
6644 ProtoBuf.populateAccessors = true;
6645
6646 /**
6647 * By default, messages are populated with default values if a field is not present on the wire. To disable
6648 * this behavior, set this setting to `false`.
6649 * @type {boolean}
6650 * @expose
6651 */
6652 ProtoBuf.populateDefaults = true;
6653
6654 /**
6655 * @alias ProtoBuf.Util
6656 * @expose
6657 */
6658 ProtoBuf.Util = (function() {
6659
6660 /**
6661 * ProtoBuf utilities.
6662 * @exports ProtoBuf.Util
6663 * @namespace
6664 */
6665 var Util = {};
6666
6667 /**
6668 * Flag if running in node or not.
6669 * @type {boolean}
6670 * @const
6671 * @expose
6672 */
6673 Util.IS_NODE = !!(
6674 typeof process === 'object' && process+'' === '[object process]' && !process['browser']
6675 );
6676
6677 /**
6678 * Constructs a XMLHttpRequest object.
6679 * @return {XMLHttpRequest}
6680 * @throws {Error} If XMLHttpRequest is not supported
6681 * @expose
6682 */
6683 Util.XHR = function() {
6684 // No dependencies please, ref: http://www.quirksmode.org/js/xmlhttp.html
6685 var XMLHttpFactories = [
6686 function () {return new XMLHttpRequest()},
6687 function () {return new ActiveXObject("Msxml2.XMLHTTP")},
6688 function () {return new ActiveXObject("Msxml3.XMLHTTP")},
6689 function () {return new ActiveXObject("Microsoft.XMLHTTP")}
6690 ];
6691 /** @type {?XMLHttpRequest} */
6692 var xhr = null;
6693 for (var i=0;i<XMLHttpFactories.length;i++) {
6694 try { xhr = XMLHttpFactories[i](); }
6695 catch (e) { continue; }
6696 break;
6697 }
6698 if (!xhr)
6699 throw Error("XMLHttpRequest is not supported");
6700 return xhr;
6701 };
6702
6703 /**
6704 * Fetches a resource.
6705 * @param {string} path Resource path
6706 * @param {function(?string)=} callback Callback receiving the resource's contents. If omitted the resource will
6707 * be fetched synchronously. If the request failed, contents will be null.
6708 * @return {?string|undefined} Resource contents if callback is omitted (null if the request failed), else undefined.
6709 * @expose
6710 */
6711 Util.fetch = function(path, callback) {
6712 if (callback && typeof callback != 'function')
6713 callback = null;
6714 if (Util.IS_NODE) {
6715 var fs = require$$2;
6716 if (callback) {
6717 fs.readFile(path, function(err, data) {
6718 if (err)
6719 callback(null);
6720 else
6721 callback(""+data);
6722 });
6723 } else
6724 try {
6725 return fs.readFileSync(path);
6726 } catch (e) {
6727 return null;
6728 }
6729 } else {
6730 var xhr = Util.XHR();
6731 xhr.open('GET', path, callback ? true : false);
6732 // xhr.setRequestHeader('User-Agent', 'XMLHTTP/1.0');
6733 xhr.setRequestHeader('Accept', 'text/plain');
6734 if (typeof xhr.overrideMimeType === 'function') xhr.overrideMimeType('text/plain');
6735 if (callback) {
6736 xhr.onreadystatechange = function() {
6737 if (xhr.readyState != 4) return;
6738 if (/* remote */ xhr.status == 200 || /* local */ (xhr.status == 0 && typeof xhr.responseText === 'string'))
6739 callback(xhr.responseText);
6740 else
6741 callback(null);
6742 };
6743 if (xhr.readyState == 4)
6744 return;
6745 xhr.send(null);
6746 } else {
6747 xhr.send(null);
6748 if (/* remote */ xhr.status == 200 || /* local */ (xhr.status == 0 && typeof xhr.responseText === 'string'))
6749 return xhr.responseText;
6750 return null;
6751 }
6752 }
6753 };
6754
6755 /**
6756 * Converts a string to camel case.
6757 * @param {string} str
6758 * @returns {string}
6759 * @expose
6760 */
6761 Util.toCamelCase = function(str) {
6762 return str.replace(/_([a-zA-Z])/g, function ($0, $1) {
6763 return $1.toUpperCase();
6764 });
6765 };
6766
6767 return Util;
6768 })();
6769
6770 /**
6771 * Language expressions.
6772 * @type {!Object.<string,!RegExp>}
6773 * @expose
6774 */
6775 ProtoBuf.Lang = {
6776
6777 // Characters always ending a statement
6778 DELIM: /[\s\{\}=;:\[\],'"\(\)<>]/g,
6779
6780 // Field rules
6781 RULE: /^(?:required|optional|repeated|map)$/,
6782
6783 // Field types
6784 TYPE: /^(?:double|float|int32|uint32|sint32|int64|uint64|sint64|fixed32|sfixed32|fixed64|sfixed64|bool|string|bytes)$/,
6785
6786 // Names
6787 NAME: /^[a-zA-Z_][a-zA-Z_0-9]*$/,
6788
6789 // Type definitions
6790 TYPEDEF: /^[a-zA-Z][a-zA-Z_0-9]*$/,
6791
6792 // Type references
6793 TYPEREF: /^(?:\.?[a-zA-Z_][a-zA-Z_0-9]*)(?:\.[a-zA-Z_][a-zA-Z_0-9]*)*$/,
6794
6795 // Fully qualified type references
6796 FQTYPEREF: /^(?:\.[a-zA-Z_][a-zA-Z_0-9]*)+$/,
6797
6798 // All numbers
6799 NUMBER: /^-?(?:[1-9][0-9]*|0|0[xX][0-9a-fA-F]+|0[0-7]+|([0-9]*(\.[0-9]*)?([Ee][+-]?[0-9]+)?)|inf|nan)$/,
6800
6801 // Decimal numbers
6802 NUMBER_DEC: /^(?:[1-9][0-9]*|0)$/,
6803
6804 // Hexadecimal numbers
6805 NUMBER_HEX: /^0[xX][0-9a-fA-F]+$/,
6806
6807 // Octal numbers
6808 NUMBER_OCT: /^0[0-7]+$/,
6809
6810 // Floating point numbers
6811 NUMBER_FLT: /^([0-9]*(\.[0-9]*)?([Ee][+-]?[0-9]+)?|inf|nan)$/,
6812
6813 // Booleans
6814 BOOL: /^(?:true|false)$/i,
6815
6816 // Id numbers
6817 ID: /^(?:[1-9][0-9]*|0|0[xX][0-9a-fA-F]+|0[0-7]+)$/,
6818
6819 // Negative id numbers (enum values)
6820 NEGID: /^\-?(?:[1-9][0-9]*|0|0[xX][0-9a-fA-F]+|0[0-7]+)$/,
6821
6822 // Whitespaces
6823 WHITESPACE: /\s/,
6824
6825 // All strings
6826 STRING: /(?:"([^"\\]*(?:\\.[^"\\]*)*)")|(?:'([^'\\]*(?:\\.[^'\\]*)*)')/g,
6827
6828 // Double quoted strings
6829 STRING_DQ: /(?:"([^"\\]*(?:\\.[^"\\]*)*)")/g,
6830
6831 // Single quoted strings
6832 STRING_SQ: /(?:'([^'\\]*(?:\\.[^'\\]*)*)')/g
6833 };
6834
6835
6836 /**
6837 * @alias ProtoBuf.Reflect
6838 * @expose
6839 */
6840 ProtoBuf.Reflect = (function(ProtoBuf) {
6841
6842 /**
6843 * Reflection types.
6844 * @exports ProtoBuf.Reflect
6845 * @namespace
6846 */
6847 var Reflect = {};
6848
6849 /**
6850 * Constructs a Reflect base class.
6851 * @exports ProtoBuf.Reflect.T
6852 * @constructor
6853 * @abstract
6854 * @param {!ProtoBuf.Builder} builder Builder reference
6855 * @param {?ProtoBuf.Reflect.T} parent Parent object
6856 * @param {string} name Object name
6857 */
6858 var T = function(builder, parent, name) {
6859
6860 /**
6861 * Builder reference.
6862 * @type {!ProtoBuf.Builder}
6863 * @expose
6864 */
6865 this.builder = builder;
6866
6867 /**
6868 * Parent object.
6869 * @type {?ProtoBuf.Reflect.T}
6870 * @expose
6871 */
6872 this.parent = parent;
6873
6874 /**
6875 * Object name in namespace.
6876 * @type {string}
6877 * @expose
6878 */
6879 this.name = name;
6880
6881 /**
6882 * Fully qualified class name
6883 * @type {string}
6884 * @expose
6885 */
6886 this.className;
6887 };
6888
6889 /**
6890 * @alias ProtoBuf.Reflect.T.prototype
6891 * @inner
6892 */
6893 var TPrototype = T.prototype;
6894
6895 /**
6896 * Returns the fully qualified name of this object.
6897 * @returns {string} Fully qualified name as of ".PATH.TO.THIS"
6898 * @expose
6899 */
6900 TPrototype.fqn = function() {
6901 var name = this.name,
6902 ptr = this;
6903 do {
6904 ptr = ptr.parent;
6905 if (ptr == null)
6906 break;
6907 name = ptr.name+"."+name;
6908 } while (true);
6909 return name;
6910 };
6911
6912 /**
6913 * Returns a string representation of this Reflect object (its fully qualified name).
6914 * @param {boolean=} includeClass Set to true to include the class name. Defaults to false.
6915 * @return String representation
6916 * @expose
6917 */
6918 TPrototype.toString = function(includeClass) {
6919 return (includeClass ? this.className + " " : "") + this.fqn();
6920 };
6921
6922 /**
6923 * Builds this type.
6924 * @throws {Error} If this type cannot be built directly
6925 * @expose
6926 */
6927 TPrototype.build = function() {
6928 throw Error(this.toString(true)+" cannot be built directly");
6929 };
6930
6931 /**
6932 * @alias ProtoBuf.Reflect.T
6933 * @expose
6934 */
6935 Reflect.T = T;
6936
6937 /**
6938 * Constructs a new Namespace.
6939 * @exports ProtoBuf.Reflect.Namespace
6940 * @param {!ProtoBuf.Builder} builder Builder reference
6941 * @param {?ProtoBuf.Reflect.Namespace} parent Namespace parent
6942 * @param {string} name Namespace name
6943 * @param {Object.<string,*>=} options Namespace options
6944 * @param {string?} syntax The syntax level of this definition (e.g., proto3)
6945 * @constructor
6946 * @extends ProtoBuf.Reflect.T
6947 */
6948 var Namespace = function(builder, parent, name, options, syntax) {
6949 T.call(this, builder, parent, name);
6950
6951 /**
6952 * @override
6953 */
6954 this.className = "Namespace";
6955
6956 /**
6957 * Children inside the namespace.
6958 * @type {!Array.<ProtoBuf.Reflect.T>}
6959 */
6960 this.children = [];
6961
6962 /**
6963 * Options.
6964 * @type {!Object.<string, *>}
6965 */
6966 this.options = options || {};
6967
6968 /**
6969 * Syntax level (e.g., proto2 or proto3).
6970 * @type {!string}
6971 */
6972 this.syntax = syntax || "proto2";
6973 };
6974
6975 /**
6976 * @alias ProtoBuf.Reflect.Namespace.prototype
6977 * @inner
6978 */
6979 var NamespacePrototype = Namespace.prototype = Object.create(T.prototype);
6980
6981 /**
6982 * Returns an array of the namespace's children.
6983 * @param {ProtoBuf.Reflect.T=} type Filter type (returns instances of this type only). Defaults to null (all children).
6984 * @return {Array.<ProtoBuf.Reflect.T>}
6985 * @expose
6986 */
6987 NamespacePrototype.getChildren = function(type) {
6988 type = type || null;
6989 if (type == null)
6990 return this.children.slice();
6991 var children = [];
6992 for (var i=0, k=this.children.length; i<k; ++i)
6993 if (this.children[i] instanceof type)
6994 children.push(this.children[i]);
6995 return children;
6996 };
6997
6998 /**
6999 * Adds a child to the namespace.
7000 * @param {ProtoBuf.Reflect.T} child Child
7001 * @throws {Error} If the child cannot be added (duplicate)
7002 * @expose
7003 */
7004 NamespacePrototype.addChild = function(child) {
7005 var other;
7006 if (other = this.getChild(child.name)) {
7007 // Try to revert camelcase transformation on collision
7008 if (other instanceof Message.Field && other.name !== other.originalName && this.getChild(other.originalName) === null)
7009 other.name = other.originalName; // Revert previous first (effectively keeps both originals)
7010 else if (child instanceof Message.Field && child.name !== child.originalName && this.getChild(child.originalName) === null)
7011 child.name = child.originalName;
7012 else
7013 throw Error("Duplicate name in namespace "+this.toString(true)+": "+child.name);
7014 }
7015 this.children.push(child);
7016 };
7017
7018 /**
7019 * Gets a child by its name or id.
7020 * @param {string|number} nameOrId Child name or id
7021 * @return {?ProtoBuf.Reflect.T} The child or null if not found
7022 * @expose
7023 */
7024 NamespacePrototype.getChild = function(nameOrId) {
7025 var key = typeof nameOrId === 'number' ? 'id' : 'name';
7026 for (var i=0, k=this.children.length; i<k; ++i)
7027 if (this.children[i][key] === nameOrId)
7028 return this.children[i];
7029 return null;
7030 };
7031
7032 /**
7033 * Resolves a reflect object inside of this namespace.
7034 * @param {string|!Array.<string>} qn Qualified name to resolve
7035 * @param {boolean=} excludeNonNamespace Excludes non-namespace types, defaults to `false`
7036 * @return {?ProtoBuf.Reflect.Namespace} The resolved type or null if not found
7037 * @expose
7038 */
7039 NamespacePrototype.resolve = function(qn, excludeNonNamespace) {
7040 var part = typeof qn === 'string' ? qn.split(".") : qn,
7041 ptr = this,
7042 i = 0;
7043 if (part[i] === "") { // Fully qualified name, e.g. ".My.Message'
7044 while (ptr.parent !== null)
7045 ptr = ptr.parent;
7046 i++;
7047 }
7048 var child;
7049 do {
7050 do {
7051 if (!(ptr instanceof Reflect.Namespace)) {
7052 ptr = null;
7053 break;
7054 }
7055 child = ptr.getChild(part[i]);
7056 if (!child || !(child instanceof Reflect.T) || (excludeNonNamespace && !(child instanceof Reflect.Namespace))) {
7057 ptr = null;
7058 break;
7059 }
7060 ptr = child; i++;
7061 } while (i < part.length);
7062 if (ptr != null)
7063 break; // Found
7064 // Else search the parent
7065 if (this.parent !== null)
7066 return this.parent.resolve(qn, excludeNonNamespace);
7067 } while (ptr != null);
7068 return ptr;
7069 };
7070
7071 /**
7072 * Determines the shortest qualified name of the specified type, if any, relative to this namespace.
7073 * @param {!ProtoBuf.Reflect.T} t Reflection type
7074 * @returns {string} The shortest qualified name or, if there is none, the fqn
7075 * @expose
7076 */
7077 NamespacePrototype.qn = function(t) {
7078 var part = [], ptr = t;
7079 do {
7080 part.unshift(ptr.name);
7081 ptr = ptr.parent;
7082 } while (ptr !== null);
7083 for (var len=1; len <= part.length; len++) {
7084 var qn = part.slice(part.length-len);
7085 if (t === this.resolve(qn, t instanceof Reflect.Namespace))
7086 return qn.join(".");
7087 }
7088 return t.fqn();
7089 };
7090
7091 /**
7092 * Builds the namespace and returns the runtime counterpart.
7093 * @return {Object.<string,Function|Object>} Runtime namespace
7094 * @expose
7095 */
7096 NamespacePrototype.build = function() {
7097 /** @dict */
7098 var ns = {};
7099 var children = this.children;
7100 for (var i=0, k=children.length, child; i<k; ++i) {
7101 child = children[i];
7102 if (child instanceof Namespace)
7103 ns[child.name] = child.build();
7104 }
7105 if (Object.defineProperty)
7106 Object.defineProperty(ns, "$options", { "value": this.buildOpt() });
7107 return ns;
7108 };
7109
7110 /**
7111 * Builds the namespace's '$options' property.
7112 * @return {Object.<string,*>}
7113 */
7114 NamespacePrototype.buildOpt = function() {
7115 var opt = {},
7116 keys = Object.keys(this.options);
7117 for (var i=0, k=keys.length; i<k; ++i) {
7118 var key = keys[i],
7119 val = this.options[keys[i]];
7120 // TODO: Options are not resolved, yet.
7121 // if (val instanceof Namespace) {
7122 // opt[key] = val.build();
7123 // } else {
7124 opt[key] = val;
7125 // }
7126 }
7127 return opt;
7128 };
7129
7130 /**
7131 * Gets the value assigned to the option with the specified name.
7132 * @param {string=} name Returns the option value if specified, otherwise all options are returned.
7133 * @return {*|Object.<string,*>}null} Option value or NULL if there is no such option
7134 */
7135 NamespacePrototype.getOption = function(name) {
7136 if (typeof name === 'undefined')
7137 return this.options;
7138 return typeof this.options[name] !== 'undefined' ? this.options[name] : null;
7139 };
7140
7141 /**
7142 * @alias ProtoBuf.Reflect.Namespace
7143 * @expose
7144 */
7145 Reflect.Namespace = Namespace;
7146
7147 /**
7148 * Constructs a new Element implementation that checks and converts values for a
7149 * particular field type, as appropriate.
7150 *
7151 * An Element represents a single value: either the value of a singular field,
7152 * or a value contained in one entry of a repeated field or map field. This
7153 * class does not implement these higher-level concepts; it only encapsulates
7154 * the low-level typechecking and conversion.
7155 *
7156 * @exports ProtoBuf.Reflect.Element
7157 * @param {{name: string, wireType: number}} type Resolved data type
7158 * @param {ProtoBuf.Reflect.T|null} resolvedType Resolved type, if relevant
7159 * (e.g. submessage field).
7160 * @param {boolean} isMapKey Is this element a Map key? The value will be
7161 * converted to string form if so.
7162 * @param {string} syntax Syntax level of defining message type, e.g.,
7163 * proto2 or proto3.
7164 * @param {string} name Name of the field containing this element (for error
7165 * messages)
7166 * @constructor
7167 */
7168 var Element = function(type, resolvedType, isMapKey, syntax, name) {
7169
7170 /**
7171 * Element type, as a string (e.g., int32).
7172 * @type {{name: string, wireType: number}}
7173 */
7174 this.type = type;
7175
7176 /**
7177 * Element type reference to submessage or enum definition, if needed.
7178 * @type {ProtoBuf.Reflect.T|null}
7179 */
7180 this.resolvedType = resolvedType;
7181
7182 /**
7183 * Element is a map key.
7184 * @type {boolean}
7185 */
7186 this.isMapKey = isMapKey;
7187
7188 /**
7189 * Syntax level of defining message type, e.g., proto2 or proto3.
7190 * @type {string}
7191 */
7192 this.syntax = syntax;
7193
7194 /**
7195 * Name of the field containing this element (for error messages)
7196 * @type {string}
7197 */
7198 this.name = name;
7199
7200 if (isMapKey && ProtoBuf.MAP_KEY_TYPES.indexOf(type) < 0)
7201 throw Error("Invalid map key type: " + type.name);
7202 };
7203
7204 var ElementPrototype = Element.prototype;
7205
7206 /**
7207 * Obtains a (new) default value for the specified type.
7208 * @param type {string|{name: string, wireType: number}} Field type
7209 * @returns {*} Default value
7210 * @inner
7211 */
7212 function mkDefault(type) {
7213 if (typeof type === 'string')
7214 type = ProtoBuf.TYPES[type];
7215 if (typeof type.defaultValue === 'undefined')
7216 throw Error("default value for type "+type.name+" is not supported");
7217 if (type == ProtoBuf.TYPES["bytes"])
7218 return new ByteBuffer(0);
7219 return type.defaultValue;
7220 }
7221
7222 /**
7223 * Returns the default value for this field in proto3.
7224 * @function
7225 * @param type {string|{name: string, wireType: number}} the field type
7226 * @returns {*} Default value
7227 */
7228 Element.defaultFieldValue = mkDefault;
7229
7230 /**
7231 * Makes a Long from a value.
7232 * @param {{low: number, high: number, unsigned: boolean}|string|number} value Value
7233 * @param {boolean=} unsigned Whether unsigned or not, defaults to reuse it from Long-like objects or to signed for
7234 * strings and numbers
7235 * @returns {!Long}
7236 * @throws {Error} If the value cannot be converted to a Long
7237 * @inner
7238 */
7239 function mkLong(value, unsigned) {
7240 if (value && typeof value.low === 'number' && typeof value.high === 'number' && typeof value.unsigned === 'boolean'
7241 && value.low === value.low && value.high === value.high)
7242 return new ProtoBuf.Long(value.low, value.high, typeof unsigned === 'undefined' ? value.unsigned : unsigned);
7243 if (typeof value === 'string')
7244 return ProtoBuf.Long.fromString(value, unsigned || false, 10);
7245 if (typeof value === 'number')
7246 return ProtoBuf.Long.fromNumber(value, unsigned || false);
7247 throw Error("not convertible to Long");
7248 }
7249
7250 ElementPrototype.toString = function() {
7251 return (this.name || '') + (this.isMapKey ? 'map' : 'value') + ' element';
7252 };
7253
7254 /**
7255 * Checks if the given value can be set for an element of this type (singular
7256 * field or one element of a repeated field or map).
7257 * @param {*} value Value to check
7258 * @return {*} Verified, maybe adjusted, value
7259 * @throws {Error} If the value cannot be verified for this element slot
7260 * @expose
7261 */
7262 ElementPrototype.verifyValue = function(value) {
7263 var self = this;
7264 function fail(val, msg) {
7265 throw Error("Illegal value for "+self.toString(true)+" of type "+self.type.name+": "+val+" ("+msg+")");
7266 }
7267 switch (this.type) {
7268 // Signed 32bit
7269 case ProtoBuf.TYPES["int32"]:
7270 case ProtoBuf.TYPES["sint32"]:
7271 case ProtoBuf.TYPES["sfixed32"]:
7272 // Account for !NaN: value === value
7273 if (typeof value !== 'number' || (value === value && value % 1 !== 0))
7274 fail(typeof value, "not an integer");
7275 return value > 4294967295 ? value | 0 : value;
7276
7277 // Unsigned 32bit
7278 case ProtoBuf.TYPES["uint32"]:
7279 case ProtoBuf.TYPES["fixed32"]:
7280 if (typeof value !== 'number' || (value === value && value % 1 !== 0))
7281 fail(typeof value, "not an integer");
7282 return value < 0 ? value >>> 0 : value;
7283
7284 // Signed 64bit
7285 case ProtoBuf.TYPES["int64"]:
7286 case ProtoBuf.TYPES["sint64"]:
7287 case ProtoBuf.TYPES["sfixed64"]: {
7288 if (ProtoBuf.Long)
7289 try {
7290 return mkLong(value, false);
7291 } catch (e) {
7292 fail(typeof value, e.message);
7293 }
7294 else
7295 fail(typeof value, "requires Long.js");
7296 }
7297
7298 // Unsigned 64bit
7299 case ProtoBuf.TYPES["uint64"]:
7300 case ProtoBuf.TYPES["fixed64"]: {
7301 if (ProtoBuf.Long)
7302 try {
7303 return mkLong(value, true);
7304 } catch (e) {
7305 fail(typeof value, e.message);
7306 }
7307 else
7308 fail(typeof value, "requires Long.js");
7309 }
7310
7311 // Bool
7312 case ProtoBuf.TYPES["bool"]:
7313 if (typeof value !== 'boolean')
7314 fail(typeof value, "not a boolean");
7315 return value;
7316
7317 // Float
7318 case ProtoBuf.TYPES["float"]:
7319 case ProtoBuf.TYPES["double"]:
7320 if (typeof value !== 'number')
7321 fail(typeof value, "not a number");
7322 return value;
7323
7324 // Length-delimited string
7325 case ProtoBuf.TYPES["string"]:
7326 if (typeof value !== 'string' && !(value && value instanceof String))
7327 fail(typeof value, "not a string");
7328 return ""+value; // Convert String object to string
7329
7330 // Length-delimited bytes
7331 case ProtoBuf.TYPES["bytes"]:
7332 if (ByteBuffer.isByteBuffer(value))
7333 return value;
7334 return ByteBuffer.wrap(value, "base64");
7335
7336 // Constant enum value
7337 case ProtoBuf.TYPES["enum"]: {
7338 var values = this.resolvedType.getChildren(ProtoBuf.Reflect.Enum.Value);
7339 for (i=0; i<values.length; i++)
7340 if (values[i].name == value)
7341 return values[i].id;
7342 else if (values[i].id == value)
7343 return values[i].id;
7344
7345 if (this.syntax === 'proto3') {
7346 // proto3: just make sure it's an integer.
7347 if (typeof value !== 'number' || (value === value && value % 1 !== 0))
7348 fail(typeof value, "not an integer");
7349 if (value > 4294967295 || value < 0)
7350 fail(typeof value, "not in range for uint32");
7351 return value;
7352 } else {
7353 // proto2 requires enum values to be valid.
7354 fail(value, "not a valid enum value");
7355 }
7356 }
7357 // Embedded message
7358 case ProtoBuf.TYPES["group"]:
7359 case ProtoBuf.TYPES["message"]: {
7360 if (!value || typeof value !== 'object')
7361 fail(typeof value, "object expected");
7362 if (value instanceof this.resolvedType.clazz)
7363 return value;
7364 if (value instanceof ProtoBuf.Builder.Message) {
7365 // Mismatched type: Convert to object (see: https://github.com/dcodeIO/ProtoBuf.js/issues/180)
7366 var obj = {};
7367 for (var i in value)
7368 if (value.hasOwnProperty(i))
7369 obj[i] = value[i];
7370 value = obj;
7371 }
7372 // Else let's try to construct one from a key-value object
7373 return new (this.resolvedType.clazz)(value); // May throw for a hundred of reasons
7374 }
7375 }
7376
7377 // We should never end here
7378 throw Error("[INTERNAL] Illegal value for "+this.toString(true)+": "+value+" (undefined type "+this.type+")");
7379 };
7380
7381 /**
7382 * Calculates the byte length of an element on the wire.
7383 * @param {number} id Field number
7384 * @param {*} value Field value
7385 * @returns {number} Byte length
7386 * @throws {Error} If the value cannot be calculated
7387 * @expose
7388 */
7389 ElementPrototype.calculateLength = function(id, value) {
7390 if (value === null) return 0; // Nothing to encode
7391 // Tag has already been written
7392 var n;
7393 switch (this.type) {
7394 case ProtoBuf.TYPES["int32"]:
7395 return value < 0 ? ByteBuffer.calculateVarint64(value) : ByteBuffer.calculateVarint32(value);
7396 case ProtoBuf.TYPES["uint32"]:
7397 return ByteBuffer.calculateVarint32(value);
7398 case ProtoBuf.TYPES["sint32"]:
7399 return ByteBuffer.calculateVarint32(ByteBuffer.zigZagEncode32(value));
7400 case ProtoBuf.TYPES["fixed32"]:
7401 case ProtoBuf.TYPES["sfixed32"]:
7402 case ProtoBuf.TYPES["float"]:
7403 return 4;
7404 case ProtoBuf.TYPES["int64"]:
7405 case ProtoBuf.TYPES["uint64"]:
7406 return ByteBuffer.calculateVarint64(value);
7407 case ProtoBuf.TYPES["sint64"]:
7408 return ByteBuffer.calculateVarint64(ByteBuffer.zigZagEncode64(value));
7409 case ProtoBuf.TYPES["fixed64"]:
7410 case ProtoBuf.TYPES["sfixed64"]:
7411 return 8;
7412 case ProtoBuf.TYPES["bool"]:
7413 return 1;
7414 case ProtoBuf.TYPES["enum"]:
7415 return ByteBuffer.calculateVarint32(value);
7416 case ProtoBuf.TYPES["double"]:
7417 return 8;
7418 case ProtoBuf.TYPES["string"]:
7419 n = ByteBuffer.calculateUTF8Bytes(value);
7420 return ByteBuffer.calculateVarint32(n) + n;
7421 case ProtoBuf.TYPES["bytes"]:
7422 if (value.remaining() < 0)
7423 throw Error("Illegal value for "+this.toString(true)+": "+value.remaining()+" bytes remaining");
7424 return ByteBuffer.calculateVarint32(value.remaining()) + value.remaining();
7425 case ProtoBuf.TYPES["message"]:
7426 n = this.resolvedType.calculate(value);
7427 return ByteBuffer.calculateVarint32(n) + n;
7428 case ProtoBuf.TYPES["group"]:
7429 n = this.resolvedType.calculate(value);
7430 return n + ByteBuffer.calculateVarint32((id << 3) | ProtoBuf.WIRE_TYPES.ENDGROUP);
7431 }
7432 // We should never end here
7433 throw Error("[INTERNAL] Illegal value to encode in "+this.toString(true)+": "+value+" (unknown type)");
7434 };
7435
7436 /**
7437 * Encodes a value to the specified buffer. Does not encode the key.
7438 * @param {number} id Field number
7439 * @param {*} value Field value
7440 * @param {ByteBuffer} buffer ByteBuffer to encode to
7441 * @return {ByteBuffer} The ByteBuffer for chaining
7442 * @throws {Error} If the value cannot be encoded
7443 * @expose
7444 */
7445 ElementPrototype.encodeValue = function(id, value, buffer) {
7446 if (value === null) return buffer; // Nothing to encode
7447 // Tag has already been written
7448
7449 switch (this.type) {
7450 // 32bit signed varint
7451 case ProtoBuf.TYPES["int32"]:
7452 // "If you use int32 or int64 as the type for a negative number, the resulting varint is always ten bytes
7453 // long – it is, effectively, treated like a very large unsigned integer." (see #122)
7454 if (value < 0)
7455 buffer.writeVarint64(value);
7456 else
7457 buffer.writeVarint32(value);
7458 break;
7459
7460 // 32bit unsigned varint
7461 case ProtoBuf.TYPES["uint32"]:
7462 buffer.writeVarint32(value);
7463 break;
7464
7465 // 32bit varint zig-zag
7466 case ProtoBuf.TYPES["sint32"]:
7467 buffer.writeVarint32ZigZag(value);
7468 break;
7469
7470 // Fixed unsigned 32bit
7471 case ProtoBuf.TYPES["fixed32"]:
7472 buffer.writeUint32(value);
7473 break;
7474
7475 // Fixed signed 32bit
7476 case ProtoBuf.TYPES["sfixed32"]:
7477 buffer.writeInt32(value);
7478 break;
7479
7480 // 64bit varint as-is
7481 case ProtoBuf.TYPES["int64"]:
7482 case ProtoBuf.TYPES["uint64"]:
7483 buffer.writeVarint64(value); // throws
7484 break;
7485
7486 // 64bit varint zig-zag
7487 case ProtoBuf.TYPES["sint64"]:
7488 buffer.writeVarint64ZigZag(value); // throws
7489 break;
7490
7491 // Fixed unsigned 64bit
7492 case ProtoBuf.TYPES["fixed64"]:
7493 buffer.writeUint64(value); // throws
7494 break;
7495
7496 // Fixed signed 64bit
7497 case ProtoBuf.TYPES["sfixed64"]:
7498 buffer.writeInt64(value); // throws
7499 break;
7500
7501 // Bool
7502 case ProtoBuf.TYPES["bool"]:
7503 if (typeof value === 'string')
7504 buffer.writeVarint32(value.toLowerCase() === 'false' ? 0 : !!value);
7505 else
7506 buffer.writeVarint32(value ? 1 : 0);
7507 break;
7508
7509 // Constant enum value
7510 case ProtoBuf.TYPES["enum"]:
7511 buffer.writeVarint32(value);
7512 break;
7513
7514 // 32bit float
7515 case ProtoBuf.TYPES["float"]:
7516 buffer.writeFloat32(value);
7517 break;
7518
7519 // 64bit float
7520 case ProtoBuf.TYPES["double"]:
7521 buffer.writeFloat64(value);
7522 break;
7523
7524 // Length-delimited string
7525 case ProtoBuf.TYPES["string"]:
7526 buffer.writeVString(value);
7527 break;
7528
7529 // Length-delimited bytes
7530 case ProtoBuf.TYPES["bytes"]:
7531 if (value.remaining() < 0)
7532 throw Error("Illegal value for "+this.toString(true)+": "+value.remaining()+" bytes remaining");
7533 var prevOffset = value.offset;
7534 buffer.writeVarint32(value.remaining());
7535 buffer.append(value);
7536 value.offset = prevOffset;
7537 break;
7538
7539 // Embedded message
7540 case ProtoBuf.TYPES["message"]:
7541 var bb = new ByteBuffer().LE();
7542 this.resolvedType.encode(value, bb);
7543 buffer.writeVarint32(bb.offset);
7544 buffer.append(bb.flip());
7545 break;
7546
7547 // Legacy group
7548 case ProtoBuf.TYPES["group"]:
7549 this.resolvedType.encode(value, buffer);
7550 buffer.writeVarint32((id << 3) | ProtoBuf.WIRE_TYPES.ENDGROUP);
7551 break;
7552
7553 default:
7554 // We should never end here
7555 throw Error("[INTERNAL] Illegal value to encode in "+this.toString(true)+": "+value+" (unknown type)");
7556 }
7557 return buffer;
7558 };
7559
7560 /**
7561 * Decode one element value from the specified buffer.
7562 * @param {ByteBuffer} buffer ByteBuffer to decode from
7563 * @param {number} wireType The field wire type
7564 * @param {number} id The field number
7565 * @return {*} Decoded value
7566 * @throws {Error} If the field cannot be decoded
7567 * @expose
7568 */
7569 ElementPrototype.decode = function(buffer, wireType, id) {
7570 if (wireType != this.type.wireType)
7571 throw Error("Unexpected wire type for element");
7572
7573 var value, nBytes;
7574 switch (this.type) {
7575 // 32bit signed varint
7576 case ProtoBuf.TYPES["int32"]:
7577 return buffer.readVarint32() | 0;
7578
7579 // 32bit unsigned varint
7580 case ProtoBuf.TYPES["uint32"]:
7581 return buffer.readVarint32() >>> 0;
7582
7583 // 32bit signed varint zig-zag
7584 case ProtoBuf.TYPES["sint32"]:
7585 return buffer.readVarint32ZigZag() | 0;
7586
7587 // Fixed 32bit unsigned
7588 case ProtoBuf.TYPES["fixed32"]:
7589 return buffer.readUint32() >>> 0;
7590
7591 case ProtoBuf.TYPES["sfixed32"]:
7592 return buffer.readInt32() | 0;
7593
7594 // 64bit signed varint
7595 case ProtoBuf.TYPES["int64"]:
7596 return buffer.readVarint64();
7597
7598 // 64bit unsigned varint
7599 case ProtoBuf.TYPES["uint64"]:
7600 return buffer.readVarint64().toUnsigned();
7601
7602 // 64bit signed varint zig-zag
7603 case ProtoBuf.TYPES["sint64"]:
7604 return buffer.readVarint64ZigZag();
7605
7606 // Fixed 64bit unsigned
7607 case ProtoBuf.TYPES["fixed64"]:
7608 return buffer.readUint64();
7609
7610 // Fixed 64bit signed
7611 case ProtoBuf.TYPES["sfixed64"]:
7612 return buffer.readInt64();
7613
7614 // Bool varint
7615 case ProtoBuf.TYPES["bool"]:
7616 return !!buffer.readVarint32();
7617
7618 // Constant enum value (varint)
7619 case ProtoBuf.TYPES["enum"]:
7620 // The following Builder.Message#set will already throw
7621 return buffer.readVarint32();
7622
7623 // 32bit float
7624 case ProtoBuf.TYPES["float"]:
7625 return buffer.readFloat();
7626
7627 // 64bit float
7628 case ProtoBuf.TYPES["double"]:
7629 return buffer.readDouble();
7630
7631 // Length-delimited string
7632 case ProtoBuf.TYPES["string"]:
7633 return buffer.readVString();
7634
7635 // Length-delimited bytes
7636 case ProtoBuf.TYPES["bytes"]: {
7637 nBytes = buffer.readVarint32();
7638 if (buffer.remaining() < nBytes)
7639 throw Error("Illegal number of bytes for "+this.toString(true)+": "+nBytes+" required but got only "+buffer.remaining());
7640 value = buffer.clone(); // Offset already set
7641 value.limit = value.offset+nBytes;
7642 buffer.offset += nBytes;
7643 return value;
7644 }
7645
7646 // Length-delimited embedded message
7647 case ProtoBuf.TYPES["message"]: {
7648 nBytes = buffer.readVarint32();
7649 return this.resolvedType.decode(buffer, nBytes);
7650 }
7651
7652 // Legacy group
7653 case ProtoBuf.TYPES["group"]:
7654 return this.resolvedType.decode(buffer, -1, id);
7655 }
7656
7657 // We should never end here
7658 throw Error("[INTERNAL] Illegal decode type");
7659 };
7660
7661 /**
7662 * Converts a value from a string to the canonical element type.
7663 *
7664 * Legal only when isMapKey is true.
7665 *
7666 * @param {string} str The string value
7667 * @returns {*} The value
7668 */
7669 ElementPrototype.valueFromString = function(str) {
7670 if (!this.isMapKey) {
7671 throw Error("valueFromString() called on non-map-key element");
7672 }
7673
7674 switch (this.type) {
7675 case ProtoBuf.TYPES["int32"]:
7676 case ProtoBuf.TYPES["sint32"]:
7677 case ProtoBuf.TYPES["sfixed32"]:
7678 case ProtoBuf.TYPES["uint32"]:
7679 case ProtoBuf.TYPES["fixed32"]:
7680 return this.verifyValue(parseInt(str));
7681
7682 case ProtoBuf.TYPES["int64"]:
7683 case ProtoBuf.TYPES["sint64"]:
7684 case ProtoBuf.TYPES["sfixed64"]:
7685 case ProtoBuf.TYPES["uint64"]:
7686 case ProtoBuf.TYPES["fixed64"]:
7687 // Long-based fields support conversions from string already.
7688 return this.verifyValue(str);
7689
7690 case ProtoBuf.TYPES["bool"]:
7691 return str === "true";
7692
7693 case ProtoBuf.TYPES["string"]:
7694 return this.verifyValue(str);
7695
7696 case ProtoBuf.TYPES["bytes"]:
7697 return ByteBuffer.fromBinary(str);
7698 }
7699 };
7700
7701 /**
7702 * Converts a value from the canonical element type to a string.
7703 *
7704 * It should be the case that `valueFromString(valueToString(val))` returns
7705 * a value equivalent to `verifyValue(val)` for every legal value of `val`
7706 * according to this element type.
7707 *
7708 * This may be used when the element must be stored or used as a string,
7709 * e.g., as a map key on an Object.
7710 *
7711 * Legal only when isMapKey is true.
7712 *
7713 * @param {*} val The value
7714 * @returns {string} The string form of the value.
7715 */
7716 ElementPrototype.valueToString = function(value) {
7717 if (!this.isMapKey) {
7718 throw Error("valueToString() called on non-map-key element");
7719 }
7720
7721 if (this.type === ProtoBuf.TYPES["bytes"]) {
7722 return value.toString("binary");
7723 } else {
7724 return value.toString();
7725 }
7726 };
7727
7728 /**
7729 * @alias ProtoBuf.Reflect.Element
7730 * @expose
7731 */
7732 Reflect.Element = Element;
7733
7734 /**
7735 * Constructs a new Message.
7736 * @exports ProtoBuf.Reflect.Message
7737 * @param {!ProtoBuf.Builder} builder Builder reference
7738 * @param {!ProtoBuf.Reflect.Namespace} parent Parent message or namespace
7739 * @param {string} name Message name
7740 * @param {Object.<string,*>=} options Message options
7741 * @param {boolean=} isGroup `true` if this is a legacy group
7742 * @param {string?} syntax The syntax level of this definition (e.g., proto3)
7743 * @constructor
7744 * @extends ProtoBuf.Reflect.Namespace
7745 */
7746 var Message = function(builder, parent, name, options, isGroup, syntax) {
7747 Namespace.call(this, builder, parent, name, options, syntax);
7748
7749 /**
7750 * @override
7751 */
7752 this.className = "Message";
7753
7754 /**
7755 * Extensions range.
7756 * @type {!Array.<number>|undefined}
7757 * @expose
7758 */
7759 this.extensions = undefined;
7760
7761 /**
7762 * Runtime message class.
7763 * @type {?function(new:ProtoBuf.Builder.Message)}
7764 * @expose
7765 */
7766 this.clazz = null;
7767
7768 /**
7769 * Whether this is a legacy group or not.
7770 * @type {boolean}
7771 * @expose
7772 */
7773 this.isGroup = !!isGroup;
7774
7775 // The following cached collections are used to efficiently iterate over or look up fields when decoding.
7776
7777 /**
7778 * Cached fields.
7779 * @type {?Array.<!ProtoBuf.Reflect.Message.Field>}
7780 * @private
7781 */
7782 this._fields = null;
7783
7784 /**
7785 * Cached fields by id.
7786 * @type {?Object.<number,!ProtoBuf.Reflect.Message.Field>}
7787 * @private
7788 */
7789 this._fieldsById = null;
7790
7791 /**
7792 * Cached fields by name.
7793 * @type {?Object.<string,!ProtoBuf.Reflect.Message.Field>}
7794 * @private
7795 */
7796 this._fieldsByName = null;
7797 };
7798
7799 /**
7800 * @alias ProtoBuf.Reflect.Message.prototype
7801 * @inner
7802 */
7803 var MessagePrototype = Message.prototype = Object.create(Namespace.prototype);
7804
7805 /**
7806 * Builds the message and returns the runtime counterpart, which is a fully functional class.
7807 * @see ProtoBuf.Builder.Message
7808 * @param {boolean=} rebuild Whether to rebuild or not, defaults to false
7809 * @return {ProtoBuf.Reflect.Message} Message class
7810 * @throws {Error} If the message cannot be built
7811 * @expose
7812 */
7813 MessagePrototype.build = function(rebuild) {
7814 if (this.clazz && !rebuild)
7815 return this.clazz;
7816
7817 // Create the runtime Message class in its own scope
7818 var clazz = (function(ProtoBuf, T) {
7819
7820 var fields = T.getChildren(ProtoBuf.Reflect.Message.Field),
7821 oneofs = T.getChildren(ProtoBuf.Reflect.Message.OneOf);
7822
7823 /**
7824 * Constructs a new runtime Message.
7825 * @name ProtoBuf.Builder.Message
7826 * @class Barebone of all runtime messages.
7827 * @param {!Object.<string,*>|string} values Preset values
7828 * @param {...string} var_args
7829 * @constructor
7830 * @throws {Error} If the message cannot be created
7831 */
7832 var Message = function(values, var_args) {
7833 ProtoBuf.Builder.Message.call(this);
7834
7835 // Create virtual oneof properties
7836 for (var i=0, k=oneofs.length; i<k; ++i)
7837 this[oneofs[i].name] = null;
7838 // Create fields and set default values
7839 for (i=0, k=fields.length; i<k; ++i) {
7840 var field = fields[i];
7841 this[field.name] =
7842 field.repeated ? [] :
7843 (field.map ? new ProtoBuf.Map(field) : null);
7844 if ((field.required || T.syntax === 'proto3') &&
7845 field.defaultValue !== null)
7846 this[field.name] = field.defaultValue;
7847 }
7848
7849 if (arguments.length > 0) {
7850 var value;
7851 // Set field values from a values object
7852 if (arguments.length === 1 && values !== null && typeof values === 'object' &&
7853 /* not _another_ Message */ (typeof values.encode !== 'function' || values instanceof Message) &&
7854 /* not a repeated field */ !Array.isArray(values) &&
7855 /* not a Map */ !(values instanceof ProtoBuf.Map) &&
7856 /* not a ByteBuffer */ !ByteBuffer.isByteBuffer(values) &&
7857 /* not an ArrayBuffer */ !(values instanceof ArrayBuffer) &&
7858 /* not a Long */ !(ProtoBuf.Long && values instanceof ProtoBuf.Long)) {
7859 this.$set(values);
7860 } else // Set field values from arguments, in declaration order
7861 for (i=0, k=arguments.length; i<k; ++i)
7862 if (typeof (value = arguments[i]) !== 'undefined')
7863 this.$set(fields[i].name, value); // May throw
7864 }
7865 };
7866
7867 /**
7868 * @alias ProtoBuf.Builder.Message.prototype
7869 * @inner
7870 */
7871 var MessagePrototype = Message.prototype = Object.create(ProtoBuf.Builder.Message.prototype);
7872
7873 /**
7874 * Adds a value to a repeated field.
7875 * @name ProtoBuf.Builder.Message#add
7876 * @function
7877 * @param {string} key Field name
7878 * @param {*} value Value to add
7879 * @param {boolean=} noAssert Whether to assert the value or not (asserts by default)
7880 * @returns {!ProtoBuf.Builder.Message} this
7881 * @throws {Error} If the value cannot be added
7882 * @expose
7883 */
7884 MessagePrototype.add = function(key, value, noAssert) {
7885 var field = T._fieldsByName[key];
7886 if (!noAssert) {
7887 if (!field)
7888 throw Error(this+"#"+key+" is undefined");
7889 if (!(field instanceof ProtoBuf.Reflect.Message.Field))
7890 throw Error(this+"#"+key+" is not a field: "+field.toString(true)); // May throw if it's an enum or embedded message
7891 if (!field.repeated)
7892 throw Error(this+"#"+key+" is not a repeated field");
7893 value = field.verifyValue(value, true);
7894 }
7895 if (this[key] === null)
7896 this[key] = [];
7897 this[key].push(value);
7898 return this;
7899 };
7900
7901 /**
7902 * Adds a value to a repeated field. This is an alias for {@link ProtoBuf.Builder.Message#add}.
7903 * @name ProtoBuf.Builder.Message#$add
7904 * @function
7905 * @param {string} key Field name
7906 * @param {*} value Value to add
7907 * @param {boolean=} noAssert Whether to assert the value or not (asserts by default)
7908 * @returns {!ProtoBuf.Builder.Message} this
7909 * @throws {Error} If the value cannot be added
7910 * @expose
7911 */
7912 MessagePrototype.$add = MessagePrototype.add;
7913
7914 /**
7915 * Sets a field's value.
7916 * @name ProtoBuf.Builder.Message#set
7917 * @function
7918 * @param {string|!Object.<string,*>} keyOrObj String key or plain object holding multiple values
7919 * @param {(*|boolean)=} value Value to set if key is a string, otherwise omitted
7920 * @param {boolean=} noAssert Whether to not assert for an actual field / proper value type, defaults to `false`
7921 * @returns {!ProtoBuf.Builder.Message} this
7922 * @throws {Error} If the value cannot be set
7923 * @expose
7924 */
7925 MessagePrototype.set = function(keyOrObj, value, noAssert) {
7926 if (keyOrObj && typeof keyOrObj === 'object') {
7927 noAssert = value;
7928 for (var ikey in keyOrObj) {
7929 // Check if virtual oneof field - don't set these
7930 if (keyOrObj.hasOwnProperty(ikey) && typeof (value = keyOrObj[ikey]) !== 'undefined' && T._oneofsByName[ikey] === undefined)
7931 this.$set(ikey, value, noAssert);
7932 }
7933 return this;
7934 }
7935 var field = T._fieldsByName[keyOrObj];
7936 if (!noAssert) {
7937 if (!field)
7938 throw Error(this+"#"+keyOrObj+" is not a field: undefined");
7939 if (!(field instanceof ProtoBuf.Reflect.Message.Field))
7940 throw Error(this+"#"+keyOrObj+" is not a field: "+field.toString(true));
7941 this[field.name] = (value = field.verifyValue(value)); // May throw
7942 } else
7943 this[keyOrObj] = value;
7944 if (field && field.oneof) { // Field is part of an OneOf (not a virtual OneOf field)
7945 var currentField = this[field.oneof.name]; // Virtual field references currently set field
7946 if (value !== null) {
7947 if (currentField !== null && currentField !== field.name)
7948 this[currentField] = null; // Clear currently set field
7949 this[field.oneof.name] = field.name; // Point virtual field at this field
7950 } else if (/* value === null && */currentField === keyOrObj)
7951 this[field.oneof.name] = null; // Clear virtual field (current field explicitly cleared)
7952 }
7953 return this;
7954 };
7955
7956 /**
7957 * Sets a field's value. This is an alias for [@link ProtoBuf.Builder.Message#set}.
7958 * @name ProtoBuf.Builder.Message#$set
7959 * @function
7960 * @param {string|!Object.<string,*>} keyOrObj String key or plain object holding multiple values
7961 * @param {(*|boolean)=} value Value to set if key is a string, otherwise omitted
7962 * @param {boolean=} noAssert Whether to not assert the value, defaults to `false`
7963 * @throws {Error} If the value cannot be set
7964 * @expose
7965 */
7966 MessagePrototype.$set = MessagePrototype.set;
7967
7968 /**
7969 * Gets a field's value.
7970 * @name ProtoBuf.Builder.Message#get
7971 * @function
7972 * @param {string} key Key
7973 * @param {boolean=} noAssert Whether to not assert for an actual field, defaults to `false`
7974 * @return {*} Value
7975 * @throws {Error} If there is no such field
7976 * @expose
7977 */
7978 MessagePrototype.get = function(key, noAssert) {
7979 if (noAssert)
7980 return this[key];
7981 var field = T._fieldsByName[key];
7982 if (!field || !(field instanceof ProtoBuf.Reflect.Message.Field))
7983 throw Error(this+"#"+key+" is not a field: undefined");
7984 if (!(field instanceof ProtoBuf.Reflect.Message.Field))
7985 throw Error(this+"#"+key+" is not a field: "+field.toString(true));
7986 return this[field.name];
7987 };
7988
7989 /**
7990 * Gets a field's value. This is an alias for {@link ProtoBuf.Builder.Message#$get}.
7991 * @name ProtoBuf.Builder.Message#$get
7992 * @function
7993 * @param {string} key Key
7994 * @return {*} Value
7995 * @throws {Error} If there is no such field
7996 * @expose
7997 */
7998 MessagePrototype.$get = MessagePrototype.get;
7999
8000 // Getters and setters
8001
8002 for (var i=0; i<fields.length; i++) {
8003 var field = fields[i];
8004 // no setters for extension fields as these are named by their fqn
8005 if (field instanceof ProtoBuf.Reflect.Message.ExtensionField)
8006 continue;
8007
8008 if (T.builder.options['populateAccessors'])
8009 (function(field) {
8010 // set/get[SomeValue]
8011 var Name = field.originalName.replace(/(_[a-zA-Z])/g, function(match) {
8012 return match.toUpperCase().replace('_','');
8013 });
8014 Name = Name.substring(0,1).toUpperCase() + Name.substring(1);
8015
8016 // set/get_[some_value] FIXME: Do we really need these?
8017 var name = field.originalName.replace(/([A-Z])/g, function(match) {
8018 return "_"+match;
8019 });
8020
8021 /**
8022 * The current field's unbound setter function.
8023 * @function
8024 * @param {*} value
8025 * @param {boolean=} noAssert
8026 * @returns {!ProtoBuf.Builder.Message}
8027 * @inner
8028 */
8029 var setter = function(value, noAssert) {
8030 this[field.name] = noAssert ? value : field.verifyValue(value);
8031 return this;
8032 };
8033
8034 /**
8035 * The current field's unbound getter function.
8036 * @function
8037 * @returns {*}
8038 * @inner
8039 */
8040 var getter = function() {
8041 return this[field.name];
8042 };
8043
8044 if (T.getChild("set"+Name) === null)
8045 /**
8046 * Sets a value. This method is present for each field, but only if there is no name conflict with
8047 * another field.
8048 * @name ProtoBuf.Builder.Message#set[SomeField]
8049 * @function
8050 * @param {*} value Value to set
8051 * @param {boolean=} noAssert Whether to not assert the value, defaults to `false`
8052 * @returns {!ProtoBuf.Builder.Message} this
8053 * @abstract
8054 * @throws {Error} If the value cannot be set
8055 */
8056 MessagePrototype["set"+Name] = setter;
8057
8058 if (T.getChild("set_"+name) === null)
8059 /**
8060 * Sets a value. This method is present for each field, but only if there is no name conflict with
8061 * another field.
8062 * @name ProtoBuf.Builder.Message#set_[some_field]
8063 * @function
8064 * @param {*} value Value to set
8065 * @param {boolean=} noAssert Whether to not assert the value, defaults to `false`
8066 * @returns {!ProtoBuf.Builder.Message} this
8067 * @abstract
8068 * @throws {Error} If the value cannot be set
8069 */
8070 MessagePrototype["set_"+name] = setter;
8071
8072 if (T.getChild("get"+Name) === null)
8073 /**
8074 * Gets a value. This method is present for each field, but only if there is no name conflict with
8075 * another field.
8076 * @name ProtoBuf.Builder.Message#get[SomeField]
8077 * @function
8078 * @abstract
8079 * @return {*} The value
8080 */
8081 MessagePrototype["get"+Name] = getter;
8082
8083 if (T.getChild("get_"+name) === null)
8084 /**
8085 * Gets a value. This method is present for each field, but only if there is no name conflict with
8086 * another field.
8087 * @name ProtoBuf.Builder.Message#get_[some_field]
8088 * @function
8089 * @return {*} The value
8090 * @abstract
8091 */
8092 MessagePrototype["get_"+name] = getter;
8093
8094 })(field);
8095 }
8096
8097 // En-/decoding
8098
8099 /**
8100 * Encodes the message.
8101 * @name ProtoBuf.Builder.Message#$encode
8102 * @function
8103 * @param {(!ByteBuffer|boolean)=} buffer ByteBuffer to encode to. Will create a new one and flip it if omitted.
8104 * @param {boolean=} noVerify Whether to not verify field values, defaults to `false`
8105 * @return {!ByteBuffer} Encoded message as a ByteBuffer
8106 * @throws {Error} If the message cannot be encoded or if required fields are missing. The later still
8107 * returns the encoded ByteBuffer in the `encoded` property on the error.
8108 * @expose
8109 * @see ProtoBuf.Builder.Message#encode64
8110 * @see ProtoBuf.Builder.Message#encodeHex
8111 * @see ProtoBuf.Builder.Message#encodeAB
8112 */
8113 MessagePrototype.encode = function(buffer, noVerify) {
8114 if (typeof buffer === 'boolean')
8115 noVerify = buffer,
8116 buffer = undefined;
8117 var isNew = false;
8118 if (!buffer)
8119 buffer = new ByteBuffer(),
8120 isNew = true;
8121 var le = buffer.littleEndian;
8122 try {
8123 T.encode(this, buffer.LE(), noVerify);
8124 return (isNew ? buffer.flip() : buffer).LE(le);
8125 } catch (e) {
8126 buffer.LE(le);
8127 throw(e);
8128 }
8129 };
8130
8131 /**
8132 * Encodes a message using the specified data payload.
8133 * @param {!Object.<string,*>} data Data payload
8134 * @param {(!ByteBuffer|boolean)=} buffer ByteBuffer to encode to. Will create a new one and flip it if omitted.
8135 * @param {boolean=} noVerify Whether to not verify field values, defaults to `false`
8136 * @return {!ByteBuffer} Encoded message as a ByteBuffer
8137 * @expose
8138 */
8139 Message.encode = function(data, buffer, noVerify) {
8140 return new Message(data).encode(buffer, noVerify);
8141 };
8142
8143 /**
8144 * Calculates the byte length of the message.
8145 * @name ProtoBuf.Builder.Message#calculate
8146 * @function
8147 * @returns {number} Byte length
8148 * @throws {Error} If the message cannot be calculated or if required fields are missing.
8149 * @expose
8150 */
8151 MessagePrototype.calculate = function() {
8152 return T.calculate(this);
8153 };
8154
8155 /**
8156 * Encodes the varint32 length-delimited message.
8157 * @name ProtoBuf.Builder.Message#encodeDelimited
8158 * @function
8159 * @param {(!ByteBuffer|boolean)=} buffer ByteBuffer to encode to. Will create a new one and flip it if omitted.
8160 * @param {boolean=} noVerify Whether to not verify field values, defaults to `false`
8161 * @return {!ByteBuffer} Encoded message as a ByteBuffer
8162 * @throws {Error} If the message cannot be encoded or if required fields are missing. The later still
8163 * returns the encoded ByteBuffer in the `encoded` property on the error.
8164 * @expose
8165 */
8166 MessagePrototype.encodeDelimited = function(buffer, noVerify) {
8167 var isNew = false;
8168 if (!buffer)
8169 buffer = new ByteBuffer(),
8170 isNew = true;
8171 var enc = new ByteBuffer().LE();
8172 T.encode(this, enc, noVerify).flip();
8173 buffer.writeVarint32(enc.remaining());
8174 buffer.append(enc);
8175 return isNew ? buffer.flip() : buffer;
8176 };
8177
8178 /**
8179 * Directly encodes the message to an ArrayBuffer.
8180 * @name ProtoBuf.Builder.Message#encodeAB
8181 * @function
8182 * @return {ArrayBuffer} Encoded message as ArrayBuffer
8183 * @throws {Error} If the message cannot be encoded or if required fields are missing. The later still
8184 * returns the encoded ArrayBuffer in the `encoded` property on the error.
8185 * @expose
8186 */
8187 MessagePrototype.encodeAB = function() {
8188 try {
8189 return this.encode().toArrayBuffer();
8190 } catch (e) {
8191 if (e["encoded"]) e["encoded"] = e["encoded"].toArrayBuffer();
8192 throw(e);
8193 }
8194 };
8195
8196 /**
8197 * Returns the message as an ArrayBuffer. This is an alias for {@link ProtoBuf.Builder.Message#encodeAB}.
8198 * @name ProtoBuf.Builder.Message#toArrayBuffer
8199 * @function
8200 * @return {ArrayBuffer} Encoded message as ArrayBuffer
8201 * @throws {Error} If the message cannot be encoded or if required fields are missing. The later still
8202 * returns the encoded ArrayBuffer in the `encoded` property on the error.
8203 * @expose
8204 */
8205 MessagePrototype.toArrayBuffer = MessagePrototype.encodeAB;
8206
8207 /**
8208 * Directly encodes the message to a node Buffer.
8209 * @name ProtoBuf.Builder.Message#encodeNB
8210 * @function
8211 * @return {!Buffer}
8212 * @throws {Error} If the message cannot be encoded, not running under node.js or if required fields are
8213 * missing. The later still returns the encoded node Buffer in the `encoded` property on the error.
8214 * @expose
8215 */
8216 MessagePrototype.encodeNB = function() {
8217 try {
8218 return this.encode().toBuffer();
8219 } catch (e) {
8220 if (e["encoded"]) e["encoded"] = e["encoded"].toBuffer();
8221 throw(e);
8222 }
8223 };
8224
8225 /**
8226 * Returns the message as a node Buffer. This is an alias for {@link ProtoBuf.Builder.Message#encodeNB}.
8227 * @name ProtoBuf.Builder.Message#toBuffer
8228 * @function
8229 * @return {!Buffer}
8230 * @throws {Error} If the message cannot be encoded or if required fields are missing. The later still
8231 * returns the encoded node Buffer in the `encoded` property on the error.
8232 * @expose
8233 */
8234 MessagePrototype.toBuffer = MessagePrototype.encodeNB;
8235
8236 /**
8237 * Directly encodes the message to a base64 encoded string.
8238 * @name ProtoBuf.Builder.Message#encode64
8239 * @function
8240 * @return {string} Base64 encoded string
8241 * @throws {Error} If the underlying buffer cannot be encoded or if required fields are missing. The later
8242 * still returns the encoded base64 string in the `encoded` property on the error.
8243 * @expose
8244 */
8245 MessagePrototype.encode64 = function() {
8246 try {
8247 return this.encode().toBase64();
8248 } catch (e) {
8249 if (e["encoded"]) e["encoded"] = e["encoded"].toBase64();
8250 throw(e);
8251 }
8252 };
8253
8254 /**
8255 * Returns the message as a base64 encoded string. This is an alias for {@link ProtoBuf.Builder.Message#encode64}.
8256 * @name ProtoBuf.Builder.Message#toBase64
8257 * @function
8258 * @return {string} Base64 encoded string
8259 * @throws {Error} If the message cannot be encoded or if required fields are missing. The later still
8260 * returns the encoded base64 string in the `encoded` property on the error.
8261 * @expose
8262 */
8263 MessagePrototype.toBase64 = MessagePrototype.encode64;
8264
8265 /**
8266 * Directly encodes the message to a hex encoded string.
8267 * @name ProtoBuf.Builder.Message#encodeHex
8268 * @function
8269 * @return {string} Hex encoded string
8270 * @throws {Error} If the underlying buffer cannot be encoded or if required fields are missing. The later
8271 * still returns the encoded hex string in the `encoded` property on the error.
8272 * @expose
8273 */
8274 MessagePrototype.encodeHex = function() {
8275 try {
8276 return this.encode().toHex();
8277 } catch (e) {
8278 if (e["encoded"]) e["encoded"] = e["encoded"].toHex();
8279 throw(e);
8280 }
8281 };
8282
8283 /**
8284 * Returns the message as a hex encoded string. This is an alias for {@link ProtoBuf.Builder.Message#encodeHex}.
8285 * @name ProtoBuf.Builder.Message#toHex
8286 * @function
8287 * @return {string} Hex encoded string
8288 * @throws {Error} If the message cannot be encoded or if required fields are missing. The later still
8289 * returns the encoded hex string in the `encoded` property on the error.
8290 * @expose
8291 */
8292 MessagePrototype.toHex = MessagePrototype.encodeHex;
8293
8294 /**
8295 * Clones a message object or field value to a raw object.
8296 * @param {*} obj Object to clone
8297 * @param {boolean} binaryAsBase64 Whether to include binary data as base64 strings or as a buffer otherwise
8298 * @param {boolean} longsAsStrings Whether to encode longs as strings
8299 * @param {!ProtoBuf.Reflect.T=} resolvedType The resolved field type if a field
8300 * @returns {*} Cloned object
8301 * @inner
8302 */
8303 function cloneRaw(obj, binaryAsBase64, longsAsStrings, resolvedType) {
8304 if (obj === null || typeof obj !== 'object') {
8305 // Convert enum values to their respective names
8306 if (resolvedType && resolvedType instanceof ProtoBuf.Reflect.Enum) {
8307 var name = ProtoBuf.Reflect.Enum.getName(resolvedType.object, obj);
8308 if (name !== null)
8309 return name;
8310 }
8311 // Pass-through string, number, boolean, null...
8312 return obj;
8313 }
8314 // Convert ByteBuffers to raw buffer or strings
8315 if (ByteBuffer.isByteBuffer(obj))
8316 return binaryAsBase64 ? obj.toBase64() : obj.toBuffer();
8317 // Convert Longs to proper objects or strings
8318 if (ProtoBuf.Long.isLong(obj))
8319 return longsAsStrings ? obj.toString() : ProtoBuf.Long.fromValue(obj);
8320 var clone;
8321 // Clone arrays
8322 if (Array.isArray(obj)) {
8323 clone = [];
8324 obj.forEach(function(v, k) {
8325 clone[k] = cloneRaw(v, binaryAsBase64, longsAsStrings, resolvedType);
8326 });
8327 return clone;
8328 }
8329 clone = {};
8330 // Convert maps to objects
8331 if (obj instanceof ProtoBuf.Map) {
8332 var it = obj.entries();
8333 for (var e = it.next(); !e.done; e = it.next())
8334 clone[obj.keyElem.valueToString(e.value[0])] = cloneRaw(e.value[1], binaryAsBase64, longsAsStrings, obj.valueElem.resolvedType);
8335 return clone;
8336 }
8337 // Everything else is a non-null object
8338 var type = obj.$type,
8339 field = undefined;
8340 for (var i in obj)
8341 if (obj.hasOwnProperty(i)) {
8342 if (type && (field = type.getChild(i)))
8343 clone[i] = cloneRaw(obj[i], binaryAsBase64, longsAsStrings, field.resolvedType);
8344 else
8345 clone[i] = cloneRaw(obj[i], binaryAsBase64, longsAsStrings);
8346 }
8347 return clone;
8348 }
8349
8350 /**
8351 * Returns the message's raw payload.
8352 * @param {boolean=} binaryAsBase64 Whether to include binary data as base64 strings instead of Buffers, defaults to `false`
8353 * @param {boolean} longsAsStrings Whether to encode longs as strings
8354 * @returns {Object.<string,*>} Raw payload
8355 * @expose
8356 */
8357 MessagePrototype.toRaw = function(binaryAsBase64, longsAsStrings) {
8358 return cloneRaw(this, !!binaryAsBase64, !!longsAsStrings, this.$type);
8359 };
8360
8361 /**
8362 * Encodes a message to JSON.
8363 * @returns {string} JSON string
8364 * @expose
8365 */
8366 MessagePrototype.encodeJSON = function() {
8367 return JSON.stringify(
8368 cloneRaw(this,
8369 /* binary-as-base64 */ true,
8370 /* longs-as-strings */ true,
8371 this.$type
8372 )
8373 );
8374 };
8375
8376 /**
8377 * Decodes a message from the specified buffer or string.
8378 * @name ProtoBuf.Builder.Message.decode
8379 * @function
8380 * @param {!ByteBuffer|!ArrayBuffer|!Buffer|string} buffer Buffer to decode from
8381 * @param {(number|string)=} length Message length. Defaults to decode all the remainig data.
8382 * @param {string=} enc Encoding if buffer is a string: hex, utf8 (not recommended), defaults to base64
8383 * @return {!ProtoBuf.Builder.Message} Decoded message
8384 * @throws {Error} If the message cannot be decoded or if required fields are missing. The later still
8385 * returns the decoded message with missing fields in the `decoded` property on the error.
8386 * @expose
8387 * @see ProtoBuf.Builder.Message.decode64
8388 * @see ProtoBuf.Builder.Message.decodeHex
8389 */
8390 Message.decode = function(buffer, length, enc) {
8391 if (typeof length === 'string')
8392 enc = length,
8393 length = -1;
8394 if (typeof buffer === 'string')
8395 buffer = ByteBuffer.wrap(buffer, enc ? enc : "base64");
8396 else if (!ByteBuffer.isByteBuffer(buffer))
8397 buffer = ByteBuffer.wrap(buffer); // May throw
8398 var le = buffer.littleEndian;
8399 try {
8400 var msg = T.decode(buffer.LE(), length);
8401 buffer.LE(le);
8402 return msg;
8403 } catch (e) {
8404 buffer.LE(le);
8405 throw(e);
8406 }
8407 };
8408
8409 /**
8410 * Decodes a varint32 length-delimited message from the specified buffer or string.
8411 * @name ProtoBuf.Builder.Message.decodeDelimited
8412 * @function
8413 * @param {!ByteBuffer|!ArrayBuffer|!Buffer|string} buffer Buffer to decode from
8414 * @param {string=} enc Encoding if buffer is a string: hex, utf8 (not recommended), defaults to base64
8415 * @return {ProtoBuf.Builder.Message} Decoded message or `null` if not enough bytes are available yet
8416 * @throws {Error} If the message cannot be decoded or if required fields are missing. The later still
8417 * returns the decoded message with missing fields in the `decoded` property on the error.
8418 * @expose
8419 */
8420 Message.decodeDelimited = function(buffer, enc) {
8421 if (typeof buffer === 'string')
8422 buffer = ByteBuffer.wrap(buffer, enc ? enc : "base64");
8423 else if (!ByteBuffer.isByteBuffer(buffer))
8424 buffer = ByteBuffer.wrap(buffer); // May throw
8425 if (buffer.remaining() < 1)
8426 return null;
8427 var off = buffer.offset,
8428 len = buffer.readVarint32();
8429 if (buffer.remaining() < len) {
8430 buffer.offset = off;
8431 return null;
8432 }
8433 try {
8434 var msg = T.decode(buffer.slice(buffer.offset, buffer.offset + len).LE());
8435 buffer.offset += len;
8436 return msg;
8437 } catch (err) {
8438 buffer.offset += len;
8439 throw err;
8440 }
8441 };
8442
8443 /**
8444 * Decodes the message from the specified base64 encoded string.
8445 * @name ProtoBuf.Builder.Message.decode64
8446 * @function
8447 * @param {string} str String to decode from
8448 * @return {!ProtoBuf.Builder.Message} Decoded message
8449 * @throws {Error} If the message cannot be decoded or if required fields are missing. The later still
8450 * returns the decoded message with missing fields in the `decoded` property on the error.
8451 * @expose
8452 */
8453 Message.decode64 = function(str) {
8454 return Message.decode(str, "base64");
8455 };
8456
8457 /**
8458 * Decodes the message from the specified hex encoded string.
8459 * @name ProtoBuf.Builder.Message.decodeHex
8460 * @function
8461 * @param {string} str String to decode from
8462 * @return {!ProtoBuf.Builder.Message} Decoded message
8463 * @throws {Error} If the message cannot be decoded or if required fields are missing. The later still
8464 * returns the decoded message with missing fields in the `decoded` property on the error.
8465 * @expose
8466 */
8467 Message.decodeHex = function(str) {
8468 return Message.decode(str, "hex");
8469 };
8470
8471 /**
8472 * Decodes the message from a JSON string.
8473 * @name ProtoBuf.Builder.Message.decodeJSON
8474 * @function
8475 * @param {string} str String to decode from
8476 * @return {!ProtoBuf.Builder.Message} Decoded message
8477 * @throws {Error} If the message cannot be decoded or if required fields are
8478 * missing.
8479 * @expose
8480 */
8481 Message.decodeJSON = function(str) {
8482 return new Message(JSON.parse(str));
8483 };
8484
8485 // Utility
8486
8487 /**
8488 * Returns a string representation of this Message.
8489 * @name ProtoBuf.Builder.Message#toString
8490 * @function
8491 * @return {string} String representation as of ".Fully.Qualified.MessageName"
8492 * @expose
8493 */
8494 MessagePrototype.toString = function() {
8495 return T.toString();
8496 };
8497
8498 if (Object.defineProperty)
8499 Object.defineProperty(Message, '$options', { "value": T.buildOpt() }),
8500 Object.defineProperty(MessagePrototype, "$options", { "value": Message["$options"] }),
8501 Object.defineProperty(Message, "$type", { "value": T }),
8502 Object.defineProperty(MessagePrototype, "$type", { "value": T });
8503
8504 return Message;
8505
8506 })(ProtoBuf, this);
8507
8508 // Static enums and prototyped sub-messages / cached collections
8509 this._fields = [];
8510 this._fieldsById = {};
8511 this._fieldsByName = {};
8512 this._oneofsByName = {};
8513 for (var i=0, k=this.children.length, child; i<k; i++) {
8514 child = this.children[i];
8515 if (child instanceof Enum || child instanceof Message || child instanceof Service) {
8516 if (clazz.hasOwnProperty(child.name))
8517 throw Error("Illegal reflect child of "+this.toString(true)+": "+child.toString(true)+" cannot override static property '"+child.name+"'");
8518 clazz[child.name] = child.build();
8519 } else if (child instanceof Message.Field)
8520 child.build(),
8521 this._fields.push(child),
8522 this._fieldsById[child.id] = child,
8523 this._fieldsByName[child.name] = child;
8524 else if (child instanceof Message.OneOf) {
8525 this._oneofsByName[child.name] = child;
8526 }
8527 else if (!(child instanceof Message.OneOf) && !(child instanceof Extension)) // Not built
8528 throw Error("Illegal reflect child of "+this.toString(true)+": "+this.children[i].toString(true));
8529 }
8530
8531 return this.clazz = clazz;
8532 };
8533
8534 /**
8535 * Encodes a runtime message's contents to the specified buffer.
8536 * @param {!ProtoBuf.Builder.Message} message Runtime message to encode
8537 * @param {ByteBuffer} buffer ByteBuffer to write to
8538 * @param {boolean=} noVerify Whether to not verify field values, defaults to `false`
8539 * @return {ByteBuffer} The ByteBuffer for chaining
8540 * @throws {Error} If required fields are missing or the message cannot be encoded for another reason
8541 * @expose
8542 */
8543 MessagePrototype.encode = function(message, buffer, noVerify) {
8544 var fieldMissing = null,
8545 field;
8546 for (var i=0, k=this._fields.length, val; i<k; ++i) {
8547 field = this._fields[i];
8548 val = message[field.name];
8549 if (field.required && val === null) {
8550 if (fieldMissing === null)
8551 fieldMissing = field;
8552 } else
8553 field.encode(noVerify ? val : field.verifyValue(val), buffer, message);
8554 }
8555 if (fieldMissing !== null) {
8556 var err = Error("Missing at least one required field for "+this.toString(true)+": "+fieldMissing);
8557 err["encoded"] = buffer; // Still expose what we got
8558 throw(err);
8559 }
8560 return buffer;
8561 };
8562
8563 /**
8564 * Calculates a runtime message's byte length.
8565 * @param {!ProtoBuf.Builder.Message} message Runtime message to encode
8566 * @returns {number} Byte length
8567 * @throws {Error} If required fields are missing or the message cannot be calculated for another reason
8568 * @expose
8569 */
8570 MessagePrototype.calculate = function(message) {
8571 for (var n=0, i=0, k=this._fields.length, field, val; i<k; ++i) {
8572 field = this._fields[i];
8573 val = message[field.name];
8574 if (field.required && val === null)
8575 throw Error("Missing at least one required field for "+this.toString(true)+": "+field);
8576 else
8577 n += field.calculate(val, message);
8578 }
8579 return n;
8580 };
8581
8582 /**
8583 * Skips all data until the end of the specified group has been reached.
8584 * @param {number} expectedId Expected GROUPEND id
8585 * @param {!ByteBuffer} buf ByteBuffer
8586 * @returns {boolean} `true` if a value as been skipped, `false` if the end has been reached
8587 * @throws {Error} If it wasn't possible to find the end of the group (buffer overrun or end tag mismatch)
8588 * @inner
8589 */
8590 function skipTillGroupEnd(expectedId, buf) {
8591 var tag = buf.readVarint32(), // Throws on OOB
8592 wireType = tag & 0x07,
8593 id = tag >>> 3;
8594 switch (wireType) {
8595 case ProtoBuf.WIRE_TYPES.VARINT:
8596 do tag = buf.readUint8();
8597 while ((tag & 0x80) === 0x80);
8598 break;
8599 case ProtoBuf.WIRE_TYPES.BITS64:
8600 buf.offset += 8;
8601 break;
8602 case ProtoBuf.WIRE_TYPES.LDELIM:
8603 tag = buf.readVarint32(); // reads the varint
8604 buf.offset += tag; // skips n bytes
8605 break;
8606 case ProtoBuf.WIRE_TYPES.STARTGROUP:
8607 skipTillGroupEnd(id, buf);
8608 break;
8609 case ProtoBuf.WIRE_TYPES.ENDGROUP:
8610 if (id === expectedId)
8611 return false;
8612 else
8613 throw Error("Illegal GROUPEND after unknown group: "+id+" ("+expectedId+" expected)");
8614 case ProtoBuf.WIRE_TYPES.BITS32:
8615 buf.offset += 4;
8616 break;
8617 default:
8618 throw Error("Illegal wire type in unknown group "+expectedId+": "+wireType);
8619 }
8620 return true;
8621 }
8622
8623 /**
8624 * Decodes an encoded message and returns the decoded message.
8625 * @param {ByteBuffer} buffer ByteBuffer to decode from
8626 * @param {number=} length Message length. Defaults to decode all remaining data.
8627 * @param {number=} expectedGroupEndId Expected GROUPEND id if this is a legacy group
8628 * @return {ProtoBuf.Builder.Message} Decoded message
8629 * @throws {Error} If the message cannot be decoded
8630 * @expose
8631 */
8632 MessagePrototype.decode = function(buffer, length, expectedGroupEndId) {
8633 if (typeof length !== 'number')
8634 length = -1;
8635 var start = buffer.offset,
8636 msg = new (this.clazz)(),
8637 tag, wireType, id, field;
8638 while (buffer.offset < start+length || (length === -1 && buffer.remaining() > 0)) {
8639 tag = buffer.readVarint32();
8640 wireType = tag & 0x07;
8641 id = tag >>> 3;
8642 if (wireType === ProtoBuf.WIRE_TYPES.ENDGROUP) {
8643 if (id !== expectedGroupEndId)
8644 throw Error("Illegal group end indicator for "+this.toString(true)+": "+id+" ("+(expectedGroupEndId ? expectedGroupEndId+" expected" : "not a group")+")");
8645 break;
8646 }
8647 if (!(field = this._fieldsById[id])) {
8648 // "messages created by your new code can be parsed by your old code: old binaries simply ignore the new field when parsing."
8649 switch (wireType) {
8650 case ProtoBuf.WIRE_TYPES.VARINT:
8651 buffer.readVarint32();
8652 break;
8653 case ProtoBuf.WIRE_TYPES.BITS32:
8654 buffer.offset += 4;
8655 break;
8656 case ProtoBuf.WIRE_TYPES.BITS64:
8657 buffer.offset += 8;
8658 break;
8659 case ProtoBuf.WIRE_TYPES.LDELIM:
8660 var len = buffer.readVarint32();
8661 buffer.offset += len;
8662 break;
8663 case ProtoBuf.WIRE_TYPES.STARTGROUP:
8664 while (skipTillGroupEnd(id, buffer)) {}
8665 break;
8666 default:
8667 throw Error("Illegal wire type for unknown field "+id+" in "+this.toString(true)+"#decode: "+wireType);
8668 }
8669 continue;
8670 }
8671 if (field.repeated && !field.options["packed"]) {
8672 msg[field.name].push(field.decode(wireType, buffer));
8673 } else if (field.map) {
8674 var keyval = field.decode(wireType, buffer);
8675 msg[field.name].set(keyval[0], keyval[1]);
8676 } else {
8677 msg[field.name] = field.decode(wireType, buffer);
8678 if (field.oneof) { // Field is part of an OneOf (not a virtual OneOf field)
8679 var currentField = msg[field.oneof.name]; // Virtual field references currently set field
8680 if (currentField !== null && currentField !== field.name)
8681 msg[currentField] = null; // Clear currently set field
8682 msg[field.oneof.name] = field.name; // Point virtual field at this field
8683 }
8684 }
8685 }
8686
8687 // Check if all required fields are present and set default values for optional fields that are not
8688 for (var i=0, k=this._fields.length; i<k; ++i) {
8689 field = this._fields[i];
8690 if (msg[field.name] === null) {
8691 if (this.syntax === "proto3") { // Proto3 sets default values by specification
8692 msg[field.name] = field.defaultValue;
8693 } else if (field.required) {
8694 var err = Error("Missing at least one required field for " + this.toString(true) + ": " + field.name);
8695 err["decoded"] = msg; // Still expose what we got
8696 throw(err);
8697 } else if (ProtoBuf.populateDefaults && field.defaultValue !== null)
8698 msg[field.name] = field.defaultValue;
8699 }
8700 }
8701 return msg;
8702 };
8703
8704 /**
8705 * @alias ProtoBuf.Reflect.Message
8706 * @expose
8707 */
8708 Reflect.Message = Message;
8709
8710 /**
8711 * Constructs a new Message Field.
8712 * @exports ProtoBuf.Reflect.Message.Field
8713 * @param {!ProtoBuf.Builder} builder Builder reference
8714 * @param {!ProtoBuf.Reflect.Message} message Message reference
8715 * @param {string} rule Rule, one of requried, optional, repeated
8716 * @param {string?} keytype Key data type, if any.
8717 * @param {string} type Data type, e.g. int32
8718 * @param {string} name Field name
8719 * @param {number} id Unique field id
8720 * @param {Object.<string,*>=} options Options
8721 * @param {!ProtoBuf.Reflect.Message.OneOf=} oneof Enclosing OneOf
8722 * @param {string?} syntax The syntax level of this definition (e.g., proto3)
8723 * @constructor
8724 * @extends ProtoBuf.Reflect.T
8725 */
8726 var Field = function(builder, message, rule, keytype, type, name, id, options, oneof, syntax) {
8727 T.call(this, builder, message, name);
8728
8729 /**
8730 * @override
8731 */
8732 this.className = "Message.Field";
8733
8734 /**
8735 * Message field required flag.
8736 * @type {boolean}
8737 * @expose
8738 */
8739 this.required = rule === "required";
8740
8741 /**
8742 * Message field repeated flag.
8743 * @type {boolean}
8744 * @expose
8745 */
8746 this.repeated = rule === "repeated";
8747
8748 /**
8749 * Message field map flag.
8750 * @type {boolean}
8751 * @expose
8752 */
8753 this.map = rule === "map";
8754
8755 /**
8756 * Message field key type. Type reference string if unresolved, protobuf
8757 * type if resolved. Valid only if this.map === true, null otherwise.
8758 * @type {string|{name: string, wireType: number}|null}
8759 * @expose
8760 */
8761 this.keyType = keytype || null;
8762
8763 /**
8764 * Message field type. Type reference string if unresolved, protobuf type if
8765 * resolved. In a map field, this is the value type.
8766 * @type {string|{name: string, wireType: number}}
8767 * @expose
8768 */
8769 this.type = type;
8770
8771 /**
8772 * Resolved type reference inside the global namespace.
8773 * @type {ProtoBuf.Reflect.T|null}
8774 * @expose
8775 */
8776 this.resolvedType = null;
8777
8778 /**
8779 * Unique message field id.
8780 * @type {number}
8781 * @expose
8782 */
8783 this.id = id;
8784
8785 /**
8786 * Message field options.
8787 * @type {!Object.<string,*>}
8788 * @dict
8789 * @expose
8790 */
8791 this.options = options || {};
8792
8793 /**
8794 * Default value.
8795 * @type {*}
8796 * @expose
8797 */
8798 this.defaultValue = null;
8799
8800 /**
8801 * Enclosing OneOf.
8802 * @type {?ProtoBuf.Reflect.Message.OneOf}
8803 * @expose
8804 */
8805 this.oneof = oneof || null;
8806
8807 /**
8808 * Syntax level of this definition (e.g., proto3).
8809 * @type {string}
8810 * @expose
8811 */
8812 this.syntax = syntax || 'proto2';
8813
8814 /**
8815 * Original field name.
8816 * @type {string}
8817 * @expose
8818 */
8819 this.originalName = this.name; // Used to revert camelcase transformation on naming collisions
8820
8821 /**
8822 * Element implementation. Created in build() after types are resolved.
8823 * @type {ProtoBuf.Element}
8824 * @expose
8825 */
8826 this.element = null;
8827
8828 /**
8829 * Key element implementation, for map fields. Created in build() after
8830 * types are resolved.
8831 * @type {ProtoBuf.Element}
8832 * @expose
8833 */
8834 this.keyElement = null;
8835
8836 // Convert field names to camel case notation if the override is set
8837 if (this.builder.options['convertFieldsToCamelCase'] && !(this instanceof Message.ExtensionField))
8838 this.name = ProtoBuf.Util.toCamelCase(this.name);
8839 };
8840
8841 /**
8842 * @alias ProtoBuf.Reflect.Message.Field.prototype
8843 * @inner
8844 */
8845 var FieldPrototype = Field.prototype = Object.create(T.prototype);
8846
8847 /**
8848 * Builds the field.
8849 * @override
8850 * @expose
8851 */
8852 FieldPrototype.build = function() {
8853 this.element = new Element(this.type, this.resolvedType, false, this.syntax, this.name);
8854 if (this.map)
8855 this.keyElement = new Element(this.keyType, undefined, true, this.syntax, this.name);
8856
8857 // In proto3, fields do not have field presence, and every field is set to
8858 // its type's default value ("", 0, 0.0, or false).
8859 if (this.syntax === 'proto3' && !this.repeated && !this.map)
8860 this.defaultValue = Element.defaultFieldValue(this.type);
8861
8862 // Otherwise, default values are present when explicitly specified
8863 else if (typeof this.options['default'] !== 'undefined')
8864 this.defaultValue = this.verifyValue(this.options['default']);
8865 };
8866
8867 /**
8868 * Checks if the given value can be set for this field.
8869 * @param {*} value Value to check
8870 * @param {boolean=} skipRepeated Whether to skip the repeated value check or not. Defaults to false.
8871 * @return {*} Verified, maybe adjusted, value
8872 * @throws {Error} If the value cannot be set for this field
8873 * @expose
8874 */
8875 FieldPrototype.verifyValue = function(value, skipRepeated) {
8876 skipRepeated = skipRepeated || false;
8877 var self = this;
8878 function fail(val, msg) {
8879 throw Error("Illegal value for "+self.toString(true)+" of type "+self.type.name+": "+val+" ("+msg+")");
8880 }
8881 if (value === null) { // NULL values for optional fields
8882 if (this.required)
8883 fail(typeof value, "required");
8884 if (this.syntax === 'proto3' && this.type !== ProtoBuf.TYPES["message"])
8885 fail(typeof value, "proto3 field without field presence cannot be null");
8886 return null;
8887 }
8888 var i;
8889 if (this.repeated && !skipRepeated) { // Repeated values as arrays
8890 if (!Array.isArray(value))
8891 value = [value];
8892 var res = [];
8893 for (i=0; i<value.length; i++)
8894 res.push(this.element.verifyValue(value[i]));
8895 return res;
8896 }
8897 if (this.map && !skipRepeated) { // Map values as objects
8898 if (!(value instanceof ProtoBuf.Map)) {
8899 // If not already a Map, attempt to convert.
8900 if (!(value instanceof Object)) {
8901 fail(typeof value,
8902 "expected ProtoBuf.Map or raw object for map field");
8903 }
8904 return new ProtoBuf.Map(this, value);
8905 } else {
8906 return value;
8907 }
8908 }
8909 // All non-repeated fields expect no array
8910 if (!this.repeated && Array.isArray(value))
8911 fail(typeof value, "no array expected");
8912
8913 return this.element.verifyValue(value);
8914 };
8915
8916 /**
8917 * Determines whether the field will have a presence on the wire given its
8918 * value.
8919 * @param {*} value Verified field value
8920 * @param {!ProtoBuf.Builder.Message} message Runtime message
8921 * @return {boolean} Whether the field will be present on the wire
8922 */
8923 FieldPrototype.hasWirePresence = function(value, message) {
8924 if (this.syntax !== 'proto3')
8925 return (value !== null);
8926 if (this.oneof && message[this.oneof.name] === this.name)
8927 return true;
8928 switch (this.type) {
8929 case ProtoBuf.TYPES["int32"]:
8930 case ProtoBuf.TYPES["sint32"]:
8931 case ProtoBuf.TYPES["sfixed32"]:
8932 case ProtoBuf.TYPES["uint32"]:
8933 case ProtoBuf.TYPES["fixed32"]:
8934 return value !== 0;
8935
8936 case ProtoBuf.TYPES["int64"]:
8937 case ProtoBuf.TYPES["sint64"]:
8938 case ProtoBuf.TYPES["sfixed64"]:
8939 case ProtoBuf.TYPES["uint64"]:
8940 case ProtoBuf.TYPES["fixed64"]:
8941 return value.low !== 0 || value.high !== 0;
8942
8943 case ProtoBuf.TYPES["bool"]:
8944 return value;
8945
8946 case ProtoBuf.TYPES["float"]:
8947 case ProtoBuf.TYPES["double"]:
8948 return value !== 0.0;
8949
8950 case ProtoBuf.TYPES["string"]:
8951 return value.length > 0;
8952
8953 case ProtoBuf.TYPES["bytes"]:
8954 return value.remaining() > 0;
8955
8956 case ProtoBuf.TYPES["enum"]:
8957 return value !== 0;
8958
8959 case ProtoBuf.TYPES["message"]:
8960 return value !== null;
8961 default:
8962 return true;
8963 }
8964 };
8965
8966 /**
8967 * Encodes the specified field value to the specified buffer.
8968 * @param {*} value Verified field value
8969 * @param {ByteBuffer} buffer ByteBuffer to encode to
8970 * @param {!ProtoBuf.Builder.Message} message Runtime message
8971 * @return {ByteBuffer} The ByteBuffer for chaining
8972 * @throws {Error} If the field cannot be encoded
8973 * @expose
8974 */
8975 FieldPrototype.encode = function(value, buffer, message) {
8976 if (this.type === null || typeof this.type !== 'object')
8977 throw Error("[INTERNAL] Unresolved type in "+this.toString(true)+": "+this.type);
8978 if (value === null || (this.repeated && value.length == 0))
8979 return buffer; // Optional omitted
8980 try {
8981 if (this.repeated) {
8982 var i;
8983 // "Only repeated fields of primitive numeric types (types which use the varint, 32-bit, or 64-bit wire
8984 // types) can be declared 'packed'."
8985 if (this.options["packed"] && ProtoBuf.PACKABLE_WIRE_TYPES.indexOf(this.type.wireType) >= 0) {
8986 // "All of the elements of the field are packed into a single key-value pair with wire type 2
8987 // (length-delimited). Each element is encoded the same way it would be normally, except without a
8988 // tag preceding it."
8989 buffer.writeVarint32((this.id << 3) | ProtoBuf.WIRE_TYPES.LDELIM);
8990 buffer.ensureCapacity(buffer.offset += 1); // We do not know the length yet, so let's assume a varint of length 1
8991 var start = buffer.offset; // Remember where the contents begin
8992 for (i=0; i<value.length; i++)
8993 this.element.encodeValue(this.id, value[i], buffer);
8994 var len = buffer.offset-start,
8995 varintLen = ByteBuffer.calculateVarint32(len);
8996 if (varintLen > 1) { // We need to move the contents
8997 var contents = buffer.slice(start, buffer.offset);
8998 start += varintLen-1;
8999 buffer.offset = start;
9000 buffer.append(contents);
9001 }
9002 buffer.writeVarint32(len, start-varintLen);
9003 } else {
9004 // "If your message definition has repeated elements (without the [packed=true] option), the encoded
9005 // message has zero or more key-value pairs with the same tag number"
9006 for (i=0; i<value.length; i++)
9007 buffer.writeVarint32((this.id << 3) | this.type.wireType),
9008 this.element.encodeValue(this.id, value[i], buffer);
9009 }
9010 } else if (this.map) {
9011 // Write out each map entry as a submessage.
9012 value.forEach(function(val, key, m) {
9013 // Compute the length of the submessage (key, val) pair.
9014 var length =
9015 ByteBuffer.calculateVarint32((1 << 3) | this.keyType.wireType) +
9016 this.keyElement.calculateLength(1, key) +
9017 ByteBuffer.calculateVarint32((2 << 3) | this.type.wireType) +
9018 this.element.calculateLength(2, val);
9019
9020 // Submessage with wire type of length-delimited.
9021 buffer.writeVarint32((this.id << 3) | ProtoBuf.WIRE_TYPES.LDELIM);
9022 buffer.writeVarint32(length);
9023
9024 // Write out the key and val.
9025 buffer.writeVarint32((1 << 3) | this.keyType.wireType);
9026 this.keyElement.encodeValue(1, key, buffer);
9027 buffer.writeVarint32((2 << 3) | this.type.wireType);
9028 this.element.encodeValue(2, val, buffer);
9029 }, this);
9030 } else {
9031 if (this.hasWirePresence(value, message)) {
9032 buffer.writeVarint32((this.id << 3) | this.type.wireType);
9033 this.element.encodeValue(this.id, value, buffer);
9034 }
9035 }
9036 } catch (e) {
9037 throw Error("Illegal value for "+this.toString(true)+": "+value+" ("+e+")");
9038 }
9039 return buffer;
9040 };
9041
9042 /**
9043 * Calculates the length of this field's value on the network level.
9044 * @param {*} value Field value
9045 * @param {!ProtoBuf.Builder.Message} message Runtime message
9046 * @returns {number} Byte length
9047 * @expose
9048 */
9049 FieldPrototype.calculate = function(value, message) {
9050 value = this.verifyValue(value); // May throw
9051 if (this.type === null || typeof this.type !== 'object')
9052 throw Error("[INTERNAL] Unresolved type in "+this.toString(true)+": "+this.type);
9053 if (value === null || (this.repeated && value.length == 0))
9054 return 0; // Optional omitted
9055 var n = 0;
9056 try {
9057 if (this.repeated) {
9058 var i, ni;
9059 if (this.options["packed"] && ProtoBuf.PACKABLE_WIRE_TYPES.indexOf(this.type.wireType) >= 0) {
9060 n += ByteBuffer.calculateVarint32((this.id << 3) | ProtoBuf.WIRE_TYPES.LDELIM);
9061 ni = 0;
9062 for (i=0; i<value.length; i++)
9063 ni += this.element.calculateLength(this.id, value[i]);
9064 n += ByteBuffer.calculateVarint32(ni);
9065 n += ni;
9066 } else {
9067 for (i=0; i<value.length; i++)
9068 n += ByteBuffer.calculateVarint32((this.id << 3) | this.type.wireType),
9069 n += this.element.calculateLength(this.id, value[i]);
9070 }
9071 } else if (this.map) {
9072 // Each map entry becomes a submessage.
9073 value.forEach(function(val, key, m) {
9074 // Compute the length of the submessage (key, val) pair.
9075 var length =
9076 ByteBuffer.calculateVarint32((1 << 3) | this.keyType.wireType) +
9077 this.keyElement.calculateLength(1, key) +
9078 ByteBuffer.calculateVarint32((2 << 3) | this.type.wireType) +
9079 this.element.calculateLength(2, val);
9080
9081 n += ByteBuffer.calculateVarint32((this.id << 3) | ProtoBuf.WIRE_TYPES.LDELIM);
9082 n += ByteBuffer.calculateVarint32(length);
9083 n += length;
9084 }, this);
9085 } else {
9086 if (this.hasWirePresence(value, message)) {
9087 n += ByteBuffer.calculateVarint32((this.id << 3) | this.type.wireType);
9088 n += this.element.calculateLength(this.id, value);
9089 }
9090 }
9091 } catch (e) {
9092 throw Error("Illegal value for "+this.toString(true)+": "+value+" ("+e+")");
9093 }
9094 return n;
9095 };
9096
9097 /**
9098 * Decode the field value from the specified buffer.
9099 * @param {number} wireType Leading wire type
9100 * @param {ByteBuffer} buffer ByteBuffer to decode from
9101 * @param {boolean=} skipRepeated Whether to skip the repeated check or not. Defaults to false.
9102 * @return {*} Decoded value: array for packed repeated fields, [key, value] for
9103 * map fields, or an individual value otherwise.
9104 * @throws {Error} If the field cannot be decoded
9105 * @expose
9106 */
9107 FieldPrototype.decode = function(wireType, buffer, skipRepeated) {
9108 var value, nBytes;
9109
9110 // We expect wireType to match the underlying type's wireType unless we see
9111 // a packed repeated field, or unless this is a map field.
9112 var wireTypeOK =
9113 (!this.map && wireType == this.type.wireType) ||
9114 (!skipRepeated && this.repeated && this.options["packed"] &&
9115 wireType == ProtoBuf.WIRE_TYPES.LDELIM) ||
9116 (this.map && wireType == ProtoBuf.WIRE_TYPES.LDELIM);
9117 if (!wireTypeOK)
9118 throw Error("Illegal wire type for field "+this.toString(true)+": "+wireType+" ("+this.type.wireType+" expected)");
9119
9120 // Handle packed repeated fields.
9121 if (wireType == ProtoBuf.WIRE_TYPES.LDELIM && this.repeated && this.options["packed"] && ProtoBuf.PACKABLE_WIRE_TYPES.indexOf(this.type.wireType) >= 0) {
9122 if (!skipRepeated) {
9123 nBytes = buffer.readVarint32();
9124 nBytes = buffer.offset + nBytes; // Limit
9125 var values = [];
9126 while (buffer.offset < nBytes)
9127 values.push(this.decode(this.type.wireType, buffer, true));
9128 return values;
9129 }
9130 // Read the next value otherwise...
9131 }
9132
9133 // Handle maps.
9134 if (this.map) {
9135 // Read one (key, value) submessage, and return [key, value]
9136 var key = Element.defaultFieldValue(this.keyType);
9137 value = Element.defaultFieldValue(this.type);
9138
9139 // Read the length
9140 nBytes = buffer.readVarint32();
9141 if (buffer.remaining() < nBytes)
9142 throw Error("Illegal number of bytes for "+this.toString(true)+": "+nBytes+" required but got only "+buffer.remaining());
9143
9144 // Get a sub-buffer of this key/value submessage
9145 var msgbuf = buffer.clone();
9146 msgbuf.limit = msgbuf.offset + nBytes;
9147 buffer.offset += nBytes;
9148
9149 while (msgbuf.remaining() > 0) {
9150 var tag = msgbuf.readVarint32();
9151 wireType = tag & 0x07;
9152 var id = tag >>> 3;
9153 if (id === 1) {
9154 key = this.keyElement.decode(msgbuf, wireType, id);
9155 } else if (id === 2) {
9156 value = this.element.decode(msgbuf, wireType, id);
9157 } else {
9158 throw Error("Unexpected tag in map field key/value submessage");
9159 }
9160 }
9161
9162 return [key, value];
9163 }
9164
9165 // Handle singular and non-packed repeated field values.
9166 return this.element.decode(buffer, wireType, this.id);
9167 };
9168
9169 /**
9170 * @alias ProtoBuf.Reflect.Message.Field
9171 * @expose
9172 */
9173 Reflect.Message.Field = Field;
9174
9175 /**
9176 * Constructs a new Message ExtensionField.
9177 * @exports ProtoBuf.Reflect.Message.ExtensionField
9178 * @param {!ProtoBuf.Builder} builder Builder reference
9179 * @param {!ProtoBuf.Reflect.Message} message Message reference
9180 * @param {string} rule Rule, one of requried, optional, repeated
9181 * @param {string} type Data type, e.g. int32
9182 * @param {string} name Field name
9183 * @param {number} id Unique field id
9184 * @param {!Object.<string,*>=} options Options
9185 * @constructor
9186 * @extends ProtoBuf.Reflect.Message.Field
9187 */
9188 var ExtensionField = function(builder, message, rule, type, name, id, options) {
9189 Field.call(this, builder, message, rule, /* keytype = */ null, type, name, id, options);
9190
9191 /**
9192 * Extension reference.
9193 * @type {!ProtoBuf.Reflect.Extension}
9194 * @expose
9195 */
9196 this.extension;
9197 };
9198
9199 // Extends Field
9200 ExtensionField.prototype = Object.create(Field.prototype);
9201
9202 /**
9203 * @alias ProtoBuf.Reflect.Message.ExtensionField
9204 * @expose
9205 */
9206 Reflect.Message.ExtensionField = ExtensionField;
9207
9208 /**
9209 * Constructs a new Message OneOf.
9210 * @exports ProtoBuf.Reflect.Message.OneOf
9211 * @param {!ProtoBuf.Builder} builder Builder reference
9212 * @param {!ProtoBuf.Reflect.Message} message Message reference
9213 * @param {string} name OneOf name
9214 * @constructor
9215 * @extends ProtoBuf.Reflect.T
9216 */
9217 var OneOf = function(builder, message, name) {
9218 T.call(this, builder, message, name);
9219
9220 /**
9221 * Enclosed fields.
9222 * @type {!Array.<!ProtoBuf.Reflect.Message.Field>}
9223 * @expose
9224 */
9225 this.fields = [];
9226 };
9227
9228 /**
9229 * @alias ProtoBuf.Reflect.Message.OneOf
9230 * @expose
9231 */
9232 Reflect.Message.OneOf = OneOf;
9233
9234 /**
9235 * Constructs a new Enum.
9236 * @exports ProtoBuf.Reflect.Enum
9237 * @param {!ProtoBuf.Builder} builder Builder reference
9238 * @param {!ProtoBuf.Reflect.T} parent Parent Reflect object
9239 * @param {string} name Enum name
9240 * @param {Object.<string,*>=} options Enum options
9241 * @param {string?} syntax The syntax level (e.g., proto3)
9242 * @constructor
9243 * @extends ProtoBuf.Reflect.Namespace
9244 */
9245 var Enum = function(builder, parent, name, options, syntax) {
9246 Namespace.call(this, builder, parent, name, options, syntax);
9247
9248 /**
9249 * @override
9250 */
9251 this.className = "Enum";
9252
9253 /**
9254 * Runtime enum object.
9255 * @type {Object.<string,number>|null}
9256 * @expose
9257 */
9258 this.object = null;
9259 };
9260
9261 /**
9262 * Gets the string name of an enum value.
9263 * @param {!ProtoBuf.Builder.Enum} enm Runtime enum
9264 * @param {number} value Enum value
9265 * @returns {?string} Name or `null` if not present
9266 * @expose
9267 */
9268 Enum.getName = function(enm, value) {
9269 var keys = Object.keys(enm);
9270 for (var i=0, key; i<keys.length; ++i)
9271 if (enm[key = keys[i]] === value)
9272 return key;
9273 return null;
9274 };
9275
9276 /**
9277 * @alias ProtoBuf.Reflect.Enum.prototype
9278 * @inner
9279 */
9280 var EnumPrototype = Enum.prototype = Object.create(Namespace.prototype);
9281
9282 /**
9283 * Builds this enum and returns the runtime counterpart.
9284 * @param {boolean} rebuild Whether to rebuild or not, defaults to false
9285 * @returns {!Object.<string,number>}
9286 * @expose
9287 */
9288 EnumPrototype.build = function(rebuild) {
9289 if (this.object && !rebuild)
9290 return this.object;
9291 var enm = new ProtoBuf.Builder.Enum(),
9292 values = this.getChildren(Enum.Value);
9293 for (var i=0, k=values.length; i<k; ++i)
9294 enm[values[i]['name']] = values[i]['id'];
9295 if (Object.defineProperty)
9296 Object.defineProperty(enm, '$options', {
9297 "value": this.buildOpt(),
9298 "enumerable": false
9299 });
9300 return this.object = enm;
9301 };
9302
9303 /**
9304 * @alias ProtoBuf.Reflect.Enum
9305 * @expose
9306 */
9307 Reflect.Enum = Enum;
9308
9309 /**
9310 * Constructs a new Enum Value.
9311 * @exports ProtoBuf.Reflect.Enum.Value
9312 * @param {!ProtoBuf.Builder} builder Builder reference
9313 * @param {!ProtoBuf.Reflect.Enum} enm Enum reference
9314 * @param {string} name Field name
9315 * @param {number} id Unique field id
9316 * @constructor
9317 * @extends ProtoBuf.Reflect.T
9318 */
9319 var Value = function(builder, enm, name, id) {
9320 T.call(this, builder, enm, name);
9321
9322 /**
9323 * @override
9324 */
9325 this.className = "Enum.Value";
9326
9327 /**
9328 * Unique enum value id.
9329 * @type {number}
9330 * @expose
9331 */
9332 this.id = id;
9333 };
9334
9335 // Extends T
9336 Value.prototype = Object.create(T.prototype);
9337
9338 /**
9339 * @alias ProtoBuf.Reflect.Enum.Value
9340 * @expose
9341 */
9342 Reflect.Enum.Value = Value;
9343
9344 /**
9345 * An extension (field).
9346 * @exports ProtoBuf.Reflect.Extension
9347 * @constructor
9348 * @param {!ProtoBuf.Builder} builder Builder reference
9349 * @param {!ProtoBuf.Reflect.T} parent Parent object
9350 * @param {string} name Object name
9351 * @param {!ProtoBuf.Reflect.Message.Field} field Extension field
9352 */
9353 var Extension = function(builder, parent, name, field) {
9354 T.call(this, builder, parent, name);
9355
9356 /**
9357 * Extended message field.
9358 * @type {!ProtoBuf.Reflect.Message.Field}
9359 * @expose
9360 */
9361 this.field = field;
9362 };
9363
9364 // Extends T
9365 Extension.prototype = Object.create(T.prototype);
9366
9367 /**
9368 * @alias ProtoBuf.Reflect.Extension
9369 * @expose
9370 */
9371 Reflect.Extension = Extension;
9372
9373 /**
9374 * Constructs a new Service.
9375 * @exports ProtoBuf.Reflect.Service
9376 * @param {!ProtoBuf.Builder} builder Builder reference
9377 * @param {!ProtoBuf.Reflect.Namespace} root Root
9378 * @param {string} name Service name
9379 * @param {Object.<string,*>=} options Options
9380 * @constructor
9381 * @extends ProtoBuf.Reflect.Namespace
9382 */
9383 var Service = function(builder, root, name, options) {
9384 Namespace.call(this, builder, root, name, options);
9385
9386 /**
9387 * @override
9388 */
9389 this.className = "Service";
9390
9391 /**
9392 * Built runtime service class.
9393 * @type {?function(new:ProtoBuf.Builder.Service)}
9394 */
9395 this.clazz = null;
9396 };
9397
9398 /**
9399 * @alias ProtoBuf.Reflect.Service.prototype
9400 * @inner
9401 */
9402 var ServicePrototype = Service.prototype = Object.create(Namespace.prototype);
9403
9404 /**
9405 * Builds the service and returns the runtime counterpart, which is a fully functional class.
9406 * @see ProtoBuf.Builder.Service
9407 * @param {boolean=} rebuild Whether to rebuild or not
9408 * @return {Function} Service class
9409 * @throws {Error} If the message cannot be built
9410 * @expose
9411 */
9412 ServicePrototype.build = function(rebuild) {
9413 if (this.clazz && !rebuild)
9414 return this.clazz;
9415
9416 // Create the runtime Service class in its own scope
9417 return this.clazz = (function(ProtoBuf, T) {
9418
9419 /**
9420 * Constructs a new runtime Service.
9421 * @name ProtoBuf.Builder.Service
9422 * @param {function(string, ProtoBuf.Builder.Message, function(Error, ProtoBuf.Builder.Message=))=} rpcImpl RPC implementation receiving the method name and the message
9423 * @class Barebone of all runtime services.
9424 * @constructor
9425 * @throws {Error} If the service cannot be created
9426 */
9427 var Service = function(rpcImpl) {
9428 ProtoBuf.Builder.Service.call(this);
9429
9430 /**
9431 * Service implementation.
9432 * @name ProtoBuf.Builder.Service#rpcImpl
9433 * @type {!function(string, ProtoBuf.Builder.Message, function(Error, ProtoBuf.Builder.Message=))}
9434 * @expose
9435 */
9436 this.rpcImpl = rpcImpl || function(name, msg, callback) {
9437 // This is what a user has to implement: A function receiving the method name, the actual message to
9438 // send (type checked) and the callback that's either provided with the error as its first
9439 // argument or null and the actual response message.
9440 setTimeout(callback.bind(this, Error("Not implemented, see: https://github.com/dcodeIO/ProtoBuf.js/wiki/Services")), 0); // Must be async!
9441 };
9442 };
9443
9444 /**
9445 * @alias ProtoBuf.Builder.Service.prototype
9446 * @inner
9447 */
9448 var ServicePrototype = Service.prototype = Object.create(ProtoBuf.Builder.Service.prototype);
9449
9450 /**
9451 * Asynchronously performs an RPC call using the given RPC implementation.
9452 * @name ProtoBuf.Builder.Service.[Method]
9453 * @function
9454 * @param {!function(string, ProtoBuf.Builder.Message, function(Error, ProtoBuf.Builder.Message=))} rpcImpl RPC implementation
9455 * @param {ProtoBuf.Builder.Message} req Request
9456 * @param {function(Error, (ProtoBuf.Builder.Message|ByteBuffer|Buffer|string)=)} callback Callback receiving
9457 * the error if any and the response either as a pre-parsed message or as its raw bytes
9458 * @abstract
9459 */
9460
9461 /**
9462 * Asynchronously performs an RPC call using the instance's RPC implementation.
9463 * @name ProtoBuf.Builder.Service#[Method]
9464 * @function
9465 * @param {ProtoBuf.Builder.Message} req Request
9466 * @param {function(Error, (ProtoBuf.Builder.Message|ByteBuffer|Buffer|string)=)} callback Callback receiving
9467 * the error if any and the response either as a pre-parsed message or as its raw bytes
9468 * @abstract
9469 */
9470
9471 var rpc = T.getChildren(ProtoBuf.Reflect.Service.RPCMethod);
9472 for (var i=0; i<rpc.length; i++) {
9473 (function(method) {
9474
9475 // service#Method(message, callback)
9476 ServicePrototype[method.name] = function(req, callback) {
9477 try {
9478 try {
9479 // If given as a buffer, decode the request. Will throw a TypeError if not a valid buffer.
9480 req = method.resolvedRequestType.clazz.decode(ByteBuffer.wrap(req));
9481 } catch (err) {
9482 if (!(err instanceof TypeError))
9483 throw err;
9484 }
9485 if (req === null || typeof req !== 'object')
9486 throw Error("Illegal arguments");
9487 if (!(req instanceof method.resolvedRequestType.clazz))
9488 req = new method.resolvedRequestType.clazz(req);
9489 this.rpcImpl(method.fqn(), req, function(err, res) { // Assumes that this is properly async
9490 if (err) {
9491 callback(err);
9492 return;
9493 }
9494 // Coalesce to empty string when service response has empty content
9495 if (res === null)
9496 res = '';
9497 try { res = method.resolvedResponseType.clazz.decode(res); } catch (notABuffer) {}
9498 if (!res || !(res instanceof method.resolvedResponseType.clazz)) {
9499 callback(Error("Illegal response type received in service method "+ T.name+"#"+method.name));
9500 return;
9501 }
9502 callback(null, res);
9503 });
9504 } catch (err) {
9505 setTimeout(callback.bind(this, err), 0);
9506 }
9507 };
9508
9509 // Service.Method(rpcImpl, message, callback)
9510 Service[method.name] = function(rpcImpl, req, callback) {
9511 new Service(rpcImpl)[method.name](req, callback);
9512 };
9513
9514 if (Object.defineProperty)
9515 Object.defineProperty(Service[method.name], "$options", { "value": method.buildOpt() }),
9516 Object.defineProperty(ServicePrototype[method.name], "$options", { "value": Service[method.name]["$options"] });
9517 })(rpc[i]);
9518 }
9519
9520 if (Object.defineProperty)
9521 Object.defineProperty(Service, "$options", { "value": T.buildOpt() }),
9522 Object.defineProperty(ServicePrototype, "$options", { "value": Service["$options"] }),
9523 Object.defineProperty(Service, "$type", { "value": T }),
9524 Object.defineProperty(ServicePrototype, "$type", { "value": T });
9525
9526 return Service;
9527
9528 })(ProtoBuf, this);
9529 };
9530
9531 /**
9532 * @alias ProtoBuf.Reflect.Service
9533 * @expose
9534 */
9535 Reflect.Service = Service;
9536
9537 /**
9538 * Abstract service method.
9539 * @exports ProtoBuf.Reflect.Service.Method
9540 * @param {!ProtoBuf.Builder} builder Builder reference
9541 * @param {!ProtoBuf.Reflect.Service} svc Service
9542 * @param {string} name Method name
9543 * @param {Object.<string,*>=} options Options
9544 * @constructor
9545 * @extends ProtoBuf.Reflect.T
9546 */
9547 var Method = function(builder, svc, name, options) {
9548 T.call(this, builder, svc, name);
9549
9550 /**
9551 * @override
9552 */
9553 this.className = "Service.Method";
9554
9555 /**
9556 * Options.
9557 * @type {Object.<string, *>}
9558 * @expose
9559 */
9560 this.options = options || {};
9561 };
9562
9563 /**
9564 * @alias ProtoBuf.Reflect.Service.Method.prototype
9565 * @inner
9566 */
9567 var MethodPrototype = Method.prototype = Object.create(T.prototype);
9568
9569 /**
9570 * Builds the method's '$options' property.
9571 * @name ProtoBuf.Reflect.Service.Method#buildOpt
9572 * @function
9573 * @return {Object.<string,*>}
9574 */
9575 MethodPrototype.buildOpt = NamespacePrototype.buildOpt;
9576
9577 /**
9578 * @alias ProtoBuf.Reflect.Service.Method
9579 * @expose
9580 */
9581 Reflect.Service.Method = Method;
9582
9583 /**
9584 * RPC service method.
9585 * @exports ProtoBuf.Reflect.Service.RPCMethod
9586 * @param {!ProtoBuf.Builder} builder Builder reference
9587 * @param {!ProtoBuf.Reflect.Service} svc Service
9588 * @param {string} name Method name
9589 * @param {string} request Request message name
9590 * @param {string} response Response message name
9591 * @param {boolean} request_stream Whether requests are streamed
9592 * @param {boolean} response_stream Whether responses are streamed
9593 * @param {Object.<string,*>=} options Options
9594 * @constructor
9595 * @extends ProtoBuf.Reflect.Service.Method
9596 */
9597 var RPCMethod = function(builder, svc, name, request, response, request_stream, response_stream, options) {
9598 Method.call(this, builder, svc, name, options);
9599
9600 /**
9601 * @override
9602 */
9603 this.className = "Service.RPCMethod";
9604
9605 /**
9606 * Request message name.
9607 * @type {string}
9608 * @expose
9609 */
9610 this.requestName = request;
9611
9612 /**
9613 * Response message name.
9614 * @type {string}
9615 * @expose
9616 */
9617 this.responseName = response;
9618
9619 /**
9620 * Whether requests are streamed
9621 * @type {bool}
9622 * @expose
9623 */
9624 this.requestStream = request_stream;
9625
9626 /**
9627 * Whether responses are streamed
9628 * @type {bool}
9629 * @expose
9630 */
9631 this.responseStream = response_stream;
9632
9633 /**
9634 * Resolved request message type.
9635 * @type {ProtoBuf.Reflect.Message}
9636 * @expose
9637 */
9638 this.resolvedRequestType = null;
9639
9640 /**
9641 * Resolved response message type.
9642 * @type {ProtoBuf.Reflect.Message}
9643 * @expose
9644 */
9645 this.resolvedResponseType = null;
9646 };
9647
9648 // Extends Method
9649 RPCMethod.prototype = Object.create(Method.prototype);
9650
9651 /**
9652 * @alias ProtoBuf.Reflect.Service.RPCMethod
9653 * @expose
9654 */
9655 Reflect.Service.RPCMethod = RPCMethod;
9656
9657 return Reflect;
9658
9659 })(ProtoBuf);
9660
9661 /**
9662 * @alias ProtoBuf.Builder
9663 * @expose
9664 */
9665 ProtoBuf.Builder = (function(ProtoBuf, Lang, Reflect) {
9666
9667 /**
9668 * Constructs a new Builder.
9669 * @exports ProtoBuf.Builder
9670 * @class Provides the functionality to build protocol messages.
9671 * @param {Object.<string,*>=} options Options
9672 * @constructor
9673 */
9674 var Builder = function(options) {
9675
9676 /**
9677 * Namespace.
9678 * @type {ProtoBuf.Reflect.Namespace}
9679 * @expose
9680 */
9681 this.ns = new Reflect.Namespace(this, null, ""); // Global namespace
9682
9683 /**
9684 * Namespace pointer.
9685 * @type {ProtoBuf.Reflect.T}
9686 * @expose
9687 */
9688 this.ptr = this.ns;
9689
9690 /**
9691 * Resolved flag.
9692 * @type {boolean}
9693 * @expose
9694 */
9695 this.resolved = false;
9696
9697 /**
9698 * The current building result.
9699 * @type {Object.<string,ProtoBuf.Builder.Message|Object>|null}
9700 * @expose
9701 */
9702 this.result = null;
9703
9704 /**
9705 * Imported files.
9706 * @type {Array.<string>}
9707 * @expose
9708 */
9709 this.files = {};
9710
9711 /**
9712 * Import root override.
9713 * @type {?string}
9714 * @expose
9715 */
9716 this.importRoot = null;
9717
9718 /**
9719 * Options.
9720 * @type {!Object.<string, *>}
9721 * @expose
9722 */
9723 this.options = options || {};
9724 };
9725
9726 /**
9727 * @alias ProtoBuf.Builder.prototype
9728 * @inner
9729 */
9730 var BuilderPrototype = Builder.prototype;
9731
9732 // ----- Definition tests -----
9733
9734 /**
9735 * Tests if a definition most likely describes a message.
9736 * @param {!Object} def
9737 * @returns {boolean}
9738 * @expose
9739 */
9740 Builder.isMessage = function(def) {
9741 // Messages require a string name
9742 if (typeof def["name"] !== 'string')
9743 return false;
9744 // Messages do not contain values (enum) or rpc methods (service)
9745 if (typeof def["values"] !== 'undefined' || typeof def["rpc"] !== 'undefined')
9746 return false;
9747 return true;
9748 };
9749
9750 /**
9751 * Tests if a definition most likely describes a message field.
9752 * @param {!Object} def
9753 * @returns {boolean}
9754 * @expose
9755 */
9756 Builder.isMessageField = function(def) {
9757 // Message fields require a string rule, name and type and an id
9758 if (typeof def["rule"] !== 'string' || typeof def["name"] !== 'string' || typeof def["type"] !== 'string' || typeof def["id"] === 'undefined')
9759 return false;
9760 return true;
9761 };
9762
9763 /**
9764 * Tests if a definition most likely describes an enum.
9765 * @param {!Object} def
9766 * @returns {boolean}
9767 * @expose
9768 */
9769 Builder.isEnum = function(def) {
9770 // Enums require a string name
9771 if (typeof def["name"] !== 'string')
9772 return false;
9773 // Enums require at least one value
9774 if (typeof def["values"] === 'undefined' || !Array.isArray(def["values"]) || def["values"].length === 0)
9775 return false;
9776 return true;
9777 };
9778
9779 /**
9780 * Tests if a definition most likely describes a service.
9781 * @param {!Object} def
9782 * @returns {boolean}
9783 * @expose
9784 */
9785 Builder.isService = function(def) {
9786 // Services require a string name and an rpc object
9787 if (typeof def["name"] !== 'string' || typeof def["rpc"] !== 'object' || !def["rpc"])
9788 return false;
9789 return true;
9790 };
9791
9792 /**
9793 * Tests if a definition most likely describes an extended message
9794 * @param {!Object} def
9795 * @returns {boolean}
9796 * @expose
9797 */
9798 Builder.isExtend = function(def) {
9799 // Extends rquire a string ref
9800 if (typeof def["ref"] !== 'string')
9801 return false;
9802 return true;
9803 };
9804
9805 // ----- Building -----
9806
9807 /**
9808 * Resets the pointer to the root namespace.
9809 * @returns {!ProtoBuf.Builder} this
9810 * @expose
9811 */
9812 BuilderPrototype.reset = function() {
9813 this.ptr = this.ns;
9814 return this;
9815 };
9816
9817 /**
9818 * Defines a namespace on top of the current pointer position and places the pointer on it.
9819 * @param {string} namespace
9820 * @return {!ProtoBuf.Builder} this
9821 * @expose
9822 */
9823 BuilderPrototype.define = function(namespace) {
9824 if (typeof namespace !== 'string' || !Lang.TYPEREF.test(namespace))
9825 throw Error("illegal namespace: "+namespace);
9826 namespace.split(".").forEach(function(part) {
9827 var ns = this.ptr.getChild(part);
9828 if (ns === null) // Keep existing
9829 this.ptr.addChild(ns = new Reflect.Namespace(this, this.ptr, part));
9830 this.ptr = ns;
9831 }, this);
9832 return this;
9833 };
9834
9835 /**
9836 * Creates the specified definitions at the current pointer position.
9837 * @param {!Array.<!Object>} defs Messages, enums or services to create
9838 * @returns {!ProtoBuf.Builder} this
9839 * @throws {Error} If a message definition is invalid
9840 * @expose
9841 */
9842 BuilderPrototype.create = function(defs) {
9843 if (!defs)
9844 return this; // Nothing to create
9845 if (!Array.isArray(defs))
9846 defs = [defs];
9847 else {
9848 if (defs.length === 0)
9849 return this;
9850 defs = defs.slice();
9851 }
9852
9853 // It's quite hard to keep track of scopes and memory here, so let's do this iteratively.
9854 var stack = [defs];
9855 while (stack.length > 0) {
9856 defs = stack.pop();
9857
9858 if (!Array.isArray(defs)) // Stack always contains entire namespaces
9859 throw Error("not a valid namespace: "+JSON.stringify(defs));
9860
9861 while (defs.length > 0) {
9862 var def = defs.shift(); // Namespaces always contain an array of messages, enums and services
9863
9864 if (Builder.isMessage(def)) {
9865 var obj = new Reflect.Message(this, this.ptr, def["name"], def["options"], def["isGroup"], def["syntax"]);
9866
9867 // Create OneOfs
9868 var oneofs = {};
9869 if (def["oneofs"])
9870 Object.keys(def["oneofs"]).forEach(function(name) {
9871 obj.addChild(oneofs[name] = new Reflect.Message.OneOf(this, obj, name));
9872 }, this);
9873
9874 // Create fields
9875 if (def["fields"])
9876 def["fields"].forEach(function(fld) {
9877 if (obj.getChild(fld["id"]|0) !== null)
9878 throw Error("duplicate or invalid field id in "+obj.name+": "+fld['id']);
9879 if (fld["options"] && typeof fld["options"] !== 'object')
9880 throw Error("illegal field options in "+obj.name+"#"+fld["name"]);
9881 var oneof = null;
9882 if (typeof fld["oneof"] === 'string' && !(oneof = oneofs[fld["oneof"]]))
9883 throw Error("illegal oneof in "+obj.name+"#"+fld["name"]+": "+fld["oneof"]);
9884 fld = new Reflect.Message.Field(this, obj, fld["rule"], fld["keytype"], fld["type"], fld["name"], fld["id"], fld["options"], oneof, def["syntax"]);
9885 if (oneof)
9886 oneof.fields.push(fld);
9887 obj.addChild(fld);
9888 }, this);
9889
9890 // Push children to stack
9891 var subObj = [];
9892 if (def["enums"])
9893 def["enums"].forEach(function(enm) {
9894 subObj.push(enm);
9895 });
9896 if (def["messages"])
9897 def["messages"].forEach(function(msg) {
9898 subObj.push(msg);
9899 });
9900 if (def["services"])
9901 def["services"].forEach(function(svc) {
9902 subObj.push(svc);
9903 });
9904
9905 // Set extension ranges
9906 if (def["extensions"]) {
9907 if (typeof def["extensions"][0] === 'number') // pre 5.0.1
9908 obj.extensions = [ def["extensions"] ];
9909 else
9910 obj.extensions = def["extensions"];
9911 }
9912
9913 // Create on top of current namespace
9914 this.ptr.addChild(obj);
9915 if (subObj.length > 0) {
9916 stack.push(defs); // Push the current level back
9917 defs = subObj; // Continue processing sub level
9918 subObj = null;
9919 this.ptr = obj; // And move the pointer to this namespace
9920 obj = null;
9921 continue;
9922 }
9923 subObj = null;
9924
9925 } else if (Builder.isEnum(def)) {
9926
9927 obj = new Reflect.Enum(this, this.ptr, def["name"], def["options"], def["syntax"]);
9928 def["values"].forEach(function(val) {
9929 obj.addChild(new Reflect.Enum.Value(this, obj, val["name"], val["id"]));
9930 }, this);
9931 this.ptr.addChild(obj);
9932
9933 } else if (Builder.isService(def)) {
9934
9935 obj = new Reflect.Service(this, this.ptr, def["name"], def["options"]);
9936 Object.keys(def["rpc"]).forEach(function(name) {
9937 var mtd = def["rpc"][name];
9938 obj.addChild(new Reflect.Service.RPCMethod(this, obj, name, mtd["request"], mtd["response"], !!mtd["request_stream"], !!mtd["response_stream"], mtd["options"]));
9939 }, this);
9940 this.ptr.addChild(obj);
9941
9942 } else if (Builder.isExtend(def)) {
9943
9944 obj = this.ptr.resolve(def["ref"], true);
9945 if (obj) {
9946 def["fields"].forEach(function(fld) {
9947 if (obj.getChild(fld['id']|0) !== null)
9948 throw Error("duplicate extended field id in "+obj.name+": "+fld['id']);
9949 // Check if field id is allowed to be extended
9950 if (obj.extensions) {
9951 var valid = false;
9952 obj.extensions.forEach(function(range) {
9953 if (fld["id"] >= range[0] && fld["id"] <= range[1])
9954 valid = true;
9955 });
9956 if (!valid)
9957 throw Error("illegal extended field id in "+obj.name+": "+fld['id']+" (not within valid ranges)");
9958 }
9959 // Convert extension field names to camel case notation if the override is set
9960 var name = fld["name"];
9961 if (this.options['convertFieldsToCamelCase'])
9962 name = ProtoBuf.Util.toCamelCase(name);
9963 // see #161: Extensions use their fully qualified name as their runtime key and...
9964 var field = new Reflect.Message.ExtensionField(this, obj, fld["rule"], fld["type"], this.ptr.fqn()+'.'+name, fld["id"], fld["options"]);
9965 // ...are added on top of the current namespace as an extension which is used for
9966 // resolving their type later on (the extension always keeps the original name to
9967 // prevent naming collisions)
9968 var ext = new Reflect.Extension(this, this.ptr, fld["name"], field);
9969 field.extension = ext;
9970 this.ptr.addChild(ext);
9971 obj.addChild(field);
9972 }, this);
9973
9974 } else if (!/\.?google\.protobuf\./.test(def["ref"])) // Silently skip internal extensions
9975 throw Error("extended message "+def["ref"]+" is not defined");
9976
9977 } else
9978 throw Error("not a valid definition: "+JSON.stringify(def));
9979
9980 def = null;
9981 obj = null;
9982 }
9983 // Break goes here
9984 defs = null;
9985 this.ptr = this.ptr.parent; // Namespace done, continue at parent
9986 }
9987 this.resolved = false; // Require re-resolve
9988 this.result = null; // Require re-build
9989 return this;
9990 };
9991
9992 /**
9993 * Propagates syntax to all children.
9994 * @param {!Object} parent
9995 * @inner
9996 */
9997 function propagateSyntax(parent) {
9998 if (parent['messages']) {
9999 parent['messages'].forEach(function(child) {
10000 child["syntax"] = parent["syntax"];
10001 propagateSyntax(child);
10002 });
10003 }
10004 if (parent['enums']) {
10005 parent['enums'].forEach(function(child) {
10006 child["syntax"] = parent["syntax"];
10007 });
10008 }
10009 }
10010
10011 /**
10012 * Imports another definition into this builder.
10013 * @param {Object.<string,*>} json Parsed import
10014 * @param {(string|{root: string, file: string})=} filename Imported file name
10015 * @returns {!ProtoBuf.Builder} this
10016 * @throws {Error} If the definition or file cannot be imported
10017 * @expose
10018 */
10019 BuilderPrototype["import"] = function(json, filename) {
10020 var delim = '/';
10021
10022 // Make sure to skip duplicate imports
10023
10024 if (typeof filename === 'string') {
10025
10026 if (ProtoBuf.Util.IS_NODE)
10027 filename = require$$2['resolve'](filename);
10028 if (this.files[filename] === true)
10029 return this.reset();
10030 this.files[filename] = true;
10031
10032 } else if (typeof filename === 'object') { // Object with root, file.
10033
10034 var root = filename.root;
10035 if (ProtoBuf.Util.IS_NODE)
10036 root = require$$2['resolve'](root);
10037 if (root.indexOf("\\") >= 0 || filename.file.indexOf("\\") >= 0)
10038 delim = '\\';
10039 var fname;
10040 if (ProtoBuf.Util.IS_NODE)
10041 fname = require$$2['join'](root, filename.file);
10042 else
10043 fname = root + delim + filename.file;
10044 if (this.files[fname] === true)
10045 return this.reset();
10046 this.files[fname] = true;
10047 }
10048
10049 // Import imports
10050
10051 if (json['imports'] && json['imports'].length > 0) {
10052 var importRoot,
10053 resetRoot = false;
10054
10055 if (typeof filename === 'object') { // If an import root is specified, override
10056
10057 this.importRoot = filename["root"]; resetRoot = true; // ... and reset afterwards
10058 importRoot = this.importRoot;
10059 filename = filename["file"];
10060 if (importRoot.indexOf("\\") >= 0 || filename.indexOf("\\") >= 0)
10061 delim = '\\';
10062
10063 } else if (typeof filename === 'string') {
10064
10065 if (this.importRoot) // If import root is overridden, use it
10066 importRoot = this.importRoot;
10067 else { // Otherwise compute from filename
10068 if (filename.indexOf("/") >= 0) { // Unix
10069 importRoot = filename.replace(/\/[^\/]*$/, "");
10070 if (/* /file.proto */ importRoot === "")
10071 importRoot = "/";
10072 } else if (filename.indexOf("\\") >= 0) { // Windows
10073 importRoot = filename.replace(/\\[^\\]*$/, "");
10074 delim = '\\';
10075 } else
10076 importRoot = ".";
10077 }
10078
10079 } else
10080 importRoot = null;
10081
10082 for (var i=0; i<json['imports'].length; i++) {
10083 if (typeof json['imports'][i] === 'string') { // Import file
10084 if (!importRoot)
10085 throw Error("cannot determine import root");
10086 var importFilename = json['imports'][i];
10087 if (importFilename === "google/protobuf/descriptor.proto")
10088 continue; // Not needed and therefore not used
10089 if (ProtoBuf.Util.IS_NODE)
10090 importFilename = require$$2['join'](importRoot, importFilename);
10091 else
10092 importFilename = importRoot + delim + importFilename;
10093 if (this.files[importFilename] === true)
10094 continue; // Already imported
10095 if (/\.proto$/i.test(importFilename) && !ProtoBuf.DotProto) // If this is a light build
10096 importFilename = importFilename.replace(/\.proto$/, ".json"); // always load the JSON file
10097 var contents = ProtoBuf.Util.fetch(importFilename);
10098 if (contents === null)
10099 throw Error("failed to import '"+importFilename+"' in '"+filename+"': file not found");
10100 if (/\.json$/i.test(importFilename)) // Always possible
10101 this["import"](JSON.parse(contents+""), importFilename); // May throw
10102 else
10103 this["import"](ProtoBuf.DotProto.Parser.parse(contents), importFilename); // May throw
10104 } else // Import structure
10105 if (!filename)
10106 this["import"](json['imports'][i]);
10107 else if (/\.(\w+)$/.test(filename)) // With extension: Append _importN to the name portion to make it unique
10108 this["import"](json['imports'][i], filename.replace(/^(.+)\.(\w+)$/, function($0, $1, $2) { return $1+"_import"+i+"."+$2; }));
10109 else // Without extension: Append _importN to make it unique
10110 this["import"](json['imports'][i], filename+"_import"+i);
10111 }
10112 if (resetRoot) // Reset import root override when all imports are done
10113 this.importRoot = null;
10114 }
10115
10116 // Import structures
10117
10118 if (json['package'])
10119 this.define(json['package']);
10120 if (json['syntax'])
10121 propagateSyntax(json);
10122 var base = this.ptr;
10123 if (json['options'])
10124 Object.keys(json['options']).forEach(function(key) {
10125 base.options[key] = json['options'][key];
10126 });
10127 if (json['messages'])
10128 this.create(json['messages']),
10129 this.ptr = base;
10130 if (json['enums'])
10131 this.create(json['enums']),
10132 this.ptr = base;
10133 if (json['services'])
10134 this.create(json['services']),
10135 this.ptr = base;
10136 if (json['extends'])
10137 this.create(json['extends']);
10138
10139 return this.reset();
10140 };
10141
10142 /**
10143 * Resolves all namespace objects.
10144 * @throws {Error} If a type cannot be resolved
10145 * @returns {!ProtoBuf.Builder} this
10146 * @expose
10147 */
10148 BuilderPrototype.resolveAll = function() {
10149 // Resolve all reflected objects
10150 var res;
10151 if (this.ptr == null || typeof this.ptr.type === 'object')
10152 return this; // Done (already resolved)
10153
10154 if (this.ptr instanceof Reflect.Namespace) { // Resolve children
10155
10156 this.ptr.children.forEach(function(child) {
10157 this.ptr = child;
10158 this.resolveAll();
10159 }, this);
10160
10161 } else if (this.ptr instanceof Reflect.Message.Field) { // Resolve type
10162
10163 if (!Lang.TYPE.test(this.ptr.type)) {
10164 if (!Lang.TYPEREF.test(this.ptr.type))
10165 throw Error("illegal type reference in "+this.ptr.toString(true)+": "+this.ptr.type);
10166 res = (this.ptr instanceof Reflect.Message.ExtensionField ? this.ptr.extension.parent : this.ptr.parent).resolve(this.ptr.type, true);
10167 if (!res)
10168 throw Error("unresolvable type reference in "+this.ptr.toString(true)+": "+this.ptr.type);
10169 this.ptr.resolvedType = res;
10170 if (res instanceof Reflect.Enum) {
10171 this.ptr.type = ProtoBuf.TYPES["enum"];
10172 if (this.ptr.syntax === 'proto3' && res.syntax !== 'proto3')
10173 throw Error("proto3 message cannot reference proto2 enum");
10174 }
10175 else if (res instanceof Reflect.Message)
10176 this.ptr.type = res.isGroup ? ProtoBuf.TYPES["group"] : ProtoBuf.TYPES["message"];
10177 else
10178 throw Error("illegal type reference in "+this.ptr.toString(true)+": "+this.ptr.type);
10179 } else
10180 this.ptr.type = ProtoBuf.TYPES[this.ptr.type];
10181
10182 // If it's a map field, also resolve the key type. The key type can be only a numeric, string, or bool type
10183 // (i.e., no enums or messages), so we don't need to resolve against the current namespace.
10184 if (this.ptr.map) {
10185 if (!Lang.TYPE.test(this.ptr.keyType))
10186 throw Error("illegal key type for map field in "+this.ptr.toString(true)+": "+this.ptr.keyType);
10187 this.ptr.keyType = ProtoBuf.TYPES[this.ptr.keyType];
10188 }
10189
10190 // If it's a repeated and packable field then proto3 mandates it should be packed by
10191 // default
10192 if (
10193 this.ptr.syntax === 'proto3' &&
10194 this.ptr.repeated && this.ptr.options.packed === undefined &&
10195 ProtoBuf.PACKABLE_WIRE_TYPES.indexOf(this.ptr.type.wireType) !== -1
10196 ) {
10197 this.ptr.options.packed = true;
10198 }
10199
10200 } else if (this.ptr instanceof ProtoBuf.Reflect.Service.Method) {
10201
10202 if (this.ptr instanceof ProtoBuf.Reflect.Service.RPCMethod) {
10203 res = this.ptr.parent.resolve(this.ptr.requestName, true);
10204 if (!res || !(res instanceof ProtoBuf.Reflect.Message))
10205 throw Error("Illegal type reference in "+this.ptr.toString(true)+": "+this.ptr.requestName);
10206 this.ptr.resolvedRequestType = res;
10207 res = this.ptr.parent.resolve(this.ptr.responseName, true);
10208 if (!res || !(res instanceof ProtoBuf.Reflect.Message))
10209 throw Error("Illegal type reference in "+this.ptr.toString(true)+": "+this.ptr.responseName);
10210 this.ptr.resolvedResponseType = res;
10211 } else // Should not happen as nothing else is implemented
10212 throw Error("illegal service type in "+this.ptr.toString(true));
10213
10214 } else if (
10215 !(this.ptr instanceof ProtoBuf.Reflect.Message.OneOf) && // Not built
10216 !(this.ptr instanceof ProtoBuf.Reflect.Extension) && // Not built
10217 !(this.ptr instanceof ProtoBuf.Reflect.Enum.Value) // Built in enum
10218 )
10219 throw Error("illegal object in namespace: "+typeof(this.ptr)+": "+this.ptr);
10220
10221 return this.reset();
10222 };
10223
10224 /**
10225 * Builds the protocol. This will first try to resolve all definitions and, if this has been successful,
10226 * return the built package.
10227 * @param {(string|Array.<string>)=} path Specifies what to return. If omitted, the entire namespace will be returned.
10228 * @returns {!ProtoBuf.Builder.Message|!Object.<string,*>}
10229 * @throws {Error} If a type could not be resolved
10230 * @expose
10231 */
10232 BuilderPrototype.build = function(path) {
10233 this.reset();
10234 if (!this.resolved)
10235 this.resolveAll(),
10236 this.resolved = true,
10237 this.result = null; // Require re-build
10238 if (this.result === null) // (Re-)Build
10239 this.result = this.ns.build();
10240 if (!path)
10241 return this.result;
10242 var part = typeof path === 'string' ? path.split(".") : path,
10243 ptr = this.result; // Build namespace pointer (no hasChild etc.)
10244 for (var i=0; i<part.length; i++)
10245 if (ptr[part[i]])
10246 ptr = ptr[part[i]];
10247 else {
10248 ptr = null;
10249 break;
10250 }
10251 return ptr;
10252 };
10253
10254 /**
10255 * Similar to {@link ProtoBuf.Builder#build}, but looks up the internal reflection descriptor.
10256 * @param {string=} path Specifies what to return. If omitted, the entire namespace wiil be returned.
10257 * @param {boolean=} excludeNonNamespace Excludes non-namespace types like fields, defaults to `false`
10258 * @returns {?ProtoBuf.Reflect.T} Reflection descriptor or `null` if not found
10259 */
10260 BuilderPrototype.lookup = function(path, excludeNonNamespace) {
10261 return path ? this.ns.resolve(path, excludeNonNamespace) : this.ns;
10262 };
10263
10264 /**
10265 * Returns a string representation of this object.
10266 * @return {string} String representation as of "Builder"
10267 * @expose
10268 */
10269 BuilderPrototype.toString = function() {
10270 return "Builder";
10271 };
10272
10273 // ----- Base classes -----
10274 // Exist for the sole purpose of being able to "... instanceof ProtoBuf.Builder.Message" etc.
10275
10276 /**
10277 * @alias ProtoBuf.Builder.Message
10278 */
10279 Builder.Message = function() {};
10280
10281 /**
10282 * @alias ProtoBuf.Builder.Enum
10283 */
10284 Builder.Enum = function() {};
10285
10286 /**
10287 * @alias ProtoBuf.Builder.Message
10288 */
10289 Builder.Service = function() {};
10290
10291 return Builder;
10292
10293 })(ProtoBuf, ProtoBuf.Lang, ProtoBuf.Reflect);
10294
10295 /**
10296 * @alias ProtoBuf.Map
10297 * @expose
10298 */
10299 ProtoBuf.Map = (function(ProtoBuf, Reflect) {
10300
10301 /**
10302 * Constructs a new Map. A Map is a container that is used to implement map
10303 * fields on message objects. It closely follows the ES6 Map API; however,
10304 * it is distinct because we do not want to depend on external polyfills or
10305 * on ES6 itself.
10306 *
10307 * @exports ProtoBuf.Map
10308 * @param {!ProtoBuf.Reflect.Field} field Map field
10309 * @param {Object.<string,*>=} contents Initial contents
10310 * @constructor
10311 */
10312 var Map = function(field, contents) {
10313 if (!field.map)
10314 throw Error("field is not a map");
10315
10316 /**
10317 * The field corresponding to this map.
10318 * @type {!ProtoBuf.Reflect.Field}
10319 */
10320 this.field = field;
10321
10322 /**
10323 * Element instance corresponding to key type.
10324 * @type {!ProtoBuf.Reflect.Element}
10325 */
10326 this.keyElem = new Reflect.Element(field.keyType, null, true, field.syntax);
10327
10328 /**
10329 * Element instance corresponding to value type.
10330 * @type {!ProtoBuf.Reflect.Element}
10331 */
10332 this.valueElem = new Reflect.Element(field.type, field.resolvedType, false, field.syntax);
10333
10334 /**
10335 * Internal map: stores mapping of (string form of key) -> (key, value)
10336 * pair.
10337 *
10338 * We provide map semantics for arbitrary key types, but we build on top
10339 * of an Object, which has only string keys. In order to avoid the need
10340 * to convert a string key back to its native type in many situations,
10341 * we store the native key value alongside the value. Thus, we only need
10342 * a one-way mapping from a key type to its string form that guarantees
10343 * uniqueness and equality (i.e., str(K1) === str(K2) if and only if K1
10344 * === K2).
10345 *
10346 * @type {!Object<string, {key: *, value: *}>}
10347 */
10348 this.map = {};
10349
10350 /**
10351 * Returns the number of elements in the map.
10352 */
10353 Object.defineProperty(this, "size", {
10354 get: function() { return Object.keys(this.map).length; }
10355 });
10356
10357 // Fill initial contents from a raw object.
10358 if (contents) {
10359 var keys = Object.keys(contents);
10360 for (var i = 0; i < keys.length; i++) {
10361 var key = this.keyElem.valueFromString(keys[i]);
10362 var val = this.valueElem.verifyValue(contents[keys[i]]);
10363 this.map[this.keyElem.valueToString(key)] =
10364 { key: key, value: val };
10365 }
10366 }
10367 };
10368
10369 var MapPrototype = Map.prototype;
10370
10371 /**
10372 * Helper: return an iterator over an array.
10373 * @param {!Array<*>} arr the array
10374 * @returns {!Object} an iterator
10375 * @inner
10376 */
10377 function arrayIterator(arr) {
10378 var idx = 0;
10379 return {
10380 next: function() {
10381 if (idx < arr.length)
10382 return { done: false, value: arr[idx++] };
10383 return { done: true };
10384 }
10385 }
10386 }
10387
10388 /**
10389 * Clears the map.
10390 */
10391 MapPrototype.clear = function() {
10392 this.map = {};
10393 };
10394
10395 /**
10396 * Deletes a particular key from the map.
10397 * @returns {boolean} Whether any entry with this key was deleted.
10398 */
10399 MapPrototype["delete"] = function(key) {
10400 var keyValue = this.keyElem.valueToString(this.keyElem.verifyValue(key));
10401 var hadKey = keyValue in this.map;
10402 delete this.map[keyValue];
10403 return hadKey;
10404 };
10405
10406 /**
10407 * Returns an iterator over [key, value] pairs in the map.
10408 * @returns {Object} The iterator
10409 */
10410 MapPrototype.entries = function() {
10411 var entries = [];
10412 var strKeys = Object.keys(this.map);
10413 for (var i = 0, entry; i < strKeys.length; i++)
10414 entries.push([(entry=this.map[strKeys[i]]).key, entry.value]);
10415 return arrayIterator(entries);
10416 };
10417
10418 /**
10419 * Returns an iterator over keys in the map.
10420 * @returns {Object} The iterator
10421 */
10422 MapPrototype.keys = function() {
10423 var keys = [];
10424 var strKeys = Object.keys(this.map);
10425 for (var i = 0; i < strKeys.length; i++)
10426 keys.push(this.map[strKeys[i]].key);
10427 return arrayIterator(keys);
10428 };
10429
10430 /**
10431 * Returns an iterator over values in the map.
10432 * @returns {!Object} The iterator
10433 */
10434 MapPrototype.values = function() {
10435 var values = [];
10436 var strKeys = Object.keys(this.map);
10437 for (var i = 0; i < strKeys.length; i++)
10438 values.push(this.map[strKeys[i]].value);
10439 return arrayIterator(values);
10440 };
10441
10442 /**
10443 * Iterates over entries in the map, calling a function on each.
10444 * @param {function(this:*, *, *, *)} cb The callback to invoke with value, key, and map arguments.
10445 * @param {Object=} thisArg The `this` value for the callback
10446 */
10447 MapPrototype.forEach = function(cb, thisArg) {
10448 var strKeys = Object.keys(this.map);
10449 for (var i = 0, entry; i < strKeys.length; i++)
10450 cb.call(thisArg, (entry=this.map[strKeys[i]]).value, entry.key, this);
10451 };
10452
10453 /**
10454 * Sets a key in the map to the given value.
10455 * @param {*} key The key
10456 * @param {*} value The value
10457 * @returns {!ProtoBuf.Map} The map instance
10458 */
10459 MapPrototype.set = function(key, value) {
10460 var keyValue = this.keyElem.verifyValue(key);
10461 var valValue = this.valueElem.verifyValue(value);
10462 this.map[this.keyElem.valueToString(keyValue)] =
10463 { key: keyValue, value: valValue };
10464 return this;
10465 };
10466
10467 /**
10468 * Gets the value corresponding to a key in the map.
10469 * @param {*} key The key
10470 * @returns {*|undefined} The value, or `undefined` if key not present
10471 */
10472 MapPrototype.get = function(key) {
10473 var keyValue = this.keyElem.valueToString(this.keyElem.verifyValue(key));
10474 if (!(keyValue in this.map))
10475 return undefined;
10476 return this.map[keyValue].value;
10477 };
10478
10479 /**
10480 * Determines whether the given key is present in the map.
10481 * @param {*} key The key
10482 * @returns {boolean} `true` if the key is present
10483 */
10484 MapPrototype.has = function(key) {
10485 var keyValue = this.keyElem.valueToString(this.keyElem.verifyValue(key));
10486 return (keyValue in this.map);
10487 };
10488
10489 return Map;
10490 })(ProtoBuf, ProtoBuf.Reflect);
10491
10492
10493 /**
10494 * Constructs a new empty Builder.
10495 * @param {Object.<string,*>=} options Builder options, defaults to global options set on ProtoBuf
10496 * @return {!ProtoBuf.Builder} Builder
10497 * @expose
10498 */
10499 ProtoBuf.newBuilder = function(options) {
10500 options = options || {};
10501 if (typeof options['convertFieldsToCamelCase'] === 'undefined')
10502 options['convertFieldsToCamelCase'] = ProtoBuf.convertFieldsToCamelCase;
10503 if (typeof options['populateAccessors'] === 'undefined')
10504 options['populateAccessors'] = ProtoBuf.populateAccessors;
10505 return new ProtoBuf.Builder(options);
10506 };
10507
10508 /**
10509 * Loads a .json definition and returns the Builder.
10510 * @param {!*|string} json JSON definition
10511 * @param {(ProtoBuf.Builder|string|{root: string, file: string})=} builder Builder to append to. Will create a new one if omitted.
10512 * @param {(string|{root: string, file: string})=} filename The corresponding file name if known. Must be specified for imports.
10513 * @return {ProtoBuf.Builder} Builder to create new messages
10514 * @throws {Error} If the definition cannot be parsed or built
10515 * @expose
10516 */
10517 ProtoBuf.loadJson = function(json, builder, filename) {
10518 if (typeof builder === 'string' || (builder && typeof builder["file"] === 'string' && typeof builder["root"] === 'string'))
10519 filename = builder,
10520 builder = null;
10521 if (!builder || typeof builder !== 'object')
10522 builder = ProtoBuf.newBuilder();
10523 if (typeof json === 'string')
10524 json = JSON.parse(json);
10525 builder["import"](json, filename);
10526 builder.resolveAll();
10527 return builder;
10528 };
10529
10530 /**
10531 * Loads a .json file and returns the Builder.
10532 * @param {string|!{root: string, file: string}} filename Path to json file or an object specifying 'file' with
10533 * an overridden 'root' path for all imported files.
10534 * @param {function(?Error, !ProtoBuf.Builder=)=} callback Callback that will receive `null` as the first and
10535 * the Builder as its second argument on success, otherwise the error as its first argument. If omitted, the
10536 * file will be read synchronously and this function will return the Builder.
10537 * @param {ProtoBuf.Builder=} builder Builder to append to. Will create a new one if omitted.
10538 * @return {?ProtoBuf.Builder|undefined} The Builder if synchronous (no callback specified, will be NULL if the
10539 * request has failed), else undefined
10540 * @expose
10541 */
10542 ProtoBuf.loadJsonFile = function(filename, callback, builder) {
10543 if (callback && typeof callback === 'object')
10544 builder = callback,
10545 callback = null;
10546 else if (!callback || typeof callback !== 'function')
10547 callback = null;
10548 if (callback)
10549 return ProtoBuf.Util.fetch(typeof filename === 'string' ? filename : filename["root"]+"/"+filename["file"], function(contents) {
10550 if (contents === null) {
10551 callback(Error("Failed to fetch file"));
10552 return;
10553 }
10554 try {
10555 callback(null, ProtoBuf.loadJson(JSON.parse(contents), builder, filename));
10556 } catch (e) {
10557 callback(e);
10558 }
10559 });
10560 var contents = ProtoBuf.Util.fetch(typeof filename === 'object' ? filename["root"]+"/"+filename["file"] : filename);
10561 return contents === null ? null : ProtoBuf.loadJson(JSON.parse(contents), builder, filename);
10562 };
10563
10564 return ProtoBuf;
10565 });
10566 });
10567
10568 var messageCompiled = protobufLight.newBuilder({})['import']({
10569 package: 'push_server.messages2',
10570 syntax: 'proto2',
10571 options: {
10572 objc_class_prefix: 'AVIM'
10573 },
10574 messages: [{
10575 name: 'JsonObjectMessage',
10576 syntax: 'proto2',
10577 fields: [{
10578 rule: 'required',
10579 type: 'string',
10580 name: 'data',
10581 id: 1
10582 }]
10583 }, {
10584 name: 'UnreadTuple',
10585 syntax: 'proto2',
10586 fields: [{
10587 rule: 'required',
10588 type: 'string',
10589 name: 'cid',
10590 id: 1
10591 }, {
10592 rule: 'required',
10593 type: 'int32',
10594 name: 'unread',
10595 id: 2
10596 }, {
10597 rule: 'optional',
10598 type: 'string',
10599 name: 'mid',
10600 id: 3
10601 }, {
10602 rule: 'optional',
10603 type: 'int64',
10604 name: 'timestamp',
10605 id: 4
10606 }, {
10607 rule: 'optional',
10608 type: 'string',
10609 name: 'from',
10610 id: 5
10611 }, {
10612 rule: 'optional',
10613 type: 'string',
10614 name: 'data',
10615 id: 6
10616 }, {
10617 rule: 'optional',
10618 type: 'int64',
10619 name: 'patchTimestamp',
10620 id: 7
10621 }, {
10622 rule: 'optional',
10623 type: 'bool',
10624 name: 'mentioned',
10625 id: 8
10626 }, {
10627 rule: 'optional',
10628 type: 'bytes',
10629 name: 'binaryMsg',
10630 id: 9
10631 }, {
10632 rule: 'optional',
10633 type: 'int32',
10634 name: 'convType',
10635 id: 10
10636 }]
10637 }, {
10638 name: 'LogItem',
10639 syntax: 'proto2',
10640 fields: [{
10641 rule: 'optional',
10642 type: 'string',
10643 name: 'from',
10644 id: 1
10645 }, {
10646 rule: 'optional',
10647 type: 'string',
10648 name: 'data',
10649 id: 2
10650 }, {
10651 rule: 'optional',
10652 type: 'int64',
10653 name: 'timestamp',
10654 id: 3
10655 }, {
10656 rule: 'optional',
10657 type: 'string',
10658 name: 'msgId',
10659 id: 4
10660 }, {
10661 rule: 'optional',
10662 type: 'int64',
10663 name: 'ackAt',
10664 id: 5
10665 }, {
10666 rule: 'optional',
10667 type: 'int64',
10668 name: 'readAt',
10669 id: 6
10670 }, {
10671 rule: 'optional',
10672 type: 'int64',
10673 name: 'patchTimestamp',
10674 id: 7
10675 }, {
10676 rule: 'optional',
10677 type: 'bool',
10678 name: 'mentionAll',
10679 id: 8
10680 }, {
10681 rule: 'repeated',
10682 type: 'string',
10683 name: 'mentionPids',
10684 id: 9
10685 }, {
10686 rule: 'optional',
10687 type: 'bool',
10688 name: 'bin',
10689 id: 10
10690 }, {
10691 rule: 'optional',
10692 type: 'int32',
10693 name: 'convType',
10694 id: 11
10695 }]
10696 }, {
10697 name: 'ConvMemberInfo',
10698 syntax: 'proto2',
10699 fields: [{
10700 rule: 'optional',
10701 type: 'string',
10702 name: 'pid',
10703 id: 1
10704 }, {
10705 rule: 'optional',
10706 type: 'string',
10707 name: 'role',
10708 id: 2
10709 }, {
10710 rule: 'optional',
10711 type: 'string',
10712 name: 'infoId',
10713 id: 3
10714 }]
10715 }, {
10716 name: 'DataCommand',
10717 syntax: 'proto2',
10718 fields: [{
10719 rule: 'repeated',
10720 type: 'string',
10721 name: 'ids',
10722 id: 1
10723 }, {
10724 rule: 'repeated',
10725 type: 'JsonObjectMessage',
10726 name: 'msg',
10727 id: 2
10728 }, {
10729 rule: 'optional',
10730 type: 'bool',
10731 name: 'offline',
10732 id: 3
10733 }]
10734 }, {
10735 name: 'SessionCommand',
10736 syntax: 'proto2',
10737 fields: [{
10738 rule: 'optional',
10739 type: 'int64',
10740 name: 't',
10741 id: 1
10742 }, {
10743 rule: 'optional',
10744 type: 'string',
10745 name: 'n',
10746 id: 2
10747 }, {
10748 rule: 'optional',
10749 type: 'string',
10750 name: 's',
10751 id: 3
10752 }, {
10753 rule: 'optional',
10754 type: 'string',
10755 name: 'ua',
10756 id: 4
10757 }, {
10758 rule: 'optional',
10759 type: 'bool',
10760 name: 'r',
10761 id: 5
10762 }, {
10763 rule: 'optional',
10764 type: 'string',
10765 name: 'tag',
10766 id: 6
10767 }, {
10768 rule: 'optional',
10769 type: 'string',
10770 name: 'deviceId',
10771 id: 7
10772 }, {
10773 rule: 'repeated',
10774 type: 'string',
10775 name: 'sessionPeerIds',
10776 id: 8
10777 }, {
10778 rule: 'repeated',
10779 type: 'string',
10780 name: 'onlineSessionPeerIds',
10781 id: 9
10782 }, {
10783 rule: 'optional',
10784 type: 'string',
10785 name: 'st',
10786 id: 10
10787 }, {
10788 rule: 'optional',
10789 type: 'int32',
10790 name: 'stTtl',
10791 id: 11
10792 }, {
10793 rule: 'optional',
10794 type: 'int32',
10795 name: 'code',
10796 id: 12
10797 }, {
10798 rule: 'optional',
10799 type: 'string',
10800 name: 'reason',
10801 id: 13
10802 }, {
10803 rule: 'optional',
10804 type: 'string',
10805 name: 'deviceToken',
10806 id: 14
10807 }, {
10808 rule: 'optional',
10809 type: 'bool',
10810 name: 'sp',
10811 id: 15
10812 }, {
10813 rule: 'optional',
10814 type: 'string',
10815 name: 'detail',
10816 id: 16
10817 }, {
10818 rule: 'optional',
10819 type: 'int64',
10820 name: 'lastUnreadNotifTime',
10821 id: 17
10822 }, {
10823 rule: 'optional',
10824 type: 'int64',
10825 name: 'lastPatchTime',
10826 id: 18
10827 }, {
10828 rule: 'optional',
10829 type: 'int64',
10830 name: 'configBitmap',
10831 id: 19
10832 }]
10833 }, {
10834 name: 'ErrorCommand',
10835 syntax: 'proto2',
10836 fields: [{
10837 rule: 'required',
10838 type: 'int32',
10839 name: 'code',
10840 id: 1
10841 }, {
10842 rule: 'required',
10843 type: 'string',
10844 name: 'reason',
10845 id: 2
10846 }, {
10847 rule: 'optional',
10848 type: 'int32',
10849 name: 'appCode',
10850 id: 3
10851 }, {
10852 rule: 'optional',
10853 type: 'string',
10854 name: 'detail',
10855 id: 4
10856 }, {
10857 rule: 'repeated',
10858 type: 'string',
10859 name: 'pids',
10860 id: 5
10861 }, {
10862 rule: 'optional',
10863 type: 'string',
10864 name: 'appMsg',
10865 id: 6
10866 }]
10867 }, {
10868 name: 'DirectCommand',
10869 syntax: 'proto2',
10870 fields: [{
10871 rule: 'optional',
10872 type: 'string',
10873 name: 'msg',
10874 id: 1
10875 }, {
10876 rule: 'optional',
10877 type: 'string',
10878 name: 'uid',
10879 id: 2
10880 }, {
10881 rule: 'optional',
10882 type: 'string',
10883 name: 'fromPeerId',
10884 id: 3
10885 }, {
10886 rule: 'optional',
10887 type: 'int64',
10888 name: 'timestamp',
10889 id: 4
10890 }, {
10891 rule: 'optional',
10892 type: 'bool',
10893 name: 'offline',
10894 id: 5
10895 }, {
10896 rule: 'optional',
10897 type: 'bool',
10898 name: 'hasMore',
10899 id: 6
10900 }, {
10901 rule: 'repeated',
10902 type: 'string',
10903 name: 'toPeerIds',
10904 id: 7
10905 }, {
10906 rule: 'optional',
10907 type: 'bool',
10908 name: 'r',
10909 id: 10
10910 }, {
10911 rule: 'optional',
10912 type: 'string',
10913 name: 'cid',
10914 id: 11
10915 }, {
10916 rule: 'optional',
10917 type: 'string',
10918 name: 'id',
10919 id: 12
10920 }, {
10921 rule: 'optional',
10922 type: 'bool',
10923 name: 'transient',
10924 id: 13
10925 }, {
10926 rule: 'optional',
10927 type: 'string',
10928 name: 'dt',
10929 id: 14
10930 }, {
10931 rule: 'optional',
10932 type: 'string',
10933 name: 'roomId',
10934 id: 15
10935 }, {
10936 rule: 'optional',
10937 type: 'string',
10938 name: 'pushData',
10939 id: 16
10940 }, {
10941 rule: 'optional',
10942 type: 'bool',
10943 name: 'will',
10944 id: 17
10945 }, {
10946 rule: 'optional',
10947 type: 'int64',
10948 name: 'patchTimestamp',
10949 id: 18
10950 }, {
10951 rule: 'optional',
10952 type: 'bytes',
10953 name: 'binaryMsg',
10954 id: 19
10955 }, {
10956 rule: 'repeated',
10957 type: 'string',
10958 name: 'mentionPids',
10959 id: 20
10960 }, {
10961 rule: 'optional',
10962 type: 'bool',
10963 name: 'mentionAll',
10964 id: 21
10965 }, {
10966 rule: 'optional',
10967 type: 'int32',
10968 name: 'convType',
10969 id: 22
10970 }]
10971 }, {
10972 name: 'AckCommand',
10973 syntax: 'proto2',
10974 fields: [{
10975 rule: 'optional',
10976 type: 'int32',
10977 name: 'code',
10978 id: 1
10979 }, {
10980 rule: 'optional',
10981 type: 'string',
10982 name: 'reason',
10983 id: 2
10984 }, {
10985 rule: 'optional',
10986 type: 'string',
10987 name: 'mid',
10988 id: 3
10989 }, {
10990 rule: 'optional',
10991 type: 'string',
10992 name: 'cid',
10993 id: 4
10994 }, {
10995 rule: 'optional',
10996 type: 'int64',
10997 name: 't',
10998 id: 5
10999 }, {
11000 rule: 'optional',
11001 type: 'string',
11002 name: 'uid',
11003 id: 6
11004 }, {
11005 rule: 'optional',
11006 type: 'int64',
11007 name: 'fromts',
11008 id: 7
11009 }, {
11010 rule: 'optional',
11011 type: 'int64',
11012 name: 'tots',
11013 id: 8
11014 }, {
11015 rule: 'optional',
11016 type: 'string',
11017 name: 'type',
11018 id: 9
11019 }, {
11020 rule: 'repeated',
11021 type: 'string',
11022 name: 'ids',
11023 id: 10
11024 }, {
11025 rule: 'optional',
11026 type: 'int32',
11027 name: 'appCode',
11028 id: 11
11029 }, {
11030 rule: 'optional',
11031 type: 'string',
11032 name: 'appMsg',
11033 id: 12
11034 }]
11035 }, {
11036 name: 'UnreadCommand',
11037 syntax: 'proto2',
11038 fields: [{
11039 rule: 'repeated',
11040 type: 'UnreadTuple',
11041 name: 'convs',
11042 id: 1
11043 }, {
11044 rule: 'optional',
11045 type: 'int64',
11046 name: 'notifTime',
11047 id: 2
11048 }]
11049 }, {
11050 name: 'ConvCommand',
11051 syntax: 'proto2',
11052 fields: [{
11053 rule: 'repeated',
11054 type: 'string',
11055 name: 'm',
11056 id: 1
11057 }, {
11058 rule: 'optional',
11059 type: 'bool',
11060 name: 'transient',
11061 id: 2
11062 }, {
11063 rule: 'optional',
11064 type: 'bool',
11065 name: 'unique',
11066 id: 3
11067 }, {
11068 rule: 'optional',
11069 type: 'string',
11070 name: 'cid',
11071 id: 4
11072 }, {
11073 rule: 'optional',
11074 type: 'string',
11075 name: 'cdate',
11076 id: 5
11077 }, {
11078 rule: 'optional',
11079 type: 'string',
11080 name: 'initBy',
11081 id: 6
11082 }, {
11083 rule: 'optional',
11084 type: 'string',
11085 name: 'sort',
11086 id: 7
11087 }, {
11088 rule: 'optional',
11089 type: 'int32',
11090 name: 'limit',
11091 id: 8
11092 }, {
11093 rule: 'optional',
11094 type: 'int32',
11095 name: 'skip',
11096 id: 9
11097 }, {
11098 rule: 'optional',
11099 type: 'int32',
11100 name: 'flag',
11101 id: 10
11102 }, {
11103 rule: 'optional',
11104 type: 'int32',
11105 name: 'count',
11106 id: 11
11107 }, {
11108 rule: 'optional',
11109 type: 'string',
11110 name: 'udate',
11111 id: 12
11112 }, {
11113 rule: 'optional',
11114 type: 'int64',
11115 name: 't',
11116 id: 13
11117 }, {
11118 rule: 'optional',
11119 type: 'string',
11120 name: 'n',
11121 id: 14
11122 }, {
11123 rule: 'optional',
11124 type: 'string',
11125 name: 's',
11126 id: 15
11127 }, {
11128 rule: 'optional',
11129 type: 'bool',
11130 name: 'statusSub',
11131 id: 16
11132 }, {
11133 rule: 'optional',
11134 type: 'bool',
11135 name: 'statusPub',
11136 id: 17
11137 }, {
11138 rule: 'optional',
11139 type: 'int32',
11140 name: 'statusTTL',
11141 id: 18
11142 }, {
11143 rule: 'optional',
11144 type: 'string',
11145 name: 'uniqueId',
11146 id: 19
11147 }, {
11148 rule: 'optional',
11149 type: 'string',
11150 name: 'targetClientId',
11151 id: 20
11152 }, {
11153 rule: 'optional',
11154 type: 'int64',
11155 name: 'maxReadTimestamp',
11156 id: 21
11157 }, {
11158 rule: 'optional',
11159 type: 'int64',
11160 name: 'maxAckTimestamp',
11161 id: 22
11162 }, {
11163 rule: 'optional',
11164 type: 'bool',
11165 name: 'queryAllMembers',
11166 id: 23
11167 }, {
11168 rule: 'repeated',
11169 type: 'MaxReadTuple',
11170 name: 'maxReadTuples',
11171 id: 24
11172 }, {
11173 rule: 'repeated',
11174 type: 'string',
11175 name: 'cids',
11176 id: 25
11177 }, {
11178 rule: 'optional',
11179 type: 'ConvMemberInfo',
11180 name: 'info',
11181 id: 26
11182 }, {
11183 rule: 'optional',
11184 type: 'bool',
11185 name: 'tempConv',
11186 id: 27
11187 }, {
11188 rule: 'optional',
11189 type: 'int32',
11190 name: 'tempConvTTL',
11191 id: 28
11192 }, {
11193 rule: 'repeated',
11194 type: 'string',
11195 name: 'tempConvIds',
11196 id: 29
11197 }, {
11198 rule: 'repeated',
11199 type: 'string',
11200 name: 'allowedPids',
11201 id: 30
11202 }, {
11203 rule: 'repeated',
11204 type: 'ErrorCommand',
11205 name: 'failedPids',
11206 id: 31
11207 }, {
11208 rule: 'optional',
11209 type: 'string',
11210 name: 'next',
11211 id: 40
11212 }, {
11213 rule: 'optional',
11214 type: 'JsonObjectMessage',
11215 name: 'results',
11216 id: 100
11217 }, {
11218 rule: 'optional',
11219 type: 'JsonObjectMessage',
11220 name: 'where',
11221 id: 101
11222 }, {
11223 rule: 'optional',
11224 type: 'JsonObjectMessage',
11225 name: 'attr',
11226 id: 103
11227 }, {
11228 rule: 'optional',
11229 type: 'JsonObjectMessage',
11230 name: 'attrModified',
11231 id: 104
11232 }]
11233 }, {
11234 name: 'RoomCommand',
11235 syntax: 'proto2',
11236 fields: [{
11237 rule: 'optional',
11238 type: 'string',
11239 name: 'roomId',
11240 id: 1
11241 }, {
11242 rule: 'optional',
11243 type: 'string',
11244 name: 's',
11245 id: 2
11246 }, {
11247 rule: 'optional',
11248 type: 'int64',
11249 name: 't',
11250 id: 3
11251 }, {
11252 rule: 'optional',
11253 type: 'string',
11254 name: 'n',
11255 id: 4
11256 }, {
11257 rule: 'optional',
11258 type: 'bool',
11259 name: 'transient',
11260 id: 5
11261 }, {
11262 rule: 'repeated',
11263 type: 'string',
11264 name: 'roomPeerIds',
11265 id: 6
11266 }, {
11267 rule: 'optional',
11268 type: 'string',
11269 name: 'byPeerId',
11270 id: 7
11271 }]
11272 }, {
11273 name: 'LogsCommand',
11274 syntax: 'proto2',
11275 fields: [{
11276 rule: 'optional',
11277 type: 'string',
11278 name: 'cid',
11279 id: 1
11280 }, {
11281 rule: 'optional',
11282 type: 'int32',
11283 name: 'l',
11284 id: 2
11285 }, {
11286 rule: 'optional',
11287 type: 'int32',
11288 name: 'limit',
11289 id: 3
11290 }, {
11291 rule: 'optional',
11292 type: 'int64',
11293 name: 't',
11294 id: 4
11295 }, {
11296 rule: 'optional',
11297 type: 'int64',
11298 name: 'tt',
11299 id: 5
11300 }, {
11301 rule: 'optional',
11302 type: 'string',
11303 name: 'tmid',
11304 id: 6
11305 }, {
11306 rule: 'optional',
11307 type: 'string',
11308 name: 'mid',
11309 id: 7
11310 }, {
11311 rule: 'optional',
11312 type: 'string',
11313 name: 'checksum',
11314 id: 8
11315 }, {
11316 rule: 'optional',
11317 type: 'bool',
11318 name: 'stored',
11319 id: 9
11320 }, {
11321 rule: 'optional',
11322 type: 'QueryDirection',
11323 name: 'direction',
11324 id: 10,
11325 options: {
11326 default: 'OLD'
11327 }
11328 }, {
11329 rule: 'optional',
11330 type: 'bool',
11331 name: 'tIncluded',
11332 id: 11
11333 }, {
11334 rule: 'optional',
11335 type: 'bool',
11336 name: 'ttIncluded',
11337 id: 12
11338 }, {
11339 rule: 'optional',
11340 type: 'int32',
11341 name: 'lctype',
11342 id: 13
11343 }, {
11344 rule: 'repeated',
11345 type: 'LogItem',
11346 name: 'logs',
11347 id: 105
11348 }],
11349 enums: [{
11350 name: 'QueryDirection',
11351 syntax: 'proto2',
11352 values: [{
11353 name: 'OLD',
11354 id: 1
11355 }, {
11356 name: 'NEW',
11357 id: 2
11358 }]
11359 }]
11360 }, {
11361 name: 'RcpCommand',
11362 syntax: 'proto2',
11363 fields: [{
11364 rule: 'optional',
11365 type: 'string',
11366 name: 'id',
11367 id: 1
11368 }, {
11369 rule: 'optional',
11370 type: 'string',
11371 name: 'cid',
11372 id: 2
11373 }, {
11374 rule: 'optional',
11375 type: 'int64',
11376 name: 't',
11377 id: 3
11378 }, {
11379 rule: 'optional',
11380 type: 'bool',
11381 name: 'read',
11382 id: 4
11383 }, {
11384 rule: 'optional',
11385 type: 'string',
11386 name: 'from',
11387 id: 5
11388 }]
11389 }, {
11390 name: 'ReadTuple',
11391 syntax: 'proto2',
11392 fields: [{
11393 rule: 'required',
11394 type: 'string',
11395 name: 'cid',
11396 id: 1
11397 }, {
11398 rule: 'optional',
11399 type: 'int64',
11400 name: 'timestamp',
11401 id: 2
11402 }, {
11403 rule: 'optional',
11404 type: 'string',
11405 name: 'mid',
11406 id: 3
11407 }]
11408 }, {
11409 name: 'MaxReadTuple',
11410 syntax: 'proto2',
11411 fields: [{
11412 rule: 'optional',
11413 type: 'string',
11414 name: 'pid',
11415 id: 1
11416 }, {
11417 rule: 'optional',
11418 type: 'int64',
11419 name: 'maxAckTimestamp',
11420 id: 2
11421 }, {
11422 rule: 'optional',
11423 type: 'int64',
11424 name: 'maxReadTimestamp',
11425 id: 3
11426 }]
11427 }, {
11428 name: 'ReadCommand',
11429 syntax: 'proto2',
11430 fields: [{
11431 rule: 'optional',
11432 type: 'string',
11433 name: 'cid',
11434 id: 1
11435 }, {
11436 rule: 'repeated',
11437 type: 'string',
11438 name: 'cids',
11439 id: 2
11440 }, {
11441 rule: 'repeated',
11442 type: 'ReadTuple',
11443 name: 'convs',
11444 id: 3
11445 }]
11446 }, {
11447 name: 'PresenceCommand',
11448 syntax: 'proto2',
11449 fields: [{
11450 rule: 'optional',
11451 type: 'StatusType',
11452 name: 'status',
11453 id: 1
11454 }, {
11455 rule: 'repeated',
11456 type: 'string',
11457 name: 'sessionPeerIds',
11458 id: 2
11459 }, {
11460 rule: 'optional',
11461 type: 'string',
11462 name: 'cid',
11463 id: 3
11464 }]
11465 }, {
11466 name: 'ReportCommand',
11467 syntax: 'proto2',
11468 fields: [{
11469 rule: 'optional',
11470 type: 'bool',
11471 name: 'initiative',
11472 id: 1
11473 }, {
11474 rule: 'optional',
11475 type: 'string',
11476 name: 'type',
11477 id: 2
11478 }, {
11479 rule: 'optional',
11480 type: 'string',
11481 name: 'data',
11482 id: 3
11483 }]
11484 }, {
11485 name: 'PatchItem',
11486 syntax: 'proto2',
11487 fields: [{
11488 rule: 'optional',
11489 type: 'string',
11490 name: 'cid',
11491 id: 1
11492 }, {
11493 rule: 'optional',
11494 type: 'string',
11495 name: 'mid',
11496 id: 2
11497 }, {
11498 rule: 'optional',
11499 type: 'int64',
11500 name: 'timestamp',
11501 id: 3
11502 }, {
11503 rule: 'optional',
11504 type: 'bool',
11505 name: 'recall',
11506 id: 4
11507 }, {
11508 rule: 'optional',
11509 type: 'string',
11510 name: 'data',
11511 id: 5
11512 }, {
11513 rule: 'optional',
11514 type: 'int64',
11515 name: 'patchTimestamp',
11516 id: 6
11517 }, {
11518 rule: 'optional',
11519 type: 'string',
11520 name: 'from',
11521 id: 7
11522 }, {
11523 rule: 'optional',
11524 type: 'bytes',
11525 name: 'binaryMsg',
11526 id: 8
11527 }, {
11528 rule: 'optional',
11529 type: 'bool',
11530 name: 'mentionAll',
11531 id: 9
11532 }, {
11533 rule: 'repeated',
11534 type: 'string',
11535 name: 'mentionPids',
11536 id: 10
11537 }, {
11538 rule: 'optional',
11539 type: 'int64',
11540 name: 'patchCode',
11541 id: 11
11542 }, {
11543 rule: 'optional',
11544 type: 'string',
11545 name: 'patchReason',
11546 id: 12
11547 }]
11548 }, {
11549 name: 'PatchCommand',
11550 syntax: 'proto2',
11551 fields: [{
11552 rule: 'repeated',
11553 type: 'PatchItem',
11554 name: 'patches',
11555 id: 1
11556 }, {
11557 rule: 'optional',
11558 type: 'int64',
11559 name: 'lastPatchTime',
11560 id: 2
11561 }]
11562 }, {
11563 name: 'PubsubCommand',
11564 syntax: 'proto2',
11565 fields: [{
11566 rule: 'optional',
11567 type: 'string',
11568 name: 'cid',
11569 id: 1
11570 }, {
11571 rule: 'repeated',
11572 type: 'string',
11573 name: 'cids',
11574 id: 2
11575 }, {
11576 rule: 'optional',
11577 type: 'string',
11578 name: 'topic',
11579 id: 3
11580 }, {
11581 rule: 'optional',
11582 type: 'string',
11583 name: 'subtopic',
11584 id: 4
11585 }, {
11586 rule: 'repeated',
11587 type: 'string',
11588 name: 'topics',
11589 id: 5
11590 }, {
11591 rule: 'repeated',
11592 type: 'string',
11593 name: 'subtopics',
11594 id: 6
11595 }, {
11596 rule: 'optional',
11597 type: 'JsonObjectMessage',
11598 name: 'results',
11599 id: 7
11600 }]
11601 }, {
11602 name: 'BlacklistCommand',
11603 syntax: 'proto2',
11604 fields: [{
11605 rule: 'optional',
11606 type: 'string',
11607 name: 'srcCid',
11608 id: 1
11609 }, {
11610 rule: 'repeated',
11611 type: 'string',
11612 name: 'toPids',
11613 id: 2
11614 }, {
11615 rule: 'optional',
11616 type: 'string',
11617 name: 'srcPid',
11618 id: 3
11619 }, {
11620 rule: 'repeated',
11621 type: 'string',
11622 name: 'toCids',
11623 id: 4
11624 }, {
11625 rule: 'optional',
11626 type: 'int32',
11627 name: 'limit',
11628 id: 5
11629 }, {
11630 rule: 'optional',
11631 type: 'string',
11632 name: 'next',
11633 id: 6
11634 }, {
11635 rule: 'repeated',
11636 type: 'string',
11637 name: 'blockedPids',
11638 id: 8
11639 }, {
11640 rule: 'repeated',
11641 type: 'string',
11642 name: 'blockedCids',
11643 id: 9
11644 }, {
11645 rule: 'repeated',
11646 type: 'string',
11647 name: 'allowedPids',
11648 id: 10
11649 }, {
11650 rule: 'repeated',
11651 type: 'ErrorCommand',
11652 name: 'failedPids',
11653 id: 11
11654 }, {
11655 rule: 'optional',
11656 type: 'int64',
11657 name: 't',
11658 id: 12
11659 }, {
11660 rule: 'optional',
11661 type: 'string',
11662 name: 'n',
11663 id: 13
11664 }, {
11665 rule: 'optional',
11666 type: 'string',
11667 name: 's',
11668 id: 14
11669 }]
11670 }, {
11671 name: 'GenericCommand',
11672 syntax: 'proto2',
11673 fields: [{
11674 rule: 'optional',
11675 type: 'CommandType',
11676 name: 'cmd',
11677 id: 1
11678 }, {
11679 rule: 'optional',
11680 type: 'OpType',
11681 name: 'op',
11682 id: 2
11683 }, {
11684 rule: 'optional',
11685 type: 'string',
11686 name: 'appId',
11687 id: 3
11688 }, {
11689 rule: 'optional',
11690 type: 'string',
11691 name: 'peerId',
11692 id: 4
11693 }, {
11694 rule: 'optional',
11695 type: 'int32',
11696 name: 'i',
11697 id: 5
11698 }, {
11699 rule: 'optional',
11700 type: 'string',
11701 name: 'installationId',
11702 id: 6
11703 }, {
11704 rule: 'optional',
11705 type: 'int32',
11706 name: 'priority',
11707 id: 7
11708 }, {
11709 rule: 'optional',
11710 type: 'int32',
11711 name: 'service',
11712 id: 8
11713 }, {
11714 rule: 'optional',
11715 type: 'int64',
11716 name: 'serverTs',
11717 id: 9
11718 }, {
11719 rule: 'optional',
11720 type: 'int64',
11721 name: 'clientTs',
11722 id: 10
11723 }, {
11724 rule: 'optional',
11725 type: 'int32',
11726 name: 'notificationType',
11727 id: 11
11728 }, {
11729 rule: 'optional',
11730 type: 'DataCommand',
11731 name: 'dataMessage',
11732 id: 101
11733 }, {
11734 rule: 'optional',
11735 type: 'SessionCommand',
11736 name: 'sessionMessage',
11737 id: 102
11738 }, {
11739 rule: 'optional',
11740 type: 'ErrorCommand',
11741 name: 'errorMessage',
11742 id: 103
11743 }, {
11744 rule: 'optional',
11745 type: 'DirectCommand',
11746 name: 'directMessage',
11747 id: 104
11748 }, {
11749 rule: 'optional',
11750 type: 'AckCommand',
11751 name: 'ackMessage',
11752 id: 105
11753 }, {
11754 rule: 'optional',
11755 type: 'UnreadCommand',
11756 name: 'unreadMessage',
11757 id: 106
11758 }, {
11759 rule: 'optional',
11760 type: 'ReadCommand',
11761 name: 'readMessage',
11762 id: 107
11763 }, {
11764 rule: 'optional',
11765 type: 'RcpCommand',
11766 name: 'rcpMessage',
11767 id: 108
11768 }, {
11769 rule: 'optional',
11770 type: 'LogsCommand',
11771 name: 'logsMessage',
11772 id: 109
11773 }, {
11774 rule: 'optional',
11775 type: 'ConvCommand',
11776 name: 'convMessage',
11777 id: 110
11778 }, {
11779 rule: 'optional',
11780 type: 'RoomCommand',
11781 name: 'roomMessage',
11782 id: 111
11783 }, {
11784 rule: 'optional',
11785 type: 'PresenceCommand',
11786 name: 'presenceMessage',
11787 id: 112
11788 }, {
11789 rule: 'optional',
11790 type: 'ReportCommand',
11791 name: 'reportMessage',
11792 id: 113
11793 }, {
11794 rule: 'optional',
11795 type: 'PatchCommand',
11796 name: 'patchMessage',
11797 id: 114
11798 }, {
11799 rule: 'optional',
11800 type: 'PubsubCommand',
11801 name: 'pubsubMessage',
11802 id: 115
11803 }, {
11804 rule: 'optional',
11805 type: 'BlacklistCommand',
11806 name: 'blacklistMessage',
11807 id: 116
11808 }]
11809 }],
11810 enums: [{
11811 name: 'CommandType',
11812 syntax: 'proto2',
11813 values: [{
11814 name: 'session',
11815 id: 0
11816 }, {
11817 name: 'conv',
11818 id: 1
11819 }, {
11820 name: 'direct',
11821 id: 2
11822 }, {
11823 name: 'ack',
11824 id: 3
11825 }, {
11826 name: 'rcp',
11827 id: 4
11828 }, {
11829 name: 'unread',
11830 id: 5
11831 }, {
11832 name: 'logs',
11833 id: 6
11834 }, {
11835 name: 'error',
11836 id: 7
11837 }, {
11838 name: 'login',
11839 id: 8
11840 }, {
11841 name: 'data',
11842 id: 9
11843 }, {
11844 name: 'room',
11845 id: 10
11846 }, {
11847 name: 'read',
11848 id: 11
11849 }, {
11850 name: 'presence',
11851 id: 12
11852 }, {
11853 name: 'report',
11854 id: 13
11855 }, {
11856 name: 'echo',
11857 id: 14
11858 }, {
11859 name: 'loggedin',
11860 id: 15
11861 }, {
11862 name: 'logout',
11863 id: 16
11864 }, {
11865 name: 'loggedout',
11866 id: 17
11867 }, {
11868 name: 'patch',
11869 id: 18
11870 }, {
11871 name: 'pubsub',
11872 id: 19
11873 }, {
11874 name: 'blacklist',
11875 id: 20
11876 }, {
11877 name: 'goaway',
11878 id: 21
11879 }]
11880 }, {
11881 name: 'OpType',
11882 syntax: 'proto2',
11883 values: [{
11884 name: 'open',
11885 id: 1
11886 }, {
11887 name: 'add',
11888 id: 2
11889 }, {
11890 name: 'remove',
11891 id: 3
11892 }, {
11893 name: 'close',
11894 id: 4
11895 }, {
11896 name: 'opened',
11897 id: 5
11898 }, {
11899 name: 'closed',
11900 id: 6
11901 }, {
11902 name: 'query',
11903 id: 7
11904 }, {
11905 name: 'query_result',
11906 id: 8
11907 }, {
11908 name: 'conflict',
11909 id: 9
11910 }, {
11911 name: 'added',
11912 id: 10
11913 }, {
11914 name: 'removed',
11915 id: 11
11916 }, {
11917 name: 'refresh',
11918 id: 12
11919 }, {
11920 name: 'refreshed',
11921 id: 13
11922 }, {
11923 name: 'start',
11924 id: 30
11925 }, {
11926 name: 'started',
11927 id: 31
11928 }, {
11929 name: 'joined',
11930 id: 32
11931 }, {
11932 name: 'members_joined',
11933 id: 33
11934 }, {
11935 name: 'left',
11936 id: 39
11937 }, {
11938 name: 'members_left',
11939 id: 40
11940 }, {
11941 name: 'results',
11942 id: 42
11943 }, {
11944 name: 'count',
11945 id: 43
11946 }, {
11947 name: 'result',
11948 id: 44
11949 }, {
11950 name: 'update',
11951 id: 45
11952 }, {
11953 name: 'updated',
11954 id: 46
11955 }, {
11956 name: 'mute',
11957 id: 47
11958 }, {
11959 name: 'unmute',
11960 id: 48
11961 }, {
11962 name: 'status',
11963 id: 49
11964 }, {
11965 name: 'members',
11966 id: 50
11967 }, {
11968 name: 'max_read',
11969 id: 51
11970 }, {
11971 name: 'is_member',
11972 id: 52
11973 }, {
11974 name: 'member_info_update',
11975 id: 53
11976 }, {
11977 name: 'member_info_updated',
11978 id: 54
11979 }, {
11980 name: 'member_info_changed',
11981 id: 55
11982 }, {
11983 name: 'join',
11984 id: 80
11985 }, {
11986 name: 'invite',
11987 id: 81
11988 }, {
11989 name: 'leave',
11990 id: 82
11991 }, {
11992 name: 'kick',
11993 id: 83
11994 }, {
11995 name: 'reject',
11996 id: 84
11997 }, {
11998 name: 'invited',
11999 id: 85
12000 }, {
12001 name: 'kicked',
12002 id: 86
12003 }, {
12004 name: 'upload',
12005 id: 100
12006 }, {
12007 name: 'uploaded',
12008 id: 101
12009 }, {
12010 name: 'subscribe',
12011 id: 120
12012 }, {
12013 name: 'subscribed',
12014 id: 121
12015 }, {
12016 name: 'unsubscribe',
12017 id: 122
12018 }, {
12019 name: 'unsubscribed',
12020 id: 123
12021 }, {
12022 name: 'is_subscribed',
12023 id: 124
12024 }, {
12025 name: 'modify',
12026 id: 150
12027 }, {
12028 name: 'modified',
12029 id: 151
12030 }, {
12031 name: 'block',
12032 id: 170
12033 }, {
12034 name: 'unblock',
12035 id: 171
12036 }, {
12037 name: 'blocked',
12038 id: 172
12039 }, {
12040 name: 'unblocked',
12041 id: 173
12042 }, {
12043 name: 'members_blocked',
12044 id: 174
12045 }, {
12046 name: 'members_unblocked',
12047 id: 175
12048 }, {
12049 name: 'check_block',
12050 id: 176
12051 }, {
12052 name: 'check_result',
12053 id: 177
12054 }, {
12055 name: 'add_shutup',
12056 id: 180
12057 }, {
12058 name: 'remove_shutup',
12059 id: 181
12060 }, {
12061 name: 'query_shutup',
12062 id: 182
12063 }, {
12064 name: 'shutup_added',
12065 id: 183
12066 }, {
12067 name: 'shutup_removed',
12068 id: 184
12069 }, {
12070 name: 'shutup_result',
12071 id: 185
12072 }, {
12073 name: 'shutuped',
12074 id: 186
12075 }, {
12076 name: 'unshutuped',
12077 id: 187
12078 }, {
12079 name: 'members_shutuped',
12080 id: 188
12081 }, {
12082 name: 'members_unshutuped',
12083 id: 189
12084 }, {
12085 name: 'check_shutup',
12086 id: 190
12087 }]
12088 }, {
12089 name: 'StatusType',
12090 syntax: 'proto2',
12091 values: [{
12092 name: 'on',
12093 id: 1
12094 }, {
12095 name: 'off',
12096 id: 2
12097 }]
12098 }],
12099 isNamespace: true
12100 }).build();
12101
12102 var _messages$push_server = messageCompiled.push_server.messages2,
12103 JsonObjectMessage = _messages$push_server.JsonObjectMessage,
12104 UnreadTuple = _messages$push_server.UnreadTuple,
12105 LogItem = _messages$push_server.LogItem,
12106 DataCommand = _messages$push_server.DataCommand,
12107 SessionCommand = _messages$push_server.SessionCommand,
12108 ErrorCommand = _messages$push_server.ErrorCommand,
12109 DirectCommand = _messages$push_server.DirectCommand,
12110 AckCommand = _messages$push_server.AckCommand,
12111 UnreadCommand = _messages$push_server.UnreadCommand,
12112 ConvCommand = _messages$push_server.ConvCommand,
12113 RoomCommand = _messages$push_server.RoomCommand,
12114 LogsCommand = _messages$push_server.LogsCommand,
12115 RcpCommand = _messages$push_server.RcpCommand,
12116 ReadTuple = _messages$push_server.ReadTuple,
12117 MaxReadTuple = _messages$push_server.MaxReadTuple,
12118 ReadCommand = _messages$push_server.ReadCommand,
12119 PresenceCommand = _messages$push_server.PresenceCommand,
12120 ReportCommand = _messages$push_server.ReportCommand,
12121 GenericCommand = _messages$push_server.GenericCommand,
12122 BlacklistCommand = _messages$push_server.BlacklistCommand,
12123 PatchCommand = _messages$push_server.PatchCommand,
12124 PatchItem = _messages$push_server.PatchItem,
12125 ConvMemberInfo = _messages$push_server.ConvMemberInfo,
12126 CommandType = _messages$push_server.CommandType,
12127 OpType = _messages$push_server.OpType,
12128 StatusType = _messages$push_server.StatusType;
12129
12130 var message = /*#__PURE__*/Object.freeze({
12131 JsonObjectMessage: JsonObjectMessage,
12132 UnreadTuple: UnreadTuple,
12133 LogItem: LogItem,
12134 DataCommand: DataCommand,
12135 SessionCommand: SessionCommand,
12136 ErrorCommand: ErrorCommand,
12137 DirectCommand: DirectCommand,
12138 AckCommand: AckCommand,
12139 UnreadCommand: UnreadCommand,
12140 ConvCommand: ConvCommand,
12141 RoomCommand: RoomCommand,
12142 LogsCommand: LogsCommand,
12143 RcpCommand: RcpCommand,
12144 ReadTuple: ReadTuple,
12145 MaxReadTuple: MaxReadTuple,
12146 ReadCommand: ReadCommand,
12147 PresenceCommand: PresenceCommand,
12148 ReportCommand: ReportCommand,
12149 GenericCommand: GenericCommand,
12150 BlacklistCommand: BlacklistCommand,
12151 PatchCommand: PatchCommand,
12152 PatchItem: PatchItem,
12153 ConvMemberInfo: ConvMemberInfo,
12154 CommandType: CommandType,
12155 OpType: OpType,
12156 StatusType: StatusType
12157 });
12158
12159 var eventemitter3 = createCommonjsModule(function (module) {
12160
12161 var has = Object.prototype.hasOwnProperty
12162 , prefix = '~';
12163
12164 /**
12165 * Constructor to create a storage for our `EE` objects.
12166 * An `Events` instance is a plain object whose properties are event names.
12167 *
12168 * @constructor
12169 * @private
12170 */
12171 function Events() {}
12172
12173 //
12174 // We try to not inherit from `Object.prototype`. In some engines creating an
12175 // instance in this way is faster than calling `Object.create(null)` directly.
12176 // If `Object.create(null)` is not supported we prefix the event names with a
12177 // character to make sure that the built-in object properties are not
12178 // overridden or used as an attack vector.
12179 //
12180 if (Object.create) {
12181 Events.prototype = Object.create(null);
12182
12183 //
12184 // This hack is needed because the `__proto__` property is still inherited in
12185 // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.
12186 //
12187 if (!new Events().__proto__) prefix = false;
12188 }
12189
12190 /**
12191 * Representation of a single event listener.
12192 *
12193 * @param {Function} fn The listener function.
12194 * @param {*} context The context to invoke the listener with.
12195 * @param {Boolean} [once=false] Specify if the listener is a one-time listener.
12196 * @constructor
12197 * @private
12198 */
12199 function EE(fn, context, once) {
12200 this.fn = fn;
12201 this.context = context;
12202 this.once = once || false;
12203 }
12204
12205 /**
12206 * Add a listener for a given event.
12207 *
12208 * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
12209 * @param {(String|Symbol)} event The event name.
12210 * @param {Function} fn The listener function.
12211 * @param {*} context The context to invoke the listener with.
12212 * @param {Boolean} once Specify if the listener is a one-time listener.
12213 * @returns {EventEmitter}
12214 * @private
12215 */
12216 function addListener(emitter, event, fn, context, once) {
12217 if (typeof fn !== 'function') {
12218 throw new TypeError('The listener must be a function');
12219 }
12220
12221 var listener = new EE(fn, context || emitter, once)
12222 , evt = prefix ? prefix + event : event;
12223
12224 if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;
12225 else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);
12226 else emitter._events[evt] = [emitter._events[evt], listener];
12227
12228 return emitter;
12229 }
12230
12231 /**
12232 * Clear event by name.
12233 *
12234 * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
12235 * @param {(String|Symbol)} evt The Event name.
12236 * @private
12237 */
12238 function clearEvent(emitter, evt) {
12239 if (--emitter._eventsCount === 0) emitter._events = new Events();
12240 else delete emitter._events[evt];
12241 }
12242
12243 /**
12244 * Minimal `EventEmitter` interface that is molded against the Node.js
12245 * `EventEmitter` interface.
12246 *
12247 * @constructor
12248 * @public
12249 */
12250 function EventEmitter() {
12251 this._events = new Events();
12252 this._eventsCount = 0;
12253 }
12254
12255 /**
12256 * Return an array listing the events for which the emitter has registered
12257 * listeners.
12258 *
12259 * @returns {Array}
12260 * @public
12261 */
12262 EventEmitter.prototype.eventNames = function eventNames() {
12263 var names = []
12264 , events
12265 , name;
12266
12267 if (this._eventsCount === 0) return names;
12268
12269 for (name in (events = this._events)) {
12270 if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);
12271 }
12272
12273 if (Object.getOwnPropertySymbols) {
12274 return names.concat(Object.getOwnPropertySymbols(events));
12275 }
12276
12277 return names;
12278 };
12279
12280 /**
12281 * Return the listeners registered for a given event.
12282 *
12283 * @param {(String|Symbol)} event The event name.
12284 * @returns {Array} The registered listeners.
12285 * @public
12286 */
12287 EventEmitter.prototype.listeners = function listeners(event) {
12288 var evt = prefix ? prefix + event : event
12289 , handlers = this._events[evt];
12290
12291 if (!handlers) return [];
12292 if (handlers.fn) return [handlers.fn];
12293
12294 for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {
12295 ee[i] = handlers[i].fn;
12296 }
12297
12298 return ee;
12299 };
12300
12301 /**
12302 * Return the number of listeners listening to a given event.
12303 *
12304 * @param {(String|Symbol)} event The event name.
12305 * @returns {Number} The number of listeners.
12306 * @public
12307 */
12308 EventEmitter.prototype.listenerCount = function listenerCount(event) {
12309 var evt = prefix ? prefix + event : event
12310 , listeners = this._events[evt];
12311
12312 if (!listeners) return 0;
12313 if (listeners.fn) return 1;
12314 return listeners.length;
12315 };
12316
12317 /**
12318 * Calls each of the listeners registered for a given event.
12319 *
12320 * @param {(String|Symbol)} event The event name.
12321 * @returns {Boolean} `true` if the event had listeners, else `false`.
12322 * @public
12323 */
12324 EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {
12325 var evt = prefix ? prefix + event : event;
12326
12327 if (!this._events[evt]) return false;
12328
12329 var listeners = this._events[evt]
12330 , len = arguments.length
12331 , args
12332 , i;
12333
12334 if (listeners.fn) {
12335 if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);
12336
12337 switch (len) {
12338 case 1: return listeners.fn.call(listeners.context), true;
12339 case 2: return listeners.fn.call(listeners.context, a1), true;
12340 case 3: return listeners.fn.call(listeners.context, a1, a2), true;
12341 case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;
12342 case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;
12343 case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;
12344 }
12345
12346 for (i = 1, args = new Array(len -1); i < len; i++) {
12347 args[i - 1] = arguments[i];
12348 }
12349
12350 listeners.fn.apply(listeners.context, args);
12351 } else {
12352 var length = listeners.length
12353 , j;
12354
12355 for (i = 0; i < length; i++) {
12356 if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);
12357
12358 switch (len) {
12359 case 1: listeners[i].fn.call(listeners[i].context); break;
12360 case 2: listeners[i].fn.call(listeners[i].context, a1); break;
12361 case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;
12362 case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;
12363 default:
12364 if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {
12365 args[j - 1] = arguments[j];
12366 }
12367
12368 listeners[i].fn.apply(listeners[i].context, args);
12369 }
12370 }
12371 }
12372
12373 return true;
12374 };
12375
12376 /**
12377 * Add a listener for a given event.
12378 *
12379 * @param {(String|Symbol)} event The event name.
12380 * @param {Function} fn The listener function.
12381 * @param {*} [context=this] The context to invoke the listener with.
12382 * @returns {EventEmitter} `this`.
12383 * @public
12384 */
12385 EventEmitter.prototype.on = function on(event, fn, context) {
12386 return addListener(this, event, fn, context, false);
12387 };
12388
12389 /**
12390 * Add a one-time listener for a given event.
12391 *
12392 * @param {(String|Symbol)} event The event name.
12393 * @param {Function} fn The listener function.
12394 * @param {*} [context=this] The context to invoke the listener with.
12395 * @returns {EventEmitter} `this`.
12396 * @public
12397 */
12398 EventEmitter.prototype.once = function once(event, fn, context) {
12399 return addListener(this, event, fn, context, true);
12400 };
12401
12402 /**
12403 * Remove the listeners of a given event.
12404 *
12405 * @param {(String|Symbol)} event The event name.
12406 * @param {Function} fn Only remove the listeners that match this function.
12407 * @param {*} context Only remove the listeners that have this context.
12408 * @param {Boolean} once Only remove one-time listeners.
12409 * @returns {EventEmitter} `this`.
12410 * @public
12411 */
12412 EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {
12413 var evt = prefix ? prefix + event : event;
12414
12415 if (!this._events[evt]) return this;
12416 if (!fn) {
12417 clearEvent(this, evt);
12418 return this;
12419 }
12420
12421 var listeners = this._events[evt];
12422
12423 if (listeners.fn) {
12424 if (
12425 listeners.fn === fn &&
12426 (!once || listeners.once) &&
12427 (!context || listeners.context === context)
12428 ) {
12429 clearEvent(this, evt);
12430 }
12431 } else {
12432 for (var i = 0, events = [], length = listeners.length; i < length; i++) {
12433 if (
12434 listeners[i].fn !== fn ||
12435 (once && !listeners[i].once) ||
12436 (context && listeners[i].context !== context)
12437 ) {
12438 events.push(listeners[i]);
12439 }
12440 }
12441
12442 //
12443 // Reset the array, or remove it completely if we have no more listeners.
12444 //
12445 if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;
12446 else clearEvent(this, evt);
12447 }
12448
12449 return this;
12450 };
12451
12452 /**
12453 * Remove all listeners, or those of the specified event.
12454 *
12455 * @param {(String|Symbol)} [event] The event name.
12456 * @returns {EventEmitter} `this`.
12457 * @public
12458 */
12459 EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {
12460 var evt;
12461
12462 if (event) {
12463 evt = prefix ? prefix + event : event;
12464 if (this._events[evt]) clearEvent(this, evt);
12465 } else {
12466 this._events = new Events();
12467 this._eventsCount = 0;
12468 }
12469
12470 return this;
12471 };
12472
12473 //
12474 // Alias methods names because people roll like that.
12475 //
12476 EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
12477 EventEmitter.prototype.addListener = EventEmitter.prototype.on;
12478
12479 //
12480 // Expose the prefix.
12481 //
12482 EventEmitter.prefixed = prefix;
12483
12484 //
12485 // Allow `EventEmitter` to be imported as module namespace.
12486 //
12487 EventEmitter.EventEmitter = EventEmitter;
12488
12489 //
12490 // Expose the module.
12491 //
12492 {
12493 module.exports = EventEmitter;
12494 }
12495 });
12496
12497 var runtime = createCommonjsModule(function (module) {
12498 /**
12499 * Copyright (c) 2014-present, Facebook, Inc.
12500 *
12501 * This source code is licensed under the MIT license found in the
12502 * LICENSE file in the root directory of this source tree.
12503 */
12504
12505 !(function(global) {
12506
12507 var Op = Object.prototype;
12508 var hasOwn = Op.hasOwnProperty;
12509 var undefined$1; // More compressible than void 0.
12510 var $Symbol = typeof Symbol === "function" ? Symbol : {};
12511 var iteratorSymbol = $Symbol.iterator || "@@iterator";
12512 var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator";
12513 var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";
12514 var runtime = global.regeneratorRuntime;
12515 if (runtime) {
12516 {
12517 // If regeneratorRuntime is defined globally and we're in a module,
12518 // make the exports object identical to regeneratorRuntime.
12519 module.exports = runtime;
12520 }
12521 // Don't bother evaluating the rest of this file if the runtime was
12522 // already defined globally.
12523 return;
12524 }
12525
12526 // Define the runtime globally (as expected by generated code) as either
12527 // module.exports (if we're in a module) or a new, empty object.
12528 runtime = global.regeneratorRuntime = module.exports;
12529
12530 function wrap(innerFn, outerFn, self, tryLocsList) {
12531 // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator.
12532 var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator;
12533 var generator = Object.create(protoGenerator.prototype);
12534 var context = new Context(tryLocsList || []);
12535
12536 // The ._invoke method unifies the implementations of the .next,
12537 // .throw, and .return methods.
12538 generator._invoke = makeInvokeMethod(innerFn, self, context);
12539
12540 return generator;
12541 }
12542 runtime.wrap = wrap;
12543
12544 // Try/catch helper to minimize deoptimizations. Returns a completion
12545 // record like context.tryEntries[i].completion. This interface could
12546 // have been (and was previously) designed to take a closure to be
12547 // invoked without arguments, but in all the cases we care about we
12548 // already have an existing method we want to call, so there's no need
12549 // to create a new function object. We can even get away with assuming
12550 // the method takes exactly one argument, since that happens to be true
12551 // in every case, so we don't have to touch the arguments object. The
12552 // only additional allocation required is the completion record, which
12553 // has a stable shape and so hopefully should be cheap to allocate.
12554 function tryCatch(fn, obj, arg) {
12555 try {
12556 return { type: "normal", arg: fn.call(obj, arg) };
12557 } catch (err) {
12558 return { type: "throw", arg: err };
12559 }
12560 }
12561
12562 var GenStateSuspendedStart = "suspendedStart";
12563 var GenStateSuspendedYield = "suspendedYield";
12564 var GenStateExecuting = "executing";
12565 var GenStateCompleted = "completed";
12566
12567 // Returning this object from the innerFn has the same effect as
12568 // breaking out of the dispatch switch statement.
12569 var ContinueSentinel = {};
12570
12571 // Dummy constructor functions that we use as the .constructor and
12572 // .constructor.prototype properties for functions that return Generator
12573 // objects. For full spec compliance, you may wish to configure your
12574 // minifier not to mangle the names of these two functions.
12575 function Generator() {}
12576 function GeneratorFunction() {}
12577 function GeneratorFunctionPrototype() {}
12578
12579 // This is a polyfill for %IteratorPrototype% for environments that
12580 // don't natively support it.
12581 var IteratorPrototype = {};
12582 IteratorPrototype[iteratorSymbol] = function () {
12583 return this;
12584 };
12585
12586 var getProto = Object.getPrototypeOf;
12587 var NativeIteratorPrototype = getProto && getProto(getProto(values([])));
12588 if (NativeIteratorPrototype &&
12589 NativeIteratorPrototype !== Op &&
12590 hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) {
12591 // This environment has a native %IteratorPrototype%; use it instead
12592 // of the polyfill.
12593 IteratorPrototype = NativeIteratorPrototype;
12594 }
12595
12596 var Gp = GeneratorFunctionPrototype.prototype =
12597 Generator.prototype = Object.create(IteratorPrototype);
12598 GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype;
12599 GeneratorFunctionPrototype.constructor = GeneratorFunction;
12600 GeneratorFunctionPrototype[toStringTagSymbol] =
12601 GeneratorFunction.displayName = "GeneratorFunction";
12602
12603 // Helper for defining the .next, .throw, and .return methods of the
12604 // Iterator interface in terms of a single ._invoke method.
12605 function defineIteratorMethods(prototype) {
12606 ["next", "throw", "return"].forEach(function(method) {
12607 prototype[method] = function(arg) {
12608 return this._invoke(method, arg);
12609 };
12610 });
12611 }
12612
12613 runtime.isGeneratorFunction = function(genFun) {
12614 var ctor = typeof genFun === "function" && genFun.constructor;
12615 return ctor
12616 ? ctor === GeneratorFunction ||
12617 // For the native GeneratorFunction constructor, the best we can
12618 // do is to check its .name property.
12619 (ctor.displayName || ctor.name) === "GeneratorFunction"
12620 : false;
12621 };
12622
12623 runtime.mark = function(genFun) {
12624 if (Object.setPrototypeOf) {
12625 Object.setPrototypeOf(genFun, GeneratorFunctionPrototype);
12626 } else {
12627 genFun.__proto__ = GeneratorFunctionPrototype;
12628 if (!(toStringTagSymbol in genFun)) {
12629 genFun[toStringTagSymbol] = "GeneratorFunction";
12630 }
12631 }
12632 genFun.prototype = Object.create(Gp);
12633 return genFun;
12634 };
12635
12636 // Within the body of any async function, `await x` is transformed to
12637 // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test
12638 // `hasOwn.call(value, "__await")` to determine if the yielded value is
12639 // meant to be awaited.
12640 runtime.awrap = function(arg) {
12641 return { __await: arg };
12642 };
12643
12644 function AsyncIterator(generator) {
12645 function invoke(method, arg, resolve, reject) {
12646 var record = tryCatch(generator[method], generator, arg);
12647 if (record.type === "throw") {
12648 reject(record.arg);
12649 } else {
12650 var result = record.arg;
12651 var value = result.value;
12652 if (value &&
12653 typeof value === "object" &&
12654 hasOwn.call(value, "__await")) {
12655 return Promise.resolve(value.__await).then(function(value) {
12656 invoke("next", value, resolve, reject);
12657 }, function(err) {
12658 invoke("throw", err, resolve, reject);
12659 });
12660 }
12661
12662 return Promise.resolve(value).then(function(unwrapped) {
12663 // When a yielded Promise is resolved, its final value becomes
12664 // the .value of the Promise<{value,done}> result for the
12665 // current iteration.
12666 result.value = unwrapped;
12667 resolve(result);
12668 }, function(error) {
12669 // If a rejected Promise was yielded, throw the rejection back
12670 // into the async generator function so it can be handled there.
12671 return invoke("throw", error, resolve, reject);
12672 });
12673 }
12674 }
12675
12676 var previousPromise;
12677
12678 function enqueue(method, arg) {
12679 function callInvokeWithMethodAndArg() {
12680 return new Promise(function(resolve, reject) {
12681 invoke(method, arg, resolve, reject);
12682 });
12683 }
12684
12685 return previousPromise =
12686 // If enqueue has been called before, then we want to wait until
12687 // all previous Promises have been resolved before calling invoke,
12688 // so that results are always delivered in the correct order. If
12689 // enqueue has not been called before, then it is important to
12690 // call invoke immediately, without waiting on a callback to fire,
12691 // so that the async generator function has the opportunity to do
12692 // any necessary setup in a predictable way. This predictability
12693 // is why the Promise constructor synchronously invokes its
12694 // executor callback, and why async functions synchronously
12695 // execute code before the first await. Since we implement simple
12696 // async functions in terms of async generators, it is especially
12697 // important to get this right, even though it requires care.
12698 previousPromise ? previousPromise.then(
12699 callInvokeWithMethodAndArg,
12700 // Avoid propagating failures to Promises returned by later
12701 // invocations of the iterator.
12702 callInvokeWithMethodAndArg
12703 ) : callInvokeWithMethodAndArg();
12704 }
12705
12706 // Define the unified helper method that is used to implement .next,
12707 // .throw, and .return (see defineIteratorMethods).
12708 this._invoke = enqueue;
12709 }
12710
12711 defineIteratorMethods(AsyncIterator.prototype);
12712 AsyncIterator.prototype[asyncIteratorSymbol] = function () {
12713 return this;
12714 };
12715 runtime.AsyncIterator = AsyncIterator;
12716
12717 // Note that simple async functions are implemented on top of
12718 // AsyncIterator objects; they just return a Promise for the value of
12719 // the final result produced by the iterator.
12720 runtime.async = function(innerFn, outerFn, self, tryLocsList) {
12721 var iter = new AsyncIterator(
12722 wrap(innerFn, outerFn, self, tryLocsList)
12723 );
12724
12725 return runtime.isGeneratorFunction(outerFn)
12726 ? iter // If outerFn is a generator, return the full iterator.
12727 : iter.next().then(function(result) {
12728 return result.done ? result.value : iter.next();
12729 });
12730 };
12731
12732 function makeInvokeMethod(innerFn, self, context) {
12733 var state = GenStateSuspendedStart;
12734
12735 return function invoke(method, arg) {
12736 if (state === GenStateExecuting) {
12737 throw new Error("Generator is already running");
12738 }
12739
12740 if (state === GenStateCompleted) {
12741 if (method === "throw") {
12742 throw arg;
12743 }
12744
12745 // Be forgiving, per 25.3.3.3.3 of the spec:
12746 // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume
12747 return doneResult();
12748 }
12749
12750 context.method = method;
12751 context.arg = arg;
12752
12753 while (true) {
12754 var delegate = context.delegate;
12755 if (delegate) {
12756 var delegateResult = maybeInvokeDelegate(delegate, context);
12757 if (delegateResult) {
12758 if (delegateResult === ContinueSentinel) continue;
12759 return delegateResult;
12760 }
12761 }
12762
12763 if (context.method === "next") {
12764 // Setting context._sent for legacy support of Babel's
12765 // function.sent implementation.
12766 context.sent = context._sent = context.arg;
12767
12768 } else if (context.method === "throw") {
12769 if (state === GenStateSuspendedStart) {
12770 state = GenStateCompleted;
12771 throw context.arg;
12772 }
12773
12774 context.dispatchException(context.arg);
12775
12776 } else if (context.method === "return") {
12777 context.abrupt("return", context.arg);
12778 }
12779
12780 state = GenStateExecuting;
12781
12782 var record = tryCatch(innerFn, self, context);
12783 if (record.type === "normal") {
12784 // If an exception is thrown from innerFn, we leave state ===
12785 // GenStateExecuting and loop back for another invocation.
12786 state = context.done
12787 ? GenStateCompleted
12788 : GenStateSuspendedYield;
12789
12790 if (record.arg === ContinueSentinel) {
12791 continue;
12792 }
12793
12794 return {
12795 value: record.arg,
12796 done: context.done
12797 };
12798
12799 } else if (record.type === "throw") {
12800 state = GenStateCompleted;
12801 // Dispatch the exception by looping back around to the
12802 // context.dispatchException(context.arg) call above.
12803 context.method = "throw";
12804 context.arg = record.arg;
12805 }
12806 }
12807 };
12808 }
12809
12810 // Call delegate.iterator[context.method](context.arg) and handle the
12811 // result, either by returning a { value, done } result from the
12812 // delegate iterator, or by modifying context.method and context.arg,
12813 // setting context.delegate to null, and returning the ContinueSentinel.
12814 function maybeInvokeDelegate(delegate, context) {
12815 var method = delegate.iterator[context.method];
12816 if (method === undefined$1) {
12817 // A .throw or .return when the delegate iterator has no .throw
12818 // method always terminates the yield* loop.
12819 context.delegate = null;
12820
12821 if (context.method === "throw") {
12822 if (delegate.iterator.return) {
12823 // If the delegate iterator has a return method, give it a
12824 // chance to clean up.
12825 context.method = "return";
12826 context.arg = undefined$1;
12827 maybeInvokeDelegate(delegate, context);
12828
12829 if (context.method === "throw") {
12830 // If maybeInvokeDelegate(context) changed context.method from
12831 // "return" to "throw", let that override the TypeError below.
12832 return ContinueSentinel;
12833 }
12834 }
12835
12836 context.method = "throw";
12837 context.arg = new TypeError(
12838 "The iterator does not provide a 'throw' method");
12839 }
12840
12841 return ContinueSentinel;
12842 }
12843
12844 var record = tryCatch(method, delegate.iterator, context.arg);
12845
12846 if (record.type === "throw") {
12847 context.method = "throw";
12848 context.arg = record.arg;
12849 context.delegate = null;
12850 return ContinueSentinel;
12851 }
12852
12853 var info = record.arg;
12854
12855 if (! info) {
12856 context.method = "throw";
12857 context.arg = new TypeError("iterator result is not an object");
12858 context.delegate = null;
12859 return ContinueSentinel;
12860 }
12861
12862 if (info.done) {
12863 // Assign the result of the finished delegate to the temporary
12864 // variable specified by delegate.resultName (see delegateYield).
12865 context[delegate.resultName] = info.value;
12866
12867 // Resume execution at the desired location (see delegateYield).
12868 context.next = delegate.nextLoc;
12869
12870 // If context.method was "throw" but the delegate handled the
12871 // exception, let the outer generator proceed normally. If
12872 // context.method was "next", forget context.arg since it has been
12873 // "consumed" by the delegate iterator. If context.method was
12874 // "return", allow the original .return call to continue in the
12875 // outer generator.
12876 if (context.method !== "return") {
12877 context.method = "next";
12878 context.arg = undefined$1;
12879 }
12880
12881 } else {
12882 // Re-yield the result returned by the delegate method.
12883 return info;
12884 }
12885
12886 // The delegate iterator is finished, so forget it and continue with
12887 // the outer generator.
12888 context.delegate = null;
12889 return ContinueSentinel;
12890 }
12891
12892 // Define Generator.prototype.{next,throw,return} in terms of the
12893 // unified ._invoke helper method.
12894 defineIteratorMethods(Gp);
12895
12896 Gp[toStringTagSymbol] = "Generator";
12897
12898 // A Generator should always return itself as the iterator object when the
12899 // @@iterator function is called on it. Some browsers' implementations of the
12900 // iterator prototype chain incorrectly implement this, causing the Generator
12901 // object to not be returned from this call. This ensures that doesn't happen.
12902 // See https://github.com/facebook/regenerator/issues/274 for more details.
12903 Gp[iteratorSymbol] = function() {
12904 return this;
12905 };
12906
12907 Gp.toString = function() {
12908 return "[object Generator]";
12909 };
12910
12911 function pushTryEntry(locs) {
12912 var entry = { tryLoc: locs[0] };
12913
12914 if (1 in locs) {
12915 entry.catchLoc = locs[1];
12916 }
12917
12918 if (2 in locs) {
12919 entry.finallyLoc = locs[2];
12920 entry.afterLoc = locs[3];
12921 }
12922
12923 this.tryEntries.push(entry);
12924 }
12925
12926 function resetTryEntry(entry) {
12927 var record = entry.completion || {};
12928 record.type = "normal";
12929 delete record.arg;
12930 entry.completion = record;
12931 }
12932
12933 function Context(tryLocsList) {
12934 // The root entry object (effectively a try statement without a catch
12935 // or a finally block) gives us a place to store values thrown from
12936 // locations where there is no enclosing try statement.
12937 this.tryEntries = [{ tryLoc: "root" }];
12938 tryLocsList.forEach(pushTryEntry, this);
12939 this.reset(true);
12940 }
12941
12942 runtime.keys = function(object) {
12943 var keys = [];
12944 for (var key in object) {
12945 keys.push(key);
12946 }
12947 keys.reverse();
12948
12949 // Rather than returning an object with a next method, we keep
12950 // things simple and return the next function itself.
12951 return function next() {
12952 while (keys.length) {
12953 var key = keys.pop();
12954 if (key in object) {
12955 next.value = key;
12956 next.done = false;
12957 return next;
12958 }
12959 }
12960
12961 // To avoid creating an additional object, we just hang the .value
12962 // and .done properties off the next function object itself. This
12963 // also ensures that the minifier will not anonymize the function.
12964 next.done = true;
12965 return next;
12966 };
12967 };
12968
12969 function values(iterable) {
12970 if (iterable) {
12971 var iteratorMethod = iterable[iteratorSymbol];
12972 if (iteratorMethod) {
12973 return iteratorMethod.call(iterable);
12974 }
12975
12976 if (typeof iterable.next === "function") {
12977 return iterable;
12978 }
12979
12980 if (!isNaN(iterable.length)) {
12981 var i = -1, next = function next() {
12982 while (++i < iterable.length) {
12983 if (hasOwn.call(iterable, i)) {
12984 next.value = iterable[i];
12985 next.done = false;
12986 return next;
12987 }
12988 }
12989
12990 next.value = undefined$1;
12991 next.done = true;
12992
12993 return next;
12994 };
12995
12996 return next.next = next;
12997 }
12998 }
12999
13000 // Return an iterator with no values.
13001 return { next: doneResult };
13002 }
13003 runtime.values = values;
13004
13005 function doneResult() {
13006 return { value: undefined$1, done: true };
13007 }
13008
13009 Context.prototype = {
13010 constructor: Context,
13011
13012 reset: function(skipTempReset) {
13013 this.prev = 0;
13014 this.next = 0;
13015 // Resetting context._sent for legacy support of Babel's
13016 // function.sent implementation.
13017 this.sent = this._sent = undefined$1;
13018 this.done = false;
13019 this.delegate = null;
13020
13021 this.method = "next";
13022 this.arg = undefined$1;
13023
13024 this.tryEntries.forEach(resetTryEntry);
13025
13026 if (!skipTempReset) {
13027 for (var name in this) {
13028 // Not sure about the optimal order of these conditions:
13029 if (name.charAt(0) === "t" &&
13030 hasOwn.call(this, name) &&
13031 !isNaN(+name.slice(1))) {
13032 this[name] = undefined$1;
13033 }
13034 }
13035 }
13036 },
13037
13038 stop: function() {
13039 this.done = true;
13040
13041 var rootEntry = this.tryEntries[0];
13042 var rootRecord = rootEntry.completion;
13043 if (rootRecord.type === "throw") {
13044 throw rootRecord.arg;
13045 }
13046
13047 return this.rval;
13048 },
13049
13050 dispatchException: function(exception) {
13051 if (this.done) {
13052 throw exception;
13053 }
13054
13055 var context = this;
13056 function handle(loc, caught) {
13057 record.type = "throw";
13058 record.arg = exception;
13059 context.next = loc;
13060
13061 if (caught) {
13062 // If the dispatched exception was caught by a catch block,
13063 // then let that catch block handle the exception normally.
13064 context.method = "next";
13065 context.arg = undefined$1;
13066 }
13067
13068 return !! caught;
13069 }
13070
13071 for (var i = this.tryEntries.length - 1; i >= 0; --i) {
13072 var entry = this.tryEntries[i];
13073 var record = entry.completion;
13074
13075 if (entry.tryLoc === "root") {
13076 // Exception thrown outside of any try block that could handle
13077 // it, so set the completion value of the entire function to
13078 // throw the exception.
13079 return handle("end");
13080 }
13081
13082 if (entry.tryLoc <= this.prev) {
13083 var hasCatch = hasOwn.call(entry, "catchLoc");
13084 var hasFinally = hasOwn.call(entry, "finallyLoc");
13085
13086 if (hasCatch && hasFinally) {
13087 if (this.prev < entry.catchLoc) {
13088 return handle(entry.catchLoc, true);
13089 } else if (this.prev < entry.finallyLoc) {
13090 return handle(entry.finallyLoc);
13091 }
13092
13093 } else if (hasCatch) {
13094 if (this.prev < entry.catchLoc) {
13095 return handle(entry.catchLoc, true);
13096 }
13097
13098 } else if (hasFinally) {
13099 if (this.prev < entry.finallyLoc) {
13100 return handle(entry.finallyLoc);
13101 }
13102
13103 } else {
13104 throw new Error("try statement without catch or finally");
13105 }
13106 }
13107 }
13108 },
13109
13110 abrupt: function(type, arg) {
13111 for (var i = this.tryEntries.length - 1; i >= 0; --i) {
13112 var entry = this.tryEntries[i];
13113 if (entry.tryLoc <= this.prev &&
13114 hasOwn.call(entry, "finallyLoc") &&
13115 this.prev < entry.finallyLoc) {
13116 var finallyEntry = entry;
13117 break;
13118 }
13119 }
13120
13121 if (finallyEntry &&
13122 (type === "break" ||
13123 type === "continue") &&
13124 finallyEntry.tryLoc <= arg &&
13125 arg <= finallyEntry.finallyLoc) {
13126 // Ignore the finally entry if control is not jumping to a
13127 // location outside the try/catch block.
13128 finallyEntry = null;
13129 }
13130
13131 var record = finallyEntry ? finallyEntry.completion : {};
13132 record.type = type;
13133 record.arg = arg;
13134
13135 if (finallyEntry) {
13136 this.method = "next";
13137 this.next = finallyEntry.finallyLoc;
13138 return ContinueSentinel;
13139 }
13140
13141 return this.complete(record);
13142 },
13143
13144 complete: function(record, afterLoc) {
13145 if (record.type === "throw") {
13146 throw record.arg;
13147 }
13148
13149 if (record.type === "break" ||
13150 record.type === "continue") {
13151 this.next = record.arg;
13152 } else if (record.type === "return") {
13153 this.rval = this.arg = record.arg;
13154 this.method = "return";
13155 this.next = "end";
13156 } else if (record.type === "normal" && afterLoc) {
13157 this.next = afterLoc;
13158 }
13159
13160 return ContinueSentinel;
13161 },
13162
13163 finish: function(finallyLoc) {
13164 for (var i = this.tryEntries.length - 1; i >= 0; --i) {
13165 var entry = this.tryEntries[i];
13166 if (entry.finallyLoc === finallyLoc) {
13167 this.complete(entry.completion, entry.afterLoc);
13168 resetTryEntry(entry);
13169 return ContinueSentinel;
13170 }
13171 }
13172 },
13173
13174 "catch": function(tryLoc) {
13175 for (var i = this.tryEntries.length - 1; i >= 0; --i) {
13176 var entry = this.tryEntries[i];
13177 if (entry.tryLoc === tryLoc) {
13178 var record = entry.completion;
13179 if (record.type === "throw") {
13180 var thrown = record.arg;
13181 resetTryEntry(entry);
13182 }
13183 return thrown;
13184 }
13185 }
13186
13187 // The context.catch method must only be called with a location
13188 // argument that corresponds to a known catch block.
13189 throw new Error("illegal catch attempt");
13190 },
13191
13192 delegateYield: function(iterable, resultName, nextLoc) {
13193 this.delegate = {
13194 iterator: values(iterable),
13195 resultName: resultName,
13196 nextLoc: nextLoc
13197 };
13198
13199 if (this.method === "next") {
13200 // Deliberately forget the last sent value so that we don't
13201 // accidentally pass it on to the delegate.
13202 this.arg = undefined$1;
13203 }
13204
13205 return ContinueSentinel;
13206 }
13207 };
13208 })(
13209 // In sloppy mode, unbound `this` refers to the global object, fallback to
13210 // Function constructor if we're in global strict mode. That is sadly a form
13211 // of indirect eval which violates Content Security Policy.
13212 (function() {
13213 return this || (typeof self === "object" && self);
13214 })() || Function("return this")()
13215 );
13216 });
13217
13218 /**
13219 * Copyright (c) 2014-present, Facebook, Inc.
13220 *
13221 * This source code is licensed under the MIT license found in the
13222 * LICENSE file in the root directory of this source tree.
13223 */
13224
13225 // This method of obtaining a reference to the global object needs to be
13226 // kept identical to the way it is obtained in runtime.js
13227 var g = (function() {
13228 return this || (typeof self === "object" && self);
13229 })() || Function("return this")();
13230
13231 // Use `getOwnPropertyNames` because not all browsers support calling
13232 // `hasOwnProperty` on the global `self` object in a worker. See #183.
13233 var hadRuntime = g.regeneratorRuntime &&
13234 Object.getOwnPropertyNames(g).indexOf("regeneratorRuntime") >= 0;
13235
13236 // Save the old regeneratorRuntime in case it needs to be restored later.
13237 var oldRuntime = hadRuntime && g.regeneratorRuntime;
13238
13239 // Force reevalutation of runtime.js.
13240 g.regeneratorRuntime = undefined;
13241
13242 var runtimeModule = runtime;
13243
13244 if (hadRuntime) {
13245 // Restore the original runtime.
13246 g.regeneratorRuntime = oldRuntime;
13247 } else {
13248 // Remove the global property added by runtime.js.
13249 try {
13250 delete g.regeneratorRuntime;
13251 } catch(e) {
13252 g.regeneratorRuntime = undefined;
13253 }
13254 }
13255
13256 var regenerator = runtimeModule;
13257
13258 /**
13259 * Helpers.
13260 */
13261
13262 var s = 1000;
13263 var m = s * 60;
13264 var h = m * 60;
13265 var d = h * 24;
13266 var w = d * 7;
13267 var y = d * 365.25;
13268
13269 /**
13270 * Parse or format the given `val`.
13271 *
13272 * Options:
13273 *
13274 * - `long` verbose formatting [false]
13275 *
13276 * @param {String|Number} val
13277 * @param {Object} [options]
13278 * @throws {Error} throw an error if val is not a non-empty string or a number
13279 * @return {String|Number}
13280 * @api public
13281 */
13282
13283 var ms = function(val, options) {
13284 options = options || {};
13285 var type = typeof val;
13286 if (type === 'string' && val.length > 0) {
13287 return parse(val);
13288 } else if (type === 'number' && isNaN(val) === false) {
13289 return options.long ? fmtLong(val) : fmtShort(val);
13290 }
13291 throw new Error(
13292 'val is not a non-empty string or a valid number. val=' +
13293 JSON.stringify(val)
13294 );
13295 };
13296
13297 /**
13298 * Parse the given `str` and return milliseconds.
13299 *
13300 * @param {String} str
13301 * @return {Number}
13302 * @api private
13303 */
13304
13305 function parse(str) {
13306 str = String(str);
13307 if (str.length > 100) {
13308 return;
13309 }
13310 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(
13311 str
13312 );
13313 if (!match) {
13314 return;
13315 }
13316 var n = parseFloat(match[1]);
13317 var type = (match[2] || 'ms').toLowerCase();
13318 switch (type) {
13319 case 'years':
13320 case 'year':
13321 case 'yrs':
13322 case 'yr':
13323 case 'y':
13324 return n * y;
13325 case 'weeks':
13326 case 'week':
13327 case 'w':
13328 return n * w;
13329 case 'days':
13330 case 'day':
13331 case 'd':
13332 return n * d;
13333 case 'hours':
13334 case 'hour':
13335 case 'hrs':
13336 case 'hr':
13337 case 'h':
13338 return n * h;
13339 case 'minutes':
13340 case 'minute':
13341 case 'mins':
13342 case 'min':
13343 case 'm':
13344 return n * m;
13345 case 'seconds':
13346 case 'second':
13347 case 'secs':
13348 case 'sec':
13349 case 's':
13350 return n * s;
13351 case 'milliseconds':
13352 case 'millisecond':
13353 case 'msecs':
13354 case 'msec':
13355 case 'ms':
13356 return n;
13357 default:
13358 return undefined;
13359 }
13360 }
13361
13362 /**
13363 * Short format for `ms`.
13364 *
13365 * @param {Number} ms
13366 * @return {String}
13367 * @api private
13368 */
13369
13370 function fmtShort(ms) {
13371 var msAbs = Math.abs(ms);
13372 if (msAbs >= d) {
13373 return Math.round(ms / d) + 'd';
13374 }
13375 if (msAbs >= h) {
13376 return Math.round(ms / h) + 'h';
13377 }
13378 if (msAbs >= m) {
13379 return Math.round(ms / m) + 'm';
13380 }
13381 if (msAbs >= s) {
13382 return Math.round(ms / s) + 's';
13383 }
13384 return ms + 'ms';
13385 }
13386
13387 /**
13388 * Long format for `ms`.
13389 *
13390 * @param {Number} ms
13391 * @return {String}
13392 * @api private
13393 */
13394
13395 function fmtLong(ms) {
13396 var msAbs = Math.abs(ms);
13397 if (msAbs >= d) {
13398 return plural(ms, msAbs, d, 'day');
13399 }
13400 if (msAbs >= h) {
13401 return plural(ms, msAbs, h, 'hour');
13402 }
13403 if (msAbs >= m) {
13404 return plural(ms, msAbs, m, 'minute');
13405 }
13406 if (msAbs >= s) {
13407 return plural(ms, msAbs, s, 'second');
13408 }
13409 return ms + ' ms';
13410 }
13411
13412 /**
13413 * Pluralization helper.
13414 */
13415
13416 function plural(ms, msAbs, n, name) {
13417 var isPlural = msAbs >= n * 1.5;
13418 return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');
13419 }
13420
13421 /**
13422 * This is the common logic for both the Node.js and web browser
13423 * implementations of `debug()`.
13424 */
13425 function setup(env) {
13426 createDebug.debug = createDebug;
13427 createDebug.default = createDebug;
13428 createDebug.coerce = coerce;
13429 createDebug.disable = disable;
13430 createDebug.enable = enable;
13431 createDebug.enabled = enabled;
13432 createDebug.humanize = ms;
13433 Object.keys(env).forEach(function (key) {
13434 createDebug[key] = env[key];
13435 });
13436 /**
13437 * Active `debug` instances.
13438 */
13439
13440 createDebug.instances = [];
13441 /**
13442 * The currently active debug mode names, and names to skip.
13443 */
13444
13445 createDebug.names = [];
13446 createDebug.skips = [];
13447 /**
13448 * Map of special "%n" handling functions, for the debug "format" argument.
13449 *
13450 * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
13451 */
13452
13453 createDebug.formatters = {};
13454 /**
13455 * Selects a color for a debug namespace
13456 * @param {String} namespace The namespace string for the for the debug instance to be colored
13457 * @return {Number|String} An ANSI color code for the given namespace
13458 * @api private
13459 */
13460
13461 function selectColor(namespace) {
13462 var hash = 0;
13463
13464 for (var i = 0; i < namespace.length; i++) {
13465 hash = (hash << 5) - hash + namespace.charCodeAt(i);
13466 hash |= 0; // Convert to 32bit integer
13467 }
13468
13469 return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
13470 }
13471
13472 createDebug.selectColor = selectColor;
13473 /**
13474 * Create a debugger with the given `namespace`.
13475 *
13476 * @param {String} namespace
13477 * @return {Function}
13478 * @api public
13479 */
13480
13481 function createDebug(namespace) {
13482 var prevTime;
13483
13484 function debug() {
13485 // Disabled?
13486 if (!debug.enabled) {
13487 return;
13488 }
13489
13490 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
13491 args[_key] = arguments[_key];
13492 }
13493
13494 var self = debug; // Set `diff` timestamp
13495
13496 var curr = Number(new Date());
13497 var ms = curr - (prevTime || curr);
13498 self.diff = ms;
13499 self.prev = prevTime;
13500 self.curr = curr;
13501 prevTime = curr;
13502 args[0] = createDebug.coerce(args[0]);
13503
13504 if (typeof args[0] !== 'string') {
13505 // Anything else let's inspect with %O
13506 args.unshift('%O');
13507 } // Apply any `formatters` transformations
13508
13509
13510 var index = 0;
13511 args[0] = args[0].replace(/%([a-zA-Z%])/g, function (match, format) {
13512 // If we encounter an escaped % then don't increase the array index
13513 if (match === '%%') {
13514 return match;
13515 }
13516
13517 index++;
13518 var formatter = createDebug.formatters[format];
13519
13520 if (typeof formatter === 'function') {
13521 var val = args[index];
13522 match = formatter.call(self, val); // Now we need to remove `args[index]` since it's inlined in the `format`
13523
13524 args.splice(index, 1);
13525 index--;
13526 }
13527
13528 return match;
13529 }); // Apply env-specific formatting (colors, etc.)
13530
13531 createDebug.formatArgs.call(self, args);
13532 var logFn = self.log || createDebug.log;
13533 logFn.apply(self, args);
13534 }
13535
13536 debug.namespace = namespace;
13537 debug.enabled = createDebug.enabled(namespace);
13538 debug.useColors = createDebug.useColors();
13539 debug.color = selectColor(namespace);
13540 debug.destroy = destroy;
13541 debug.extend = extend; // Debug.formatArgs = formatArgs;
13542 // debug.rawLog = rawLog;
13543 // env-specific initialization logic for debug instances
13544
13545 if (typeof createDebug.init === 'function') {
13546 createDebug.init(debug);
13547 }
13548
13549 createDebug.instances.push(debug);
13550 return debug;
13551 }
13552
13553 function destroy() {
13554 var index = createDebug.instances.indexOf(this);
13555
13556 if (index !== -1) {
13557 createDebug.instances.splice(index, 1);
13558 return true;
13559 }
13560
13561 return false;
13562 }
13563
13564 function extend(namespace, delimiter) {
13565 return createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);
13566 }
13567 /**
13568 * Enables a debug mode by namespaces. This can include modes
13569 * separated by a colon and wildcards.
13570 *
13571 * @param {String} namespaces
13572 * @api public
13573 */
13574
13575
13576 function enable(namespaces) {
13577 createDebug.save(namespaces);
13578 createDebug.names = [];
13579 createDebug.skips = [];
13580 var i;
13581 var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
13582 var len = split.length;
13583
13584 for (i = 0; i < len; i++) {
13585 if (!split[i]) {
13586 // ignore empty strings
13587 continue;
13588 }
13589
13590 namespaces = split[i].replace(/\*/g, '.*?');
13591
13592 if (namespaces[0] === '-') {
13593 createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
13594 } else {
13595 createDebug.names.push(new RegExp('^' + namespaces + '$'));
13596 }
13597 }
13598
13599 for (i = 0; i < createDebug.instances.length; i++) {
13600 var instance = createDebug.instances[i];
13601 instance.enabled = createDebug.enabled(instance.namespace);
13602 }
13603 }
13604 /**
13605 * Disable debug output.
13606 *
13607 * @api public
13608 */
13609
13610
13611 function disable() {
13612 createDebug.enable('');
13613 }
13614 /**
13615 * Returns true if the given mode name is enabled, false otherwise.
13616 *
13617 * @param {String} name
13618 * @return {Boolean}
13619 * @api public
13620 */
13621
13622
13623 function enabled(name) {
13624 if (name[name.length - 1] === '*') {
13625 return true;
13626 }
13627
13628 var i;
13629 var len;
13630
13631 for (i = 0, len = createDebug.skips.length; i < len; i++) {
13632 if (createDebug.skips[i].test(name)) {
13633 return false;
13634 }
13635 }
13636
13637 for (i = 0, len = createDebug.names.length; i < len; i++) {
13638 if (createDebug.names[i].test(name)) {
13639 return true;
13640 }
13641 }
13642
13643 return false;
13644 }
13645 /**
13646 * Coerce `val`.
13647 *
13648 * @param {Mixed} val
13649 * @return {Mixed}
13650 * @api private
13651 */
13652
13653
13654 function coerce(val) {
13655 if (val instanceof Error) {
13656 return val.stack || val.message;
13657 }
13658
13659 return val;
13660 }
13661
13662 createDebug.enable(createDebug.load());
13663 return createDebug;
13664 }
13665
13666 var common = setup;
13667
13668 var browser = createCommonjsModule(function (module, exports) {
13669
13670 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); }
13671
13672 /* eslint-env browser */
13673
13674 /**
13675 * This is the web browser implementation of `debug()`.
13676 */
13677 exports.log = log;
13678 exports.formatArgs = formatArgs;
13679 exports.save = save;
13680 exports.load = load;
13681 exports.useColors = useColors;
13682 exports.storage = localstorage();
13683 /**
13684 * Colors.
13685 */
13686
13687 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'];
13688 /**
13689 * Currently only WebKit-based Web Inspectors, Firefox >= v31,
13690 * and the Firebug extension (any Firefox version) are known
13691 * to support "%c" CSS customizations.
13692 *
13693 * TODO: add a `localStorage` variable to explicitly enable/disable colors
13694 */
13695 // eslint-disable-next-line complexity
13696
13697 function useColors() {
13698 // NB: In an Electron preload script, document will be defined but not fully
13699 // initialized. Since we know we're in Chrome, we'll just detect this case
13700 // explicitly
13701 if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {
13702 return true;
13703 } // Internet Explorer and Edge do not support colors.
13704
13705
13706 if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
13707 return false;
13708 } // Is webkit? http://stackoverflow.com/a/16459606/376773
13709 // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
13710
13711
13712 return typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || // Is firebug? http://stackoverflow.com/a/398120/376773
13713 typeof window !== 'undefined' && window.console && (window.console.firebug || window.console.exception && window.console.table) || // Is firefox >= v31?
13714 // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
13715 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
13716 typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/);
13717 }
13718 /**
13719 * Colorize log arguments if enabled.
13720 *
13721 * @api public
13722 */
13723
13724
13725 function formatArgs(args) {
13726 args[0] = (this.useColors ? '%c' : '') + this.namespace + (this.useColors ? ' %c' : ' ') + args[0] + (this.useColors ? '%c ' : ' ') + '+' + module.exports.humanize(this.diff);
13727
13728 if (!this.useColors) {
13729 return;
13730 }
13731
13732 var c = 'color: ' + this.color;
13733 args.splice(1, 0, c, 'color: inherit'); // The final "%c" is somewhat tricky, because there could be other
13734 // arguments passed either before or after the %c, so we need to
13735 // figure out the correct index to insert the CSS into
13736
13737 var index = 0;
13738 var lastC = 0;
13739 args[0].replace(/%[a-zA-Z%]/g, function (match) {
13740 if (match === '%%') {
13741 return;
13742 }
13743
13744 index++;
13745
13746 if (match === '%c') {
13747 // We only are interested in the *last* %c
13748 // (the user may have provided their own)
13749 lastC = index;
13750 }
13751 });
13752 args.splice(lastC, 0, c);
13753 }
13754 /**
13755 * Invokes `console.log()` when available.
13756 * No-op when `console.log` is not a "function".
13757 *
13758 * @api public
13759 */
13760
13761
13762 function log() {
13763 var _console;
13764
13765 // This hackery is required for IE8/9, where
13766 // the `console.log` function doesn't have 'apply'
13767 return (typeof console === "undefined" ? "undefined" : _typeof(console)) === 'object' && console.log && (_console = console).log.apply(_console, arguments);
13768 }
13769 /**
13770 * Save `namespaces`.
13771 *
13772 * @param {String} namespaces
13773 * @api private
13774 */
13775
13776
13777 function save(namespaces) {
13778 try {
13779 if (namespaces) {
13780 exports.storage.setItem('debug', namespaces);
13781 } else {
13782 exports.storage.removeItem('debug');
13783 }
13784 } catch (error) {// Swallow
13785 // XXX (@Qix-) should we be logging these?
13786 }
13787 }
13788 /**
13789 * Load `namespaces`.
13790 *
13791 * @return {String} returns the previously persisted debug modes
13792 * @api private
13793 */
13794
13795
13796 function load() {
13797 var r;
13798
13799 try {
13800 r = exports.storage.getItem('debug');
13801 } catch (error) {} // Swallow
13802 // XXX (@Qix-) should we be logging these?
13803 // If debug isn't set in LS, and we're in Electron, try to load $DEBUG
13804
13805
13806 if (!r && typeof process !== 'undefined' && 'env' in process) {
13807 r = process.env.DEBUG;
13808 }
13809
13810 return r;
13811 }
13812 /**
13813 * Localstorage attempts to return the localstorage.
13814 *
13815 * This is necessary because safari throws
13816 * when a user disables cookies/localstorage
13817 * and you attempt to access it.
13818 *
13819 * @return {LocalStorage}
13820 * @api private
13821 */
13822
13823
13824 function localstorage() {
13825 try {
13826 // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context
13827 // The Browser also has localStorage in the global context.
13828 return localStorage;
13829 } catch (error) {// Swallow
13830 // XXX (@Qix-) should we be logging these?
13831 }
13832 }
13833
13834 module.exports = common(exports);
13835 var formatters = module.exports.formatters;
13836 /**
13837 * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
13838 */
13839
13840 formatters.j = function (v) {
13841 try {
13842 return JSON.stringify(v);
13843 } catch (error) {
13844 return '[UnexpectedJSONParseError]: ' + error.message;
13845 }
13846 };
13847 });
13848 var browser_1 = browser.log;
13849 var browser_2 = browser.formatArgs;
13850 var browser_3 = browser.save;
13851 var browser_4 = browser.load;
13852 var browser_5 = browser.useColors;
13853 var browser_6 = browser.storage;
13854 var browser_7 = browser.colors;
13855
13856 var componentEmitter = createCommonjsModule(function (module) {
13857 /**
13858 * Expose `Emitter`.
13859 */
13860 {
13861 module.exports = Emitter;
13862 }
13863 /**
13864 * Initialize a new `Emitter`.
13865 *
13866 * @api public
13867 */
13868
13869
13870 function Emitter(obj) {
13871 if (obj) return mixin(obj);
13872 }
13873 /**
13874 * Mixin the emitter properties.
13875 *
13876 * @param {Object} obj
13877 * @return {Object}
13878 * @api private
13879 */
13880
13881 function mixin(obj) {
13882 for (var key in Emitter.prototype) {
13883 obj[key] = Emitter.prototype[key];
13884 }
13885
13886 return obj;
13887 }
13888 /**
13889 * Listen on the given `event` with `fn`.
13890 *
13891 * @param {String} event
13892 * @param {Function} fn
13893 * @return {Emitter}
13894 * @api public
13895 */
13896
13897
13898 Emitter.prototype.on = Emitter.prototype.addEventListener = function (event, fn) {
13899 this._callbacks = this._callbacks || {};
13900 (this._callbacks['$' + event] = this._callbacks['$' + event] || []).push(fn);
13901 return this;
13902 };
13903 /**
13904 * Adds an `event` listener that will be invoked a single
13905 * time then automatically removed.
13906 *
13907 * @param {String} event
13908 * @param {Function} fn
13909 * @return {Emitter}
13910 * @api public
13911 */
13912
13913
13914 Emitter.prototype.once = function (event, fn) {
13915 function on() {
13916 this.off(event, on);
13917 fn.apply(this, arguments);
13918 }
13919
13920 on.fn = fn;
13921 this.on(event, on);
13922 return this;
13923 };
13924 /**
13925 * Remove the given callback for `event` or all
13926 * registered callbacks.
13927 *
13928 * @param {String} event
13929 * @param {Function} fn
13930 * @return {Emitter}
13931 * @api public
13932 */
13933
13934
13935 Emitter.prototype.off = Emitter.prototype.removeListener = Emitter.prototype.removeAllListeners = Emitter.prototype.removeEventListener = function (event, fn) {
13936 this._callbacks = this._callbacks || {}; // all
13937
13938 if (0 == arguments.length) {
13939 this._callbacks = {};
13940 return this;
13941 } // specific event
13942
13943
13944 var callbacks = this._callbacks['$' + event];
13945 if (!callbacks) return this; // remove all handlers
13946
13947 if (1 == arguments.length) {
13948 delete this._callbacks['$' + event];
13949 return this;
13950 } // remove specific handler
13951
13952
13953 var cb;
13954
13955 for (var i = 0; i < callbacks.length; i++) {
13956 cb = callbacks[i];
13957
13958 if (cb === fn || cb.fn === fn) {
13959 callbacks.splice(i, 1);
13960 break;
13961 }
13962 } // Remove event specific arrays for event types that no
13963 // one is subscribed for to avoid memory leak.
13964
13965
13966 if (callbacks.length === 0) {
13967 delete this._callbacks['$' + event];
13968 }
13969
13970 return this;
13971 };
13972 /**
13973 * Emit `event` with the given args.
13974 *
13975 * @param {String} event
13976 * @param {Mixed} ...
13977 * @return {Emitter}
13978 */
13979
13980
13981 Emitter.prototype.emit = function (event) {
13982 this._callbacks = this._callbacks || {};
13983 var args = new Array(arguments.length - 1),
13984 callbacks = this._callbacks['$' + event];
13985
13986 for (var i = 1; i < arguments.length; i++) {
13987 args[i - 1] = arguments[i];
13988 }
13989
13990 if (callbacks) {
13991 callbacks = callbacks.slice(0);
13992
13993 for (var i = 0, len = callbacks.length; i < len; ++i) {
13994 callbacks[i].apply(this, args);
13995 }
13996 }
13997
13998 return this;
13999 };
14000 /**
14001 * Return array of callbacks for `event`.
14002 *
14003 * @param {String} event
14004 * @return {Array}
14005 * @api public
14006 */
14007
14008
14009 Emitter.prototype.listeners = function (event) {
14010 this._callbacks = this._callbacks || {};
14011 return this._callbacks['$' + event] || [];
14012 };
14013 /**
14014 * Check if this emitter has `event` handlers.
14015 *
14016 * @param {String} event
14017 * @return {Boolean}
14018 * @api public
14019 */
14020
14021
14022 Emitter.prototype.hasListeners = function (event) {
14023 return !!this.listeners(event).length;
14024 };
14025 });
14026
14027 var fastSafeStringify = stringify;
14028 stringify.default = stringify;
14029 stringify.stable = deterministicStringify;
14030 stringify.stableStringify = deterministicStringify;
14031
14032 var arr = [];
14033 var replacerStack = [];
14034
14035 // Regular stringify
14036 function stringify (obj, replacer, spacer) {
14037 decirc(obj, '', [], undefined);
14038 var res;
14039 if (replacerStack.length === 0) {
14040 res = JSON.stringify(obj, replacer, spacer);
14041 } else {
14042 res = JSON.stringify(obj, replaceGetterValues(replacer), spacer);
14043 }
14044 while (arr.length !== 0) {
14045 var part = arr.pop();
14046 if (part.length === 4) {
14047 Object.defineProperty(part[0], part[1], part[3]);
14048 } else {
14049 part[0][part[1]] = part[2];
14050 }
14051 }
14052 return res
14053 }
14054 function decirc (val, k, stack, parent) {
14055 var i;
14056 if (typeof val === 'object' && val !== null) {
14057 for (i = 0; i < stack.length; i++) {
14058 if (stack[i] === val) {
14059 var propertyDescriptor = Object.getOwnPropertyDescriptor(parent, k);
14060 if (propertyDescriptor.get !== undefined) {
14061 if (propertyDescriptor.configurable) {
14062 Object.defineProperty(parent, k, { value: '[Circular]' });
14063 arr.push([parent, k, val, propertyDescriptor]);
14064 } else {
14065 replacerStack.push([val, k]);
14066 }
14067 } else {
14068 parent[k] = '[Circular]';
14069 arr.push([parent, k, val]);
14070 }
14071 return
14072 }
14073 }
14074 stack.push(val);
14075 // Optimize for Arrays. Big arrays could kill the performance otherwise!
14076 if (Array.isArray(val)) {
14077 for (i = 0; i < val.length; i++) {
14078 decirc(val[i], i, stack, val);
14079 }
14080 } else {
14081 var keys = Object.keys(val);
14082 for (i = 0; i < keys.length; i++) {
14083 var key = keys[i];
14084 decirc(val[key], key, stack, val);
14085 }
14086 }
14087 stack.pop();
14088 }
14089 }
14090
14091 // Stable-stringify
14092 function compareFunction (a, b) {
14093 if (a < b) {
14094 return -1
14095 }
14096 if (a > b) {
14097 return 1
14098 }
14099 return 0
14100 }
14101
14102 function deterministicStringify (obj, replacer, spacer) {
14103 var tmp = deterministicDecirc(obj, '', [], undefined) || obj;
14104 var res;
14105 if (replacerStack.length === 0) {
14106 res = JSON.stringify(tmp, replacer, spacer);
14107 } else {
14108 res = JSON.stringify(tmp, replaceGetterValues(replacer), spacer);
14109 }
14110 while (arr.length !== 0) {
14111 var part = arr.pop();
14112 if (part.length === 4) {
14113 Object.defineProperty(part[0], part[1], part[3]);
14114 } else {
14115 part[0][part[1]] = part[2];
14116 }
14117 }
14118 return res
14119 }
14120
14121 function deterministicDecirc (val, k, stack, parent) {
14122 var i;
14123 if (typeof val === 'object' && val !== null) {
14124 for (i = 0; i < stack.length; i++) {
14125 if (stack[i] === val) {
14126 var propertyDescriptor = Object.getOwnPropertyDescriptor(parent, k);
14127 if (propertyDescriptor.get !== undefined) {
14128 if (propertyDescriptor.configurable) {
14129 Object.defineProperty(parent, k, { value: '[Circular]' });
14130 arr.push([parent, k, val, propertyDescriptor]);
14131 } else {
14132 replacerStack.push([val, k]);
14133 }
14134 } else {
14135 parent[k] = '[Circular]';
14136 arr.push([parent, k, val]);
14137 }
14138 return
14139 }
14140 }
14141 if (typeof val.toJSON === 'function') {
14142 return
14143 }
14144 stack.push(val);
14145 // Optimize for Arrays. Big arrays could kill the performance otherwise!
14146 if (Array.isArray(val)) {
14147 for (i = 0; i < val.length; i++) {
14148 deterministicDecirc(val[i], i, stack, val);
14149 }
14150 } else {
14151 // Create a temporary object in the required way
14152 var tmp = {};
14153 var keys = Object.keys(val).sort(compareFunction);
14154 for (i = 0; i < keys.length; i++) {
14155 var key = keys[i];
14156 deterministicDecirc(val[key], key, stack, val);
14157 tmp[key] = val[key];
14158 }
14159 if (parent !== undefined) {
14160 arr.push([parent, k, val]);
14161 parent[k] = tmp;
14162 } else {
14163 return tmp
14164 }
14165 }
14166 stack.pop();
14167 }
14168 }
14169
14170 // wraps replacer function to handle values we couldn't replace
14171 // and mark them as [Circular]
14172 function replaceGetterValues (replacer) {
14173 replacer = replacer !== undefined ? replacer : function (k, v) { return v };
14174 return function (key, val) {
14175 if (replacerStack.length > 0) {
14176 for (var i = 0; i < replacerStack.length; i++) {
14177 var part = replacerStack[i];
14178 if (part[1] === key && part[0] === val) {
14179 val = '[Circular]';
14180 replacerStack.splice(i, 1);
14181 break
14182 }
14183 }
14184 }
14185 return replacer.call(this, key, val)
14186 }
14187 }
14188
14189 function _typeof$1(obj) {
14190 if (typeof Symbol === "function" && _typeof(Symbol.iterator) === "symbol") {
14191 _typeof$1 = function _typeof$1(obj) {
14192 return _typeof(obj);
14193 };
14194 } else {
14195 _typeof$1 = function _typeof$1(obj) {
14196 return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : _typeof(obj);
14197 };
14198 }
14199
14200 return _typeof$1(obj);
14201 }
14202 /**
14203 * Check if `obj` is an object.
14204 *
14205 * @param {Object} obj
14206 * @return {Boolean}
14207 * @api private
14208 */
14209
14210
14211 function isObject(obj) {
14212 return obj !== null && _typeof$1(obj) === 'object';
14213 }
14214
14215 var isObject_1 = isObject;
14216
14217 function _typeof$2(obj) {
14218 if (typeof Symbol === "function" && _typeof(Symbol.iterator) === "symbol") {
14219 _typeof$2 = function _typeof$1(obj) {
14220 return _typeof(obj);
14221 };
14222 } else {
14223 _typeof$2 = function _typeof$1(obj) {
14224 return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : _typeof(obj);
14225 };
14226 }
14227
14228 return _typeof$2(obj);
14229 }
14230 /**
14231 * Module of mixed-in functions shared between node and client code
14232 */
14233
14234 /**
14235 * Expose `RequestBase`.
14236 */
14237
14238
14239 var requestBase = RequestBase;
14240 /**
14241 * Initialize a new `RequestBase`.
14242 *
14243 * @api public
14244 */
14245
14246 function RequestBase(obj) {
14247 if (obj) return mixin(obj);
14248 }
14249 /**
14250 * Mixin the prototype properties.
14251 *
14252 * @param {Object} obj
14253 * @return {Object}
14254 * @api private
14255 */
14256
14257
14258 function mixin(obj) {
14259 for (var key in RequestBase.prototype) {
14260 if (Object.prototype.hasOwnProperty.call(RequestBase.prototype, key)) obj[key] = RequestBase.prototype[key];
14261 }
14262
14263 return obj;
14264 }
14265 /**
14266 * Clear previous timeout.
14267 *
14268 * @return {Request} for chaining
14269 * @api public
14270 */
14271
14272
14273 RequestBase.prototype.clearTimeout = function () {
14274 clearTimeout(this._timer);
14275 clearTimeout(this._responseTimeoutTimer);
14276 clearTimeout(this._uploadTimeoutTimer);
14277 delete this._timer;
14278 delete this._responseTimeoutTimer;
14279 delete this._uploadTimeoutTimer;
14280 return this;
14281 };
14282 /**
14283 * Override default response body parser
14284 *
14285 * This function will be called to convert incoming data into request.body
14286 *
14287 * @param {Function}
14288 * @api public
14289 */
14290
14291
14292 RequestBase.prototype.parse = function (fn) {
14293 this._parser = fn;
14294 return this;
14295 };
14296 /**
14297 * Set format of binary response body.
14298 * In browser valid formats are 'blob' and 'arraybuffer',
14299 * which return Blob and ArrayBuffer, respectively.
14300 *
14301 * In Node all values result in Buffer.
14302 *
14303 * Examples:
14304 *
14305 * req.get('/')
14306 * .responseType('blob')
14307 * .end(callback);
14308 *
14309 * @param {String} val
14310 * @return {Request} for chaining
14311 * @api public
14312 */
14313
14314
14315 RequestBase.prototype.responseType = function (val) {
14316 this._responseType = val;
14317 return this;
14318 };
14319 /**
14320 * Override default request body serializer
14321 *
14322 * This function will be called to convert data set via .send or .attach into payload to send
14323 *
14324 * @param {Function}
14325 * @api public
14326 */
14327
14328
14329 RequestBase.prototype.serialize = function (fn) {
14330 this._serializer = fn;
14331 return this;
14332 };
14333 /**
14334 * Set timeouts.
14335 *
14336 * - response timeout is time between sending request and receiving the first byte of the response. Includes DNS and connection time.
14337 * - 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.
14338 * - upload is the time since last bit of data was sent or received. This timeout works only if deadline timeout is off
14339 *
14340 * Value of 0 or false means no timeout.
14341 *
14342 * @param {Number|Object} ms or {response, deadline}
14343 * @return {Request} for chaining
14344 * @api public
14345 */
14346
14347
14348 RequestBase.prototype.timeout = function (options) {
14349 if (!options || _typeof$2(options) !== 'object') {
14350 this._timeout = options;
14351 this._responseTimeout = 0;
14352 this._uploadTimeout = 0;
14353 return this;
14354 }
14355
14356 for (var option in options) {
14357 if (Object.prototype.hasOwnProperty.call(options, option)) {
14358 switch (option) {
14359 case 'deadline':
14360 this._timeout = options.deadline;
14361 break;
14362
14363 case 'response':
14364 this._responseTimeout = options.response;
14365 break;
14366
14367 case 'upload':
14368 this._uploadTimeout = options.upload;
14369 break;
14370
14371 default:
14372 console.warn('Unknown timeout option', option);
14373 }
14374 }
14375 }
14376
14377 return this;
14378 };
14379 /**
14380 * Set number of retry attempts on error.
14381 *
14382 * Failed requests will be retried 'count' times if timeout or err.code >= 500.
14383 *
14384 * @param {Number} count
14385 * @param {Function} [fn]
14386 * @return {Request} for chaining
14387 * @api public
14388 */
14389
14390
14391 RequestBase.prototype.retry = function (count, fn) {
14392 // Default to 1 if no count passed or true
14393 if (arguments.length === 0 || count === true) count = 1;
14394 if (count <= 0) count = 0;
14395 this._maxRetries = count;
14396 this._retries = 0;
14397 this._retryCallback = fn;
14398 return this;
14399 };
14400
14401 var ERROR_CODES = ['ECONNRESET', 'ETIMEDOUT', 'EADDRINFO', 'ESOCKETTIMEDOUT'];
14402 /**
14403 * Determine if a request should be retried.
14404 * (Borrowed from segmentio/superagent-retry)
14405 *
14406 * @param {Error} err an error
14407 * @param {Response} [res] response
14408 * @returns {Boolean} if segment should be retried
14409 */
14410
14411 RequestBase.prototype._shouldRetry = function (err, res) {
14412 if (!this._maxRetries || this._retries++ >= this._maxRetries) {
14413 return false;
14414 }
14415
14416 if (this._retryCallback) {
14417 try {
14418 var override = this._retryCallback(err, res);
14419
14420 if (override === true) return true;
14421 if (override === false) return false; // undefined falls back to defaults
14422 } catch (err2) {
14423 console.error(err2);
14424 }
14425 }
14426
14427 if (res && res.status && res.status >= 500 && res.status !== 501) return true;
14428
14429 if (err) {
14430 if (err.code && ERROR_CODES.indexOf(err.code) !== -1) return true; // Superagent timeout
14431
14432 if (err.timeout && err.code === 'ECONNABORTED') return true;
14433 if (err.crossDomain) return true;
14434 }
14435
14436 return false;
14437 };
14438 /**
14439 * Retry request
14440 *
14441 * @return {Request} for chaining
14442 * @api private
14443 */
14444
14445
14446 RequestBase.prototype._retry = function () {
14447 this.clearTimeout(); // node
14448
14449 if (this.req) {
14450 this.req = null;
14451 this.req = this.request();
14452 }
14453
14454 this._aborted = false;
14455 this.timedout = false;
14456 return this._end();
14457 };
14458 /**
14459 * Promise support
14460 *
14461 * @param {Function} resolve
14462 * @param {Function} [reject]
14463 * @return {Request}
14464 */
14465
14466
14467 RequestBase.prototype.then = function (resolve, reject) {
14468 var _this = this;
14469
14470 if (!this._fullfilledPromise) {
14471 var self = this;
14472
14473 if (this._endCalled) {
14474 console.warn('Warning: superagent request was sent twice, because both .end() and .then() were called. Never call .end() if you use promises');
14475 }
14476
14477 this._fullfilledPromise = new Promise(function (resolve, reject) {
14478 self.on('abort', function () {
14479 var err = new Error('Aborted');
14480 err.code = 'ABORTED';
14481 err.status = _this.status;
14482 err.method = _this.method;
14483 err.url = _this.url;
14484 reject(err);
14485 });
14486 self.end(function (err, res) {
14487 if (err) reject(err);else resolve(res);
14488 });
14489 });
14490 }
14491
14492 return this._fullfilledPromise.then(resolve, reject);
14493 };
14494
14495 RequestBase.prototype.catch = function (cb) {
14496 return this.then(undefined, cb);
14497 };
14498 /**
14499 * Allow for extension
14500 */
14501
14502
14503 RequestBase.prototype.use = function (fn) {
14504 fn(this);
14505 return this;
14506 };
14507
14508 RequestBase.prototype.ok = function (cb) {
14509 if (typeof cb !== 'function') throw new Error('Callback required');
14510 this._okCallback = cb;
14511 return this;
14512 };
14513
14514 RequestBase.prototype._isResponseOK = function (res) {
14515 if (!res) {
14516 return false;
14517 }
14518
14519 if (this._okCallback) {
14520 return this._okCallback(res);
14521 }
14522
14523 return res.status >= 200 && res.status < 300;
14524 };
14525 /**
14526 * Get request header `field`.
14527 * Case-insensitive.
14528 *
14529 * @param {String} field
14530 * @return {String}
14531 * @api public
14532 */
14533
14534
14535 RequestBase.prototype.get = function (field) {
14536 return this._header[field.toLowerCase()];
14537 };
14538 /**
14539 * Get case-insensitive header `field` value.
14540 * This is a deprecated internal API. Use `.get(field)` instead.
14541 *
14542 * (getHeader is no longer used internally by the superagent code base)
14543 *
14544 * @param {String} field
14545 * @return {String}
14546 * @api private
14547 * @deprecated
14548 */
14549
14550
14551 RequestBase.prototype.getHeader = RequestBase.prototype.get;
14552 /**
14553 * Set header `field` to `val`, or multiple fields with one object.
14554 * Case-insensitive.
14555 *
14556 * Examples:
14557 *
14558 * req.get('/')
14559 * .set('Accept', 'application/json')
14560 * .set('X-API-Key', 'foobar')
14561 * .end(callback);
14562 *
14563 * req.get('/')
14564 * .set({ Accept: 'application/json', 'X-API-Key': 'foobar' })
14565 * .end(callback);
14566 *
14567 * @param {String|Object} field
14568 * @param {String} val
14569 * @return {Request} for chaining
14570 * @api public
14571 */
14572
14573 RequestBase.prototype.set = function (field, val) {
14574 if (isObject_1(field)) {
14575 for (var key in field) {
14576 if (Object.prototype.hasOwnProperty.call(field, key)) this.set(key, field[key]);
14577 }
14578
14579 return this;
14580 }
14581
14582 this._header[field.toLowerCase()] = val;
14583 this.header[field] = val;
14584 return this;
14585 }; // eslint-disable-next-line valid-jsdoc
14586
14587 /**
14588 * Remove header `field`.
14589 * Case-insensitive.
14590 *
14591 * Example:
14592 *
14593 * req.get('/')
14594 * .unset('User-Agent')
14595 * .end(callback);
14596 *
14597 * @param {String} field field name
14598 */
14599
14600
14601 RequestBase.prototype.unset = function (field) {
14602 delete this._header[field.toLowerCase()];
14603 delete this.header[field];
14604 return this;
14605 };
14606 /**
14607 * Write the field `name` and `val`, or multiple fields with one object
14608 * for "multipart/form-data" request bodies.
14609 *
14610 * ``` js
14611 * request.post('/upload')
14612 * .field('foo', 'bar')
14613 * .end(callback);
14614 *
14615 * request.post('/upload')
14616 * .field({ foo: 'bar', baz: 'qux' })
14617 * .end(callback);
14618 * ```
14619 *
14620 * @param {String|Object} name name of field
14621 * @param {String|Blob|File|Buffer|fs.ReadStream} val value of field
14622 * @return {Request} for chaining
14623 * @api public
14624 */
14625
14626
14627 RequestBase.prototype.field = function (name, val) {
14628 // name should be either a string or an object.
14629 if (name === null || undefined === name) {
14630 throw new Error('.field(name, val) name can not be empty');
14631 }
14632
14633 if (this._data) {
14634 throw new Error(".field() can't be used if .send() is used. Please use only .send() or only .field() & .attach()");
14635 }
14636
14637 if (isObject_1(name)) {
14638 for (var key in name) {
14639 if (Object.prototype.hasOwnProperty.call(name, key)) this.field(key, name[key]);
14640 }
14641
14642 return this;
14643 }
14644
14645 if (Array.isArray(val)) {
14646 for (var i in val) {
14647 if (Object.prototype.hasOwnProperty.call(val, i)) this.field(name, val[i]);
14648 }
14649
14650 return this;
14651 } // val should be defined now
14652
14653
14654 if (val === null || undefined === val) {
14655 throw new Error('.field(name, val) val can not be empty');
14656 }
14657
14658 if (typeof val === 'boolean') {
14659 val = String(val);
14660 }
14661
14662 this._getFormData().append(name, val);
14663
14664 return this;
14665 };
14666 /**
14667 * Abort the request, and clear potential timeout.
14668 *
14669 * @return {Request} request
14670 * @api public
14671 */
14672
14673
14674 RequestBase.prototype.abort = function () {
14675 if (this._aborted) {
14676 return this;
14677 }
14678
14679 this._aborted = true;
14680 if (this.xhr) this.xhr.abort(); // browser
14681
14682 if (this.req) this.req.abort(); // node
14683
14684 this.clearTimeout();
14685 this.emit('abort');
14686 return this;
14687 };
14688
14689 RequestBase.prototype._auth = function (user, pass, options, base64Encoder) {
14690 switch (options.type) {
14691 case 'basic':
14692 this.set('Authorization', "Basic ".concat(base64Encoder("".concat(user, ":").concat(pass))));
14693 break;
14694
14695 case 'auto':
14696 this.username = user;
14697 this.password = pass;
14698 break;
14699
14700 case 'bearer':
14701 // usage would be .auth(accessToken, { type: 'bearer' })
14702 this.set('Authorization', "Bearer ".concat(user));
14703 break;
14704
14705 default:
14706 break;
14707 }
14708
14709 return this;
14710 };
14711 /**
14712 * Enable transmission of cookies with x-domain requests.
14713 *
14714 * Note that for this to work the origin must not be
14715 * using "Access-Control-Allow-Origin" with a wildcard,
14716 * and also must set "Access-Control-Allow-Credentials"
14717 * to "true".
14718 *
14719 * @api public
14720 */
14721
14722
14723 RequestBase.prototype.withCredentials = function (on) {
14724 // This is browser-only functionality. Node side is no-op.
14725 if (on === undefined) on = true;
14726 this._withCredentials = on;
14727 return this;
14728 };
14729 /**
14730 * Set the max redirects to `n`. Does nothing in browser XHR implementation.
14731 *
14732 * @param {Number} n
14733 * @return {Request} for chaining
14734 * @api public
14735 */
14736
14737
14738 RequestBase.prototype.redirects = function (n) {
14739 this._maxRedirects = n;
14740 return this;
14741 };
14742 /**
14743 * Maximum size of buffered response body, in bytes. Counts uncompressed size.
14744 * Default 200MB.
14745 *
14746 * @param {Number} n number of bytes
14747 * @return {Request} for chaining
14748 */
14749
14750
14751 RequestBase.prototype.maxResponseSize = function (n) {
14752 if (typeof n !== 'number') {
14753 throw new TypeError('Invalid argument');
14754 }
14755
14756 this._maxResponseSize = n;
14757 return this;
14758 };
14759 /**
14760 * Convert to a plain javascript object (not JSON string) of scalar properties.
14761 * Note as this method is designed to return a useful non-this value,
14762 * it cannot be chained.
14763 *
14764 * @return {Object} describing method, url, and data of this request
14765 * @api public
14766 */
14767
14768
14769 RequestBase.prototype.toJSON = function () {
14770 return {
14771 method: this.method,
14772 url: this.url,
14773 data: this._data,
14774 headers: this._header
14775 };
14776 };
14777 /**
14778 * Send `data` as the request body, defaulting the `.type()` to "json" when
14779 * an object is given.
14780 *
14781 * Examples:
14782 *
14783 * // manual json
14784 * request.post('/user')
14785 * .type('json')
14786 * .send('{"name":"tj"}')
14787 * .end(callback)
14788 *
14789 * // auto json
14790 * request.post('/user')
14791 * .send({ name: 'tj' })
14792 * .end(callback)
14793 *
14794 * // manual x-www-form-urlencoded
14795 * request.post('/user')
14796 * .type('form')
14797 * .send('name=tj')
14798 * .end(callback)
14799 *
14800 * // auto x-www-form-urlencoded
14801 * request.post('/user')
14802 * .type('form')
14803 * .send({ name: 'tj' })
14804 * .end(callback)
14805 *
14806 * // defaults to x-www-form-urlencoded
14807 * request.post('/user')
14808 * .send('name=tobi')
14809 * .send('species=ferret')
14810 * .end(callback)
14811 *
14812 * @param {String|Object} data
14813 * @return {Request} for chaining
14814 * @api public
14815 */
14816 // eslint-disable-next-line complexity
14817
14818
14819 RequestBase.prototype.send = function (data) {
14820 var isObj = isObject_1(data);
14821 var type = this._header['content-type'];
14822
14823 if (this._formData) {
14824 throw new Error(".send() can't be used if .attach() or .field() is used. Please use only .send() or only .field() & .attach()");
14825 }
14826
14827 if (isObj && !this._data) {
14828 if (Array.isArray(data)) {
14829 this._data = [];
14830 } else if (!this._isHost(data)) {
14831 this._data = {};
14832 }
14833 } else if (data && this._data && this._isHost(this._data)) {
14834 throw new Error("Can't merge these send calls");
14835 } // merge
14836
14837
14838 if (isObj && isObject_1(this._data)) {
14839 for (var key in data) {
14840 if (Object.prototype.hasOwnProperty.call(data, key)) this._data[key] = data[key];
14841 }
14842 } else if (typeof data === 'string') {
14843 // default to x-www-form-urlencoded
14844 if (!type) this.type('form');
14845 type = this._header['content-type'];
14846
14847 if (type === 'application/x-www-form-urlencoded') {
14848 this._data = this._data ? "".concat(this._data, "&").concat(data) : data;
14849 } else {
14850 this._data = (this._data || '') + data;
14851 }
14852 } else {
14853 this._data = data;
14854 }
14855
14856 if (!isObj || this._isHost(data)) {
14857 return this;
14858 } // default to json
14859
14860
14861 if (!type) this.type('json');
14862 return this;
14863 };
14864 /**
14865 * Sort `querystring` by the sort function
14866 *
14867 *
14868 * Examples:
14869 *
14870 * // default order
14871 * request.get('/user')
14872 * .query('name=Nick')
14873 * .query('search=Manny')
14874 * .sortQuery()
14875 * .end(callback)
14876 *
14877 * // customized sort function
14878 * request.get('/user')
14879 * .query('name=Nick')
14880 * .query('search=Manny')
14881 * .sortQuery(function(a, b){
14882 * return a.length - b.length;
14883 * })
14884 * .end(callback)
14885 *
14886 *
14887 * @param {Function} sort
14888 * @return {Request} for chaining
14889 * @api public
14890 */
14891
14892
14893 RequestBase.prototype.sortQuery = function (sort) {
14894 // _sort default to true but otherwise can be a function or boolean
14895 this._sort = typeof sort === 'undefined' ? true : sort;
14896 return this;
14897 };
14898 /**
14899 * Compose querystring to append to req.url
14900 *
14901 * @api private
14902 */
14903
14904
14905 RequestBase.prototype._finalizeQueryString = function () {
14906 var query = this._query.join('&');
14907
14908 if (query) {
14909 this.url += (this.url.indexOf('?') >= 0 ? '&' : '?') + query;
14910 }
14911
14912 this._query.length = 0; // Makes the call idempotent
14913
14914 if (this._sort) {
14915 var index = this.url.indexOf('?');
14916
14917 if (index >= 0) {
14918 var queryArr = this.url.substring(index + 1).split('&');
14919
14920 if (typeof this._sort === 'function') {
14921 queryArr.sort(this._sort);
14922 } else {
14923 queryArr.sort();
14924 }
14925
14926 this.url = this.url.substring(0, index) + '?' + queryArr.join('&');
14927 }
14928 }
14929 }; // For backwards compat only
14930
14931
14932 RequestBase.prototype._appendQueryString = function () {
14933 console.warn('Unsupported');
14934 };
14935 /**
14936 * Invoke callback with timeout error.
14937 *
14938 * @api private
14939 */
14940
14941
14942 RequestBase.prototype._timeoutError = function (reason, timeout, errno) {
14943 if (this._aborted) {
14944 return;
14945 }
14946
14947 var err = new Error("".concat(reason + timeout, "ms exceeded"));
14948 err.timeout = timeout;
14949 err.code = 'ECONNABORTED';
14950 err.errno = errno;
14951 this.timedout = true;
14952 this.abort();
14953 this.callback(err);
14954 };
14955
14956 RequestBase.prototype._setTimeouts = function () {
14957 var self = this; // deadline
14958
14959 if (this._timeout && !this._timer) {
14960 this._timer = setTimeout(function () {
14961 self._timeoutError('Timeout of ', self._timeout, 'ETIME');
14962 }, this._timeout);
14963 } // response timeout
14964
14965
14966 if (this._responseTimeout && !this._responseTimeoutTimer) {
14967 this._responseTimeoutTimer = setTimeout(function () {
14968 self._timeoutError('Response timeout of ', self._responseTimeout, 'ETIMEDOUT');
14969 }, this._responseTimeout);
14970 }
14971 };
14972
14973 /**
14974 * Return the mime type for the given `str`.
14975 *
14976 * @param {String} str
14977 * @return {String}
14978 * @api private
14979 */
14980
14981 var type = function type(str) {
14982 return str.split(/ *; */).shift();
14983 };
14984 /**
14985 * Return header field parameters.
14986 *
14987 * @param {String} str
14988 * @return {Object}
14989 * @api private
14990 */
14991
14992
14993 var params = function params(str) {
14994 return str.split(/ *; */).reduce(function (obj, str) {
14995 var parts = str.split(/ *= */);
14996 var key = parts.shift();
14997 var val = parts.shift();
14998 if (key && val) obj[key] = val;
14999 return obj;
15000 }, {});
15001 };
15002 /**
15003 * Parse Link header fields.
15004 *
15005 * @param {String} str
15006 * @return {Object}
15007 * @api private
15008 */
15009
15010
15011 var parseLinks = function parseLinks(str) {
15012 return str.split(/ *, */).reduce(function (obj, str) {
15013 var parts = str.split(/ *; */);
15014 var url = parts[0].slice(1, -1);
15015 var rel = parts[1].split(/ *= */)[1].slice(1, -1);
15016 obj[rel] = url;
15017 return obj;
15018 }, {});
15019 };
15020 /**
15021 * Strip content related fields from `header`.
15022 *
15023 * @param {Object} header
15024 * @return {Object} header
15025 * @api private
15026 */
15027
15028
15029 var cleanHeader = function cleanHeader(header, changesOrigin) {
15030 delete header['content-type'];
15031 delete header['content-length'];
15032 delete header['transfer-encoding'];
15033 delete header.host; // secuirty
15034
15035 if (changesOrigin) {
15036 delete header.authorization;
15037 delete header.cookie;
15038 }
15039
15040 return header;
15041 };
15042
15043 var utils = {
15044 type: type,
15045 params: params,
15046 parseLinks: parseLinks,
15047 cleanHeader: cleanHeader
15048 };
15049
15050 /**
15051 * Module dependencies.
15052 */
15053
15054 /**
15055 * Expose `ResponseBase`.
15056 */
15057
15058
15059 var responseBase = ResponseBase;
15060 /**
15061 * Initialize a new `ResponseBase`.
15062 *
15063 * @api public
15064 */
15065
15066 function ResponseBase(obj) {
15067 if (obj) return mixin$1(obj);
15068 }
15069 /**
15070 * Mixin the prototype properties.
15071 *
15072 * @param {Object} obj
15073 * @return {Object}
15074 * @api private
15075 */
15076
15077
15078 function mixin$1(obj) {
15079 for (var key in ResponseBase.prototype) {
15080 if (Object.prototype.hasOwnProperty.call(ResponseBase.prototype, key)) obj[key] = ResponseBase.prototype[key];
15081 }
15082
15083 return obj;
15084 }
15085 /**
15086 * Get case-insensitive `field` value.
15087 *
15088 * @param {String} field
15089 * @return {String}
15090 * @api public
15091 */
15092
15093
15094 ResponseBase.prototype.get = function (field) {
15095 return this.header[field.toLowerCase()];
15096 };
15097 /**
15098 * Set header related properties:
15099 *
15100 * - `.type` the content type without params
15101 *
15102 * A response of "Content-Type: text/plain; charset=utf-8"
15103 * will provide you with a `.type` of "text/plain".
15104 *
15105 * @param {Object} header
15106 * @api private
15107 */
15108
15109
15110 ResponseBase.prototype._setHeaderProperties = function (header) {
15111 // TODO: moar!
15112 // TODO: make this a util
15113 // content-type
15114 var ct = header['content-type'] || '';
15115 this.type = utils.type(ct); // params
15116
15117 var params = utils.params(ct);
15118
15119 for (var key in params) {
15120 if (Object.prototype.hasOwnProperty.call(params, key)) this[key] = params[key];
15121 }
15122
15123 this.links = {}; // links
15124
15125 try {
15126 if (header.link) {
15127 this.links = utils.parseLinks(header.link);
15128 }
15129 } catch (err) {// ignore
15130 }
15131 };
15132 /**
15133 * Set flags such as `.ok` based on `status`.
15134 *
15135 * For example a 2xx response will give you a `.ok` of __true__
15136 * whereas 5xx will be __false__ and `.error` will be __true__. The
15137 * `.clientError` and `.serverError` are also available to be more
15138 * specific, and `.statusType` is the class of error ranging from 1..5
15139 * sometimes useful for mapping respond colors etc.
15140 *
15141 * "sugar" properties are also defined for common cases. Currently providing:
15142 *
15143 * - .noContent
15144 * - .badRequest
15145 * - .unauthorized
15146 * - .notAcceptable
15147 * - .notFound
15148 *
15149 * @param {Number} status
15150 * @api private
15151 */
15152
15153
15154 ResponseBase.prototype._setStatusProperties = function (status) {
15155 var type = status / 100 | 0; // status / class
15156
15157 this.statusCode = status;
15158 this.status = this.statusCode;
15159 this.statusType = type; // basics
15160
15161 this.info = type === 1;
15162 this.ok = type === 2;
15163 this.redirect = type === 3;
15164 this.clientError = type === 4;
15165 this.serverError = type === 5;
15166 this.error = type === 4 || type === 5 ? this.toError() : false; // sugar
15167
15168 this.created = status === 201;
15169 this.accepted = status === 202;
15170 this.noContent = status === 204;
15171 this.badRequest = status === 400;
15172 this.unauthorized = status === 401;
15173 this.notAcceptable = status === 406;
15174 this.forbidden = status === 403;
15175 this.notFound = status === 404;
15176 this.unprocessableEntity = status === 422;
15177 };
15178
15179 function _toConsumableArray$1(arr) {
15180 return _arrayWithoutHoles$1(arr) || _iterableToArray$1(arr) || _nonIterableSpread$1();
15181 }
15182
15183 function _nonIterableSpread$1() {
15184 throw new TypeError("Invalid attempt to spread non-iterable instance");
15185 }
15186
15187 function _iterableToArray$1(iter) {
15188 if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter);
15189 }
15190
15191 function _arrayWithoutHoles$1(arr) {
15192 if (Array.isArray(arr)) {
15193 for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) {
15194 arr2[i] = arr[i];
15195 }
15196
15197 return arr2;
15198 }
15199 }
15200
15201 function Agent() {
15202 this._defaults = [];
15203 }
15204
15205 ['use', 'on', 'once', 'set', 'query', 'type', 'accept', 'auth', 'withCredentials', 'sortQuery', 'retry', 'ok', 'redirects', 'timeout', 'buffer', 'serialize', 'parse', 'ca', 'key', 'pfx', 'cert'].forEach(function (fn) {
15206 // Default setting for all requests from this agent
15207 Agent.prototype[fn] = function () {
15208 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
15209 args[_key] = arguments[_key];
15210 }
15211
15212 this._defaults.push({
15213 fn: fn,
15214 args: args
15215 });
15216
15217 return this;
15218 };
15219 });
15220
15221 Agent.prototype._setDefaults = function (req) {
15222 this._defaults.forEach(function (def) {
15223 req[def.fn].apply(req, _toConsumableArray$1(def.args));
15224 });
15225 };
15226
15227 var agentBase = Agent;
15228
15229 var client = createCommonjsModule(function (module, exports) {
15230
15231 function _typeof$1(obj) {
15232 if (typeof Symbol === "function" && _typeof(Symbol.iterator) === "symbol") {
15233 _typeof$1 = function _typeof$1(obj) {
15234 return _typeof(obj);
15235 };
15236 } else {
15237 _typeof$1 = function _typeof$1(obj) {
15238 return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : _typeof(obj);
15239 };
15240 }
15241
15242 return _typeof$1(obj);
15243 }
15244 /**
15245 * Root reference for iframes.
15246 */
15247
15248
15249 var root;
15250
15251 if (typeof window !== 'undefined') {
15252 // Browser window
15253 root = window;
15254 } else if (typeof self === 'undefined') {
15255 // Other environments
15256 console.warn('Using browser-only version of superagent in non-browser environment');
15257 root = void 0;
15258 } else {
15259 // Web Worker
15260 root = self;
15261 }
15262 /**
15263 * Noop.
15264 */
15265
15266
15267 function noop() {}
15268 /**
15269 * Expose `request`.
15270 */
15271
15272
15273 module.exports = function (method, url) {
15274 // callback
15275 if (typeof url === 'function') {
15276 return new exports.Request('GET', method).end(url);
15277 } // url first
15278
15279
15280 if (arguments.length === 1) {
15281 return new exports.Request('GET', method);
15282 }
15283
15284 return new exports.Request(method, url);
15285 };
15286
15287 exports = module.exports;
15288 var request = exports;
15289 exports.Request = Request;
15290 /**
15291 * Determine XHR.
15292 */
15293
15294 request.getXHR = function () {
15295 if (root.XMLHttpRequest && (!root.location || root.location.protocol !== 'file:' || !root.ActiveXObject)) {
15296 return new XMLHttpRequest();
15297 }
15298
15299 try {
15300 return new ActiveXObject('Microsoft.XMLHTTP');
15301 } catch (err) {}
15302
15303 try {
15304 return new ActiveXObject('Msxml2.XMLHTTP.6.0');
15305 } catch (err) {}
15306
15307 try {
15308 return new ActiveXObject('Msxml2.XMLHTTP.3.0');
15309 } catch (err) {}
15310
15311 try {
15312 return new ActiveXObject('Msxml2.XMLHTTP');
15313 } catch (err) {}
15314
15315 throw new Error('Browser-only version of superagent could not find XHR');
15316 };
15317 /**
15318 * Removes leading and trailing whitespace, added to support IE.
15319 *
15320 * @param {String} s
15321 * @return {String}
15322 * @api private
15323 */
15324
15325
15326 var trim = ''.trim ? function (s) {
15327 return s.trim();
15328 } : function (s) {
15329 return s.replace(/(^\s*|\s*$)/g, '');
15330 };
15331 /**
15332 * Serialize the given `obj`.
15333 *
15334 * @param {Object} obj
15335 * @return {String}
15336 * @api private
15337 */
15338
15339 function serialize(obj) {
15340 if (!isObject_1(obj)) return obj;
15341 var pairs = [];
15342
15343 for (var key in obj) {
15344 if (Object.prototype.hasOwnProperty.call(obj, key)) pushEncodedKeyValuePair(pairs, key, obj[key]);
15345 }
15346
15347 return pairs.join('&');
15348 }
15349 /**
15350 * Helps 'serialize' with serializing arrays.
15351 * Mutates the pairs array.
15352 *
15353 * @param {Array} pairs
15354 * @param {String} key
15355 * @param {Mixed} val
15356 */
15357
15358
15359 function pushEncodedKeyValuePair(pairs, key, val) {
15360 if (val === undefined) return;
15361
15362 if (val === null) {
15363 pairs.push(encodeURIComponent(key));
15364 return;
15365 }
15366
15367 if (Array.isArray(val)) {
15368 val.forEach(function (v) {
15369 pushEncodedKeyValuePair(pairs, key, v);
15370 });
15371 } else if (isObject_1(val)) {
15372 for (var subkey in val) {
15373 if (Object.prototype.hasOwnProperty.call(val, subkey)) pushEncodedKeyValuePair(pairs, "".concat(key, "[").concat(subkey, "]"), val[subkey]);
15374 }
15375 } else {
15376 pairs.push(encodeURIComponent(key) + '=' + encodeURIComponent(val));
15377 }
15378 }
15379 /**
15380 * Expose serialization method.
15381 */
15382
15383
15384 request.serializeObject = serialize;
15385 /**
15386 * Parse the given x-www-form-urlencoded `str`.
15387 *
15388 * @param {String} str
15389 * @return {Object}
15390 * @api private
15391 */
15392
15393 function parseString(str) {
15394 var obj = {};
15395 var pairs = str.split('&');
15396 var pair;
15397 var pos;
15398
15399 for (var i = 0, len = pairs.length; i < len; ++i) {
15400 pair = pairs[i];
15401 pos = pair.indexOf('=');
15402
15403 if (pos === -1) {
15404 obj[decodeURIComponent(pair)] = '';
15405 } else {
15406 obj[decodeURIComponent(pair.slice(0, pos))] = decodeURIComponent(pair.slice(pos + 1));
15407 }
15408 }
15409
15410 return obj;
15411 }
15412 /**
15413 * Expose parser.
15414 */
15415
15416
15417 request.parseString = parseString;
15418 /**
15419 * Default MIME type map.
15420 *
15421 * superagent.types.xml = 'application/xml';
15422 *
15423 */
15424
15425 request.types = {
15426 html: 'text/html',
15427 json: 'application/json',
15428 xml: 'text/xml',
15429 urlencoded: 'application/x-www-form-urlencoded',
15430 form: 'application/x-www-form-urlencoded',
15431 'form-data': 'application/x-www-form-urlencoded'
15432 };
15433 /**
15434 * Default serialization map.
15435 *
15436 * superagent.serialize['application/xml'] = function(obj){
15437 * return 'generated xml here';
15438 * };
15439 *
15440 */
15441
15442 request.serialize = {
15443 'application/x-www-form-urlencoded': serialize,
15444 'application/json': fastSafeStringify
15445 };
15446 /**
15447 * Default parsers.
15448 *
15449 * superagent.parse['application/xml'] = function(str){
15450 * return { object parsed from str };
15451 * };
15452 *
15453 */
15454
15455 request.parse = {
15456 'application/x-www-form-urlencoded': parseString,
15457 'application/json': JSON.parse
15458 };
15459 /**
15460 * Parse the given header `str` into
15461 * an object containing the mapped fields.
15462 *
15463 * @param {String} str
15464 * @return {Object}
15465 * @api private
15466 */
15467
15468 function parseHeader(str) {
15469 var lines = str.split(/\r?\n/);
15470 var fields = {};
15471 var index;
15472 var line;
15473 var field;
15474 var val;
15475
15476 for (var i = 0, len = lines.length; i < len; ++i) {
15477 line = lines[i];
15478 index = line.indexOf(':');
15479
15480 if (index === -1) {
15481 // could be empty line, just skip it
15482 continue;
15483 }
15484
15485 field = line.slice(0, index).toLowerCase();
15486 val = trim(line.slice(index + 1));
15487 fields[field] = val;
15488 }
15489
15490 return fields;
15491 }
15492 /**
15493 * Check if `mime` is json or has +json structured syntax suffix.
15494 *
15495 * @param {String} mime
15496 * @return {Boolean}
15497 * @api private
15498 */
15499
15500
15501 function isJSON(mime) {
15502 // should match /json or +json
15503 // but not /json-seq
15504 return /[/+]json($|[^-\w])/.test(mime);
15505 }
15506 /**
15507 * Initialize a new `Response` with the given `xhr`.
15508 *
15509 * - set flags (.ok, .error, etc)
15510 * - parse header
15511 *
15512 * Examples:
15513 *
15514 * Aliasing `superagent` as `request` is nice:
15515 *
15516 * request = superagent;
15517 *
15518 * We can use the promise-like API, or pass callbacks:
15519 *
15520 * request.get('/').end(function(res){});
15521 * request.get('/', function(res){});
15522 *
15523 * Sending data can be chained:
15524 *
15525 * request
15526 * .post('/user')
15527 * .send({ name: 'tj' })
15528 * .end(function(res){});
15529 *
15530 * Or passed to `.send()`:
15531 *
15532 * request
15533 * .post('/user')
15534 * .send({ name: 'tj' }, function(res){});
15535 *
15536 * Or passed to `.post()`:
15537 *
15538 * request
15539 * .post('/user', { name: 'tj' })
15540 * .end(function(res){});
15541 *
15542 * Or further reduced to a single call for simple cases:
15543 *
15544 * request
15545 * .post('/user', { name: 'tj' }, function(res){});
15546 *
15547 * @param {XMLHTTPRequest} xhr
15548 * @param {Object} options
15549 * @api private
15550 */
15551
15552
15553 function Response(req) {
15554 this.req = req;
15555 this.xhr = this.req.xhr; // responseText is accessible only if responseType is '' or 'text' and on older browsers
15556
15557 this.text = this.req.method !== 'HEAD' && (this.xhr.responseType === '' || this.xhr.responseType === 'text') || typeof this.xhr.responseType === 'undefined' ? this.xhr.responseText : null;
15558 this.statusText = this.req.xhr.statusText;
15559 var status = this.xhr.status; // handle IE9 bug: http://stackoverflow.com/questions/10046972/msie-returns-status-code-of-1223-for-ajax-request
15560
15561 if (status === 1223) {
15562 status = 204;
15563 }
15564
15565 this._setStatusProperties(status);
15566
15567 this.headers = parseHeader(this.xhr.getAllResponseHeaders());
15568 this.header = this.headers; // getAllResponseHeaders sometimes falsely returns "" for CORS requests, but
15569 // getResponseHeader still works. so we get content-type even if getting
15570 // other headers fails.
15571
15572 this.header['content-type'] = this.xhr.getResponseHeader('content-type');
15573
15574 this._setHeaderProperties(this.header);
15575
15576 if (this.text === null && req._responseType) {
15577 this.body = this.xhr.response;
15578 } else {
15579 this.body = this.req.method === 'HEAD' ? null : this._parseBody(this.text ? this.text : this.xhr.response);
15580 }
15581 } // eslint-disable-next-line new-cap
15582
15583
15584 responseBase(Response.prototype);
15585 /**
15586 * Parse the given body `str`.
15587 *
15588 * Used for auto-parsing of bodies. Parsers
15589 * are defined on the `superagent.parse` object.
15590 *
15591 * @param {String} str
15592 * @return {Mixed}
15593 * @api private
15594 */
15595
15596 Response.prototype._parseBody = function (str) {
15597 var parse = request.parse[this.type];
15598
15599 if (this.req._parser) {
15600 return this.req._parser(this, str);
15601 }
15602
15603 if (!parse && isJSON(this.type)) {
15604 parse = request.parse['application/json'];
15605 }
15606
15607 return parse && str && (str.length > 0 || str instanceof Object) ? parse(str) : null;
15608 };
15609 /**
15610 * Return an `Error` representative of this response.
15611 *
15612 * @return {Error}
15613 * @api public
15614 */
15615
15616
15617 Response.prototype.toError = function () {
15618 var req = this.req;
15619 var method = req.method;
15620 var url = req.url;
15621 var msg = "cannot ".concat(method, " ").concat(url, " (").concat(this.status, ")");
15622 var err = new Error(msg);
15623 err.status = this.status;
15624 err.method = method;
15625 err.url = url;
15626 return err;
15627 };
15628 /**
15629 * Expose `Response`.
15630 */
15631
15632
15633 request.Response = Response;
15634 /**
15635 * Initialize a new `Request` with the given `method` and `url`.
15636 *
15637 * @param {String} method
15638 * @param {String} url
15639 * @api public
15640 */
15641
15642 function Request(method, url) {
15643 var self = this;
15644 this._query = this._query || [];
15645 this.method = method;
15646 this.url = url;
15647 this.header = {}; // preserves header name case
15648
15649 this._header = {}; // coerces header names to lowercase
15650
15651 this.on('end', function () {
15652 var err = null;
15653 var res = null;
15654
15655 try {
15656 res = new Response(self);
15657 } catch (err2) {
15658 err = new Error('Parser is unable to parse the response');
15659 err.parse = true;
15660 err.original = err2; // issue #675: return the raw response if the response parsing fails
15661
15662 if (self.xhr) {
15663 // ie9 doesn't have 'response' property
15664 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
15665
15666 err.status = self.xhr.status ? self.xhr.status : null;
15667 err.statusCode = err.status; // backwards-compat only
15668 } else {
15669 err.rawResponse = null;
15670 err.status = null;
15671 }
15672
15673 return self.callback(err);
15674 }
15675
15676 self.emit('response', res);
15677 var new_err;
15678
15679 try {
15680 if (!self._isResponseOK(res)) {
15681 new_err = new Error(res.statusText || 'Unsuccessful HTTP response');
15682 }
15683 } catch (err2) {
15684 new_err = err2; // ok() callback can throw
15685 } // #1000 don't catch errors from the callback to avoid double calling it
15686
15687
15688 if (new_err) {
15689 new_err.original = err;
15690 new_err.response = res;
15691 new_err.status = res.status;
15692 self.callback(new_err, res);
15693 } else {
15694 self.callback(null, res);
15695 }
15696 });
15697 }
15698 /**
15699 * Mixin `Emitter` and `RequestBase`.
15700 */
15701 // eslint-disable-next-line new-cap
15702
15703
15704 componentEmitter(Request.prototype); // eslint-disable-next-line new-cap
15705
15706 requestBase(Request.prototype);
15707 /**
15708 * Set Content-Type to `type`, mapping values from `request.types`.
15709 *
15710 * Examples:
15711 *
15712 * superagent.types.xml = 'application/xml';
15713 *
15714 * request.post('/')
15715 * .type('xml')
15716 * .send(xmlstring)
15717 * .end(callback);
15718 *
15719 * request.post('/')
15720 * .type('application/xml')
15721 * .send(xmlstring)
15722 * .end(callback);
15723 *
15724 * @param {String} type
15725 * @return {Request} for chaining
15726 * @api public
15727 */
15728
15729 Request.prototype.type = function (type) {
15730 this.set('Content-Type', request.types[type] || type);
15731 return this;
15732 };
15733 /**
15734 * Set Accept to `type`, mapping values from `request.types`.
15735 *
15736 * Examples:
15737 *
15738 * superagent.types.json = 'application/json';
15739 *
15740 * request.get('/agent')
15741 * .accept('json')
15742 * .end(callback);
15743 *
15744 * request.get('/agent')
15745 * .accept('application/json')
15746 * .end(callback);
15747 *
15748 * @param {String} accept
15749 * @return {Request} for chaining
15750 * @api public
15751 */
15752
15753
15754 Request.prototype.accept = function (type) {
15755 this.set('Accept', request.types[type] || type);
15756 return this;
15757 };
15758 /**
15759 * Set Authorization field value with `user` and `pass`.
15760 *
15761 * @param {String} user
15762 * @param {String} [pass] optional in case of using 'bearer' as type
15763 * @param {Object} options with 'type' property 'auto', 'basic' or 'bearer' (default 'basic')
15764 * @return {Request} for chaining
15765 * @api public
15766 */
15767
15768
15769 Request.prototype.auth = function (user, pass, options) {
15770 if (arguments.length === 1) pass = '';
15771
15772 if (_typeof$1(pass) === 'object' && pass !== null) {
15773 // pass is optional and can be replaced with options
15774 options = pass;
15775 pass = '';
15776 }
15777
15778 if (!options) {
15779 options = {
15780 type: typeof btoa === 'function' ? 'basic' : 'auto'
15781 };
15782 }
15783
15784 var encoder = function encoder(string) {
15785 if (typeof btoa === 'function') {
15786 return btoa(string);
15787 }
15788
15789 throw new Error('Cannot use basic auth, btoa is not a function');
15790 };
15791
15792 return this._auth(user, pass, options, encoder);
15793 };
15794 /**
15795 * Add query-string `val`.
15796 *
15797 * Examples:
15798 *
15799 * request.get('/shoes')
15800 * .query('size=10')
15801 * .query({ color: 'blue' })
15802 *
15803 * @param {Object|String} val
15804 * @return {Request} for chaining
15805 * @api public
15806 */
15807
15808
15809 Request.prototype.query = function (val) {
15810 if (typeof val !== 'string') val = serialize(val);
15811 if (val) this._query.push(val);
15812 return this;
15813 };
15814 /**
15815 * Queue the given `file` as an attachment to the specified `field`,
15816 * with optional `options` (or filename).
15817 *
15818 * ``` js
15819 * request.post('/upload')
15820 * .attach('content', new Blob(['<a id="a"><b id="b">hey!</b></a>'], { type: "text/html"}))
15821 * .end(callback);
15822 * ```
15823 *
15824 * @param {String} field
15825 * @param {Blob|File} file
15826 * @param {String|Object} options
15827 * @return {Request} for chaining
15828 * @api public
15829 */
15830
15831
15832 Request.prototype.attach = function (field, file, options) {
15833 if (file) {
15834 if (this._data) {
15835 throw new Error("superagent can't mix .send() and .attach()");
15836 }
15837
15838 this._getFormData().append(field, file, options || file.name);
15839 }
15840
15841 return this;
15842 };
15843
15844 Request.prototype._getFormData = function () {
15845 if (!this._formData) {
15846 this._formData = new root.FormData();
15847 }
15848
15849 return this._formData;
15850 };
15851 /**
15852 * Invoke the callback with `err` and `res`
15853 * and handle arity check.
15854 *
15855 * @param {Error} err
15856 * @param {Response} res
15857 * @api private
15858 */
15859
15860
15861 Request.prototype.callback = function (err, res) {
15862 if (this._shouldRetry(err, res)) {
15863 return this._retry();
15864 }
15865
15866 var fn = this._callback;
15867 this.clearTimeout();
15868
15869 if (err) {
15870 if (this._maxRetries) err.retries = this._retries - 1;
15871 this.emit('error', err);
15872 }
15873
15874 fn(err, res);
15875 };
15876 /**
15877 * Invoke callback with x-domain error.
15878 *
15879 * @api private
15880 */
15881
15882
15883 Request.prototype.crossDomainError = function () {
15884 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.');
15885 err.crossDomain = true;
15886 err.status = this.status;
15887 err.method = this.method;
15888 err.url = this.url;
15889 this.callback(err);
15890 }; // This only warns, because the request is still likely to work
15891
15892
15893 Request.prototype.agent = function () {
15894 console.warn('This is not supported in browser version of superagent');
15895 return this;
15896 };
15897
15898 Request.prototype.buffer = Request.prototype.ca;
15899 Request.prototype.ca = Request.prototype.agent; // This throws, because it can't send/receive data as expected
15900
15901 Request.prototype.write = function () {
15902 throw new Error('Streaming is not supported in browser version of superagent');
15903 };
15904
15905 Request.prototype.pipe = Request.prototype.write;
15906 /**
15907 * Check if `obj` is a host object,
15908 * we don't want to serialize these :)
15909 *
15910 * @param {Object} obj host object
15911 * @return {Boolean} is a host object
15912 * @api private
15913 */
15914
15915 Request.prototype._isHost = function (obj) {
15916 // Native objects stringify to [object File], [object Blob], [object FormData], etc.
15917 return obj && _typeof$1(obj) === 'object' && !Array.isArray(obj) && Object.prototype.toString.call(obj) !== '[object Object]';
15918 };
15919 /**
15920 * Initiate request, invoking callback `fn(res)`
15921 * with an instanceof `Response`.
15922 *
15923 * @param {Function} fn
15924 * @return {Request} for chaining
15925 * @api public
15926 */
15927
15928
15929 Request.prototype.end = function (fn) {
15930 if (this._endCalled) {
15931 console.warn('Warning: .end() was called twice. This is not supported in superagent');
15932 }
15933
15934 this._endCalled = true; // store callback
15935
15936 this._callback = fn || noop; // querystring
15937
15938 this._finalizeQueryString();
15939
15940 this._end();
15941 };
15942
15943 Request.prototype._setUploadTimeout = function () {
15944 var self = this; // upload timeout it's wokrs only if deadline timeout is off
15945
15946 if (this._uploadTimeout && !this._uploadTimeoutTimer) {
15947 this._uploadTimeoutTimer = setTimeout(function () {
15948 self._timeoutError('Upload timeout of ', self._uploadTimeout, 'ETIMEDOUT');
15949 }, this._uploadTimeout);
15950 }
15951 }; // eslint-disable-next-line complexity
15952
15953
15954 Request.prototype._end = function () {
15955 if (this._aborted) return this.callback(new Error('The request has been aborted even before .end() was called'));
15956 var self = this;
15957 this.xhr = request.getXHR();
15958 var xhr = this.xhr;
15959 var data = this._formData || this._data;
15960
15961 this._setTimeouts(); // state change
15962
15963
15964 xhr.onreadystatechange = function () {
15965 var readyState = xhr.readyState;
15966
15967 if (readyState >= 2 && self._responseTimeoutTimer) {
15968 clearTimeout(self._responseTimeoutTimer);
15969 }
15970
15971 if (readyState !== 4) {
15972 return;
15973 } // In IE9, reads to any property (e.g. status) off of an aborted XHR will
15974 // result in the error "Could not complete the operation due to error c00c023f"
15975
15976
15977 var status;
15978
15979 try {
15980 status = xhr.status;
15981 } catch (err) {
15982 status = 0;
15983 }
15984
15985 if (!status) {
15986 if (self.timedout || self._aborted) return;
15987 return self.crossDomainError();
15988 }
15989
15990 self.emit('end');
15991 }; // progress
15992
15993
15994 var handleProgress = function handleProgress(direction, e) {
15995 if (e.total > 0) {
15996 e.percent = e.loaded / e.total * 100;
15997
15998 if (e.percent === 100) {
15999 clearTimeout(self._uploadTimeoutTimer);
16000 }
16001 }
16002
16003 e.direction = direction;
16004 self.emit('progress', e);
16005 };
16006
16007 if (this.hasListeners('progress')) {
16008 try {
16009 xhr.addEventListener('progress', handleProgress.bind(null, 'download'));
16010
16011 if (xhr.upload) {
16012 xhr.upload.addEventListener('progress', handleProgress.bind(null, 'upload'));
16013 }
16014 } catch (err) {// Accessing xhr.upload fails in IE from a web worker, so just pretend it doesn't exist.
16015 // Reported here:
16016 // https://connect.microsoft.com/IE/feedback/details/837245/xmlhttprequest-upload-throws-invalid-argument-when-used-from-web-worker-context
16017 }
16018 }
16019
16020 if (xhr.upload) {
16021 this._setUploadTimeout();
16022 } // initiate request
16023
16024
16025 try {
16026 if (this.username && this.password) {
16027 xhr.open(this.method, this.url, true, this.username, this.password);
16028 } else {
16029 xhr.open(this.method, this.url, true);
16030 }
16031 } catch (err) {
16032 // see #1149
16033 return this.callback(err);
16034 } // CORS
16035
16036
16037 if (this._withCredentials) xhr.withCredentials = true; // body
16038
16039 if (!this._formData && this.method !== 'GET' && this.method !== 'HEAD' && typeof data !== 'string' && !this._isHost(data)) {
16040 // serialize stuff
16041 var contentType = this._header['content-type'];
16042
16043 var _serialize = this._serializer || request.serialize[contentType ? contentType.split(';')[0] : ''];
16044
16045 if (!_serialize && isJSON(contentType)) {
16046 _serialize = request.serialize['application/json'];
16047 }
16048
16049 if (_serialize) data = _serialize(data);
16050 } // set header fields
16051
16052
16053 for (var field in this.header) {
16054 if (this.header[field] === null) continue;
16055 if (Object.prototype.hasOwnProperty.call(this.header, field)) xhr.setRequestHeader(field, this.header[field]);
16056 }
16057
16058 if (this._responseType) {
16059 xhr.responseType = this._responseType;
16060 } // send stuff
16061
16062
16063 this.emit('request', this); // IE11 xhr.send(undefined) sends 'undefined' string as POST payload (instead of nothing)
16064 // We need null here if data is undefined
16065
16066 xhr.send(typeof data === 'undefined' ? null : data);
16067 };
16068
16069 request.agent = function () {
16070 return new agentBase();
16071 };
16072
16073 ['GET', 'POST', 'OPTIONS', 'PATCH', 'PUT', 'DELETE'].forEach(function (method) {
16074 agentBase.prototype[method.toLowerCase()] = function (url, fn) {
16075 var req = new request.Request(method, url);
16076
16077 this._setDefaults(req);
16078
16079 if (fn) {
16080 req.end(fn);
16081 }
16082
16083 return req;
16084 };
16085 });
16086 agentBase.prototype.del = agentBase.prototype.delete;
16087 /**
16088 * GET `url` with optional callback `fn(res)`.
16089 *
16090 * @param {String} url
16091 * @param {Mixed|Function} [data] or fn
16092 * @param {Function} [fn]
16093 * @return {Request}
16094 * @api public
16095 */
16096
16097 request.get = function (url, data, fn) {
16098 var req = request('GET', url);
16099
16100 if (typeof data === 'function') {
16101 fn = data;
16102 data = null;
16103 }
16104
16105 if (data) req.query(data);
16106 if (fn) req.end(fn);
16107 return req;
16108 };
16109 /**
16110 * HEAD `url` with optional callback `fn(res)`.
16111 *
16112 * @param {String} url
16113 * @param {Mixed|Function} [data] or fn
16114 * @param {Function} [fn]
16115 * @return {Request}
16116 * @api public
16117 */
16118
16119
16120 request.head = function (url, data, fn) {
16121 var req = request('HEAD', url);
16122
16123 if (typeof data === 'function') {
16124 fn = data;
16125 data = null;
16126 }
16127
16128 if (data) req.query(data);
16129 if (fn) req.end(fn);
16130 return req;
16131 };
16132 /**
16133 * OPTIONS query to `url` with optional callback `fn(res)`.
16134 *
16135 * @param {String} url
16136 * @param {Mixed|Function} [data] or fn
16137 * @param {Function} [fn]
16138 * @return {Request}
16139 * @api public
16140 */
16141
16142
16143 request.options = function (url, data, fn) {
16144 var req = request('OPTIONS', url);
16145
16146 if (typeof data === 'function') {
16147 fn = data;
16148 data = null;
16149 }
16150
16151 if (data) req.send(data);
16152 if (fn) req.end(fn);
16153 return req;
16154 };
16155 /**
16156 * DELETE `url` with optional `data` and callback `fn(res)`.
16157 *
16158 * @param {String} url
16159 * @param {Mixed} [data]
16160 * @param {Function} [fn]
16161 * @return {Request}
16162 * @api public
16163 */
16164
16165
16166 function del(url, data, fn) {
16167 var req = request('DELETE', url);
16168
16169 if (typeof data === 'function') {
16170 fn = data;
16171 data = null;
16172 }
16173
16174 if (data) req.send(data);
16175 if (fn) req.end(fn);
16176 return req;
16177 }
16178
16179 request.del = del;
16180 request.delete = del;
16181 /**
16182 * PATCH `url` with optional `data` and callback `fn(res)`.
16183 *
16184 * @param {String} url
16185 * @param {Mixed} [data]
16186 * @param {Function} [fn]
16187 * @return {Request}
16188 * @api public
16189 */
16190
16191 request.patch = function (url, data, fn) {
16192 var req = request('PATCH', url);
16193
16194 if (typeof data === 'function') {
16195 fn = data;
16196 data = null;
16197 }
16198
16199 if (data) req.send(data);
16200 if (fn) req.end(fn);
16201 return req;
16202 };
16203 /**
16204 * POST `url` with optional `data` and callback `fn(res)`.
16205 *
16206 * @param {String} url
16207 * @param {Mixed} [data]
16208 * @param {Function} [fn]
16209 * @return {Request}
16210 * @api public
16211 */
16212
16213
16214 request.post = function (url, data, fn) {
16215 var req = request('POST', url);
16216
16217 if (typeof data === 'function') {
16218 fn = data;
16219 data = null;
16220 }
16221
16222 if (data) req.send(data);
16223 if (fn) req.end(fn);
16224 return req;
16225 };
16226 /**
16227 * PUT `url` with optional `data` and callback `fn(res)`.
16228 *
16229 * @param {String} url
16230 * @param {Mixed|Function} [data] or fn
16231 * @param {Function} [fn]
16232 * @return {Request}
16233 * @api public
16234 */
16235
16236
16237 request.put = function (url, data, fn) {
16238 var req = request('PUT', url);
16239
16240 if (typeof data === 'function') {
16241 fn = data;
16242 data = null;
16243 }
16244
16245 if (data) req.send(data);
16246 if (fn) req.end(fn);
16247 return req;
16248 };
16249 });
16250 var client_1 = client.Request;
16251
16252 /**
16253 * Copies the values of `source` to `array`.
16254 *
16255 * @private
16256 * @param {Array} source The array to copy values from.
16257 * @param {Array} [array=[]] The array to copy values to.
16258 * @returns {Array} Returns `array`.
16259 */
16260 function copyArray(source, array) {
16261 var index = -1,
16262 length = source.length;
16263
16264 array || (array = Array(length));
16265 while (++index < length) {
16266 array[index] = source[index];
16267 }
16268 return array;
16269 }
16270
16271 var _copyArray = copyArray;
16272
16273 /* Built-in method references for those with the same name as other `lodash` methods. */
16274 var nativeFloor = Math.floor,
16275 nativeRandom = Math.random;
16276
16277 /**
16278 * The base implementation of `_.random` without support for returning
16279 * floating-point numbers.
16280 *
16281 * @private
16282 * @param {number} lower The lower bound.
16283 * @param {number} upper The upper bound.
16284 * @returns {number} Returns the random number.
16285 */
16286 function baseRandom(lower, upper) {
16287 return lower + nativeFloor(nativeRandom() * (upper - lower + 1));
16288 }
16289
16290 var _baseRandom = baseRandom;
16291
16292 /**
16293 * A specialized version of `_.shuffle` which mutates and sets the size of `array`.
16294 *
16295 * @private
16296 * @param {Array} array The array to shuffle.
16297 * @param {number} [size=array.length] The size of `array`.
16298 * @returns {Array} Returns `array`.
16299 */
16300 function shuffleSelf(array, size) {
16301 var index = -1,
16302 length = array.length,
16303 lastIndex = length - 1;
16304
16305 size = size === undefined ? length : size;
16306 while (++index < size) {
16307 var rand = _baseRandom(index, lastIndex),
16308 value = array[rand];
16309
16310 array[rand] = array[index];
16311 array[index] = value;
16312 }
16313 array.length = size;
16314 return array;
16315 }
16316
16317 var _shuffleSelf = shuffleSelf;
16318
16319 /**
16320 * A specialized version of `_.shuffle` for arrays.
16321 *
16322 * @private
16323 * @param {Array} array The array to shuffle.
16324 * @returns {Array} Returns the new shuffled array.
16325 */
16326 function arrayShuffle(array) {
16327 return _shuffleSelf(_copyArray(array));
16328 }
16329
16330 var _arrayShuffle = arrayShuffle;
16331
16332 /**
16333 * A specialized version of `_.map` for arrays without support for iteratee
16334 * shorthands.
16335 *
16336 * @private
16337 * @param {Array} [array] The array to iterate over.
16338 * @param {Function} iteratee The function invoked per iteration.
16339 * @returns {Array} Returns the new mapped array.
16340 */
16341 function arrayMap(array, iteratee) {
16342 var index = -1,
16343 length = array == null ? 0 : array.length,
16344 result = Array(length);
16345
16346 while (++index < length) {
16347 result[index] = iteratee(array[index], index, array);
16348 }
16349 return result;
16350 }
16351
16352 var _arrayMap = arrayMap;
16353
16354 /**
16355 * The base implementation of `_.values` and `_.valuesIn` which creates an
16356 * array of `object` property values corresponding to the property names
16357 * of `props`.
16358 *
16359 * @private
16360 * @param {Object} object The object to query.
16361 * @param {Array} props The property names to get values for.
16362 * @returns {Object} Returns the array of property values.
16363 */
16364 function baseValues(object, props) {
16365 return _arrayMap(props, function(key) {
16366 return object[key];
16367 });
16368 }
16369
16370 var _baseValues = baseValues;
16371
16372 /**
16373 * The base implementation of `_.times` without support for iteratee shorthands
16374 * or max array length checks.
16375 *
16376 * @private
16377 * @param {number} n The number of times to invoke `iteratee`.
16378 * @param {Function} iteratee The function invoked per iteration.
16379 * @returns {Array} Returns the array of results.
16380 */
16381 function baseTimes(n, iteratee) {
16382 var index = -1,
16383 result = Array(n);
16384
16385 while (++index < n) {
16386 result[index] = iteratee(index);
16387 }
16388 return result;
16389 }
16390
16391 var _baseTimes = baseTimes;
16392
16393 /** Detect free variable `global` from Node.js. */
16394 var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal;
16395
16396 var _freeGlobal = freeGlobal;
16397
16398 /** Detect free variable `self`. */
16399 var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
16400
16401 /** Used as a reference to the global object. */
16402 var root = _freeGlobal || freeSelf || Function('return this')();
16403
16404 var _root = root;
16405
16406 /** Built-in value references. */
16407 var Symbol$1 = _root.Symbol;
16408
16409 var _Symbol = Symbol$1;
16410
16411 /** Used for built-in method references. */
16412 var objectProto = Object.prototype;
16413
16414 /** Used to check objects for own properties. */
16415 var hasOwnProperty$1 = objectProto.hasOwnProperty;
16416
16417 /**
16418 * Used to resolve the
16419 * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
16420 * of values.
16421 */
16422 var nativeObjectToString = objectProto.toString;
16423
16424 /** Built-in value references. */
16425 var symToStringTag = _Symbol ? _Symbol.toStringTag : undefined;
16426
16427 /**
16428 * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
16429 *
16430 * @private
16431 * @param {*} value The value to query.
16432 * @returns {string} Returns the raw `toStringTag`.
16433 */
16434 function getRawTag(value) {
16435 var isOwn = hasOwnProperty$1.call(value, symToStringTag),
16436 tag = value[symToStringTag];
16437
16438 try {
16439 value[symToStringTag] = undefined;
16440 var unmasked = true;
16441 } catch (e) {}
16442
16443 var result = nativeObjectToString.call(value);
16444 if (unmasked) {
16445 if (isOwn) {
16446 value[symToStringTag] = tag;
16447 } else {
16448 delete value[symToStringTag];
16449 }
16450 }
16451 return result;
16452 }
16453
16454 var _getRawTag = getRawTag;
16455
16456 /** Used for built-in method references. */
16457 var objectProto$1 = Object.prototype;
16458
16459 /**
16460 * Used to resolve the
16461 * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
16462 * of values.
16463 */
16464 var nativeObjectToString$1 = objectProto$1.toString;
16465
16466 /**
16467 * Converts `value` to a string using `Object.prototype.toString`.
16468 *
16469 * @private
16470 * @param {*} value The value to convert.
16471 * @returns {string} Returns the converted string.
16472 */
16473 function objectToString(value) {
16474 return nativeObjectToString$1.call(value);
16475 }
16476
16477 var _objectToString = objectToString;
16478
16479 /** `Object#toString` result references. */
16480 var nullTag = '[object Null]',
16481 undefinedTag = '[object Undefined]';
16482
16483 /** Built-in value references. */
16484 var symToStringTag$1 = _Symbol ? _Symbol.toStringTag : undefined;
16485
16486 /**
16487 * The base implementation of `getTag` without fallbacks for buggy environments.
16488 *
16489 * @private
16490 * @param {*} value The value to query.
16491 * @returns {string} Returns the `toStringTag`.
16492 */
16493 function baseGetTag(value) {
16494 if (value == null) {
16495 return value === undefined ? undefinedTag : nullTag;
16496 }
16497 return (symToStringTag$1 && symToStringTag$1 in Object(value))
16498 ? _getRawTag(value)
16499 : _objectToString(value);
16500 }
16501
16502 var _baseGetTag = baseGetTag;
16503
16504 /**
16505 * Checks if `value` is object-like. A value is object-like if it's not `null`
16506 * and has a `typeof` result of "object".
16507 *
16508 * @static
16509 * @memberOf _
16510 * @since 4.0.0
16511 * @category Lang
16512 * @param {*} value The value to check.
16513 * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
16514 * @example
16515 *
16516 * _.isObjectLike({});
16517 * // => true
16518 *
16519 * _.isObjectLike([1, 2, 3]);
16520 * // => true
16521 *
16522 * _.isObjectLike(_.noop);
16523 * // => false
16524 *
16525 * _.isObjectLike(null);
16526 * // => false
16527 */
16528 function isObjectLike(value) {
16529 return value != null && typeof value == 'object';
16530 }
16531
16532 var isObjectLike_1 = isObjectLike;
16533
16534 /** `Object#toString` result references. */
16535 var argsTag = '[object Arguments]';
16536
16537 /**
16538 * The base implementation of `_.isArguments`.
16539 *
16540 * @private
16541 * @param {*} value The value to check.
16542 * @returns {boolean} Returns `true` if `value` is an `arguments` object,
16543 */
16544 function baseIsArguments(value) {
16545 return isObjectLike_1(value) && _baseGetTag(value) == argsTag;
16546 }
16547
16548 var _baseIsArguments = baseIsArguments;
16549
16550 /** Used for built-in method references. */
16551 var objectProto$2 = Object.prototype;
16552
16553 /** Used to check objects for own properties. */
16554 var hasOwnProperty$2 = objectProto$2.hasOwnProperty;
16555
16556 /** Built-in value references. */
16557 var propertyIsEnumerable = objectProto$2.propertyIsEnumerable;
16558
16559 /**
16560 * Checks if `value` is likely an `arguments` object.
16561 *
16562 * @static
16563 * @memberOf _
16564 * @since 0.1.0
16565 * @category Lang
16566 * @param {*} value The value to check.
16567 * @returns {boolean} Returns `true` if `value` is an `arguments` object,
16568 * else `false`.
16569 * @example
16570 *
16571 * _.isArguments(function() { return arguments; }());
16572 * // => true
16573 *
16574 * _.isArguments([1, 2, 3]);
16575 * // => false
16576 */
16577 var isArguments = _baseIsArguments(function() { return arguments; }()) ? _baseIsArguments : function(value) {
16578 return isObjectLike_1(value) && hasOwnProperty$2.call(value, 'callee') &&
16579 !propertyIsEnumerable.call(value, 'callee');
16580 };
16581
16582 var isArguments_1 = isArguments;
16583
16584 /**
16585 * Checks if `value` is classified as an `Array` object.
16586 *
16587 * @static
16588 * @memberOf _
16589 * @since 0.1.0
16590 * @category Lang
16591 * @param {*} value The value to check.
16592 * @returns {boolean} Returns `true` if `value` is an array, else `false`.
16593 * @example
16594 *
16595 * _.isArray([1, 2, 3]);
16596 * // => true
16597 *
16598 * _.isArray(document.body.children);
16599 * // => false
16600 *
16601 * _.isArray('abc');
16602 * // => false
16603 *
16604 * _.isArray(_.noop);
16605 * // => false
16606 */
16607 var isArray = Array.isArray;
16608
16609 var isArray_1 = isArray;
16610
16611 /**
16612 * This method returns `false`.
16613 *
16614 * @static
16615 * @memberOf _
16616 * @since 4.13.0
16617 * @category Util
16618 * @returns {boolean} Returns `false`.
16619 * @example
16620 *
16621 * _.times(2, _.stubFalse);
16622 * // => [false, false]
16623 */
16624 function stubFalse() {
16625 return false;
16626 }
16627
16628 var stubFalse_1 = stubFalse;
16629
16630 var isBuffer_1 = createCommonjsModule(function (module, exports) {
16631 /** Detect free variable `exports`. */
16632 var freeExports = exports && !exports.nodeType && exports;
16633
16634 /** Detect free variable `module`. */
16635 var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module;
16636
16637 /** Detect the popular CommonJS extension `module.exports`. */
16638 var moduleExports = freeModule && freeModule.exports === freeExports;
16639
16640 /** Built-in value references. */
16641 var Buffer = moduleExports ? _root.Buffer : undefined;
16642
16643 /* Built-in method references for those with the same name as other `lodash` methods. */
16644 var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined;
16645
16646 /**
16647 * Checks if `value` is a buffer.
16648 *
16649 * @static
16650 * @memberOf _
16651 * @since 4.3.0
16652 * @category Lang
16653 * @param {*} value The value to check.
16654 * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.
16655 * @example
16656 *
16657 * _.isBuffer(new Buffer(2));
16658 * // => true
16659 *
16660 * _.isBuffer(new Uint8Array(2));
16661 * // => false
16662 */
16663 var isBuffer = nativeIsBuffer || stubFalse_1;
16664
16665 module.exports = isBuffer;
16666 });
16667
16668 /** Used as references for various `Number` constants. */
16669 var MAX_SAFE_INTEGER = 9007199254740991;
16670
16671 /** Used to detect unsigned integer values. */
16672 var reIsUint = /^(?:0|[1-9]\d*)$/;
16673
16674 /**
16675 * Checks if `value` is a valid array-like index.
16676 *
16677 * @private
16678 * @param {*} value The value to check.
16679 * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
16680 * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
16681 */
16682 function isIndex(value, length) {
16683 var type = typeof value;
16684 length = length == null ? MAX_SAFE_INTEGER : length;
16685
16686 return !!length &&
16687 (type == 'number' ||
16688 (type != 'symbol' && reIsUint.test(value))) &&
16689 (value > -1 && value % 1 == 0 && value < length);
16690 }
16691
16692 var _isIndex = isIndex;
16693
16694 /** Used as references for various `Number` constants. */
16695 var MAX_SAFE_INTEGER$1 = 9007199254740991;
16696
16697 /**
16698 * Checks if `value` is a valid array-like length.
16699 *
16700 * **Note:** This method is loosely based on
16701 * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
16702 *
16703 * @static
16704 * @memberOf _
16705 * @since 4.0.0
16706 * @category Lang
16707 * @param {*} value The value to check.
16708 * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
16709 * @example
16710 *
16711 * _.isLength(3);
16712 * // => true
16713 *
16714 * _.isLength(Number.MIN_VALUE);
16715 * // => false
16716 *
16717 * _.isLength(Infinity);
16718 * // => false
16719 *
16720 * _.isLength('3');
16721 * // => false
16722 */
16723 function isLength(value) {
16724 return typeof value == 'number' &&
16725 value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER$1;
16726 }
16727
16728 var isLength_1 = isLength;
16729
16730 /** `Object#toString` result references. */
16731 var argsTag$1 = '[object Arguments]',
16732 arrayTag = '[object Array]',
16733 boolTag = '[object Boolean]',
16734 dateTag = '[object Date]',
16735 errorTag = '[object Error]',
16736 funcTag = '[object Function]',
16737 mapTag = '[object Map]',
16738 numberTag = '[object Number]',
16739 objectTag = '[object Object]',
16740 regexpTag = '[object RegExp]',
16741 setTag = '[object Set]',
16742 stringTag = '[object String]',
16743 weakMapTag = '[object WeakMap]';
16744
16745 var arrayBufferTag = '[object ArrayBuffer]',
16746 dataViewTag = '[object DataView]',
16747 float32Tag = '[object Float32Array]',
16748 float64Tag = '[object Float64Array]',
16749 int8Tag = '[object Int8Array]',
16750 int16Tag = '[object Int16Array]',
16751 int32Tag = '[object Int32Array]',
16752 uint8Tag = '[object Uint8Array]',
16753 uint8ClampedTag = '[object Uint8ClampedArray]',
16754 uint16Tag = '[object Uint16Array]',
16755 uint32Tag = '[object Uint32Array]';
16756
16757 /** Used to identify `toStringTag` values of typed arrays. */
16758 var typedArrayTags = {};
16759 typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =
16760 typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =
16761 typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =
16762 typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =
16763 typedArrayTags[uint32Tag] = true;
16764 typedArrayTags[argsTag$1] = typedArrayTags[arrayTag] =
16765 typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =
16766 typedArrayTags[dataViewTag] = typedArrayTags[dateTag] =
16767 typedArrayTags[errorTag] = typedArrayTags[funcTag] =
16768 typedArrayTags[mapTag] = typedArrayTags[numberTag] =
16769 typedArrayTags[objectTag] = typedArrayTags[regexpTag] =
16770 typedArrayTags[setTag] = typedArrayTags[stringTag] =
16771 typedArrayTags[weakMapTag] = false;
16772
16773 /**
16774 * The base implementation of `_.isTypedArray` without Node.js optimizations.
16775 *
16776 * @private
16777 * @param {*} value The value to check.
16778 * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
16779 */
16780 function baseIsTypedArray(value) {
16781 return isObjectLike_1(value) &&
16782 isLength_1(value.length) && !!typedArrayTags[_baseGetTag(value)];
16783 }
16784
16785 var _baseIsTypedArray = baseIsTypedArray;
16786
16787 /**
16788 * The base implementation of `_.unary` without support for storing metadata.
16789 *
16790 * @private
16791 * @param {Function} func The function to cap arguments for.
16792 * @returns {Function} Returns the new capped function.
16793 */
16794 function baseUnary(func) {
16795 return function(value) {
16796 return func(value);
16797 };
16798 }
16799
16800 var _baseUnary = baseUnary;
16801
16802 var _nodeUtil = createCommonjsModule(function (module, exports) {
16803 /** Detect free variable `exports`. */
16804 var freeExports = exports && !exports.nodeType && exports;
16805
16806 /** Detect free variable `module`. */
16807 var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module;
16808
16809 /** Detect the popular CommonJS extension `module.exports`. */
16810 var moduleExports = freeModule && freeModule.exports === freeExports;
16811
16812 /** Detect free variable `process` from Node.js. */
16813 var freeProcess = moduleExports && _freeGlobal.process;
16814
16815 /** Used to access faster Node.js helpers. */
16816 var nodeUtil = (function() {
16817 try {
16818 // Use `util.types` for Node.js 10+.
16819 var types = freeModule && freeModule.require && freeModule.require('util').types;
16820
16821 if (types) {
16822 return types;
16823 }
16824
16825 // Legacy `process.binding('util')` for Node.js < 10.
16826 return freeProcess && freeProcess.binding && freeProcess.binding('util');
16827 } catch (e) {}
16828 }());
16829
16830 module.exports = nodeUtil;
16831 });
16832
16833 /* Node.js helper references. */
16834 var nodeIsTypedArray = _nodeUtil && _nodeUtil.isTypedArray;
16835
16836 /**
16837 * Checks if `value` is classified as a typed array.
16838 *
16839 * @static
16840 * @memberOf _
16841 * @since 3.0.0
16842 * @category Lang
16843 * @param {*} value The value to check.
16844 * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
16845 * @example
16846 *
16847 * _.isTypedArray(new Uint8Array);
16848 * // => true
16849 *
16850 * _.isTypedArray([]);
16851 * // => false
16852 */
16853 var isTypedArray = nodeIsTypedArray ? _baseUnary(nodeIsTypedArray) : _baseIsTypedArray;
16854
16855 var isTypedArray_1 = isTypedArray;
16856
16857 /** Used for built-in method references. */
16858 var objectProto$3 = Object.prototype;
16859
16860 /** Used to check objects for own properties. */
16861 var hasOwnProperty$3 = objectProto$3.hasOwnProperty;
16862
16863 /**
16864 * Creates an array of the enumerable property names of the array-like `value`.
16865 *
16866 * @private
16867 * @param {*} value The value to query.
16868 * @param {boolean} inherited Specify returning inherited property names.
16869 * @returns {Array} Returns the array of property names.
16870 */
16871 function arrayLikeKeys(value, inherited) {
16872 var isArr = isArray_1(value),
16873 isArg = !isArr && isArguments_1(value),
16874 isBuff = !isArr && !isArg && isBuffer_1(value),
16875 isType = !isArr && !isArg && !isBuff && isTypedArray_1(value),
16876 skipIndexes = isArr || isArg || isBuff || isType,
16877 result = skipIndexes ? _baseTimes(value.length, String) : [],
16878 length = result.length;
16879
16880 for (var key in value) {
16881 if ((inherited || hasOwnProperty$3.call(value, key)) &&
16882 !(skipIndexes && (
16883 // Safari 9 has enumerable `arguments.length` in strict mode.
16884 key == 'length' ||
16885 // Node.js 0.10 has enumerable non-index properties on buffers.
16886 (isBuff && (key == 'offset' || key == 'parent')) ||
16887 // PhantomJS 2 has enumerable non-index properties on typed arrays.
16888 (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) ||
16889 // Skip index properties.
16890 _isIndex(key, length)
16891 ))) {
16892 result.push(key);
16893 }
16894 }
16895 return result;
16896 }
16897
16898 var _arrayLikeKeys = arrayLikeKeys;
16899
16900 /** Used for built-in method references. */
16901 var objectProto$4 = Object.prototype;
16902
16903 /**
16904 * Checks if `value` is likely a prototype object.
16905 *
16906 * @private
16907 * @param {*} value The value to check.
16908 * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
16909 */
16910 function isPrototype(value) {
16911 var Ctor = value && value.constructor,
16912 proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto$4;
16913
16914 return value === proto;
16915 }
16916
16917 var _isPrototype = isPrototype;
16918
16919 /**
16920 * Creates a unary function that invokes `func` with its argument transformed.
16921 *
16922 * @private
16923 * @param {Function} func The function to wrap.
16924 * @param {Function} transform The argument transform.
16925 * @returns {Function} Returns the new function.
16926 */
16927 function overArg(func, transform) {
16928 return function(arg) {
16929 return func(transform(arg));
16930 };
16931 }
16932
16933 var _overArg = overArg;
16934
16935 /* Built-in method references for those with the same name as other `lodash` methods. */
16936 var nativeKeys = _overArg(Object.keys, Object);
16937
16938 var _nativeKeys = nativeKeys;
16939
16940 /** Used for built-in method references. */
16941 var objectProto$5 = Object.prototype;
16942
16943 /** Used to check objects for own properties. */
16944 var hasOwnProperty$4 = objectProto$5.hasOwnProperty;
16945
16946 /**
16947 * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
16948 *
16949 * @private
16950 * @param {Object} object The object to query.
16951 * @returns {Array} Returns the array of property names.
16952 */
16953 function baseKeys(object) {
16954 if (!_isPrototype(object)) {
16955 return _nativeKeys(object);
16956 }
16957 var result = [];
16958 for (var key in Object(object)) {
16959 if (hasOwnProperty$4.call(object, key) && key != 'constructor') {
16960 result.push(key);
16961 }
16962 }
16963 return result;
16964 }
16965
16966 var _baseKeys = baseKeys;
16967
16968 /**
16969 * Checks if `value` is the
16970 * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
16971 * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
16972 *
16973 * @static
16974 * @memberOf _
16975 * @since 0.1.0
16976 * @category Lang
16977 * @param {*} value The value to check.
16978 * @returns {boolean} Returns `true` if `value` is an object, else `false`.
16979 * @example
16980 *
16981 * _.isObject({});
16982 * // => true
16983 *
16984 * _.isObject([1, 2, 3]);
16985 * // => true
16986 *
16987 * _.isObject(_.noop);
16988 * // => true
16989 *
16990 * _.isObject(null);
16991 * // => false
16992 */
16993 function isObject$1(value) {
16994 var type = typeof value;
16995 return value != null && (type == 'object' || type == 'function');
16996 }
16997
16998 var isObject_1$1 = isObject$1;
16999
17000 /** `Object#toString` result references. */
17001 var asyncTag = '[object AsyncFunction]',
17002 funcTag$1 = '[object Function]',
17003 genTag = '[object GeneratorFunction]',
17004 proxyTag = '[object Proxy]';
17005
17006 /**
17007 * Checks if `value` is classified as a `Function` object.
17008 *
17009 * @static
17010 * @memberOf _
17011 * @since 0.1.0
17012 * @category Lang
17013 * @param {*} value The value to check.
17014 * @returns {boolean} Returns `true` if `value` is a function, else `false`.
17015 * @example
17016 *
17017 * _.isFunction(_);
17018 * // => true
17019 *
17020 * _.isFunction(/abc/);
17021 * // => false
17022 */
17023 function isFunction(value) {
17024 if (!isObject_1$1(value)) {
17025 return false;
17026 }
17027 // The use of `Object#toString` avoids issues with the `typeof` operator
17028 // in Safari 9 which returns 'object' for typed arrays and other constructors.
17029 var tag = _baseGetTag(value);
17030 return tag == funcTag$1 || tag == genTag || tag == asyncTag || tag == proxyTag;
17031 }
17032
17033 var isFunction_1 = isFunction;
17034
17035 /**
17036 * Checks if `value` is array-like. A value is considered array-like if it's
17037 * not a function and has a `value.length` that's an integer greater than or
17038 * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
17039 *
17040 * @static
17041 * @memberOf _
17042 * @since 4.0.0
17043 * @category Lang
17044 * @param {*} value The value to check.
17045 * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
17046 * @example
17047 *
17048 * _.isArrayLike([1, 2, 3]);
17049 * // => true
17050 *
17051 * _.isArrayLike(document.body.children);
17052 * // => true
17053 *
17054 * _.isArrayLike('abc');
17055 * // => true
17056 *
17057 * _.isArrayLike(_.noop);
17058 * // => false
17059 */
17060 function isArrayLike(value) {
17061 return value != null && isLength_1(value.length) && !isFunction_1(value);
17062 }
17063
17064 var isArrayLike_1 = isArrayLike;
17065
17066 /**
17067 * Creates an array of the own enumerable property names of `object`.
17068 *
17069 * **Note:** Non-object values are coerced to objects. See the
17070 * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
17071 * for more details.
17072 *
17073 * @static
17074 * @since 0.1.0
17075 * @memberOf _
17076 * @category Object
17077 * @param {Object} object The object to query.
17078 * @returns {Array} Returns the array of property names.
17079 * @example
17080 *
17081 * function Foo() {
17082 * this.a = 1;
17083 * this.b = 2;
17084 * }
17085 *
17086 * Foo.prototype.c = 3;
17087 *
17088 * _.keys(new Foo);
17089 * // => ['a', 'b'] (iteration order is not guaranteed)
17090 *
17091 * _.keys('hi');
17092 * // => ['0', '1']
17093 */
17094 function keys(object) {
17095 return isArrayLike_1(object) ? _arrayLikeKeys(object) : _baseKeys(object);
17096 }
17097
17098 var keys_1 = keys;
17099
17100 /**
17101 * Creates an array of the own enumerable string keyed property values of `object`.
17102 *
17103 * **Note:** Non-object values are coerced to objects.
17104 *
17105 * @static
17106 * @since 0.1.0
17107 * @memberOf _
17108 * @category Object
17109 * @param {Object} object The object to query.
17110 * @returns {Array} Returns the array of property values.
17111 * @example
17112 *
17113 * function Foo() {
17114 * this.a = 1;
17115 * this.b = 2;
17116 * }
17117 *
17118 * Foo.prototype.c = 3;
17119 *
17120 * _.values(new Foo);
17121 * // => [1, 2] (iteration order is not guaranteed)
17122 *
17123 * _.values('hi');
17124 * // => ['h', 'i']
17125 */
17126 function values(object) {
17127 return object == null ? [] : _baseValues(object, keys_1(object));
17128 }
17129
17130 var values_1 = values;
17131
17132 /**
17133 * The base implementation of `_.shuffle`.
17134 *
17135 * @private
17136 * @param {Array|Object} collection The collection to shuffle.
17137 * @returns {Array} Returns the new shuffled array.
17138 */
17139 function baseShuffle(collection) {
17140 return _shuffleSelf(values_1(collection));
17141 }
17142
17143 var _baseShuffle = baseShuffle;
17144
17145 /**
17146 * Creates an array of shuffled values, using a version of the
17147 * [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle).
17148 *
17149 * @static
17150 * @memberOf _
17151 * @since 0.1.0
17152 * @category Collection
17153 * @param {Array|Object} collection The collection to shuffle.
17154 * @returns {Array} Returns the new shuffled array.
17155 * @example
17156 *
17157 * _.shuffle([1, 2, 3, 4]);
17158 * // => [4, 1, 3, 2]
17159 */
17160 function shuffle(collection) {
17161 var func = isArray_1(collection) ? _arrayShuffle : _baseShuffle;
17162 return func(collection);
17163 }
17164
17165 var shuffle_1 = shuffle;
17166
17167 var stateMachine = createCommonjsModule(function (module, exports) {
17168 /*
17169
17170 Javascript State Machine Library - https://github.com/jakesgordon/javascript-state-machine
17171
17172 Copyright (c) 2012, 2013, 2014, 2015, Jake Gordon and contributors
17173 Released under the MIT license - https://github.com/jakesgordon/javascript-state-machine/blob/master/LICENSE
17174
17175 */
17176
17177 (function () {
17178
17179 var StateMachine = {
17180
17181 //---------------------------------------------------------------------------
17182
17183 VERSION: "2.4.0",
17184
17185 //---------------------------------------------------------------------------
17186
17187 Result: {
17188 SUCCEEDED: 1, // the event transitioned successfully from one state to another
17189 NOTRANSITION: 2, // the event was successfull but no state transition was necessary
17190 CANCELLED: 3, // the event was cancelled by the caller in a beforeEvent callback
17191 PENDING: 4 // the event is asynchronous and the caller is in control of when the transition occurs
17192 },
17193
17194 Error: {
17195 INVALID_TRANSITION: 100, // caller tried to fire an event that was innapropriate in the current state
17196 PENDING_TRANSITION: 200, // caller tried to fire an event while an async transition was still pending
17197 INVALID_CALLBACK: 300 // caller provided callback function threw an exception
17198 },
17199
17200 WILDCARD: '*',
17201 ASYNC: 'async',
17202
17203 //---------------------------------------------------------------------------
17204
17205 create: function(cfg, target) {
17206
17207 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 }
17208 var terminal = cfg.terminal || cfg['final'];
17209 var fsm = target || cfg.target || {};
17210 var events = cfg.events || [];
17211 var callbacks = cfg.callbacks || {};
17212 var map = {}; // track state transitions allowed for an event { event: { from: [ to ] } }
17213 var transitions = {}; // track events allowed from a state { state: [ event ] }
17214
17215 var add = function(e) {
17216 var from = Array.isArray(e.from) ? e.from : (e.from ? [e.from] : [StateMachine.WILDCARD]); // allow 'wildcard' transition if 'from' is not specified
17217 map[e.name] = map[e.name] || {};
17218 for (var n = 0 ; n < from.length ; n++) {
17219 transitions[from[n]] = transitions[from[n]] || [];
17220 transitions[from[n]].push(e.name);
17221
17222 map[e.name][from[n]] = e.to || from[n]; // allow no-op transition if 'to' is not specified
17223 }
17224 if (e.to)
17225 transitions[e.to] = transitions[e.to] || [];
17226 };
17227
17228 if (initial) {
17229 initial.event = initial.event || 'startup';
17230 add({ name: initial.event, from: 'none', to: initial.state });
17231 }
17232
17233 for(var n = 0 ; n < events.length ; n++)
17234 add(events[n]);
17235
17236 for(var name in map) {
17237 if (map.hasOwnProperty(name))
17238 fsm[name] = StateMachine.buildEvent(name, map[name]);
17239 }
17240
17241 for(var name in callbacks) {
17242 if (callbacks.hasOwnProperty(name))
17243 fsm[name] = callbacks[name];
17244 }
17245
17246 fsm.current = 'none';
17247 fsm.is = function(state) { return Array.isArray(state) ? (state.indexOf(this.current) >= 0) : (this.current === state); };
17248 fsm.can = function(event) { return !this.transition && (map[event] !== undefined) && (map[event].hasOwnProperty(this.current) || map[event].hasOwnProperty(StateMachine.WILDCARD)); };
17249 fsm.cannot = function(event) { return !this.can(event); };
17250 fsm.transitions = function() { return (transitions[this.current] || []).concat(transitions[StateMachine.WILDCARD] || []); };
17251 fsm.isFinished = function() { return this.is(terminal); };
17252 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)
17253 fsm.states = function() { return Object.keys(transitions).sort() };
17254
17255 if (initial && !initial.defer)
17256 fsm[initial.event]();
17257
17258 return fsm;
17259
17260 },
17261
17262 //===========================================================================
17263
17264 doCallback: function(fsm, func, name, from, to, args) {
17265 if (func) {
17266 try {
17267 return func.apply(fsm, [name, from, to].concat(args));
17268 }
17269 catch(e) {
17270 return fsm.error(name, from, to, args, StateMachine.Error.INVALID_CALLBACK, "an exception occurred in a caller-provided callback function", e);
17271 }
17272 }
17273 },
17274
17275 beforeAnyEvent: function(fsm, name, from, to, args) { return StateMachine.doCallback(fsm, fsm['onbeforeevent'], name, from, to, args); },
17276 afterAnyEvent: function(fsm, name, from, to, args) { return StateMachine.doCallback(fsm, fsm['onafterevent'] || fsm['onevent'], name, from, to, args); },
17277 leaveAnyState: function(fsm, name, from, to, args) { return StateMachine.doCallback(fsm, fsm['onleavestate'], name, from, to, args); },
17278 enterAnyState: function(fsm, name, from, to, args) { return StateMachine.doCallback(fsm, fsm['onenterstate'] || fsm['onstate'], name, from, to, args); },
17279 changeState: function(fsm, name, from, to, args) { return StateMachine.doCallback(fsm, fsm['onchangestate'], name, from, to, args); },
17280
17281 beforeThisEvent: function(fsm, name, from, to, args) { return StateMachine.doCallback(fsm, fsm['onbefore' + name], name, from, to, args); },
17282 afterThisEvent: function(fsm, name, from, to, args) { return StateMachine.doCallback(fsm, fsm['onafter' + name] || fsm['on' + name], name, from, to, args); },
17283 leaveThisState: function(fsm, name, from, to, args) { return StateMachine.doCallback(fsm, fsm['onleave' + from], name, from, to, args); },
17284 enterThisState: function(fsm, name, from, to, args) { return StateMachine.doCallback(fsm, fsm['onenter' + to] || fsm['on' + to], name, from, to, args); },
17285
17286 beforeEvent: function(fsm, name, from, to, args) {
17287 if ((false === StateMachine.beforeThisEvent(fsm, name, from, to, args)) ||
17288 (false === StateMachine.beforeAnyEvent( fsm, name, from, to, args)))
17289 return false;
17290 },
17291
17292 afterEvent: function(fsm, name, from, to, args) {
17293 StateMachine.afterThisEvent(fsm, name, from, to, args);
17294 StateMachine.afterAnyEvent( fsm, name, from, to, args);
17295 },
17296
17297 leaveState: function(fsm, name, from, to, args) {
17298 var specific = StateMachine.leaveThisState(fsm, name, from, to, args),
17299 general = StateMachine.leaveAnyState( fsm, name, from, to, args);
17300 if ((false === specific) || (false === general))
17301 return false;
17302 else if ((StateMachine.ASYNC === specific) || (StateMachine.ASYNC === general))
17303 return StateMachine.ASYNC;
17304 },
17305
17306 enterState: function(fsm, name, from, to, args) {
17307 StateMachine.enterThisState(fsm, name, from, to, args);
17308 StateMachine.enterAnyState( fsm, name, from, to, args);
17309 },
17310
17311 //===========================================================================
17312
17313 buildEvent: function(name, map) {
17314 return function() {
17315
17316 var from = this.current;
17317 var to = map[from] || (map[StateMachine.WILDCARD] != StateMachine.WILDCARD ? map[StateMachine.WILDCARD] : from) || from;
17318 var args = Array.prototype.slice.call(arguments); // turn arguments into pure array
17319
17320 if (this.transition)
17321 return this.error(name, from, to, args, StateMachine.Error.PENDING_TRANSITION, "event " + name + " inappropriate because previous transition did not complete");
17322
17323 if (this.cannot(name))
17324 return this.error(name, from, to, args, StateMachine.Error.INVALID_TRANSITION, "event " + name + " inappropriate in current state " + this.current);
17325
17326 if (false === StateMachine.beforeEvent(this, name, from, to, args))
17327 return StateMachine.Result.CANCELLED;
17328
17329 if (from === to) {
17330 StateMachine.afterEvent(this, name, from, to, args);
17331 return StateMachine.Result.NOTRANSITION;
17332 }
17333
17334 // 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)
17335 var fsm = this;
17336 this.transition = function() {
17337 fsm.transition = null; // this method should only ever be called once
17338 fsm.current = to;
17339 StateMachine.enterState( fsm, name, from, to, args);
17340 StateMachine.changeState(fsm, name, from, to, args);
17341 StateMachine.afterEvent( fsm, name, from, to, args);
17342 return StateMachine.Result.SUCCEEDED;
17343 };
17344 this.transition.cancel = function() { // provide a way for caller to cancel async transition if desired (issue #22)
17345 fsm.transition = null;
17346 StateMachine.afterEvent(fsm, name, from, to, args);
17347 };
17348
17349 var leave = StateMachine.leaveState(this, name, from, to, args);
17350 if (false === leave) {
17351 this.transition = null;
17352 return StateMachine.Result.CANCELLED;
17353 }
17354 else if (StateMachine.ASYNC === leave) {
17355 return StateMachine.Result.PENDING;
17356 }
17357 else {
17358 if (this.transition) // need to check in case user manually called transition() but forgot to return StateMachine.ASYNC
17359 return this.transition();
17360 }
17361
17362 };
17363 }
17364
17365 }; // StateMachine
17366
17367 //===========================================================================
17368
17369 //======
17370 // NODE
17371 //======
17372 {
17373 if (module.exports) {
17374 exports = module.exports = StateMachine;
17375 }
17376 exports.StateMachine = StateMachine;
17377 }
17378
17379 }());
17380 });
17381 var stateMachine_1 = stateMachine.StateMachine;
17382
17383 /** Built-in value references. */
17384 var getPrototype = _overArg(Object.getPrototypeOf, Object);
17385
17386 var _getPrototype = getPrototype;
17387
17388 /** `Object#toString` result references. */
17389 var objectTag$1 = '[object Object]';
17390
17391 /** Used for built-in method references. */
17392 var funcProto = Function.prototype,
17393 objectProto$6 = Object.prototype;
17394
17395 /** Used to resolve the decompiled source of functions. */
17396 var funcToString = funcProto.toString;
17397
17398 /** Used to check objects for own properties. */
17399 var hasOwnProperty$5 = objectProto$6.hasOwnProperty;
17400
17401 /** Used to infer the `Object` constructor. */
17402 var objectCtorString = funcToString.call(Object);
17403
17404 /**
17405 * Checks if `value` is a plain object, that is, an object created by the
17406 * `Object` constructor or one with a `[[Prototype]]` of `null`.
17407 *
17408 * @static
17409 * @memberOf _
17410 * @since 0.8.0
17411 * @category Lang
17412 * @param {*} value The value to check.
17413 * @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
17414 * @example
17415 *
17416 * function Foo() {
17417 * this.a = 1;
17418 * }
17419 *
17420 * _.isPlainObject(new Foo);
17421 * // => false
17422 *
17423 * _.isPlainObject([1, 2, 3]);
17424 * // => false
17425 *
17426 * _.isPlainObject({ 'x': 0, 'y': 0 });
17427 * // => true
17428 *
17429 * _.isPlainObject(Object.create(null));
17430 * // => true
17431 */
17432 function isPlainObject(value) {
17433 if (!isObjectLike_1(value) || _baseGetTag(value) != objectTag$1) {
17434 return false;
17435 }
17436 var proto = _getPrototype(value);
17437 if (proto === null) {
17438 return true;
17439 }
17440 var Ctor = hasOwnProperty$5.call(proto, 'constructor') && proto.constructor;
17441 return typeof Ctor == 'function' && Ctor instanceof Ctor &&
17442 funcToString.call(Ctor) == objectCtorString;
17443 }
17444
17445 var isPlainObject_1 = isPlainObject;
17446
17447 /* eslint-disable */
17448 var global$1 = typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : {};
17449
17450 var EXPIRED = Symbol('expired');
17451 var debug = browser('LC:Expirable');
17452
17453 var Expirable =
17454 /*#__PURE__*/
17455 function () {
17456 function Expirable(value, ttl) {
17457 this.originalValue = value;
17458
17459 if (typeof ttl === 'number') {
17460 this.expiredAt = Date.now() + ttl;
17461 }
17462 }
17463
17464 _createClass(Expirable, [{
17465 key: "value",
17466 get: function get() {
17467 var expired = this.expiredAt && this.expiredAt <= Date.now();
17468 if (expired) debug("expired: ".concat(this.originalValue));
17469 return expired ? EXPIRED : this.originalValue;
17470 }
17471 }]);
17472
17473 return Expirable;
17474 }();
17475 Expirable.EXPIRED = EXPIRED;
17476
17477 var debug$1 = browser('LC:Cache');
17478
17479 var Cache =
17480 /*#__PURE__*/
17481 function () {
17482 function Cache() {
17483 var name = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'anonymous';
17484 this.name = name;
17485 this._map = {};
17486 }
17487
17488 var _proto = Cache.prototype;
17489
17490 _proto.get = function get(key) {
17491 var cache = this._map[key];
17492
17493 if (cache) {
17494 var value = cache.value;
17495
17496 if (value !== Expirable.EXPIRED) {
17497 debug$1('[%s] hit: %s', this.name, key);
17498 return value;
17499 }
17500
17501 delete this._map[key];
17502 }
17503
17504 debug$1("[".concat(this.name, "] missed: ").concat(key));
17505 return null;
17506 };
17507
17508 _proto.set = function set(key, value, ttl) {
17509 debug$1('[%s] set: %s %d', this.name, key, ttl);
17510 this._map[key] = new Expirable(value, ttl);
17511 };
17512
17513 return Cache;
17514 }();
17515
17516 var debug$2 = {
17517 enable: function enable() {
17518 var namespaces = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'LC*';
17519 return browser.enable(namespaces);
17520 },
17521 disable: browser.disable
17522 };
17523 var tryAll = function tryAll(promiseConstructors) {
17524 var promise = new Promise(promiseConstructors[0]);
17525
17526 if (promiseConstructors.length === 1) {
17527 return promise;
17528 }
17529
17530 return promise.catch(function () {
17531 return tryAll(promiseConstructors.slice(1));
17532 });
17533 }; // eslint-disable-next-line no-sequences
17534
17535 var tap = function tap(interceptor) {
17536 return function (value) {
17537 return interceptor(value), value;
17538 };
17539 };
17540 var isIE10 = global$1.navigator && global$1.navigator.userAgent && global$1.navigator.userAgent.indexOf('MSIE 10.') !== -1;
17541 var map = new WeakMap(); // protected property helper
17542
17543 var internal = function internal(object) {
17544 if (!map.has(object)) {
17545 map.set(object, {});
17546 }
17547
17548 return map.get(object);
17549 };
17550 var compact = function compact(obj, filter) {
17551 if (!isPlainObject_1(obj)) return obj;
17552 var object = Object.assign({}, obj); // eslint-disable-next-line no-restricted-syntax
17553
17554 for (var prop in object) {
17555 if ({}.hasOwnProperty.call(object, prop)) {
17556 var value = object[prop];
17557
17558 if (value === filter) {
17559 delete object[prop];
17560 } else {
17561 object[prop] = compact(value, filter);
17562 }
17563 }
17564 }
17565
17566 return object;
17567 }; // debug utility
17568
17569 var removeNull = function removeNull(obj) {
17570 return compact(obj, null);
17571 };
17572
17573 var trim = function trim(message) {
17574 return removeNull(JSON.parse(JSON.stringify(message)));
17575 };
17576 var ensureArray = function ensureArray(target) {
17577 if (Array.isArray(target)) {
17578 return target;
17579 }
17580
17581 if (target === undefined || target === null) {
17582 return [];
17583 }
17584
17585 return [target];
17586 };
17587 var isWeapp = // eslint-disable-next-line no-undef
17588 (typeof wx === "undefined" ? "undefined" : _typeof(wx)) === 'object' && typeof wx.connectSocket === 'function'; // throttle decorator
17589 var isCNApp = function isCNApp(appId) {
17590 return appId.slice(-9) !== '-MdYXbMMI';
17591 };
17592
17593 var _class;
17594 var debug$3 = browser('LC:WebSocketPlus');
17595 var OPEN$1 = 'open';
17596 var DISCONNECT = 'disconnect';
17597 var RECONNECT = 'reconnect';
17598 var RETRY = 'retry';
17599 var SCHEDULE = 'schedule';
17600 var OFFLINE = 'offline';
17601 var ONLINE = 'online';
17602 var ERROR = 'error';
17603 var MESSAGE = 'message';
17604 var HEARTBEAT_TIME = 180000;
17605 var TIMEOUT_TIME = 380000;
17606
17607 var DEFAULT_RETRY_STRATEGY = function DEFAULT_RETRY_STRATEGY(attempt) {
17608 return Math.min(1000 * Math.pow(2, attempt), 300000);
17609 };
17610
17611 var requireConnected = function requireConnected(target, name, descriptor) {
17612 return Object.assign({}, descriptor, {
17613 value: function requireConnectedWrapper() {
17614 var _descriptor$value;
17615
17616 this.checkConnectionAvailability(name);
17617
17618 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
17619 args[_key] = arguments[_key];
17620 }
17621
17622 return (_descriptor$value = descriptor.value).call.apply(_descriptor$value, [this].concat(args));
17623 }
17624 });
17625 };
17626
17627 var WebSocketPlus = (_class =
17628 /*#__PURE__*/
17629 function (_EventEmitter) {
17630 _inheritsLoose(WebSocketPlus, _EventEmitter);
17631
17632 _createClass(WebSocketPlus, [{
17633 key: "urls",
17634 get: function get() {
17635 return this._urls;
17636 },
17637 set: function set(urls) {
17638 this._urls = ensureArray(urls);
17639 }
17640 }]);
17641
17642 function WebSocketPlus(getUrls, protocol) {
17643 var _this;
17644
17645 if (typeof websocket === 'undefined') {
17646 throw new Error('WebSocket is undefined. Polyfill is required in this runtime.');
17647 }
17648
17649 _this = _EventEmitter.call(this) || this;
17650
17651 _this.init();
17652
17653 _this._protocol = protocol;
17654 Promise.resolve(typeof getUrls === 'function' ? getUrls() : getUrls).then(ensureArray).then(function (urls) {
17655 _this._urls = urls;
17656 return _this._open();
17657 }).then(function () {
17658 _this.__postponeTimeoutTimer = _this._postponeTimeoutTimer.bind(_assertThisInitialized(_this));
17659
17660 if (global$1.addEventListener) {
17661 _this.__pause = function () {
17662 if (_this.can('pause')) _this.pause();
17663 };
17664
17665 _this.__resume = function () {
17666 if (_this.can('resume')) _this.resume();
17667 };
17668
17669 global$1.addEventListener('offline', _this.__pause);
17670 global$1.addEventListener('online', _this.__resume);
17671 }
17672
17673 _this.open();
17674 }).catch(_this.throw.bind(_assertThisInitialized(_this)));
17675 return _this;
17676 }
17677
17678 var _proto = WebSocketPlus.prototype;
17679
17680 _proto._open = function _open() {
17681 var _this2 = this;
17682
17683 return this._createWs(this._urls, this._protocol).then(function (ws) {
17684 var _this2$_urls = _toArray(_this2._urls),
17685 first = _this2$_urls[0],
17686 reset = _this2$_urls.slice(1);
17687
17688 _this2._urls = [].concat(_toConsumableArray(reset), [first]);
17689 return ws;
17690 });
17691 };
17692
17693 _proto._createWs = function _createWs(urls, protocol) {
17694 var _this3 = this;
17695
17696 return tryAll(urls.map(function (url) {
17697 return function (resolve, reject) {
17698 debug$3("connect [".concat(url, "] ").concat(protocol));
17699 var ws = protocol ? new websocket(url, protocol) : new websocket(url);
17700 ws.binaryType = _this3.binaryType || 'arraybuffer';
17701
17702 ws.onopen = function () {
17703 return resolve(ws);
17704 };
17705
17706 ws.onclose = function (error) {
17707 if (error instanceof Error) {
17708 return reject(error);
17709 } // in browser, error event is useless
17710
17711
17712 return reject(new Error("Failed to connect [".concat(url, "]")));
17713 };
17714
17715 ws.onerror = ws.onclose;
17716 };
17717 })).then(function (ws) {
17718 _this3._ws = ws;
17719 _this3._ws.onclose = _this3._handleClose.bind(_this3);
17720 _this3._ws.onmessage = _this3._handleMessage.bind(_this3);
17721 return ws;
17722 });
17723 };
17724
17725 _proto._destroyWs = function _destroyWs() {
17726 var ws = this._ws;
17727 if (!ws) return;
17728 ws.onopen = null;
17729 ws.onclose = null;
17730 ws.onerror = null;
17731 ws.onmessage = null;
17732 this._ws = null;
17733 ws.close();
17734 } // eslint-disable-next-line class-methods-use-this
17735 ;
17736
17737 _proto.onbeforeevent = function onbeforeevent(event, from, to) {
17738 for (var _len2 = arguments.length, payload = new Array(_len2 > 3 ? _len2 - 3 : 0), _key2 = 3; _key2 < _len2; _key2++) {
17739 payload[_key2 - 3] = arguments[_key2];
17740 }
17741
17742 debug$3("".concat(event, ": ").concat(from, " -> ").concat(to, " %o"), payload);
17743 };
17744
17745 _proto.onopen = function onopen() {
17746 this.emit(OPEN$1);
17747 };
17748
17749 _proto.onconnected = function onconnected() {
17750 this._startConnectionKeeper();
17751 };
17752
17753 _proto.onleaveconnected = function onleaveconnected(event, from, to) {
17754 this._stopConnectionKeeper();
17755
17756 this._destroyWs();
17757
17758 if (to === 'offline' || to === 'disconnected') {
17759 this.emit(DISCONNECT);
17760 }
17761 };
17762
17763 _proto.onpause = function onpause() {
17764 this.emit(OFFLINE);
17765 };
17766
17767 _proto.onbeforeresume = function onbeforeresume() {
17768 this.emit(ONLINE);
17769 };
17770
17771 _proto.onreconnect = function onreconnect() {
17772 this.emit(RECONNECT);
17773 };
17774
17775 _proto.ondisconnected = function ondisconnected(event, from, to) {
17776 var _this4 = this;
17777
17778 var attempt = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;
17779 var delay = DEFAULT_RETRY_STRATEGY.call(null, attempt);
17780 debug$3("schedule attempt=".concat(attempt, " delay=").concat(delay));
17781 this.emit(SCHEDULE, attempt, delay);
17782
17783 if (this.__scheduledRetry) {
17784 clearTimeout(this.__scheduledRetry);
17785 }
17786
17787 this.__scheduledRetry = setTimeout(function () {
17788 if (_this4.is('disconnected')) {
17789 _this4.retry(attempt);
17790 }
17791 }, delay);
17792 };
17793
17794 _proto.onretry = function onretry(event, from, to) {
17795 var _this5 = this;
17796
17797 var attempt = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;
17798 this.emit(RETRY, attempt);
17799
17800 this._open().then(function () {
17801 return _this5.can('reconnect') ? _this5.reconnect() : _this5._destroyWs();
17802 }, function () {
17803 return _this5.can('fail') && _this5.fail(attempt + 1);
17804 });
17805 };
17806
17807 _proto.onerror = function onerror(event, from, to, error) {
17808 this.emit(ERROR, error);
17809 };
17810
17811 _proto.onclose = function onclose() {
17812 if (global$1.removeEventListener) {
17813 if (this.__pause) global$1.removeEventListener('offline', this.__pause);
17814 if (this.__resume) global$1.removeEventListener('online', this.__resume);
17815 }
17816 };
17817
17818 _proto.checkConnectionAvailability = function checkConnectionAvailability() {
17819 var name = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'API';
17820
17821 if (!this.is('connected')) {
17822 var currentState = this.current;
17823 console.warn("".concat(name, " should not be called when the connection is ").concat(currentState));
17824
17825 if (this.is('disconnected') || this.is('reconnecting')) {
17826 console.warn('disconnect and reconnect event should be handled to avoid such calls.');
17827 }
17828
17829 throw new Error('Connection unavailable');
17830 }
17831 } // jsdoc-ignore-start
17832 ;
17833
17834 _proto. // jsdoc-ignore-end
17835 _ping = function _ping() {
17836 debug$3('ping');
17837
17838 try {
17839 this.ping();
17840 } catch (error) {
17841 console.warn("websocket ping error: ".concat(error.message));
17842 }
17843 };
17844
17845 _proto.ping = function ping() {
17846 if (this._ws.ping) {
17847 this._ws.ping();
17848 } else {
17849 console.warn("The WebSocket implement does not support sending ping frame.\n Override ping method to use application defined ping/pong mechanism.");
17850 }
17851 };
17852
17853 _proto._postponeTimeoutTimer = function _postponeTimeoutTimer() {
17854 var _this6 = this;
17855
17856 debug$3('_postponeTimeoutTimer');
17857
17858 this._clearTimeoutTimers();
17859
17860 this._timeoutTimer = setTimeout(function () {
17861 debug$3('timeout');
17862
17863 _this6.disconnect();
17864 }, TIMEOUT_TIME);
17865 };
17866
17867 _proto._clearTimeoutTimers = function _clearTimeoutTimers() {
17868 if (this._timeoutTimer) {
17869 clearTimeout(this._timeoutTimer);
17870 }
17871 };
17872
17873 _proto._startConnectionKeeper = function _startConnectionKeeper() {
17874 debug$3('start connection keeper');
17875 this._heartbeatTimer = setInterval(this._ping.bind(this), HEARTBEAT_TIME);
17876 var addListener = this._ws.addListener || this._ws.addEventListener;
17877
17878 if (!addListener) {
17879 debug$3('connection keeper disabled due to the lack of #addEventListener.');
17880 return;
17881 }
17882
17883 addListener.call(this._ws, 'message', this.__postponeTimeoutTimer);
17884 addListener.call(this._ws, 'pong', this.__postponeTimeoutTimer);
17885
17886 this._postponeTimeoutTimer();
17887 };
17888
17889 _proto._stopConnectionKeeper = function _stopConnectionKeeper() {
17890 debug$3('stop connection keeper'); // websockets/ws#489
17891
17892 var removeListener = this._ws.removeListener || this._ws.removeEventListener;
17893
17894 if (removeListener) {
17895 removeListener.call(this._ws, 'message', this.__postponeTimeoutTimer);
17896 removeListener.call(this._ws, 'pong', this.__postponeTimeoutTimer);
17897
17898 this._clearTimeoutTimers();
17899 }
17900
17901 if (this._heartbeatTimer) {
17902 clearInterval(this._heartbeatTimer);
17903 }
17904 };
17905
17906 _proto._handleClose = function _handleClose(event) {
17907 debug$3("ws closed [".concat(event.code, "] ").concat(event.reason)); // socket closed manually, ignore close event.
17908
17909 if (this.isFinished()) return;
17910 this.handleClose(event);
17911 };
17912
17913 _proto.handleClose = function handleClose() {
17914 // reconnect
17915 this.disconnect();
17916 } // jsdoc-ignore-start
17917 ;
17918
17919 _proto. // jsdoc-ignore-end
17920 send = function send(data) {
17921 debug$3('send', data);
17922
17923 this._ws.send(data);
17924 };
17925
17926 _proto._handleMessage = function _handleMessage(event) {
17927 debug$3('message', event.data);
17928 this.handleMessage(event.data);
17929 };
17930
17931 _proto.handleMessage = function handleMessage(message) {
17932 this.emit(MESSAGE, message);
17933 };
17934
17935 return WebSocketPlus;
17936 }(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);
17937 stateMachine.create({
17938 target: WebSocketPlus.prototype,
17939 initial: {
17940 state: 'initialized',
17941 event: 'init',
17942 defer: true
17943 },
17944 terminal: 'closed',
17945 events: [{
17946 name: 'open',
17947 from: 'initialized',
17948 to: 'connected'
17949 }, {
17950 name: 'disconnect',
17951 from: 'connected',
17952 to: 'disconnected'
17953 }, {
17954 name: 'retry',
17955 from: 'disconnected',
17956 to: 'reconnecting'
17957 }, {
17958 name: 'fail',
17959 from: 'reconnecting',
17960 to: 'disconnected'
17961 }, {
17962 name: 'reconnect',
17963 from: 'reconnecting',
17964 to: 'connected'
17965 }, {
17966 name: 'pause',
17967 from: ['connected', 'disconnected', 'reconnecting'],
17968 to: 'offline'
17969 }, {}, {
17970 name: 'resume',
17971 from: 'offline',
17972 to: 'disconnected'
17973 }, {
17974 name: 'close',
17975 from: ['connected', 'disconnected', 'reconnecting', 'offline'],
17976 to: 'closed'
17977 }, {
17978 name: 'throw',
17979 from: '*',
17980 to: 'error'
17981 }]
17982 });
17983
17984 var error = Object.freeze({
17985 1000: {
17986 name: 'CLOSE_NORMAL'
17987 },
17988 1006: {
17989 name: 'CLOSE_ABNORMAL'
17990 },
17991 4100: {
17992 name: 'APP_NOT_AVAILABLE',
17993 message: 'App not exists or realtime message service is disabled.'
17994 },
17995 4102: {
17996 name: 'SIGNATURE_FAILED',
17997 message: 'Login signature mismatch.'
17998 },
17999 4103: {
18000 name: 'INVALID_LOGIN',
18001 message: 'Malformed clientId.'
18002 },
18003 4105: {
18004 name: 'SESSION_REQUIRED',
18005 message: 'Message sent before session opened.'
18006 },
18007 4107: {
18008 name: 'READ_TIMEOUT'
18009 },
18010 4108: {
18011 name: 'LOGIN_TIMEOUT'
18012 },
18013 4109: {
18014 name: 'FRAME_TOO_LONG'
18015 },
18016 4110: {
18017 name: 'INVALID_ORIGIN',
18018 message: 'Access denied by domain whitelist.'
18019 },
18020 4111: {
18021 name: 'SESSION_CONFLICT'
18022 },
18023 4112: {
18024 name: 'SESSION_TOKEN_EXPIRED'
18025 },
18026 4113: {
18027 name: 'APP_QUOTA_EXCEEDED',
18028 message: 'The daily active users limit exceeded.'
18029 },
18030 4116: {
18031 name: 'MESSAGE_SENT_QUOTA_EXCEEDED',
18032 message: 'Command sent too fast.'
18033 },
18034 4200: {
18035 name: 'INTERNAL_ERROR',
18036 message: 'Internal error, please contact LeanCloud for support.'
18037 },
18038 4301: {
18039 name: 'CONVERSATION_API_FAILED',
18040 message: 'Upstream Conversatoin API failed, see error.detail for details.'
18041 },
18042 4302: {
18043 name: 'CONVERSATION_SIGNATURE_FAILED',
18044 message: 'Conversation action signature mismatch.'
18045 },
18046 4303: {
18047 name: 'CONVERSATION_NOT_FOUND'
18048 },
18049 4304: {
18050 name: 'CONVERSATION_FULL'
18051 },
18052 4305: {
18053 name: 'CONVERSATION_REJECTED_BY_APP',
18054 message: 'Conversation action rejected by hook.'
18055 },
18056 4306: {
18057 name: 'CONVERSATION_UPDATE_FAILED'
18058 },
18059 4307: {
18060 name: 'CONVERSATION_READ_ONLY'
18061 },
18062 4308: {
18063 name: 'CONVERSATION_NOT_ALLOWED'
18064 },
18065 4309: {
18066 name: 'CONVERSATION_UPDATE_REJECTED',
18067 message: 'Conversation update rejected because the client is not a member.'
18068 },
18069 4310: {
18070 name: 'CONVERSATION_QUERY_FAILED',
18071 message: 'Conversation query failed because it is too expansive.'
18072 },
18073 4311: {
18074 name: 'CONVERSATION_LOG_FAILED'
18075 },
18076 4312: {
18077 name: 'CONVERSATION_LOG_REJECTED',
18078 message: 'Message query rejected because the client is not a member of the conversation.'
18079 },
18080 4313: {
18081 name: 'SYSTEM_CONVERSATION_REQUIRED'
18082 },
18083 4314: {
18084 name: 'NORMAL_CONVERSATION_REQUIRED'
18085 },
18086 4315: {
18087 name: 'CONVERSATION_BLACKLISTED',
18088 message: 'Blacklisted in the conversation.'
18089 },
18090 4316: {
18091 name: 'TRANSIENT_CONVERSATION_REQUIRED'
18092 },
18093 4317: {
18094 name: 'CONVERSATION_MEMBERSHIP_REQUIRED'
18095 },
18096 4318: {
18097 name: 'CONVERSATION_API_QUOTA_EXCEEDED',
18098 message: 'LeanCloud API quota exceeded. You may upgrade your plan.'
18099 },
18100 4323: {
18101 name: 'TEMPORARY_CONVERSATION_EXPIRED',
18102 message: 'Temporary conversation expired or does not exist.'
18103 },
18104 4401: {
18105 name: 'INVALID_MESSAGING_TARGET',
18106 message: 'Conversation does not exist or client is not a member.'
18107 },
18108 4402: {
18109 name: 'MESSAGE_REJECTED_BY_APP',
18110 message: 'Message rejected by hook.'
18111 },
18112 4403: {
18113 name: 'MESSAGE_OWNERSHIP_REQUIRED'
18114 },
18115 4404: {
18116 name: 'MESSAGE_NOT_FOUND'
18117 },
18118 4405: {
18119 name: 'MESSAGE_UPDATE_REJECTED_BY_APP',
18120 message: 'Message update rejected by hook.'
18121 },
18122 4406: {
18123 name: 'MESSAGE_EDIT_DISABLED'
18124 },
18125 4407: {
18126 name: 'MESSAGE_RECALL_DISABLED'
18127 },
18128 5130: {
18129 name: 'OWNER_PROMOTION_NOT_ALLOWED',
18130 message: "Updating a member's role to owner is not allowed."
18131 }
18132 });
18133 var ErrorCode = Object.freeze(Object.keys(error).reduce(function (result, code) {
18134 return Object.assign(result, _defineProperty({}, error[code].name, Number(code)));
18135 }, {}));
18136 var createError = function createError(_ref) {
18137 var code = _ref.code,
18138 reason = _ref.reason,
18139 appCode = _ref.appCode,
18140 detail = _ref.detail,
18141 errorMessage = _ref.error;
18142 var message = reason || detail || errorMessage;
18143 var name = reason;
18144
18145 if (!message && error[code]) {
18146 name = error[code].name;
18147 message = error[code].message || name;
18148 }
18149
18150 if (!message) {
18151 message = "Unknow Error: ".concat(code);
18152 }
18153
18154 var err = new Error(message);
18155 return Object.assign(err, {
18156 code: code,
18157 appCode: appCode,
18158 detail: detail,
18159 name: name
18160 });
18161 };
18162
18163 var debug$4 = browser('LC:Connection');
18164 var COMMAND_TIMEOUT = 20000;
18165 var EXPIRE = Symbol('expire');
18166
18167 var Connection =
18168 /*#__PURE__*/
18169 function (_WebSocketPlus) {
18170 _inheritsLoose(Connection, _WebSocketPlus);
18171
18172 function Connection(getUrl, _ref) {
18173 var _this;
18174
18175 var format = _ref.format,
18176 version = _ref.version;
18177 debug$4('initializing Connection');
18178 var protocolString = "lc.".concat(format, ".").concat(version);
18179
18180 if (!isWeapp) {
18181 _this = _WebSocketPlus.call(this, getUrl, protocolString) || this;
18182 } else {
18183 _this = _WebSocketPlus.call(this, getUrl().then(function (urls) {
18184 return urls.map(function (url) {
18185 return "".concat(url).concat(url.indexOf('?') === -1 ? '?' : '&', "subprotocol=").concat(encodeURIComponent(protocolString));
18186 });
18187 })) || this;
18188 }
18189
18190 _this._protocalFormat = format;
18191 _this._commands = {};
18192 _this._serialId = 0;
18193 return _assertThisInitialized(_this);
18194 }
18195
18196 var _proto = Connection.prototype;
18197
18198 _proto.send =
18199 /*#__PURE__*/
18200 function () {
18201 var _send = _asyncToGenerator(
18202 /*#__PURE__*/
18203 regenerator.mark(function _callee(command) {
18204 var _this2 = this;
18205
18206 var waitingForRespond,
18207 serialId,
18208 message,
18209 _args = arguments;
18210 return regenerator.wrap(function _callee$(_context) {
18211 while (1) {
18212 switch (_context.prev = _context.next) {
18213 case 0:
18214 waitingForRespond = _args.length > 1 && _args[1] !== undefined ? _args[1] : true;
18215
18216 if (waitingForRespond) {
18217 this._serialId += 1;
18218 serialId = this._serialId;
18219 command.i = serialId; // eslint-disable-line no-param-reassign
18220 }
18221
18222 if (debug$4.enabled) debug$4('↑ %O sent', trim(command));
18223
18224 if (this._protocalFormat === 'proto2base64') {
18225 message = command.toBase64();
18226 } else if (command.toArrayBuffer) {
18227 message = command.toArrayBuffer();
18228 }
18229
18230 if (message) {
18231 _context.next = 6;
18232 break;
18233 }
18234
18235 throw new TypeError("".concat(command, " is not a GenericCommand"));
18236
18237 case 6:
18238 _WebSocketPlus.prototype.send.call(this, message);
18239
18240 if (waitingForRespond) {
18241 _context.next = 9;
18242 break;
18243 }
18244
18245 return _context.abrupt("return", undefined);
18246
18247 case 9:
18248 return _context.abrupt("return", new Promise(function (resolve, reject) {
18249 _this2._commands[serialId] = {
18250 resolve: resolve,
18251 reject: reject,
18252 timeout: setTimeout(function () {
18253 if (_this2._commands[serialId]) {
18254 if (debug$4.enabled) debug$4('✗ %O timeout', trim(command));
18255 reject(createError({
18256 error: "Command Timeout [cmd:".concat(command.cmd, " op:").concat(command.op, "]"),
18257 name: 'COMMAND_TIMEOUT'
18258 }));
18259 delete _this2._commands[serialId];
18260 }
18261 }, COMMAND_TIMEOUT)
18262 };
18263 }));
18264
18265 case 10:
18266 case "end":
18267 return _context.stop();
18268 }
18269 }
18270 }, _callee, this);
18271 }));
18272
18273 function send(_x) {
18274 return _send.apply(this, arguments);
18275 }
18276
18277 return send;
18278 }();
18279
18280 _proto.handleMessage = function handleMessage(msg) {
18281 var message;
18282
18283 try {
18284 message = GenericCommand.decode(msg);
18285 if (debug$4.enabled) debug$4('↓ %O received', trim(message));
18286 } catch (e) {
18287 console.warn('Decode message failed:', e.message, msg);
18288 return;
18289 }
18290
18291 var serialId = message.i;
18292
18293 if (serialId) {
18294 if (this._commands[serialId]) {
18295 clearTimeout(this._commands[serialId].timeout);
18296
18297 if (message.cmd === CommandType.error) {
18298 this._commands[serialId].reject(createError(message.errorMessage));
18299 } else {
18300 this._commands[serialId].resolve(message);
18301 }
18302
18303 delete this._commands[serialId];
18304 } else {
18305 console.warn("Unexpected command received with serialId [".concat(serialId, "],\n which have timed out or never been requested."));
18306 }
18307 } else {
18308 switch (message.cmd) {
18309 case CommandType.error:
18310 {
18311 this.emit(ERROR, createError(message.errorMessage));
18312 return;
18313 }
18314
18315 case CommandType.goaway:
18316 {
18317 this.emit(EXPIRE);
18318 return;
18319 }
18320
18321 default:
18322 {
18323 this.emit(MESSAGE, message);
18324 }
18325 }
18326 }
18327 };
18328
18329 _proto.ping = function ping() {
18330 return this.send(new GenericCommand({
18331 cmd: CommandType.echo
18332 })).catch(function (error) {
18333 return debug$4('ping failed:', error);
18334 });
18335 };
18336
18337 return Connection;
18338 }(WebSocketPlus);
18339
18340 var applyDecorators = function applyDecorators(decorators, target) {
18341 if (decorators) {
18342 decorators.forEach(function (decorator) {
18343 try {
18344 decorator(target);
18345 } catch (error) {
18346 if (decorator._pluginName) {
18347 error.message += "[".concat(decorator._pluginName, "]");
18348 }
18349
18350 throw error;
18351 }
18352 });
18353 }
18354 };
18355 var applyDispatcher = function applyDispatcher(dispatchers, payload) {
18356 return ensureArray(dispatchers).reduce(function (resultPromise, dispatcher) {
18357 return resultPromise.then(function (shouldDispatch) {
18358 return shouldDispatch === false ? false : dispatcher.apply(void 0, _toConsumableArray(payload));
18359 }).catch(function (error) {
18360 if (dispatcher._pluginName) {
18361 // eslint-disable-next-line no-param-reassign
18362 error.message += "[".concat(dispatcher._pluginName, "]");
18363 }
18364
18365 throw error;
18366 });
18367 }, Promise.resolve(true));
18368 };
18369
18370 var version = "5.0.0-beta.0";
18371
18372 var debug$5 = browser('LC:Realtime');
18373 var debugRequest = browser('LC:request');
18374 var routerCache = new Cache('push-router');
18375
18376 var Realtime =
18377 /*#__PURE__*/
18378 function (_EventEmitter) {
18379 _inheritsLoose(Realtime, _EventEmitter);
18380
18381 /**
18382 * @extends EventEmitter
18383 * @param {Object} options
18384 * @param {String} options.appId
18385 * @param {String} options.appKey (since 4.0.0)
18386 * @param {String|Object} [options.server] 指定服务器域名,中国节点应用此参数必填(since 4.0.0)
18387 * @param {Boolean} [options.pushOfflineMessages=false] 启用推送离线消息模式(默认为发送未读消息通知模式)
18388 * @param {Boolean} [options.noBinary=false] 设置 WebSocket 使用字符串格式收发消息(默认为二进制格式)。
18389 * 适用于 WebSocket 实现不支持二进制数据格式的情况
18390 * @param {Boolean} [options.ssl=true] 使用 wss 进行连接
18391 * @param {String|String[]} [options.RTMServers] 指定私有部署的 RTM 服务器地址(since 4.0.0)
18392 * @param {Plugin[]} [options.plugins] 加载插件(since 3.1.0)
18393 */
18394 function Realtime(_ref) {
18395 var _this2;
18396
18397 var plugins = _ref.plugins,
18398 options = _objectWithoutProperties(_ref, ["plugins"]);
18399
18400 debug$5('initializing Realtime %s %O', version, options);
18401 _this2 = _EventEmitter.call(this) || this;
18402
18403 if (typeof options.appId !== 'string') {
18404 throw new TypeError("appId [".concat(options.appId, "] is not a string"));
18405 }
18406
18407 if (typeof options.appKey !== 'string') {
18408 throw new TypeError("appKey [".concat(options.appKey, "] is not a string"));
18409 }
18410
18411 if (isCNApp(options.appId)) {
18412 if (!options.server) {
18413 throw new TypeError("server option is required for apps from CN region");
18414 }
18415 }
18416
18417 _this2._options = Object.assign({
18418 appId: undefined,
18419 appKey: undefined,
18420 pushOfflineMessages: false,
18421 noBinary: false,
18422 ssl: true,
18423 RTMServerName: process.env.RTM_SERVER_NAME // undocumented on purpose, internal use only
18424
18425 }, options);
18426 _this2._cache = new Cache('endpoints');
18427
18428 var _this = internal(_assertThisInitialized(_this2));
18429
18430 _this.clients = new Set();
18431 _this.pendingClients = new Set();
18432 var mergedPlugins = [].concat(_toConsumableArray(ensureArray(Realtime.__preRegisteredPlugins)), _toConsumableArray(ensureArray(plugins)));
18433 debug$5('Using plugins %o', mergedPlugins.map(function (plugin) {
18434 return plugin.name;
18435 }));
18436 _this2._plugins = mergedPlugins.reduce(function (result, plugin) {
18437 // eslint-disable-next-line no-restricted-syntax
18438 for (var hook in plugin) {
18439 if ({}.hasOwnProperty.call(plugin, hook) && hook !== 'name') {
18440 if (plugin.name) {
18441 ensureArray(plugin[hook]).forEach(function (value) {
18442 // eslint-disable-next-line no-param-reassign
18443 value._pluginName = plugin.name;
18444 });
18445 } // eslint-disable-next-line no-param-reassign
18446
18447
18448 result[hook] = ensureArray(result[hook]).concat(plugin[hook]);
18449 }
18450 }
18451
18452 return result;
18453 }, {}); // onRealtimeCreate hook
18454
18455 applyDecorators(_this2._plugins.onRealtimeCreate, _assertThisInitialized(_this2));
18456 return _this2;
18457 }
18458
18459 var _proto = Realtime.prototype;
18460
18461 _proto._request =
18462 /*#__PURE__*/
18463 function () {
18464 var _request2 = _asyncToGenerator(
18465 /*#__PURE__*/
18466 regenerator.mark(function _callee(_ref2) {
18467 var method, _ref2$version, version, path, query, headers, _ref2$data, data, _this$_options, appId, server, _ref3, api, url;
18468
18469 return regenerator.wrap(function _callee$(_context) {
18470 while (1) {
18471 switch (_context.prev = _context.next) {
18472 case 0:
18473 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;
18474 _this$_options = this._options, appId = _this$_options.appId, server = _this$_options.server;
18475 _context.next = 4;
18476 return this.constructor._getServerUrls({
18477 appId: appId,
18478 server: server
18479 });
18480
18481 case 4:
18482 _ref3 = _context.sent;
18483 api = _ref3.api;
18484 url = "".concat(api, "/").concat(version).concat(path);
18485 debugRequest('Req: %O %O %O', method, url, {
18486 query: query,
18487 headers: headers,
18488 data: data
18489 });
18490 return _context.abrupt("return", client(method, url).set(_objectSpread({
18491 'X-LC-Id': this._options.appId,
18492 'X-LC-Key': this._options.appKey
18493 }, headers)).query(query).send(data).then(function (response) {
18494 debugRequest('Res: %O %O %O', url, response.status, response.body);
18495 return response.body;
18496 }, function (error) {
18497 debugRequest('Error: %O %O %O', url, error.response.status, error.response.body);
18498
18499 if (error.response && error.response.body && error.response.body.code) {
18500 throw createError(error.response.body);
18501 }
18502
18503 throw error;
18504 }));
18505
18506 case 9:
18507 case "end":
18508 return _context.stop();
18509 }
18510 }
18511 }, _callee, this);
18512 }));
18513
18514 function _request(_x) {
18515 return _request2.apply(this, arguments);
18516 }
18517
18518 return _request;
18519 }();
18520
18521 _proto._open = function _open() {
18522 var _this3 = this;
18523
18524 if (this._openPromise) return this._openPromise;
18525 var format = 'protobuf2';
18526
18527 if (this._options.noBinary) {
18528 // 不发送 binary data,fallback to base64 string
18529 format = 'proto2base64';
18530 }
18531
18532 var version = 3;
18533
18534 if (this._options.pushOfflineMessages) {
18535 // 不推送离线消息,而是发送对话的未读通知
18536 version = 1;
18537 }
18538
18539 var protocol = {
18540 format: format,
18541 version: version
18542 };
18543 this._openPromise = new Promise(function (resolve, reject) {
18544 debug$5('No connection established, create a new one.');
18545 var connection = new Connection(function () {
18546 return _this3._getRTMServers(_this3._options);
18547 }, protocol);
18548 connection.on(OPEN$1, function () {
18549 return resolve(connection);
18550 }).on(ERROR, reject).on(EXPIRE,
18551 /*#__PURE__*/
18552 _asyncToGenerator(
18553 /*#__PURE__*/
18554 regenerator.mark(function _callee2() {
18555 return regenerator.wrap(function _callee2$(_context2) {
18556 while (1) {
18557 switch (_context2.prev = _context2.next) {
18558 case 0:
18559 debug$5('Connection expired. Refresh endpoints.');
18560
18561 _this3._cache.set('endpoints', null, 0);
18562
18563 _context2.next = 4;
18564 return _this3._getRTMServers(_this3._options);
18565
18566 case 4:
18567 connection.urls = _context2.sent;
18568 connection.disconnect();
18569
18570 case 6:
18571 case "end":
18572 return _context2.stop();
18573 }
18574 }
18575 }, _callee2, this);
18576 }))).on(MESSAGE, _this3._dispatchCommand.bind(_this3));
18577 /**
18578 * 连接断开。
18579 * 连接断开可能是因为 SDK 进入了离线状态(see {@link Realtime#event:OFFLINE}),或长时间没有收到服务器心跳。
18580 * 连接断开后所有的网络操作都会失败,请在连接断开后禁用相关的 UI 元素。
18581 * @event Realtime#DISCONNECT
18582 */
18583
18584 /**
18585 * 计划在一段时间后尝试重新连接
18586 * @event Realtime#SCHEDULE
18587 * @param {Number} attempt 尝试重连的次数
18588 * @param {Number} delay 延迟的毫秒数
18589 */
18590
18591 /**
18592 * 正在尝试重新连接
18593 * @event Realtime#RETRY
18594 * @param {Number} attempt 尝试重连的次数
18595 */
18596
18597 /**
18598 * 连接恢复正常。
18599 * 请重新启用在 {@link Realtime#event:DISCONNECT} 事件中禁用的相关 UI 元素
18600 * @event Realtime#RECONNECT
18601 */
18602
18603 /**
18604 * 客户端连接断开
18605 * @event IMClient#DISCONNECT
18606 * @see Realtime#event:DISCONNECT
18607 * @since 3.2.0
18608 */
18609
18610 /**
18611 * 计划在一段时间后尝试重新连接
18612 * @event IMClient#SCHEDULE
18613 * @param {Number} attempt 尝试重连的次数
18614 * @param {Number} delay 延迟的毫秒数
18615 * @since 3.2.0
18616 */
18617
18618 /**
18619 * 正在尝试重新连接
18620 * @event IMClient#RETRY
18621 * @param {Number} attempt 尝试重连的次数
18622 * @since 3.2.0
18623 */
18624
18625 /**
18626 * 客户端进入离线状态。
18627 * 这通常意味着网络已断开,或者 {@link Realtime#pause} 被调用
18628 * @event Realtime#OFFLINE
18629 * @since 3.4.0
18630 */
18631
18632 /**
18633 * 客户端恢复在线状态
18634 * 这通常意味着网络已恢复,或者 {@link Realtime#resume} 被调用
18635 * @event Realtime#ONLINE
18636 * @since 3.4.0
18637 */
18638
18639 /**
18640 * 进入离线状态。
18641 * 这通常意味着网络已断开,或者 {@link Realtime#pause} 被调用
18642 * @event IMClient#OFFLINE
18643 * @since 3.4.0
18644 */
18645
18646 /**
18647 * 恢复在线状态
18648 * 这通常意味着网络已恢复,或者 {@link Realtime#resume} 被调用
18649 * @event IMClient#ONLINE
18650 * @since 3.4.0
18651 */
18652 // event proxy
18653
18654 [DISCONNECT, RECONNECT, RETRY, SCHEDULE, OFFLINE, ONLINE].forEach(function (event) {
18655 return connection.on(event, function () {
18656 for (var _len = arguments.length, payload = new Array(_len), _key = 0; _key < _len; _key++) {
18657 payload[_key] = arguments[_key];
18658 }
18659
18660 debug$5("".concat(event, " event emitted. %o"), payload);
18661
18662 _this3.emit.apply(_this3, [event].concat(payload));
18663
18664 if (event !== RECONNECT) {
18665 internal(_this3).clients.forEach(function (client) {
18666 client.emit.apply(client, [event].concat(payload));
18667 });
18668 }
18669 });
18670 }); // override handleClose
18671
18672 connection.handleClose = function handleClose(event) {
18673 var isFatal = [ErrorCode.APP_NOT_AVAILABLE, ErrorCode.INVALID_LOGIN, ErrorCode.INVALID_ORIGIN].some(function (errorCode) {
18674 return errorCode === event.code;
18675 });
18676
18677 if (isFatal) {
18678 // in these cases, SDK should throw.
18679 this.throw(createError(event));
18680 } else {
18681 // reconnect
18682 this.disconnect();
18683 }
18684 };
18685
18686 internal(_this3).connection = connection;
18687 });
18688 return this._openPromise;
18689 };
18690
18691 _proto._getRTMServers =
18692 /*#__PURE__*/
18693 function () {
18694 var _getRTMServers2 = _asyncToGenerator(
18695 /*#__PURE__*/
18696 regenerator.mark(function _callee3(options) {
18697 var info, cachedEndPoints;
18698 return regenerator.wrap(function _callee3$(_context3) {
18699 while (1) {
18700 switch (_context3.prev = _context3.next) {
18701 case 0:
18702 if (!options.RTMServers) {
18703 _context3.next = 2;
18704 break;
18705 }
18706
18707 return _context3.abrupt("return", shuffle_1(ensureArray(options.RTMServers)));
18708
18709 case 2:
18710 cachedEndPoints = this._cache.get('endpoints');
18711
18712 if (!cachedEndPoints) {
18713 _context3.next = 9;
18714 break;
18715 }
18716
18717 _context3.next = 6;
18718 return cachedEndPoints;
18719
18720 case 6:
18721 info = _context3.sent;
18722 _context3.next = 13;
18723 break;
18724
18725 case 9:
18726 _context3.next = 11;
18727 return this.constructor._fetchRTMServers(options);
18728
18729 case 11:
18730 info = _context3.sent;
18731
18732 this._cache.set('endpoints', info, info.ttl * 1000);
18733
18734 case 13:
18735 debug$5('endpoint info: %O', info);
18736 return _context3.abrupt("return", [info.server, info.secondary]);
18737
18738 case 15:
18739 case "end":
18740 return _context3.stop();
18741 }
18742 }
18743 }, _callee3, this);
18744 }));
18745
18746 function _getRTMServers(_x2) {
18747 return _getRTMServers2.apply(this, arguments);
18748 }
18749
18750 return _getRTMServers;
18751 }();
18752
18753 Realtime._getServerUrls =
18754 /*#__PURE__*/
18755 function () {
18756 var _getServerUrls2 = _asyncToGenerator(
18757 /*#__PURE__*/
18758 regenerator.mark(function _callee4(_ref5) {
18759 var appId, server, cachedRouter, defaultProtocol;
18760 return regenerator.wrap(function _callee4$(_context4) {
18761 while (1) {
18762 switch (_context4.prev = _context4.next) {
18763 case 0:
18764 appId = _ref5.appId, server = _ref5.server;
18765 debug$5('fetch server urls');
18766
18767 if (!server) {
18768 _context4.next = 6;
18769 break;
18770 }
18771
18772 if (!(typeof server !== 'string')) {
18773 _context4.next = 5;
18774 break;
18775 }
18776
18777 return _context4.abrupt("return", server);
18778
18779 case 5:
18780 return _context4.abrupt("return", {
18781 RTMRouter: server,
18782 api: server
18783 });
18784
18785 case 6:
18786 cachedRouter = routerCache.get(appId);
18787
18788 if (!cachedRouter) {
18789 _context4.next = 9;
18790 break;
18791 }
18792
18793 return _context4.abrupt("return", cachedRouter);
18794
18795 case 9:
18796 defaultProtocol = 'https://';
18797 return _context4.abrupt("return", client.get('https://app-router.com/2/route').query({
18798 appId: appId
18799 }).timeout(20000).then(function (res) {
18800 return res.body;
18801 }).then(tap(debug$5)).then(function (_ref6) {
18802 var RTMRouterServer = _ref6.rtm_router_server,
18803 APIServer = _ref6.api_server,
18804 _ref6$ttl = _ref6.ttl,
18805 ttl = _ref6$ttl === void 0 ? 3600 : _ref6$ttl;
18806
18807 if (!RTMRouterServer) {
18808 throw new Error('rtm router not exists');
18809 }
18810
18811 var serverUrls = {
18812 RTMRouter: "".concat(defaultProtocol).concat(RTMRouterServer),
18813 api: "".concat(defaultProtocol).concat(APIServer)
18814 };
18815 routerCache.set(appId, serverUrls, ttl * 1000);
18816 return serverUrls;
18817 }).catch(function () {
18818 var id = appId.slice(0, 8).toLowerCase();
18819 var domain = 'lncldglobal.com';
18820 return {
18821 RTMRouter: "".concat(defaultProtocol).concat(id, ".rtm.").concat(domain),
18822 api: "".concat(defaultProtocol).concat(id, ".api.").concat(domain)
18823 };
18824 }));
18825
18826 case 11:
18827 case "end":
18828 return _context4.stop();
18829 }
18830 }
18831 }, _callee4, this);
18832 }));
18833
18834 function _getServerUrls(_x3) {
18835 return _getServerUrls2.apply(this, arguments);
18836 }
18837
18838 return _getServerUrls;
18839 }();
18840
18841 Realtime._fetchRTMServers = function _fetchRTMServers(_ref7) {
18842 var appId = _ref7.appId,
18843 ssl = _ref7.ssl,
18844 server = _ref7.server,
18845 RTMServerName = _ref7.RTMServerName;
18846 debug$5('fetch endpoint info');
18847 return this._getServerUrls({
18848 appId: appId,
18849 server: server
18850 }).then(tap(debug$5)).then(function (_ref8) {
18851 var RTMRouter = _ref8.RTMRouter;
18852 return client.get("".concat(RTMRouter, "/v1/route")).query({
18853 appId: appId,
18854 secure: ssl,
18855 features: isWeapp ? 'wechat' : undefined,
18856 server: RTMServerName,
18857 _t: Date.now()
18858 }).timeout(20000).then(function (res) {
18859 return res.body;
18860 }).then(tap(debug$5));
18861 });
18862 };
18863
18864 _proto._close = function _close() {
18865 if (this._openPromise) {
18866 this._openPromise.then(function (connection) {
18867 return connection.close();
18868 });
18869 }
18870
18871 delete this._openPromise;
18872 }
18873 /**
18874 * 手动进行重连。
18875 * SDK 在网络出现异常时会自动按照一定的时间间隔尝试重连,调用该方法会立即尝试重连并重置重连尝试计数器。
18876 * 只能在 `SCHEDULE` 事件之后,`RETRY` 事件之前调用,如果当前网络正常或者正在进行重连,调用该方法会抛异常。
18877 */
18878 ;
18879
18880 _proto.retry = function retry() {
18881 var _internal = internal(this),
18882 connection = _internal.connection;
18883
18884 if (!connection) {
18885 throw new Error('no connection established');
18886 }
18887
18888 if (connection.cannot('retry')) {
18889 throw new Error("retrying not allowed when not disconnected. the connection is now ".concat(connection.current));
18890 }
18891
18892 return connection.retry();
18893 }
18894 /**
18895 * 暂停,使 SDK 进入离线状态。
18896 * 你可以在网络断开、应用进入后台等时刻调用该方法让 SDK 进入离线状态,离线状态下不会尝试重连。
18897 * 在浏览器中 SDK 会自动监听网络变化,因此无需手动调用该方法。
18898 *
18899 * @since 3.4.0
18900 * @see Realtime#event:OFFLINE
18901 */
18902 ;
18903
18904 _proto.pause = function pause() {
18905 // 这个方法常常在网络断开、进入后台时被调用,此时 connection 可能没有建立或者已经 close。
18906 // 因此不像 retry,这个方法应该尽可能 loose
18907 var _internal2 = internal(this),
18908 connection = _internal2.connection;
18909
18910 if (!connection) return;
18911 if (connection.can('pause')) connection.pause();
18912 }
18913 /**
18914 * 恢复在线状态。
18915 * 你可以在网络恢复、应用回到前台等时刻调用该方法让 SDK 恢复在线状态,恢复在线状态后 SDK 会开始尝试重连。
18916 *
18917 * @since 3.4.0
18918 * @see Realtime#event:ONLINE
18919 */
18920 ;
18921
18922 _proto.resume = function resume() {
18923 // 与 pause 一样,这个方法应该尽可能 loose
18924 var _internal3 = internal(this),
18925 connection = _internal3.connection;
18926
18927 if (!connection) return;
18928 if (connection.can('resume')) connection.resume();
18929 };
18930
18931 _proto._registerPending = function _registerPending(value) {
18932 internal(this).pendingClients.add(value);
18933 };
18934
18935 _proto._deregisterPending = function _deregisterPending(client) {
18936 internal(this).pendingClients.delete(client);
18937 };
18938
18939 _proto._register = function _register(client) {
18940 internal(this).clients.add(client);
18941 };
18942
18943 _proto._deregister = function _deregister(client) {
18944 var _this = internal(this);
18945
18946 _this.clients.delete(client);
18947
18948 if (_this.clients.size + _this.pendingClients.size === 0) {
18949 this._close();
18950 }
18951 };
18952
18953 _proto._dispatchCommand = function _dispatchCommand(command) {
18954 return applyDispatcher(this._plugins.beforeCommandDispatch, [command, this]).then(function (shouldDispatch) {
18955 // no plugin handled this command
18956 if (shouldDispatch) return debug$5('[WARN] Unexpected message received: %O', trim(command));
18957 return false;
18958 });
18959 };
18960
18961 return Realtime;
18962 }(eventemitter3);
18963
18964 var polyfilledPromise = Promise;
18965
18966 exports.Protocals = message;
18967 exports.Promise = polyfilledPromise;
18968 exports.EventEmitter = eventemitter3;
18969 exports.Realtime = Realtime;
18970 exports.debug = debug$2;
18971
18972 Object.defineProperty(exports, '__esModule', { value: true });
18973
18974}));
18975//# sourceMappingURL=realtime-core-weapp.js.map