UNPKG

921 kBJavaScriptView Raw
1(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.Klic = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/bluebird/js/browser/bluebird.js":[function(require,module,exports){
2(function (process,global){
3/* @preserve
4 * The MIT License (MIT)
5 *
6 * Copyright (c) 2013-2015 Petka Antonov
7 *
8 * Permission is hereby granted, free of charge, to any person obtaining a copy
9 * of this software and associated documentation files (the "Software"), to deal
10 * in the Software without restriction, including without limitation the rights
11 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12 * copies of the Software, and to permit persons to whom the Software is
13 * furnished to do so, subject to the following conditions:
14 *
15 * The above copyright notice and this permission notice shall be included in
16 * all copies or substantial portions of the Software.
17 *
18 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
24 * THE SOFTWARE.
25 *
26 */
27/**
28 * bluebird build version 3.4.1
29 * Features enabled: core, race, call_get, generators, map, nodeify, promisify, props, reduce, settle, some, using, timers, filter, any, each
30*/
31!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.Promise=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof _dereq_=="function"&&_dereq_;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof _dereq_=="function"&&_dereq_;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
32"use strict";
33module.exports = function(Promise) {
34var SomePromiseArray = Promise._SomePromiseArray;
35function any(promises) {
36 var ret = new SomePromiseArray(promises);
37 var promise = ret.promise();
38 ret.setHowMany(1);
39 ret.setUnwrap();
40 ret.init();
41 return promise;
42}
43
44Promise.any = function (promises) {
45 return any(promises);
46};
47
48Promise.prototype.any = function () {
49 return any(this);
50};
51
52};
53
54},{}],2:[function(_dereq_,module,exports){
55"use strict";
56var firstLineError;
57try {throw new Error(); } catch (e) {firstLineError = e;}
58var schedule = _dereq_("./schedule");
59var Queue = _dereq_("./queue");
60var util = _dereq_("./util");
61
62function Async() {
63 this._customScheduler = false;
64 this._isTickUsed = false;
65 this._lateQueue = new Queue(16);
66 this._normalQueue = new Queue(16);
67 this._haveDrainedQueues = false;
68 this._trampolineEnabled = true;
69 var self = this;
70 this.drainQueues = function () {
71 self._drainQueues();
72 };
73 this._schedule = schedule;
74}
75
76Async.prototype.setScheduler = function(fn) {
77 var prev = this._schedule;
78 this._schedule = fn;
79 this._customScheduler = true;
80 return prev;
81};
82
83Async.prototype.hasCustomScheduler = function() {
84 return this._customScheduler;
85};
86
87Async.prototype.enableTrampoline = function() {
88 this._trampolineEnabled = true;
89};
90
91Async.prototype.disableTrampolineIfNecessary = function() {
92 if (util.hasDevTools) {
93 this._trampolineEnabled = false;
94 }
95};
96
97Async.prototype.haveItemsQueued = function () {
98 return this._isTickUsed || this._haveDrainedQueues;
99};
100
101
102Async.prototype.fatalError = function(e, isNode) {
103 if (isNode) {
104 process.stderr.write("Fatal " + (e instanceof Error ? e.stack : e) +
105 "\n");
106 process.exit(2);
107 } else {
108 this.throwLater(e);
109 }
110};
111
112Async.prototype.throwLater = function(fn, arg) {
113 if (arguments.length === 1) {
114 arg = fn;
115 fn = function () { throw arg; };
116 }
117 if (typeof setTimeout !== "undefined") {
118 setTimeout(function() {
119 fn(arg);
120 }, 0);
121 } else try {
122 this._schedule(function() {
123 fn(arg);
124 });
125 } catch (e) {
126 throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/MqrFmX\u000a");
127 }
128};
129
130function AsyncInvokeLater(fn, receiver, arg) {
131 this._lateQueue.push(fn, receiver, arg);
132 this._queueTick();
133}
134
135function AsyncInvoke(fn, receiver, arg) {
136 this._normalQueue.push(fn, receiver, arg);
137 this._queueTick();
138}
139
140function AsyncSettlePromises(promise) {
141 this._normalQueue._pushOne(promise);
142 this._queueTick();
143}
144
145if (!util.hasDevTools) {
146 Async.prototype.invokeLater = AsyncInvokeLater;
147 Async.prototype.invoke = AsyncInvoke;
148 Async.prototype.settlePromises = AsyncSettlePromises;
149} else {
150 Async.prototype.invokeLater = function (fn, receiver, arg) {
151 if (this._trampolineEnabled) {
152 AsyncInvokeLater.call(this, fn, receiver, arg);
153 } else {
154 this._schedule(function() {
155 setTimeout(function() {
156 fn.call(receiver, arg);
157 }, 100);
158 });
159 }
160 };
161
162 Async.prototype.invoke = function (fn, receiver, arg) {
163 if (this._trampolineEnabled) {
164 AsyncInvoke.call(this, fn, receiver, arg);
165 } else {
166 this._schedule(function() {
167 fn.call(receiver, arg);
168 });
169 }
170 };
171
172 Async.prototype.settlePromises = function(promise) {
173 if (this._trampolineEnabled) {
174 AsyncSettlePromises.call(this, promise);
175 } else {
176 this._schedule(function() {
177 promise._settlePromises();
178 });
179 }
180 };
181}
182
183Async.prototype.invokeFirst = function (fn, receiver, arg) {
184 this._normalQueue.unshift(fn, receiver, arg);
185 this._queueTick();
186};
187
188Async.prototype._drainQueue = function(queue) {
189 while (queue.length() > 0) {
190 var fn = queue.shift();
191 if (typeof fn !== "function") {
192 fn._settlePromises();
193 continue;
194 }
195 var receiver = queue.shift();
196 var arg = queue.shift();
197 fn.call(receiver, arg);
198 }
199};
200
201Async.prototype._drainQueues = function () {
202 this._drainQueue(this._normalQueue);
203 this._reset();
204 this._haveDrainedQueues = true;
205 this._drainQueue(this._lateQueue);
206};
207
208Async.prototype._queueTick = function () {
209 if (!this._isTickUsed) {
210 this._isTickUsed = true;
211 this._schedule(this.drainQueues);
212 }
213};
214
215Async.prototype._reset = function () {
216 this._isTickUsed = false;
217};
218
219module.exports = Async;
220module.exports.firstLineError = firstLineError;
221
222},{"./queue":26,"./schedule":29,"./util":36}],3:[function(_dereq_,module,exports){
223"use strict";
224module.exports = function(Promise, INTERNAL, tryConvertToPromise, debug) {
225var calledBind = false;
226var rejectThis = function(_, e) {
227 this._reject(e);
228};
229
230var targetRejected = function(e, context) {
231 context.promiseRejectionQueued = true;
232 context.bindingPromise._then(rejectThis, rejectThis, null, this, e);
233};
234
235var bindingResolved = function(thisArg, context) {
236 if (((this._bitField & 50397184) === 0)) {
237 this._resolveCallback(context.target);
238 }
239};
240
241var bindingRejected = function(e, context) {
242 if (!context.promiseRejectionQueued) this._reject(e);
243};
244
245Promise.prototype.bind = function (thisArg) {
246 if (!calledBind) {
247 calledBind = true;
248 Promise.prototype._propagateFrom = debug.propagateFromFunction();
249 Promise.prototype._boundValue = debug.boundValueFunction();
250 }
251 var maybePromise = tryConvertToPromise(thisArg);
252 var ret = new Promise(INTERNAL);
253 ret._propagateFrom(this, 1);
254 var target = this._target();
255 ret._setBoundTo(maybePromise);
256 if (maybePromise instanceof Promise) {
257 var context = {
258 promiseRejectionQueued: false,
259 promise: ret,
260 target: target,
261 bindingPromise: maybePromise
262 };
263 target._then(INTERNAL, targetRejected, undefined, ret, context);
264 maybePromise._then(
265 bindingResolved, bindingRejected, undefined, ret, context);
266 ret._setOnCancel(maybePromise);
267 } else {
268 ret._resolveCallback(target);
269 }
270 return ret;
271};
272
273Promise.prototype._setBoundTo = function (obj) {
274 if (obj !== undefined) {
275 this._bitField = this._bitField | 2097152;
276 this._boundTo = obj;
277 } else {
278 this._bitField = this._bitField & (~2097152);
279 }
280};
281
282Promise.prototype._isBound = function () {
283 return (this._bitField & 2097152) === 2097152;
284};
285
286Promise.bind = function (thisArg, value) {
287 return Promise.resolve(value).bind(thisArg);
288};
289};
290
291},{}],4:[function(_dereq_,module,exports){
292"use strict";
293var old;
294if (typeof Promise !== "undefined") old = Promise;
295function noConflict() {
296 try { if (Promise === bluebird) Promise = old; }
297 catch (e) {}
298 return bluebird;
299}
300var bluebird = _dereq_("./promise")();
301bluebird.noConflict = noConflict;
302module.exports = bluebird;
303
304},{"./promise":22}],5:[function(_dereq_,module,exports){
305"use strict";
306var cr = Object.create;
307if (cr) {
308 var callerCache = cr(null);
309 var getterCache = cr(null);
310 callerCache[" size"] = getterCache[" size"] = 0;
311}
312
313module.exports = function(Promise) {
314var util = _dereq_("./util");
315var canEvaluate = util.canEvaluate;
316var isIdentifier = util.isIdentifier;
317
318var getMethodCaller;
319var getGetter;
320if (!true) {
321var makeMethodCaller = function (methodName) {
322 return new Function("ensureMethod", " \n\
323 return function(obj) { \n\
324 'use strict' \n\
325 var len = this.length; \n\
326 ensureMethod(obj, 'methodName'); \n\
327 switch(len) { \n\
328 case 1: return obj.methodName(this[0]); \n\
329 case 2: return obj.methodName(this[0], this[1]); \n\
330 case 3: return obj.methodName(this[0], this[1], this[2]); \n\
331 case 0: return obj.methodName(); \n\
332 default: \n\
333 return obj.methodName.apply(obj, this); \n\
334 } \n\
335 }; \n\
336 ".replace(/methodName/g, methodName))(ensureMethod);
337};
338
339var makeGetter = function (propertyName) {
340 return new Function("obj", " \n\
341 'use strict'; \n\
342 return obj.propertyName; \n\
343 ".replace("propertyName", propertyName));
344};
345
346var getCompiled = function(name, compiler, cache) {
347 var ret = cache[name];
348 if (typeof ret !== "function") {
349 if (!isIdentifier(name)) {
350 return null;
351 }
352 ret = compiler(name);
353 cache[name] = ret;
354 cache[" size"]++;
355 if (cache[" size"] > 512) {
356 var keys = Object.keys(cache);
357 for (var i = 0; i < 256; ++i) delete cache[keys[i]];
358 cache[" size"] = keys.length - 256;
359 }
360 }
361 return ret;
362};
363
364getMethodCaller = function(name) {
365 return getCompiled(name, makeMethodCaller, callerCache);
366};
367
368getGetter = function(name) {
369 return getCompiled(name, makeGetter, getterCache);
370};
371}
372
373function ensureMethod(obj, methodName) {
374 var fn;
375 if (obj != null) fn = obj[methodName];
376 if (typeof fn !== "function") {
377 var message = "Object " + util.classString(obj) + " has no method '" +
378 util.toString(methodName) + "'";
379 throw new Promise.TypeError(message);
380 }
381 return fn;
382}
383
384function caller(obj) {
385 var methodName = this.pop();
386 var fn = ensureMethod(obj, methodName);
387 return fn.apply(obj, this);
388}
389Promise.prototype.call = function (methodName) {
390 var args = [].slice.call(arguments, 1);;
391 if (!true) {
392 if (canEvaluate) {
393 var maybeCaller = getMethodCaller(methodName);
394 if (maybeCaller !== null) {
395 return this._then(
396 maybeCaller, undefined, undefined, args, undefined);
397 }
398 }
399 }
400 args.push(methodName);
401 return this._then(caller, undefined, undefined, args, undefined);
402};
403
404function namedGetter(obj) {
405 return obj[this];
406}
407function indexedGetter(obj) {
408 var index = +this;
409 if (index < 0) index = Math.max(0, index + obj.length);
410 return obj[index];
411}
412Promise.prototype.get = function (propertyName) {
413 var isIndex = (typeof propertyName === "number");
414 var getter;
415 if (!isIndex) {
416 if (canEvaluate) {
417 var maybeGetter = getGetter(propertyName);
418 getter = maybeGetter !== null ? maybeGetter : namedGetter;
419 } else {
420 getter = namedGetter;
421 }
422 } else {
423 getter = indexedGetter;
424 }
425 return this._then(getter, undefined, undefined, propertyName, undefined);
426};
427};
428
429},{"./util":36}],6:[function(_dereq_,module,exports){
430"use strict";
431module.exports = function(Promise, PromiseArray, apiRejection, debug) {
432var util = _dereq_("./util");
433var tryCatch = util.tryCatch;
434var errorObj = util.errorObj;
435var async = Promise._async;
436
437Promise.prototype["break"] = Promise.prototype.cancel = function() {
438 if (!debug.cancellation()) return this._warn("cancellation is disabled");
439
440 var promise = this;
441 var child = promise;
442 while (promise.isCancellable()) {
443 if (!promise._cancelBy(child)) {
444 if (child._isFollowing()) {
445 child._followee().cancel();
446 } else {
447 child._cancelBranched();
448 }
449 break;
450 }
451
452 var parent = promise._cancellationParent;
453 if (parent == null || !parent.isCancellable()) {
454 if (promise._isFollowing()) {
455 promise._followee().cancel();
456 } else {
457 promise._cancelBranched();
458 }
459 break;
460 } else {
461 if (promise._isFollowing()) promise._followee().cancel();
462 child = promise;
463 promise = parent;
464 }
465 }
466};
467
468Promise.prototype._branchHasCancelled = function() {
469 this._branchesRemainingToCancel--;
470};
471
472Promise.prototype._enoughBranchesHaveCancelled = function() {
473 return this._branchesRemainingToCancel === undefined ||
474 this._branchesRemainingToCancel <= 0;
475};
476
477Promise.prototype._cancelBy = function(canceller) {
478 if (canceller === this) {
479 this._branchesRemainingToCancel = 0;
480 this._invokeOnCancel();
481 return true;
482 } else {
483 this._branchHasCancelled();
484 if (this._enoughBranchesHaveCancelled()) {
485 this._invokeOnCancel();
486 return true;
487 }
488 }
489 return false;
490};
491
492Promise.prototype._cancelBranched = function() {
493 if (this._enoughBranchesHaveCancelled()) {
494 this._cancel();
495 }
496};
497
498Promise.prototype._cancel = function() {
499 if (!this.isCancellable()) return;
500
501 this._setCancelled();
502 async.invoke(this._cancelPromises, this, undefined);
503};
504
505Promise.prototype._cancelPromises = function() {
506 if (this._length() > 0) this._settlePromises();
507};
508
509Promise.prototype._unsetOnCancel = function() {
510 this._onCancelField = undefined;
511};
512
513Promise.prototype.isCancellable = function() {
514 return this.isPending() && !this.isCancelled();
515};
516
517Promise.prototype._doInvokeOnCancel = function(onCancelCallback, internalOnly) {
518 if (util.isArray(onCancelCallback)) {
519 for (var i = 0; i < onCancelCallback.length; ++i) {
520 this._doInvokeOnCancel(onCancelCallback[i], internalOnly);
521 }
522 } else if (onCancelCallback !== undefined) {
523 if (typeof onCancelCallback === "function") {
524 if (!internalOnly) {
525 var e = tryCatch(onCancelCallback).call(this._boundValue());
526 if (e === errorObj) {
527 this._attachExtraTrace(e.e);
528 async.throwLater(e.e);
529 }
530 }
531 } else {
532 onCancelCallback._resultCancelled(this);
533 }
534 }
535};
536
537Promise.prototype._invokeOnCancel = function() {
538 var onCancelCallback = this._onCancel();
539 this._unsetOnCancel();
540 async.invoke(this._doInvokeOnCancel, this, onCancelCallback);
541};
542
543Promise.prototype._invokeInternalOnCancel = function() {
544 if (this.isCancellable()) {
545 this._doInvokeOnCancel(this._onCancel(), true);
546 this._unsetOnCancel();
547 }
548};
549
550Promise.prototype._resultCancelled = function() {
551 this.cancel();
552};
553
554};
555
556},{"./util":36}],7:[function(_dereq_,module,exports){
557"use strict";
558module.exports = function(NEXT_FILTER) {
559var util = _dereq_("./util");
560var getKeys = _dereq_("./es5").keys;
561var tryCatch = util.tryCatch;
562var errorObj = util.errorObj;
563
564function catchFilter(instances, cb, promise) {
565 return function(e) {
566 var boundTo = promise._boundValue();
567 predicateLoop: for (var i = 0; i < instances.length; ++i) {
568 var item = instances[i];
569
570 if (item === Error ||
571 (item != null && item.prototype instanceof Error)) {
572 if (e instanceof item) {
573 return tryCatch(cb).call(boundTo, e);
574 }
575 } else if (typeof item === "function") {
576 var matchesPredicate = tryCatch(item).call(boundTo, e);
577 if (matchesPredicate === errorObj) {
578 return matchesPredicate;
579 } else if (matchesPredicate) {
580 return tryCatch(cb).call(boundTo, e);
581 }
582 } else if (util.isObject(e)) {
583 var keys = getKeys(item);
584 for (var j = 0; j < keys.length; ++j) {
585 var key = keys[j];
586 if (item[key] != e[key]) {
587 continue predicateLoop;
588 }
589 }
590 return tryCatch(cb).call(boundTo, e);
591 }
592 }
593 return NEXT_FILTER;
594 };
595}
596
597return catchFilter;
598};
599
600},{"./es5":13,"./util":36}],8:[function(_dereq_,module,exports){
601"use strict";
602module.exports = function(Promise) {
603var longStackTraces = false;
604var contextStack = [];
605
606Promise.prototype._promiseCreated = function() {};
607Promise.prototype._pushContext = function() {};
608Promise.prototype._popContext = function() {return null;};
609Promise._peekContext = Promise.prototype._peekContext = function() {};
610
611function Context() {
612 this._trace = new Context.CapturedTrace(peekContext());
613}
614Context.prototype._pushContext = function () {
615 if (this._trace !== undefined) {
616 this._trace._promiseCreated = null;
617 contextStack.push(this._trace);
618 }
619};
620
621Context.prototype._popContext = function () {
622 if (this._trace !== undefined) {
623 var trace = contextStack.pop();
624 var ret = trace._promiseCreated;
625 trace._promiseCreated = null;
626 return ret;
627 }
628 return null;
629};
630
631function createContext() {
632 if (longStackTraces) return new Context();
633}
634
635function peekContext() {
636 var lastIndex = contextStack.length - 1;
637 if (lastIndex >= 0) {
638 return contextStack[lastIndex];
639 }
640 return undefined;
641}
642Context.CapturedTrace = null;
643Context.create = createContext;
644Context.deactivateLongStackTraces = function() {};
645Context.activateLongStackTraces = function() {
646 var Promise_pushContext = Promise.prototype._pushContext;
647 var Promise_popContext = Promise.prototype._popContext;
648 var Promise_PeekContext = Promise._peekContext;
649 var Promise_peekContext = Promise.prototype._peekContext;
650 var Promise_promiseCreated = Promise.prototype._promiseCreated;
651 Context.deactivateLongStackTraces = function() {
652 Promise.prototype._pushContext = Promise_pushContext;
653 Promise.prototype._popContext = Promise_popContext;
654 Promise._peekContext = Promise_PeekContext;
655 Promise.prototype._peekContext = Promise_peekContext;
656 Promise.prototype._promiseCreated = Promise_promiseCreated;
657 longStackTraces = false;
658 };
659 longStackTraces = true;
660 Promise.prototype._pushContext = Context.prototype._pushContext;
661 Promise.prototype._popContext = Context.prototype._popContext;
662 Promise._peekContext = Promise.prototype._peekContext = peekContext;
663 Promise.prototype._promiseCreated = function() {
664 var ctx = this._peekContext();
665 if (ctx && ctx._promiseCreated == null) ctx._promiseCreated = this;
666 };
667};
668return Context;
669};
670
671},{}],9:[function(_dereq_,module,exports){
672"use strict";
673module.exports = function(Promise, Context) {
674var getDomain = Promise._getDomain;
675var async = Promise._async;
676var Warning = _dereq_("./errors").Warning;
677var util = _dereq_("./util");
678var canAttachTrace = util.canAttachTrace;
679var unhandledRejectionHandled;
680var possiblyUnhandledRejection;
681var bluebirdFramePattern =
682 /[\\\/]bluebird[\\\/]js[\\\/](release|debug|instrumented)/;
683var stackFramePattern = null;
684var formatStack = null;
685var indentStackFrames = false;
686var printWarning;
687var debugging = !!(util.env("BLUEBIRD_DEBUG") != 0 &&
688 (true ||
689 util.env("BLUEBIRD_DEBUG") ||
690 util.env("NODE_ENV") === "development"));
691
692var warnings = !!(util.env("BLUEBIRD_WARNINGS") != 0 &&
693 (debugging || util.env("BLUEBIRD_WARNINGS")));
694
695var longStackTraces = !!(util.env("BLUEBIRD_LONG_STACK_TRACES") != 0 &&
696 (debugging || util.env("BLUEBIRD_LONG_STACK_TRACES")));
697
698var wForgottenReturn = util.env("BLUEBIRD_W_FORGOTTEN_RETURN") != 0 &&
699 (warnings || !!util.env("BLUEBIRD_W_FORGOTTEN_RETURN"));
700
701Promise.prototype.suppressUnhandledRejections = function() {
702 var target = this._target();
703 target._bitField = ((target._bitField & (~1048576)) |
704 524288);
705};
706
707Promise.prototype._ensurePossibleRejectionHandled = function () {
708 if ((this._bitField & 524288) !== 0) return;
709 this._setRejectionIsUnhandled();
710 async.invokeLater(this._notifyUnhandledRejection, this, undefined);
711};
712
713Promise.prototype._notifyUnhandledRejectionIsHandled = function () {
714 fireRejectionEvent("rejectionHandled",
715 unhandledRejectionHandled, undefined, this);
716};
717
718Promise.prototype._setReturnedNonUndefined = function() {
719 this._bitField = this._bitField | 268435456;
720};
721
722Promise.prototype._returnedNonUndefined = function() {
723 return (this._bitField & 268435456) !== 0;
724};
725
726Promise.prototype._notifyUnhandledRejection = function () {
727 if (this._isRejectionUnhandled()) {
728 var reason = this._settledValue();
729 this._setUnhandledRejectionIsNotified();
730 fireRejectionEvent("unhandledRejection",
731 possiblyUnhandledRejection, reason, this);
732 }
733};
734
735Promise.prototype._setUnhandledRejectionIsNotified = function () {
736 this._bitField = this._bitField | 262144;
737};
738
739Promise.prototype._unsetUnhandledRejectionIsNotified = function () {
740 this._bitField = this._bitField & (~262144);
741};
742
743Promise.prototype._isUnhandledRejectionNotified = function () {
744 return (this._bitField & 262144) > 0;
745};
746
747Promise.prototype._setRejectionIsUnhandled = function () {
748 this._bitField = this._bitField | 1048576;
749};
750
751Promise.prototype._unsetRejectionIsUnhandled = function () {
752 this._bitField = this._bitField & (~1048576);
753 if (this._isUnhandledRejectionNotified()) {
754 this._unsetUnhandledRejectionIsNotified();
755 this._notifyUnhandledRejectionIsHandled();
756 }
757};
758
759Promise.prototype._isRejectionUnhandled = function () {
760 return (this._bitField & 1048576) > 0;
761};
762
763Promise.prototype._warn = function(message, shouldUseOwnTrace, promise) {
764 return warn(message, shouldUseOwnTrace, promise || this);
765};
766
767Promise.onPossiblyUnhandledRejection = function (fn) {
768 var domain = getDomain();
769 possiblyUnhandledRejection =
770 typeof fn === "function" ? (domain === null ? fn : domain.bind(fn))
771 : undefined;
772};
773
774Promise.onUnhandledRejectionHandled = function (fn) {
775 var domain = getDomain();
776 unhandledRejectionHandled =
777 typeof fn === "function" ? (domain === null ? fn : domain.bind(fn))
778 : undefined;
779};
780
781var disableLongStackTraces = function() {};
782Promise.longStackTraces = function () {
783 if (async.haveItemsQueued() && !config.longStackTraces) {
784 throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a");
785 }
786 if (!config.longStackTraces && longStackTracesIsSupported()) {
787 var Promise_captureStackTrace = Promise.prototype._captureStackTrace;
788 var Promise_attachExtraTrace = Promise.prototype._attachExtraTrace;
789 config.longStackTraces = true;
790 disableLongStackTraces = function() {
791 if (async.haveItemsQueued() && !config.longStackTraces) {
792 throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a");
793 }
794 Promise.prototype._captureStackTrace = Promise_captureStackTrace;
795 Promise.prototype._attachExtraTrace = Promise_attachExtraTrace;
796 Context.deactivateLongStackTraces();
797 async.enableTrampoline();
798 config.longStackTraces = false;
799 };
800 Promise.prototype._captureStackTrace = longStackTracesCaptureStackTrace;
801 Promise.prototype._attachExtraTrace = longStackTracesAttachExtraTrace;
802 Context.activateLongStackTraces();
803 async.disableTrampolineIfNecessary();
804 }
805};
806
807Promise.hasLongStackTraces = function () {
808 return config.longStackTraces && longStackTracesIsSupported();
809};
810
811var fireDomEvent = (function() {
812 try {
813 var event = document.createEvent("CustomEvent");
814 event.initCustomEvent("testingtheevent", false, true, {});
815 util.global.dispatchEvent(event);
816 return function(name, event) {
817 var domEvent = document.createEvent("CustomEvent");
818 domEvent.initCustomEvent(name.toLowerCase(), false, true, event);
819 return !util.global.dispatchEvent(domEvent);
820 };
821 } catch (e) {}
822 return function() {
823 return false;
824 };
825})();
826
827var fireGlobalEvent = (function() {
828 if (util.isNode) {
829 return function() {
830 return process.emit.apply(process, arguments);
831 };
832 } else {
833 if (!util.global) {
834 return function() {
835 return false;
836 };
837 }
838 return function(name) {
839 var methodName = "on" + name.toLowerCase();
840 var method = util.global[methodName];
841 if (!method) return false;
842 method.apply(util.global, [].slice.call(arguments, 1));
843 return true;
844 };
845 }
846})();
847
848function generatePromiseLifecycleEventObject(name, promise) {
849 return {promise: promise};
850}
851
852var eventToObjectGenerator = {
853 promiseCreated: generatePromiseLifecycleEventObject,
854 promiseFulfilled: generatePromiseLifecycleEventObject,
855 promiseRejected: generatePromiseLifecycleEventObject,
856 promiseResolved: generatePromiseLifecycleEventObject,
857 promiseCancelled: generatePromiseLifecycleEventObject,
858 promiseChained: function(name, promise, child) {
859 return {promise: promise, child: child};
860 },
861 warning: function(name, warning) {
862 return {warning: warning};
863 },
864 unhandledRejection: function (name, reason, promise) {
865 return {reason: reason, promise: promise};
866 },
867 rejectionHandled: generatePromiseLifecycleEventObject
868};
869
870var activeFireEvent = function (name) {
871 var globalEventFired = false;
872 try {
873 globalEventFired = fireGlobalEvent.apply(null, arguments);
874 } catch (e) {
875 async.throwLater(e);
876 globalEventFired = true;
877 }
878
879 var domEventFired = false;
880 try {
881 domEventFired = fireDomEvent(name,
882 eventToObjectGenerator[name].apply(null, arguments));
883 } catch (e) {
884 async.throwLater(e);
885 domEventFired = true;
886 }
887
888 return domEventFired || globalEventFired;
889};
890
891Promise.config = function(opts) {
892 opts = Object(opts);
893 if ("longStackTraces" in opts) {
894 if (opts.longStackTraces) {
895 Promise.longStackTraces();
896 } else if (!opts.longStackTraces && Promise.hasLongStackTraces()) {
897 disableLongStackTraces();
898 }
899 }
900 if ("warnings" in opts) {
901 var warningsOption = opts.warnings;
902 config.warnings = !!warningsOption;
903 wForgottenReturn = config.warnings;
904
905 if (util.isObject(warningsOption)) {
906 if ("wForgottenReturn" in warningsOption) {
907 wForgottenReturn = !!warningsOption.wForgottenReturn;
908 }
909 }
910 }
911 if ("cancellation" in opts && opts.cancellation && !config.cancellation) {
912 if (async.haveItemsQueued()) {
913 throw new Error(
914 "cannot enable cancellation after promises are in use");
915 }
916 Promise.prototype._clearCancellationData =
917 cancellationClearCancellationData;
918 Promise.prototype._propagateFrom = cancellationPropagateFrom;
919 Promise.prototype._onCancel = cancellationOnCancel;
920 Promise.prototype._setOnCancel = cancellationSetOnCancel;
921 Promise.prototype._attachCancellationCallback =
922 cancellationAttachCancellationCallback;
923 Promise.prototype._execute = cancellationExecute;
924 propagateFromFunction = cancellationPropagateFrom;
925 config.cancellation = true;
926 }
927 if ("monitoring" in opts) {
928 if (opts.monitoring && !config.monitoring) {
929 config.monitoring = true;
930 Promise.prototype._fireEvent = activeFireEvent;
931 } else if (!opts.monitoring && config.monitoring) {
932 config.monitoring = false;
933 Promise.prototype._fireEvent = defaultFireEvent;
934 }
935 }
936};
937
938function defaultFireEvent() { return false; }
939
940Promise.prototype._fireEvent = defaultFireEvent;
941Promise.prototype._execute = function(executor, resolve, reject) {
942 try {
943 executor(resolve, reject);
944 } catch (e) {
945 return e;
946 }
947};
948Promise.prototype._onCancel = function () {};
949Promise.prototype._setOnCancel = function (handler) { ; };
950Promise.prototype._attachCancellationCallback = function(onCancel) {
951 ;
952};
953Promise.prototype._captureStackTrace = function () {};
954Promise.prototype._attachExtraTrace = function () {};
955Promise.prototype._clearCancellationData = function() {};
956Promise.prototype._propagateFrom = function (parent, flags) {
957 ;
958 ;
959};
960
961function cancellationExecute(executor, resolve, reject) {
962 var promise = this;
963 try {
964 executor(resolve, reject, function(onCancel) {
965 if (typeof onCancel !== "function") {
966 throw new TypeError("onCancel must be a function, got: " +
967 util.toString(onCancel));
968 }
969 promise._attachCancellationCallback(onCancel);
970 });
971 } catch (e) {
972 return e;
973 }
974}
975
976function cancellationAttachCancellationCallback(onCancel) {
977 if (!this.isCancellable()) return this;
978
979 var previousOnCancel = this._onCancel();
980 if (previousOnCancel !== undefined) {
981 if (util.isArray(previousOnCancel)) {
982 previousOnCancel.push(onCancel);
983 } else {
984 this._setOnCancel([previousOnCancel, onCancel]);
985 }
986 } else {
987 this._setOnCancel(onCancel);
988 }
989}
990
991function cancellationOnCancel() {
992 return this._onCancelField;
993}
994
995function cancellationSetOnCancel(onCancel) {
996 this._onCancelField = onCancel;
997}
998
999function cancellationClearCancellationData() {
1000 this._cancellationParent = undefined;
1001 this._onCancelField = undefined;
1002}
1003
1004function cancellationPropagateFrom(parent, flags) {
1005 if ((flags & 1) !== 0) {
1006 this._cancellationParent = parent;
1007 var branchesRemainingToCancel = parent._branchesRemainingToCancel;
1008 if (branchesRemainingToCancel === undefined) {
1009 branchesRemainingToCancel = 0;
1010 }
1011 parent._branchesRemainingToCancel = branchesRemainingToCancel + 1;
1012 }
1013 if ((flags & 2) !== 0 && parent._isBound()) {
1014 this._setBoundTo(parent._boundTo);
1015 }
1016}
1017
1018function bindingPropagateFrom(parent, flags) {
1019 if ((flags & 2) !== 0 && parent._isBound()) {
1020 this._setBoundTo(parent._boundTo);
1021 }
1022}
1023var propagateFromFunction = bindingPropagateFrom;
1024
1025function boundValueFunction() {
1026 var ret = this._boundTo;
1027 if (ret !== undefined) {
1028 if (ret instanceof Promise) {
1029 if (ret.isFulfilled()) {
1030 return ret.value();
1031 } else {
1032 return undefined;
1033 }
1034 }
1035 }
1036 return ret;
1037}
1038
1039function longStackTracesCaptureStackTrace() {
1040 this._trace = new CapturedTrace(this._peekContext());
1041}
1042
1043function longStackTracesAttachExtraTrace(error, ignoreSelf) {
1044 if (canAttachTrace(error)) {
1045 var trace = this._trace;
1046 if (trace !== undefined) {
1047 if (ignoreSelf) trace = trace._parent;
1048 }
1049 if (trace !== undefined) {
1050 trace.attachExtraTrace(error);
1051 } else if (!error.__stackCleaned__) {
1052 var parsed = parseStackAndMessage(error);
1053 util.notEnumerableProp(error, "stack",
1054 parsed.message + "\n" + parsed.stack.join("\n"));
1055 util.notEnumerableProp(error, "__stackCleaned__", true);
1056 }
1057 }
1058}
1059
1060function checkForgottenReturns(returnValue, promiseCreated, name, promise,
1061 parent) {
1062 if (returnValue === undefined && promiseCreated !== null &&
1063 wForgottenReturn) {
1064 if (parent !== undefined && parent._returnedNonUndefined()) return;
1065 if ((promise._bitField & 65535) === 0) return;
1066
1067 if (name) name = name + " ";
1068 var msg = "a promise was created in a " + name +
1069 "handler but was not returned from it";
1070 promise._warn(msg, true, promiseCreated);
1071 }
1072}
1073
1074function deprecated(name, replacement) {
1075 var message = name +
1076 " is deprecated and will be removed in a future version.";
1077 if (replacement) message += " Use " + replacement + " instead.";
1078 return warn(message);
1079}
1080
1081function warn(message, shouldUseOwnTrace, promise) {
1082 if (!config.warnings) return;
1083 var warning = new Warning(message);
1084 var ctx;
1085 if (shouldUseOwnTrace) {
1086 promise._attachExtraTrace(warning);
1087 } else if (config.longStackTraces && (ctx = Promise._peekContext())) {
1088 ctx.attachExtraTrace(warning);
1089 } else {
1090 var parsed = parseStackAndMessage(warning);
1091 warning.stack = parsed.message + "\n" + parsed.stack.join("\n");
1092 }
1093
1094 if (!activeFireEvent("warning", warning)) {
1095 formatAndLogError(warning, "", true);
1096 }
1097}
1098
1099function reconstructStack(message, stacks) {
1100 for (var i = 0; i < stacks.length - 1; ++i) {
1101 stacks[i].push("From previous event:");
1102 stacks[i] = stacks[i].join("\n");
1103 }
1104 if (i < stacks.length) {
1105 stacks[i] = stacks[i].join("\n");
1106 }
1107 return message + "\n" + stacks.join("\n");
1108}
1109
1110function removeDuplicateOrEmptyJumps(stacks) {
1111 for (var i = 0; i < stacks.length; ++i) {
1112 if (stacks[i].length === 0 ||
1113 ((i + 1 < stacks.length) && stacks[i][0] === stacks[i+1][0])) {
1114 stacks.splice(i, 1);
1115 i--;
1116 }
1117 }
1118}
1119
1120function removeCommonRoots(stacks) {
1121 var current = stacks[0];
1122 for (var i = 1; i < stacks.length; ++i) {
1123 var prev = stacks[i];
1124 var currentLastIndex = current.length - 1;
1125 var currentLastLine = current[currentLastIndex];
1126 var commonRootMeetPoint = -1;
1127
1128 for (var j = prev.length - 1; j >= 0; --j) {
1129 if (prev[j] === currentLastLine) {
1130 commonRootMeetPoint = j;
1131 break;
1132 }
1133 }
1134
1135 for (var j = commonRootMeetPoint; j >= 0; --j) {
1136 var line = prev[j];
1137 if (current[currentLastIndex] === line) {
1138 current.pop();
1139 currentLastIndex--;
1140 } else {
1141 break;
1142 }
1143 }
1144 current = prev;
1145 }
1146}
1147
1148function cleanStack(stack) {
1149 var ret = [];
1150 for (var i = 0; i < stack.length; ++i) {
1151 var line = stack[i];
1152 var isTraceLine = " (No stack trace)" === line ||
1153 stackFramePattern.test(line);
1154 var isInternalFrame = isTraceLine && shouldIgnore(line);
1155 if (isTraceLine && !isInternalFrame) {
1156 if (indentStackFrames && line.charAt(0) !== " ") {
1157 line = " " + line;
1158 }
1159 ret.push(line);
1160 }
1161 }
1162 return ret;
1163}
1164
1165function stackFramesAsArray(error) {
1166 var stack = error.stack.replace(/\s+$/g, "").split("\n");
1167 for (var i = 0; i < stack.length; ++i) {
1168 var line = stack[i];
1169 if (" (No stack trace)" === line || stackFramePattern.test(line)) {
1170 break;
1171 }
1172 }
1173 if (i > 0) {
1174 stack = stack.slice(i);
1175 }
1176 return stack;
1177}
1178
1179function parseStackAndMessage(error) {
1180 var stack = error.stack;
1181 var message = error.toString();
1182 stack = typeof stack === "string" && stack.length > 0
1183 ? stackFramesAsArray(error) : [" (No stack trace)"];
1184 return {
1185 message: message,
1186 stack: cleanStack(stack)
1187 };
1188}
1189
1190function formatAndLogError(error, title, isSoft) {
1191 if (typeof console !== "undefined") {
1192 var message;
1193 if (util.isObject(error)) {
1194 var stack = error.stack;
1195 message = title + formatStack(stack, error);
1196 } else {
1197 message = title + String(error);
1198 }
1199 if (typeof printWarning === "function") {
1200 printWarning(message, isSoft);
1201 } else if (typeof console.log === "function" ||
1202 typeof console.log === "object") {
1203 console.log(message);
1204 }
1205 }
1206}
1207
1208function fireRejectionEvent(name, localHandler, reason, promise) {
1209 var localEventFired = false;
1210 try {
1211 if (typeof localHandler === "function") {
1212 localEventFired = true;
1213 if (name === "rejectionHandled") {
1214 localHandler(promise);
1215 } else {
1216 localHandler(reason, promise);
1217 }
1218 }
1219 } catch (e) {
1220 async.throwLater(e);
1221 }
1222
1223 if (name === "unhandledRejection") {
1224 if (!activeFireEvent(name, reason, promise) && !localEventFired) {
1225 formatAndLogError(reason, "Unhandled rejection ");
1226 }
1227 } else {
1228 activeFireEvent(name, promise);
1229 }
1230}
1231
1232function formatNonError(obj) {
1233 var str;
1234 if (typeof obj === "function") {
1235 str = "[function " +
1236 (obj.name || "anonymous") +
1237 "]";
1238 } else {
1239 str = obj && typeof obj.toString === "function"
1240 ? obj.toString() : util.toString(obj);
1241 var ruselessToString = /\[object [a-zA-Z0-9$_]+\]/;
1242 if (ruselessToString.test(str)) {
1243 try {
1244 var newStr = JSON.stringify(obj);
1245 str = newStr;
1246 }
1247 catch(e) {
1248
1249 }
1250 }
1251 if (str.length === 0) {
1252 str = "(empty array)";
1253 }
1254 }
1255 return ("(<" + snip(str) + ">, no stack trace)");
1256}
1257
1258function snip(str) {
1259 var maxChars = 41;
1260 if (str.length < maxChars) {
1261 return str;
1262 }
1263 return str.substr(0, maxChars - 3) + "...";
1264}
1265
1266function longStackTracesIsSupported() {
1267 return typeof captureStackTrace === "function";
1268}
1269
1270var shouldIgnore = function() { return false; };
1271var parseLineInfoRegex = /[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/;
1272function parseLineInfo(line) {
1273 var matches = line.match(parseLineInfoRegex);
1274 if (matches) {
1275 return {
1276 fileName: matches[1],
1277 line: parseInt(matches[2], 10)
1278 };
1279 }
1280}
1281
1282function setBounds(firstLineError, lastLineError) {
1283 if (!longStackTracesIsSupported()) return;
1284 var firstStackLines = firstLineError.stack.split("\n");
1285 var lastStackLines = lastLineError.stack.split("\n");
1286 var firstIndex = -1;
1287 var lastIndex = -1;
1288 var firstFileName;
1289 var lastFileName;
1290 for (var i = 0; i < firstStackLines.length; ++i) {
1291 var result = parseLineInfo(firstStackLines[i]);
1292 if (result) {
1293 firstFileName = result.fileName;
1294 firstIndex = result.line;
1295 break;
1296 }
1297 }
1298 for (var i = 0; i < lastStackLines.length; ++i) {
1299 var result = parseLineInfo(lastStackLines[i]);
1300 if (result) {
1301 lastFileName = result.fileName;
1302 lastIndex = result.line;
1303 break;
1304 }
1305 }
1306 if (firstIndex < 0 || lastIndex < 0 || !firstFileName || !lastFileName ||
1307 firstFileName !== lastFileName || firstIndex >= lastIndex) {
1308 return;
1309 }
1310
1311 shouldIgnore = function(line) {
1312 if (bluebirdFramePattern.test(line)) return true;
1313 var info = parseLineInfo(line);
1314 if (info) {
1315 if (info.fileName === firstFileName &&
1316 (firstIndex <= info.line && info.line <= lastIndex)) {
1317 return true;
1318 }
1319 }
1320 return false;
1321 };
1322}
1323
1324function CapturedTrace(parent) {
1325 this._parent = parent;
1326 this._promisesCreated = 0;
1327 var length = this._length = 1 + (parent === undefined ? 0 : parent._length);
1328 captureStackTrace(this, CapturedTrace);
1329 if (length > 32) this.uncycle();
1330}
1331util.inherits(CapturedTrace, Error);
1332Context.CapturedTrace = CapturedTrace;
1333
1334CapturedTrace.prototype.uncycle = function() {
1335 var length = this._length;
1336 if (length < 2) return;
1337 var nodes = [];
1338 var stackToIndex = {};
1339
1340 for (var i = 0, node = this; node !== undefined; ++i) {
1341 nodes.push(node);
1342 node = node._parent;
1343 }
1344 length = this._length = i;
1345 for (var i = length - 1; i >= 0; --i) {
1346 var stack = nodes[i].stack;
1347 if (stackToIndex[stack] === undefined) {
1348 stackToIndex[stack] = i;
1349 }
1350 }
1351 for (var i = 0; i < length; ++i) {
1352 var currentStack = nodes[i].stack;
1353 var index = stackToIndex[currentStack];
1354 if (index !== undefined && index !== i) {
1355 if (index > 0) {
1356 nodes[index - 1]._parent = undefined;
1357 nodes[index - 1]._length = 1;
1358 }
1359 nodes[i]._parent = undefined;
1360 nodes[i]._length = 1;
1361 var cycleEdgeNode = i > 0 ? nodes[i - 1] : this;
1362
1363 if (index < length - 1) {
1364 cycleEdgeNode._parent = nodes[index + 1];
1365 cycleEdgeNode._parent.uncycle();
1366 cycleEdgeNode._length =
1367 cycleEdgeNode._parent._length + 1;
1368 } else {
1369 cycleEdgeNode._parent = undefined;
1370 cycleEdgeNode._length = 1;
1371 }
1372 var currentChildLength = cycleEdgeNode._length + 1;
1373 for (var j = i - 2; j >= 0; --j) {
1374 nodes[j]._length = currentChildLength;
1375 currentChildLength++;
1376 }
1377 return;
1378 }
1379 }
1380};
1381
1382CapturedTrace.prototype.attachExtraTrace = function(error) {
1383 if (error.__stackCleaned__) return;
1384 this.uncycle();
1385 var parsed = parseStackAndMessage(error);
1386 var message = parsed.message;
1387 var stacks = [parsed.stack];
1388
1389 var trace = this;
1390 while (trace !== undefined) {
1391 stacks.push(cleanStack(trace.stack.split("\n")));
1392 trace = trace._parent;
1393 }
1394 removeCommonRoots(stacks);
1395 removeDuplicateOrEmptyJumps(stacks);
1396 util.notEnumerableProp(error, "stack", reconstructStack(message, stacks));
1397 util.notEnumerableProp(error, "__stackCleaned__", true);
1398};
1399
1400var captureStackTrace = (function stackDetection() {
1401 var v8stackFramePattern = /^\s*at\s*/;
1402 var v8stackFormatter = function(stack, error) {
1403 if (typeof stack === "string") return stack;
1404
1405 if (error.name !== undefined &&
1406 error.message !== undefined) {
1407 return error.toString();
1408 }
1409 return formatNonError(error);
1410 };
1411
1412 if (typeof Error.stackTraceLimit === "number" &&
1413 typeof Error.captureStackTrace === "function") {
1414 Error.stackTraceLimit += 6;
1415 stackFramePattern = v8stackFramePattern;
1416 formatStack = v8stackFormatter;
1417 var captureStackTrace = Error.captureStackTrace;
1418
1419 shouldIgnore = function(line) {
1420 return bluebirdFramePattern.test(line);
1421 };
1422 return function(receiver, ignoreUntil) {
1423 Error.stackTraceLimit += 6;
1424 captureStackTrace(receiver, ignoreUntil);
1425 Error.stackTraceLimit -= 6;
1426 };
1427 }
1428 var err = new Error();
1429
1430 if (typeof err.stack === "string" &&
1431 err.stack.split("\n")[0].indexOf("stackDetection@") >= 0) {
1432 stackFramePattern = /@/;
1433 formatStack = v8stackFormatter;
1434 indentStackFrames = true;
1435 return function captureStackTrace(o) {
1436 o.stack = new Error().stack;
1437 };
1438 }
1439
1440 var hasStackAfterThrow;
1441 try { throw new Error(); }
1442 catch(e) {
1443 hasStackAfterThrow = ("stack" in e);
1444 }
1445 if (!("stack" in err) && hasStackAfterThrow &&
1446 typeof Error.stackTraceLimit === "number") {
1447 stackFramePattern = v8stackFramePattern;
1448 formatStack = v8stackFormatter;
1449 return function captureStackTrace(o) {
1450 Error.stackTraceLimit += 6;
1451 try { throw new Error(); }
1452 catch(e) { o.stack = e.stack; }
1453 Error.stackTraceLimit -= 6;
1454 };
1455 }
1456
1457 formatStack = function(stack, error) {
1458 if (typeof stack === "string") return stack;
1459
1460 if ((typeof error === "object" ||
1461 typeof error === "function") &&
1462 error.name !== undefined &&
1463 error.message !== undefined) {
1464 return error.toString();
1465 }
1466 return formatNonError(error);
1467 };
1468
1469 return null;
1470
1471})([]);
1472
1473if (typeof console !== "undefined" && typeof console.warn !== "undefined") {
1474 printWarning = function (message) {
1475 console.warn(message);
1476 };
1477 if (util.isNode && process.stderr.isTTY) {
1478 printWarning = function(message, isSoft) {
1479 var color = isSoft ? "\u001b[33m" : "\u001b[31m";
1480 console.warn(color + message + "\u001b[0m\n");
1481 };
1482 } else if (!util.isNode && typeof (new Error().stack) === "string") {
1483 printWarning = function(message, isSoft) {
1484 console.warn("%c" + message,
1485 isSoft ? "color: darkorange" : "color: red");
1486 };
1487 }
1488}
1489
1490var config = {
1491 warnings: warnings,
1492 longStackTraces: false,
1493 cancellation: false,
1494 monitoring: false
1495};
1496
1497if (longStackTraces) Promise.longStackTraces();
1498
1499return {
1500 longStackTraces: function() {
1501 return config.longStackTraces;
1502 },
1503 warnings: function() {
1504 return config.warnings;
1505 },
1506 cancellation: function() {
1507 return config.cancellation;
1508 },
1509 monitoring: function() {
1510 return config.monitoring;
1511 },
1512 propagateFromFunction: function() {
1513 return propagateFromFunction;
1514 },
1515 boundValueFunction: function() {
1516 return boundValueFunction;
1517 },
1518 checkForgottenReturns: checkForgottenReturns,
1519 setBounds: setBounds,
1520 warn: warn,
1521 deprecated: deprecated,
1522 CapturedTrace: CapturedTrace,
1523 fireDomEvent: fireDomEvent,
1524 fireGlobalEvent: fireGlobalEvent
1525};
1526};
1527
1528},{"./errors":12,"./util":36}],10:[function(_dereq_,module,exports){
1529"use strict";
1530module.exports = function(Promise) {
1531function returner() {
1532 return this.value;
1533}
1534function thrower() {
1535 throw this.reason;
1536}
1537
1538Promise.prototype["return"] =
1539Promise.prototype.thenReturn = function (value) {
1540 if (value instanceof Promise) value.suppressUnhandledRejections();
1541 return this._then(
1542 returner, undefined, undefined, {value: value}, undefined);
1543};
1544
1545Promise.prototype["throw"] =
1546Promise.prototype.thenThrow = function (reason) {
1547 return this._then(
1548 thrower, undefined, undefined, {reason: reason}, undefined);
1549};
1550
1551Promise.prototype.catchThrow = function (reason) {
1552 if (arguments.length <= 1) {
1553 return this._then(
1554 undefined, thrower, undefined, {reason: reason}, undefined);
1555 } else {
1556 var _reason = arguments[1];
1557 var handler = function() {throw _reason;};
1558 return this.caught(reason, handler);
1559 }
1560};
1561
1562Promise.prototype.catchReturn = function (value) {
1563 if (arguments.length <= 1) {
1564 if (value instanceof Promise) value.suppressUnhandledRejections();
1565 return this._then(
1566 undefined, returner, undefined, {value: value}, undefined);
1567 } else {
1568 var _value = arguments[1];
1569 if (_value instanceof Promise) _value.suppressUnhandledRejections();
1570 var handler = function() {return _value;};
1571 return this.caught(value, handler);
1572 }
1573};
1574};
1575
1576},{}],11:[function(_dereq_,module,exports){
1577"use strict";
1578module.exports = function(Promise, INTERNAL) {
1579var PromiseReduce = Promise.reduce;
1580var PromiseAll = Promise.all;
1581
1582function promiseAllThis() {
1583 return PromiseAll(this);
1584}
1585
1586function PromiseMapSeries(promises, fn) {
1587 return PromiseReduce(promises, fn, INTERNAL, INTERNAL);
1588}
1589
1590Promise.prototype.each = function (fn) {
1591 return this.mapSeries(fn)
1592 ._then(promiseAllThis, undefined, undefined, this, undefined);
1593};
1594
1595Promise.prototype.mapSeries = function (fn) {
1596 return PromiseReduce(this, fn, INTERNAL, INTERNAL);
1597};
1598
1599Promise.each = function (promises, fn) {
1600 return PromiseMapSeries(promises, fn)
1601 ._then(promiseAllThis, undefined, undefined, promises, undefined);
1602};
1603
1604Promise.mapSeries = PromiseMapSeries;
1605};
1606
1607},{}],12:[function(_dereq_,module,exports){
1608"use strict";
1609var es5 = _dereq_("./es5");
1610var Objectfreeze = es5.freeze;
1611var util = _dereq_("./util");
1612var inherits = util.inherits;
1613var notEnumerableProp = util.notEnumerableProp;
1614
1615function subError(nameProperty, defaultMessage) {
1616 function SubError(message) {
1617 if (!(this instanceof SubError)) return new SubError(message);
1618 notEnumerableProp(this, "message",
1619 typeof message === "string" ? message : defaultMessage);
1620 notEnumerableProp(this, "name", nameProperty);
1621 if (Error.captureStackTrace) {
1622 Error.captureStackTrace(this, this.constructor);
1623 } else {
1624 Error.call(this);
1625 }
1626 }
1627 inherits(SubError, Error);
1628 return SubError;
1629}
1630
1631var _TypeError, _RangeError;
1632var Warning = subError("Warning", "warning");
1633var CancellationError = subError("CancellationError", "cancellation error");
1634var TimeoutError = subError("TimeoutError", "timeout error");
1635var AggregateError = subError("AggregateError", "aggregate error");
1636try {
1637 _TypeError = TypeError;
1638 _RangeError = RangeError;
1639} catch(e) {
1640 _TypeError = subError("TypeError", "type error");
1641 _RangeError = subError("RangeError", "range error");
1642}
1643
1644var methods = ("join pop push shift unshift slice filter forEach some " +
1645 "every map indexOf lastIndexOf reduce reduceRight sort reverse").split(" ");
1646
1647for (var i = 0; i < methods.length; ++i) {
1648 if (typeof Array.prototype[methods[i]] === "function") {
1649 AggregateError.prototype[methods[i]] = Array.prototype[methods[i]];
1650 }
1651}
1652
1653es5.defineProperty(AggregateError.prototype, "length", {
1654 value: 0,
1655 configurable: false,
1656 writable: true,
1657 enumerable: true
1658});
1659AggregateError.prototype["isOperational"] = true;
1660var level = 0;
1661AggregateError.prototype.toString = function() {
1662 var indent = Array(level * 4 + 1).join(" ");
1663 var ret = "\n" + indent + "AggregateError of:" + "\n";
1664 level++;
1665 indent = Array(level * 4 + 1).join(" ");
1666 for (var i = 0; i < this.length; ++i) {
1667 var str = this[i] === this ? "[Circular AggregateError]" : this[i] + "";
1668 var lines = str.split("\n");
1669 for (var j = 0; j < lines.length; ++j) {
1670 lines[j] = indent + lines[j];
1671 }
1672 str = lines.join("\n");
1673 ret += str + "\n";
1674 }
1675 level--;
1676 return ret;
1677};
1678
1679function OperationalError(message) {
1680 if (!(this instanceof OperationalError))
1681 return new OperationalError(message);
1682 notEnumerableProp(this, "name", "OperationalError");
1683 notEnumerableProp(this, "message", message);
1684 this.cause = message;
1685 this["isOperational"] = true;
1686
1687 if (message instanceof Error) {
1688 notEnumerableProp(this, "message", message.message);
1689 notEnumerableProp(this, "stack", message.stack);
1690 } else if (Error.captureStackTrace) {
1691 Error.captureStackTrace(this, this.constructor);
1692 }
1693
1694}
1695inherits(OperationalError, Error);
1696
1697var errorTypes = Error["__BluebirdErrorTypes__"];
1698if (!errorTypes) {
1699 errorTypes = Objectfreeze({
1700 CancellationError: CancellationError,
1701 TimeoutError: TimeoutError,
1702 OperationalError: OperationalError,
1703 RejectionError: OperationalError,
1704 AggregateError: AggregateError
1705 });
1706 es5.defineProperty(Error, "__BluebirdErrorTypes__", {
1707 value: errorTypes,
1708 writable: false,
1709 enumerable: false,
1710 configurable: false
1711 });
1712}
1713
1714module.exports = {
1715 Error: Error,
1716 TypeError: _TypeError,
1717 RangeError: _RangeError,
1718 CancellationError: errorTypes.CancellationError,
1719 OperationalError: errorTypes.OperationalError,
1720 TimeoutError: errorTypes.TimeoutError,
1721 AggregateError: errorTypes.AggregateError,
1722 Warning: Warning
1723};
1724
1725},{"./es5":13,"./util":36}],13:[function(_dereq_,module,exports){
1726var isES5 = (function(){
1727 "use strict";
1728 return this === undefined;
1729})();
1730
1731if (isES5) {
1732 module.exports = {
1733 freeze: Object.freeze,
1734 defineProperty: Object.defineProperty,
1735 getDescriptor: Object.getOwnPropertyDescriptor,
1736 keys: Object.keys,
1737 names: Object.getOwnPropertyNames,
1738 getPrototypeOf: Object.getPrototypeOf,
1739 isArray: Array.isArray,
1740 isES5: isES5,
1741 propertyIsWritable: function(obj, prop) {
1742 var descriptor = Object.getOwnPropertyDescriptor(obj, prop);
1743 return !!(!descriptor || descriptor.writable || descriptor.set);
1744 }
1745 };
1746} else {
1747 var has = {}.hasOwnProperty;
1748 var str = {}.toString;
1749 var proto = {}.constructor.prototype;
1750
1751 var ObjectKeys = function (o) {
1752 var ret = [];
1753 for (var key in o) {
1754 if (has.call(o, key)) {
1755 ret.push(key);
1756 }
1757 }
1758 return ret;
1759 };
1760
1761 var ObjectGetDescriptor = function(o, key) {
1762 return {value: o[key]};
1763 };
1764
1765 var ObjectDefineProperty = function (o, key, desc) {
1766 o[key] = desc.value;
1767 return o;
1768 };
1769
1770 var ObjectFreeze = function (obj) {
1771 return obj;
1772 };
1773
1774 var ObjectGetPrototypeOf = function (obj) {
1775 try {
1776 return Object(obj).constructor.prototype;
1777 }
1778 catch (e) {
1779 return proto;
1780 }
1781 };
1782
1783 var ArrayIsArray = function (obj) {
1784 try {
1785 return str.call(obj) === "[object Array]";
1786 }
1787 catch(e) {
1788 return false;
1789 }
1790 };
1791
1792 module.exports = {
1793 isArray: ArrayIsArray,
1794 keys: ObjectKeys,
1795 names: ObjectKeys,
1796 defineProperty: ObjectDefineProperty,
1797 getDescriptor: ObjectGetDescriptor,
1798 freeze: ObjectFreeze,
1799 getPrototypeOf: ObjectGetPrototypeOf,
1800 isES5: isES5,
1801 propertyIsWritable: function() {
1802 return true;
1803 }
1804 };
1805}
1806
1807},{}],14:[function(_dereq_,module,exports){
1808"use strict";
1809module.exports = function(Promise, INTERNAL) {
1810var PromiseMap = Promise.map;
1811
1812Promise.prototype.filter = function (fn, options) {
1813 return PromiseMap(this, fn, options, INTERNAL);
1814};
1815
1816Promise.filter = function (promises, fn, options) {
1817 return PromiseMap(promises, fn, options, INTERNAL);
1818};
1819};
1820
1821},{}],15:[function(_dereq_,module,exports){
1822"use strict";
1823module.exports = function(Promise, tryConvertToPromise) {
1824var util = _dereq_("./util");
1825var CancellationError = Promise.CancellationError;
1826var errorObj = util.errorObj;
1827
1828function PassThroughHandlerContext(promise, type, handler) {
1829 this.promise = promise;
1830 this.type = type;
1831 this.handler = handler;
1832 this.called = false;
1833 this.cancelPromise = null;
1834}
1835
1836PassThroughHandlerContext.prototype.isFinallyHandler = function() {
1837 return this.type === 0;
1838};
1839
1840function FinallyHandlerCancelReaction(finallyHandler) {
1841 this.finallyHandler = finallyHandler;
1842}
1843
1844FinallyHandlerCancelReaction.prototype._resultCancelled = function() {
1845 checkCancel(this.finallyHandler);
1846};
1847
1848function checkCancel(ctx, reason) {
1849 if (ctx.cancelPromise != null) {
1850 if (arguments.length > 1) {
1851 ctx.cancelPromise._reject(reason);
1852 } else {
1853 ctx.cancelPromise._cancel();
1854 }
1855 ctx.cancelPromise = null;
1856 return true;
1857 }
1858 return false;
1859}
1860
1861function succeed() {
1862 return finallyHandler.call(this, this.promise._target()._settledValue());
1863}
1864function fail(reason) {
1865 if (checkCancel(this, reason)) return;
1866 errorObj.e = reason;
1867 return errorObj;
1868}
1869function finallyHandler(reasonOrValue) {
1870 var promise = this.promise;
1871 var handler = this.handler;
1872
1873 if (!this.called) {
1874 this.called = true;
1875 var ret = this.isFinallyHandler()
1876 ? handler.call(promise._boundValue())
1877 : handler.call(promise._boundValue(), reasonOrValue);
1878 if (ret !== undefined) {
1879 promise._setReturnedNonUndefined();
1880 var maybePromise = tryConvertToPromise(ret, promise);
1881 if (maybePromise instanceof Promise) {
1882 if (this.cancelPromise != null) {
1883 if (maybePromise.isCancelled()) {
1884 var reason =
1885 new CancellationError("late cancellation observer");
1886 promise._attachExtraTrace(reason);
1887 errorObj.e = reason;
1888 return errorObj;
1889 } else if (maybePromise.isPending()) {
1890 maybePromise._attachCancellationCallback(
1891 new FinallyHandlerCancelReaction(this));
1892 }
1893 }
1894 return maybePromise._then(
1895 succeed, fail, undefined, this, undefined);
1896 }
1897 }
1898 }
1899
1900 if (promise.isRejected()) {
1901 checkCancel(this);
1902 errorObj.e = reasonOrValue;
1903 return errorObj;
1904 } else {
1905 checkCancel(this);
1906 return reasonOrValue;
1907 }
1908}
1909
1910Promise.prototype._passThrough = function(handler, type, success, fail) {
1911 if (typeof handler !== "function") return this.then();
1912 return this._then(success,
1913 fail,
1914 undefined,
1915 new PassThroughHandlerContext(this, type, handler),
1916 undefined);
1917};
1918
1919Promise.prototype.lastly =
1920Promise.prototype["finally"] = function (handler) {
1921 return this._passThrough(handler,
1922 0,
1923 finallyHandler,
1924 finallyHandler);
1925};
1926
1927Promise.prototype.tap = function (handler) {
1928 return this._passThrough(handler, 1, finallyHandler);
1929};
1930
1931return PassThroughHandlerContext;
1932};
1933
1934},{"./util":36}],16:[function(_dereq_,module,exports){
1935"use strict";
1936module.exports = function(Promise,
1937 apiRejection,
1938 INTERNAL,
1939 tryConvertToPromise,
1940 Proxyable,
1941 debug) {
1942var errors = _dereq_("./errors");
1943var TypeError = errors.TypeError;
1944var util = _dereq_("./util");
1945var errorObj = util.errorObj;
1946var tryCatch = util.tryCatch;
1947var yieldHandlers = [];
1948
1949function promiseFromYieldHandler(value, yieldHandlers, traceParent) {
1950 for (var i = 0; i < yieldHandlers.length; ++i) {
1951 traceParent._pushContext();
1952 var result = tryCatch(yieldHandlers[i])(value);
1953 traceParent._popContext();
1954 if (result === errorObj) {
1955 traceParent._pushContext();
1956 var ret = Promise.reject(errorObj.e);
1957 traceParent._popContext();
1958 return ret;
1959 }
1960 var maybePromise = tryConvertToPromise(result, traceParent);
1961 if (maybePromise instanceof Promise) return maybePromise;
1962 }
1963 return null;
1964}
1965
1966function PromiseSpawn(generatorFunction, receiver, yieldHandler, stack) {
1967 if (debug.cancellation()) {
1968 var internal = new Promise(INTERNAL);
1969 var _finallyPromise = this._finallyPromise = new Promise(INTERNAL);
1970 this._promise = internal.lastly(function() {
1971 return _finallyPromise;
1972 });
1973 internal._captureStackTrace();
1974 internal._setOnCancel(this);
1975 } else {
1976 var promise = this._promise = new Promise(INTERNAL);
1977 promise._captureStackTrace();
1978 }
1979 this._stack = stack;
1980 this._generatorFunction = generatorFunction;
1981 this._receiver = receiver;
1982 this._generator = undefined;
1983 this._yieldHandlers = typeof yieldHandler === "function"
1984 ? [yieldHandler].concat(yieldHandlers)
1985 : yieldHandlers;
1986 this._yieldedPromise = null;
1987 this._cancellationPhase = false;
1988}
1989util.inherits(PromiseSpawn, Proxyable);
1990
1991PromiseSpawn.prototype._isResolved = function() {
1992 return this._promise === null;
1993};
1994
1995PromiseSpawn.prototype._cleanup = function() {
1996 this._promise = this._generator = null;
1997 if (debug.cancellation() && this._finallyPromise !== null) {
1998 this._finallyPromise._fulfill();
1999 this._finallyPromise = null;
2000 }
2001};
2002
2003PromiseSpawn.prototype._promiseCancelled = function() {
2004 if (this._isResolved()) return;
2005 var implementsReturn = typeof this._generator["return"] !== "undefined";
2006
2007 var result;
2008 if (!implementsReturn) {
2009 var reason = new Promise.CancellationError(
2010 "generator .return() sentinel");
2011 Promise.coroutine.returnSentinel = reason;
2012 this._promise._attachExtraTrace(reason);
2013 this._promise._pushContext();
2014 result = tryCatch(this._generator["throw"]).call(this._generator,
2015 reason);
2016 this._promise._popContext();
2017 } else {
2018 this._promise._pushContext();
2019 result = tryCatch(this._generator["return"]).call(this._generator,
2020 undefined);
2021 this._promise._popContext();
2022 }
2023 this._cancellationPhase = true;
2024 this._yieldedPromise = null;
2025 this._continue(result);
2026};
2027
2028PromiseSpawn.prototype._promiseFulfilled = function(value) {
2029 this._yieldedPromise = null;
2030 this._promise._pushContext();
2031 var result = tryCatch(this._generator.next).call(this._generator, value);
2032 this._promise._popContext();
2033 this._continue(result);
2034};
2035
2036PromiseSpawn.prototype._promiseRejected = function(reason) {
2037 this._yieldedPromise = null;
2038 this._promise._attachExtraTrace(reason);
2039 this._promise._pushContext();
2040 var result = tryCatch(this._generator["throw"])
2041 .call(this._generator, reason);
2042 this._promise._popContext();
2043 this._continue(result);
2044};
2045
2046PromiseSpawn.prototype._resultCancelled = function() {
2047 if (this._yieldedPromise instanceof Promise) {
2048 var promise = this._yieldedPromise;
2049 this._yieldedPromise = null;
2050 promise.cancel();
2051 }
2052};
2053
2054PromiseSpawn.prototype.promise = function () {
2055 return this._promise;
2056};
2057
2058PromiseSpawn.prototype._run = function () {
2059 this._generator = this._generatorFunction.call(this._receiver);
2060 this._receiver =
2061 this._generatorFunction = undefined;
2062 this._promiseFulfilled(undefined);
2063};
2064
2065PromiseSpawn.prototype._continue = function (result) {
2066 var promise = this._promise;
2067 if (result === errorObj) {
2068 this._cleanup();
2069 if (this._cancellationPhase) {
2070 return promise.cancel();
2071 } else {
2072 return promise._rejectCallback(result.e, false);
2073 }
2074 }
2075
2076 var value = result.value;
2077 if (result.done === true) {
2078 this._cleanup();
2079 if (this._cancellationPhase) {
2080 return promise.cancel();
2081 } else {
2082 return promise._resolveCallback(value);
2083 }
2084 } else {
2085 var maybePromise = tryConvertToPromise(value, this._promise);
2086 if (!(maybePromise instanceof Promise)) {
2087 maybePromise =
2088 promiseFromYieldHandler(maybePromise,
2089 this._yieldHandlers,
2090 this._promise);
2091 if (maybePromise === null) {
2092 this._promiseRejected(
2093 new TypeError(
2094 "A value %s was yielded that could not be treated as a promise\u000a\u000a See http://goo.gl/MqrFmX\u000a\u000a".replace("%s", value) +
2095 "From coroutine:\u000a" +
2096 this._stack.split("\n").slice(1, -7).join("\n")
2097 )
2098 );
2099 return;
2100 }
2101 }
2102 maybePromise = maybePromise._target();
2103 var bitField = maybePromise._bitField;
2104 ;
2105 if (((bitField & 50397184) === 0)) {
2106 this._yieldedPromise = maybePromise;
2107 maybePromise._proxy(this, null);
2108 } else if (((bitField & 33554432) !== 0)) {
2109 this._promiseFulfilled(maybePromise._value());
2110 } else if (((bitField & 16777216) !== 0)) {
2111 this._promiseRejected(maybePromise._reason());
2112 } else {
2113 this._promiseCancelled();
2114 }
2115 }
2116};
2117
2118Promise.coroutine = function (generatorFunction, options) {
2119 if (typeof generatorFunction !== "function") {
2120 throw new TypeError("generatorFunction must be a function\u000a\u000a See http://goo.gl/MqrFmX\u000a");
2121 }
2122 var yieldHandler = Object(options).yieldHandler;
2123 var PromiseSpawn$ = PromiseSpawn;
2124 var stack = new Error().stack;
2125 return function () {
2126 var generator = generatorFunction.apply(this, arguments);
2127 var spawn = new PromiseSpawn$(undefined, undefined, yieldHandler,
2128 stack);
2129 var ret = spawn.promise();
2130 spawn._generator = generator;
2131 spawn._promiseFulfilled(undefined);
2132 return ret;
2133 };
2134};
2135
2136Promise.coroutine.addYieldHandler = function(fn) {
2137 if (typeof fn !== "function") {
2138 throw new TypeError("expecting a function but got " + util.classString(fn));
2139 }
2140 yieldHandlers.push(fn);
2141};
2142
2143Promise.spawn = function (generatorFunction) {
2144 debug.deprecated("Promise.spawn()", "Promise.coroutine()");
2145 if (typeof generatorFunction !== "function") {
2146 return apiRejection("generatorFunction must be a function\u000a\u000a See http://goo.gl/MqrFmX\u000a");
2147 }
2148 var spawn = new PromiseSpawn(generatorFunction, this);
2149 var ret = spawn.promise();
2150 spawn._run(Promise.spawn);
2151 return ret;
2152};
2153};
2154
2155},{"./errors":12,"./util":36}],17:[function(_dereq_,module,exports){
2156"use strict";
2157module.exports =
2158function(Promise, PromiseArray, tryConvertToPromise, INTERNAL) {
2159var util = _dereq_("./util");
2160var canEvaluate = util.canEvaluate;
2161var tryCatch = util.tryCatch;
2162var errorObj = util.errorObj;
2163var reject;
2164
2165if (!true) {
2166if (canEvaluate) {
2167 var thenCallback = function(i) {
2168 return new Function("value", "holder", " \n\
2169 'use strict'; \n\
2170 holder.pIndex = value; \n\
2171 holder.checkFulfillment(this); \n\
2172 ".replace(/Index/g, i));
2173 };
2174
2175 var promiseSetter = function(i) {
2176 return new Function("promise", "holder", " \n\
2177 'use strict'; \n\
2178 holder.pIndex = promise; \n\
2179 ".replace(/Index/g, i));
2180 };
2181
2182 var generateHolderClass = function(total) {
2183 var props = new Array(total);
2184 for (var i = 0; i < props.length; ++i) {
2185 props[i] = "this.p" + (i+1);
2186 }
2187 var assignment = props.join(" = ") + " = null;";
2188 var cancellationCode= "var promise;\n" + props.map(function(prop) {
2189 return " \n\
2190 promise = " + prop + "; \n\
2191 if (promise instanceof Promise) { \n\
2192 promise.cancel(); \n\
2193 } \n\
2194 ";
2195 }).join("\n");
2196 var passedArguments = props.join(", ");
2197 var name = "Holder$" + total;
2198
2199
2200 var code = "return function(tryCatch, errorObj, Promise) { \n\
2201 'use strict'; \n\
2202 function [TheName](fn) { \n\
2203 [TheProperties] \n\
2204 this.fn = fn; \n\
2205 this.now = 0; \n\
2206 } \n\
2207 [TheName].prototype.checkFulfillment = function(promise) { \n\
2208 var now = ++this.now; \n\
2209 if (now === [TheTotal]) { \n\
2210 promise._pushContext(); \n\
2211 var callback = this.fn; \n\
2212 var ret = tryCatch(callback)([ThePassedArguments]); \n\
2213 promise._popContext(); \n\
2214 if (ret === errorObj) { \n\
2215 promise._rejectCallback(ret.e, false); \n\
2216 } else { \n\
2217 promise._resolveCallback(ret); \n\
2218 } \n\
2219 } \n\
2220 }; \n\
2221 \n\
2222 [TheName].prototype._resultCancelled = function() { \n\
2223 [CancellationCode] \n\
2224 }; \n\
2225 \n\
2226 return [TheName]; \n\
2227 }(tryCatch, errorObj, Promise); \n\
2228 ";
2229
2230 code = code.replace(/\[TheName\]/g, name)
2231 .replace(/\[TheTotal\]/g, total)
2232 .replace(/\[ThePassedArguments\]/g, passedArguments)
2233 .replace(/\[TheProperties\]/g, assignment)
2234 .replace(/\[CancellationCode\]/g, cancellationCode);
2235
2236 return new Function("tryCatch", "errorObj", "Promise", code)
2237 (tryCatch, errorObj, Promise);
2238 };
2239
2240 var holderClasses = [];
2241 var thenCallbacks = [];
2242 var promiseSetters = [];
2243
2244 for (var i = 0; i < 8; ++i) {
2245 holderClasses.push(generateHolderClass(i + 1));
2246 thenCallbacks.push(thenCallback(i + 1));
2247 promiseSetters.push(promiseSetter(i + 1));
2248 }
2249
2250 reject = function (reason) {
2251 this._reject(reason);
2252 };
2253}}
2254
2255Promise.join = function () {
2256 var last = arguments.length - 1;
2257 var fn;
2258 if (last > 0 && typeof arguments[last] === "function") {
2259 fn = arguments[last];
2260 if (!true) {
2261 if (last <= 8 && canEvaluate) {
2262 var ret = new Promise(INTERNAL);
2263 ret._captureStackTrace();
2264 var HolderClass = holderClasses[last - 1];
2265 var holder = new HolderClass(fn);
2266 var callbacks = thenCallbacks;
2267
2268 for (var i = 0; i < last; ++i) {
2269 var maybePromise = tryConvertToPromise(arguments[i], ret);
2270 if (maybePromise instanceof Promise) {
2271 maybePromise = maybePromise._target();
2272 var bitField = maybePromise._bitField;
2273 ;
2274 if (((bitField & 50397184) === 0)) {
2275 maybePromise._then(callbacks[i], reject,
2276 undefined, ret, holder);
2277 promiseSetters[i](maybePromise, holder);
2278 } else if (((bitField & 33554432) !== 0)) {
2279 callbacks[i].call(ret,
2280 maybePromise._value(), holder);
2281 } else if (((bitField & 16777216) !== 0)) {
2282 ret._reject(maybePromise._reason());
2283 } else {
2284 ret._cancel();
2285 }
2286 } else {
2287 callbacks[i].call(ret, maybePromise, holder);
2288 }
2289 }
2290 if (!ret._isFateSealed()) {
2291 ret._setAsyncGuaranteed();
2292 ret._setOnCancel(holder);
2293 }
2294 return ret;
2295 }
2296 }
2297 }
2298 var args = [].slice.call(arguments);;
2299 if (fn) args.pop();
2300 var ret = new PromiseArray(args).promise();
2301 return fn !== undefined ? ret.spread(fn) : ret;
2302};
2303
2304};
2305
2306},{"./util":36}],18:[function(_dereq_,module,exports){
2307"use strict";
2308module.exports = function(Promise,
2309 PromiseArray,
2310 apiRejection,
2311 tryConvertToPromise,
2312 INTERNAL,
2313 debug) {
2314var getDomain = Promise._getDomain;
2315var util = _dereq_("./util");
2316var tryCatch = util.tryCatch;
2317var errorObj = util.errorObj;
2318var EMPTY_ARRAY = [];
2319
2320function MappingPromiseArray(promises, fn, limit, _filter) {
2321 this.constructor$(promises);
2322 this._promise._captureStackTrace();
2323 var domain = getDomain();
2324 this._callback = domain === null ? fn : domain.bind(fn);
2325 this._preservedValues = _filter === INTERNAL
2326 ? new Array(this.length())
2327 : null;
2328 this._limit = limit;
2329 this._inFlight = 0;
2330 this._queue = limit >= 1 ? [] : EMPTY_ARRAY;
2331 this._init$(undefined, -2);
2332}
2333util.inherits(MappingPromiseArray, PromiseArray);
2334
2335MappingPromiseArray.prototype._init = function () {};
2336
2337MappingPromiseArray.prototype._promiseFulfilled = function (value, index) {
2338 var values = this._values;
2339 var length = this.length();
2340 var preservedValues = this._preservedValues;
2341 var limit = this._limit;
2342
2343 if (index < 0) {
2344 index = (index * -1) - 1;
2345 values[index] = value;
2346 if (limit >= 1) {
2347 this._inFlight--;
2348 this._drainQueue();
2349 if (this._isResolved()) return true;
2350 }
2351 } else {
2352 if (limit >= 1 && this._inFlight >= limit) {
2353 values[index] = value;
2354 this._queue.push(index);
2355 return false;
2356 }
2357 if (preservedValues !== null) preservedValues[index] = value;
2358
2359 var promise = this._promise;
2360 var callback = this._callback;
2361 var receiver = promise._boundValue();
2362 promise._pushContext();
2363 var ret = tryCatch(callback).call(receiver, value, index, length);
2364 var promiseCreated = promise._popContext();
2365 debug.checkForgottenReturns(
2366 ret,
2367 promiseCreated,
2368 preservedValues !== null ? "Promise.filter" : "Promise.map",
2369 promise
2370 );
2371 if (ret === errorObj) {
2372 this._reject(ret.e);
2373 return true;
2374 }
2375
2376 var maybePromise = tryConvertToPromise(ret, this._promise);
2377 if (maybePromise instanceof Promise) {
2378 maybePromise = maybePromise._target();
2379 var bitField = maybePromise._bitField;
2380 ;
2381 if (((bitField & 50397184) === 0)) {
2382 if (limit >= 1) this._inFlight++;
2383 values[index] = maybePromise;
2384 maybePromise._proxy(this, (index + 1) * -1);
2385 return false;
2386 } else if (((bitField & 33554432) !== 0)) {
2387 ret = maybePromise._value();
2388 } else if (((bitField & 16777216) !== 0)) {
2389 this._reject(maybePromise._reason());
2390 return true;
2391 } else {
2392 this._cancel();
2393 return true;
2394 }
2395 }
2396 values[index] = ret;
2397 }
2398 var totalResolved = ++this._totalResolved;
2399 if (totalResolved >= length) {
2400 if (preservedValues !== null) {
2401 this._filter(values, preservedValues);
2402 } else {
2403 this._resolve(values);
2404 }
2405 return true;
2406 }
2407 return false;
2408};
2409
2410MappingPromiseArray.prototype._drainQueue = function () {
2411 var queue = this._queue;
2412 var limit = this._limit;
2413 var values = this._values;
2414 while (queue.length > 0 && this._inFlight < limit) {
2415 if (this._isResolved()) return;
2416 var index = queue.pop();
2417 this._promiseFulfilled(values[index], index);
2418 }
2419};
2420
2421MappingPromiseArray.prototype._filter = function (booleans, values) {
2422 var len = values.length;
2423 var ret = new Array(len);
2424 var j = 0;
2425 for (var i = 0; i < len; ++i) {
2426 if (booleans[i]) ret[j++] = values[i];
2427 }
2428 ret.length = j;
2429 this._resolve(ret);
2430};
2431
2432MappingPromiseArray.prototype.preservedValues = function () {
2433 return this._preservedValues;
2434};
2435
2436function map(promises, fn, options, _filter) {
2437 if (typeof fn !== "function") {
2438 return apiRejection("expecting a function but got " + util.classString(fn));
2439 }
2440
2441 var limit = 0;
2442 if (options !== undefined) {
2443 if (typeof options === "object" && options !== null) {
2444 if (typeof options.concurrency !== "number") {
2445 return Promise.reject(
2446 new TypeError("'concurrency' must be a number but it is " +
2447 util.classString(options.concurrency)));
2448 }
2449 limit = options.concurrency;
2450 } else {
2451 return Promise.reject(new TypeError(
2452 "options argument must be an object but it is " +
2453 util.classString(options)));
2454 }
2455 }
2456 limit = typeof limit === "number" &&
2457 isFinite(limit) && limit >= 1 ? limit : 0;
2458 return new MappingPromiseArray(promises, fn, limit, _filter).promise();
2459}
2460
2461Promise.prototype.map = function (fn, options) {
2462 return map(this, fn, options, null);
2463};
2464
2465Promise.map = function (promises, fn, options, _filter) {
2466 return map(promises, fn, options, _filter);
2467};
2468
2469
2470};
2471
2472},{"./util":36}],19:[function(_dereq_,module,exports){
2473"use strict";
2474module.exports =
2475function(Promise, INTERNAL, tryConvertToPromise, apiRejection, debug) {
2476var util = _dereq_("./util");
2477var tryCatch = util.tryCatch;
2478
2479Promise.method = function (fn) {
2480 if (typeof fn !== "function") {
2481 throw new Promise.TypeError("expecting a function but got " + util.classString(fn));
2482 }
2483 return function () {
2484 var ret = new Promise(INTERNAL);
2485 ret._captureStackTrace();
2486 ret._pushContext();
2487 var value = tryCatch(fn).apply(this, arguments);
2488 var promiseCreated = ret._popContext();
2489 debug.checkForgottenReturns(
2490 value, promiseCreated, "Promise.method", ret);
2491 ret._resolveFromSyncValue(value);
2492 return ret;
2493 };
2494};
2495
2496Promise.attempt = Promise["try"] = function (fn) {
2497 if (typeof fn !== "function") {
2498 return apiRejection("expecting a function but got " + util.classString(fn));
2499 }
2500 var ret = new Promise(INTERNAL);
2501 ret._captureStackTrace();
2502 ret._pushContext();
2503 var value;
2504 if (arguments.length > 1) {
2505 debug.deprecated("calling Promise.try with more than 1 argument");
2506 var arg = arguments[1];
2507 var ctx = arguments[2];
2508 value = util.isArray(arg) ? tryCatch(fn).apply(ctx, arg)
2509 : tryCatch(fn).call(ctx, arg);
2510 } else {
2511 value = tryCatch(fn)();
2512 }
2513 var promiseCreated = ret._popContext();
2514 debug.checkForgottenReturns(
2515 value, promiseCreated, "Promise.try", ret);
2516 ret._resolveFromSyncValue(value);
2517 return ret;
2518};
2519
2520Promise.prototype._resolveFromSyncValue = function (value) {
2521 if (value === util.errorObj) {
2522 this._rejectCallback(value.e, false);
2523 } else {
2524 this._resolveCallback(value, true);
2525 }
2526};
2527};
2528
2529},{"./util":36}],20:[function(_dereq_,module,exports){
2530"use strict";
2531var util = _dereq_("./util");
2532var maybeWrapAsError = util.maybeWrapAsError;
2533var errors = _dereq_("./errors");
2534var OperationalError = errors.OperationalError;
2535var es5 = _dereq_("./es5");
2536
2537function isUntypedError(obj) {
2538 return obj instanceof Error &&
2539 es5.getPrototypeOf(obj) === Error.prototype;
2540}
2541
2542var rErrorKey = /^(?:name|message|stack|cause)$/;
2543function wrapAsOperationalError(obj) {
2544 var ret;
2545 if (isUntypedError(obj)) {
2546 ret = new OperationalError(obj);
2547 ret.name = obj.name;
2548 ret.message = obj.message;
2549 ret.stack = obj.stack;
2550 var keys = es5.keys(obj);
2551 for (var i = 0; i < keys.length; ++i) {
2552 var key = keys[i];
2553 if (!rErrorKey.test(key)) {
2554 ret[key] = obj[key];
2555 }
2556 }
2557 return ret;
2558 }
2559 util.markAsOriginatingFromRejection(obj);
2560 return obj;
2561}
2562
2563function nodebackForPromise(promise, multiArgs) {
2564 return function(err, value) {
2565 if (promise === null) return;
2566 if (err) {
2567 var wrapped = wrapAsOperationalError(maybeWrapAsError(err));
2568 promise._attachExtraTrace(wrapped);
2569 promise._reject(wrapped);
2570 } else if (!multiArgs) {
2571 promise._fulfill(value);
2572 } else {
2573 var args = [].slice.call(arguments, 1);;
2574 promise._fulfill(args);
2575 }
2576 promise = null;
2577 };
2578}
2579
2580module.exports = nodebackForPromise;
2581
2582},{"./errors":12,"./es5":13,"./util":36}],21:[function(_dereq_,module,exports){
2583"use strict";
2584module.exports = function(Promise) {
2585var util = _dereq_("./util");
2586var async = Promise._async;
2587var tryCatch = util.tryCatch;
2588var errorObj = util.errorObj;
2589
2590function spreadAdapter(val, nodeback) {
2591 var promise = this;
2592 if (!util.isArray(val)) return successAdapter.call(promise, val, nodeback);
2593 var ret =
2594 tryCatch(nodeback).apply(promise._boundValue(), [null].concat(val));
2595 if (ret === errorObj) {
2596 async.throwLater(ret.e);
2597 }
2598}
2599
2600function successAdapter(val, nodeback) {
2601 var promise = this;
2602 var receiver = promise._boundValue();
2603 var ret = val === undefined
2604 ? tryCatch(nodeback).call(receiver, null)
2605 : tryCatch(nodeback).call(receiver, null, val);
2606 if (ret === errorObj) {
2607 async.throwLater(ret.e);
2608 }
2609}
2610function errorAdapter(reason, nodeback) {
2611 var promise = this;
2612 if (!reason) {
2613 var newReason = new Error(reason + "");
2614 newReason.cause = reason;
2615 reason = newReason;
2616 }
2617 var ret = tryCatch(nodeback).call(promise._boundValue(), reason);
2618 if (ret === errorObj) {
2619 async.throwLater(ret.e);
2620 }
2621}
2622
2623Promise.prototype.asCallback = Promise.prototype.nodeify = function (nodeback,
2624 options) {
2625 if (typeof nodeback == "function") {
2626 var adapter = successAdapter;
2627 if (options !== undefined && Object(options).spread) {
2628 adapter = spreadAdapter;
2629 }
2630 this._then(
2631 adapter,
2632 errorAdapter,
2633 undefined,
2634 this,
2635 nodeback
2636 );
2637 }
2638 return this;
2639};
2640};
2641
2642},{"./util":36}],22:[function(_dereq_,module,exports){
2643"use strict";
2644module.exports = function() {
2645var makeSelfResolutionError = function () {
2646 return new TypeError("circular promise resolution chain\u000a\u000a See http://goo.gl/MqrFmX\u000a");
2647};
2648var reflectHandler = function() {
2649 return new Promise.PromiseInspection(this._target());
2650};
2651var apiRejection = function(msg) {
2652 return Promise.reject(new TypeError(msg));
2653};
2654function Proxyable() {}
2655var UNDEFINED_BINDING = {};
2656var util = _dereq_("./util");
2657
2658var getDomain;
2659if (util.isNode) {
2660 getDomain = function() {
2661 var ret = process.domain;
2662 if (ret === undefined) ret = null;
2663 return ret;
2664 };
2665} else {
2666 getDomain = function() {
2667 return null;
2668 };
2669}
2670util.notEnumerableProp(Promise, "_getDomain", getDomain);
2671
2672var es5 = _dereq_("./es5");
2673var Async = _dereq_("./async");
2674var async = new Async();
2675es5.defineProperty(Promise, "_async", {value: async});
2676var errors = _dereq_("./errors");
2677var TypeError = Promise.TypeError = errors.TypeError;
2678Promise.RangeError = errors.RangeError;
2679var CancellationError = Promise.CancellationError = errors.CancellationError;
2680Promise.TimeoutError = errors.TimeoutError;
2681Promise.OperationalError = errors.OperationalError;
2682Promise.RejectionError = errors.OperationalError;
2683Promise.AggregateError = errors.AggregateError;
2684var INTERNAL = function(){};
2685var APPLY = {};
2686var NEXT_FILTER = {};
2687var tryConvertToPromise = _dereq_("./thenables")(Promise, INTERNAL);
2688var PromiseArray =
2689 _dereq_("./promise_array")(Promise, INTERNAL,
2690 tryConvertToPromise, apiRejection, Proxyable);
2691var Context = _dereq_("./context")(Promise);
2692 /*jshint unused:false*/
2693var createContext = Context.create;
2694var debug = _dereq_("./debuggability")(Promise, Context);
2695var CapturedTrace = debug.CapturedTrace;
2696var PassThroughHandlerContext =
2697 _dereq_("./finally")(Promise, tryConvertToPromise);
2698var catchFilter = _dereq_("./catch_filter")(NEXT_FILTER);
2699var nodebackForPromise = _dereq_("./nodeback");
2700var errorObj = util.errorObj;
2701var tryCatch = util.tryCatch;
2702function check(self, executor) {
2703 if (typeof executor !== "function") {
2704 throw new TypeError("expecting a function but got " + util.classString(executor));
2705 }
2706 if (self.constructor !== Promise) {
2707 throw new TypeError("the promise constructor cannot be invoked directly\u000a\u000a See http://goo.gl/MqrFmX\u000a");
2708 }
2709}
2710
2711function Promise(executor) {
2712 this._bitField = 0;
2713 this._fulfillmentHandler0 = undefined;
2714 this._rejectionHandler0 = undefined;
2715 this._promise0 = undefined;
2716 this._receiver0 = undefined;
2717 if (executor !== INTERNAL) {
2718 check(this, executor);
2719 this._resolveFromExecutor(executor);
2720 }
2721 this._promiseCreated();
2722 this._fireEvent("promiseCreated", this);
2723}
2724
2725Promise.prototype.toString = function () {
2726 return "[object Promise]";
2727};
2728
2729Promise.prototype.caught = Promise.prototype["catch"] = function (fn) {
2730 var len = arguments.length;
2731 if (len > 1) {
2732 var catchInstances = new Array(len - 1),
2733 j = 0, i;
2734 for (i = 0; i < len - 1; ++i) {
2735 var item = arguments[i];
2736 if (util.isObject(item)) {
2737 catchInstances[j++] = item;
2738 } else {
2739 return apiRejection("expecting an object but got " + util.classString(item));
2740 }
2741 }
2742 catchInstances.length = j;
2743 fn = arguments[i];
2744 return this.then(undefined, catchFilter(catchInstances, fn, this));
2745 }
2746 return this.then(undefined, fn);
2747};
2748
2749Promise.prototype.reflect = function () {
2750 return this._then(reflectHandler,
2751 reflectHandler, undefined, this, undefined);
2752};
2753
2754Promise.prototype.then = function (didFulfill, didReject) {
2755 if (debug.warnings() && arguments.length > 0 &&
2756 typeof didFulfill !== "function" &&
2757 typeof didReject !== "function") {
2758 var msg = ".then() only accepts functions but was passed: " +
2759 util.classString(didFulfill);
2760 if (arguments.length > 1) {
2761 msg += ", " + util.classString(didReject);
2762 }
2763 this._warn(msg);
2764 }
2765 return this._then(didFulfill, didReject, undefined, undefined, undefined);
2766};
2767
2768Promise.prototype.done = function (didFulfill, didReject) {
2769 var promise =
2770 this._then(didFulfill, didReject, undefined, undefined, undefined);
2771 promise._setIsFinal();
2772};
2773
2774Promise.prototype.spread = function (fn) {
2775 if (typeof fn !== "function") {
2776 return apiRejection("expecting a function but got " + util.classString(fn));
2777 }
2778 return this.all()._then(fn, undefined, undefined, APPLY, undefined);
2779};
2780
2781Promise.prototype.toJSON = function () {
2782 var ret = {
2783 isFulfilled: false,
2784 isRejected: false,
2785 fulfillmentValue: undefined,
2786 rejectionReason: undefined
2787 };
2788 if (this.isFulfilled()) {
2789 ret.fulfillmentValue = this.value();
2790 ret.isFulfilled = true;
2791 } else if (this.isRejected()) {
2792 ret.rejectionReason = this.reason();
2793 ret.isRejected = true;
2794 }
2795 return ret;
2796};
2797
2798Promise.prototype.all = function () {
2799 if (arguments.length > 0) {
2800 this._warn(".all() was passed arguments but it does not take any");
2801 }
2802 return new PromiseArray(this).promise();
2803};
2804
2805Promise.prototype.error = function (fn) {
2806 return this.caught(util.originatesFromRejection, fn);
2807};
2808
2809Promise.getNewLibraryCopy = module.exports;
2810
2811Promise.is = function (val) {
2812 return val instanceof Promise;
2813};
2814
2815Promise.fromNode = Promise.fromCallback = function(fn) {
2816 var ret = new Promise(INTERNAL);
2817 ret._captureStackTrace();
2818 var multiArgs = arguments.length > 1 ? !!Object(arguments[1]).multiArgs
2819 : false;
2820 var result = tryCatch(fn)(nodebackForPromise(ret, multiArgs));
2821 if (result === errorObj) {
2822 ret._rejectCallback(result.e, true);
2823 }
2824 if (!ret._isFateSealed()) ret._setAsyncGuaranteed();
2825 return ret;
2826};
2827
2828Promise.all = function (promises) {
2829 return new PromiseArray(promises).promise();
2830};
2831
2832Promise.cast = function (obj) {
2833 var ret = tryConvertToPromise(obj);
2834 if (!(ret instanceof Promise)) {
2835 ret = new Promise(INTERNAL);
2836 ret._captureStackTrace();
2837 ret._setFulfilled();
2838 ret._rejectionHandler0 = obj;
2839 }
2840 return ret;
2841};
2842
2843Promise.resolve = Promise.fulfilled = Promise.cast;
2844
2845Promise.reject = Promise.rejected = function (reason) {
2846 var ret = new Promise(INTERNAL);
2847 ret._captureStackTrace();
2848 ret._rejectCallback(reason, true);
2849 return ret;
2850};
2851
2852Promise.setScheduler = function(fn) {
2853 if (typeof fn !== "function") {
2854 throw new TypeError("expecting a function but got " + util.classString(fn));
2855 }
2856 return async.setScheduler(fn);
2857};
2858
2859Promise.prototype._then = function (
2860 didFulfill,
2861 didReject,
2862 _, receiver,
2863 internalData
2864) {
2865 var haveInternalData = internalData !== undefined;
2866 var promise = haveInternalData ? internalData : new Promise(INTERNAL);
2867 var target = this._target();
2868 var bitField = target._bitField;
2869
2870 if (!haveInternalData) {
2871 promise._propagateFrom(this, 3);
2872 promise._captureStackTrace();
2873 if (receiver === undefined &&
2874 ((this._bitField & 2097152) !== 0)) {
2875 if (!((bitField & 50397184) === 0)) {
2876 receiver = this._boundValue();
2877 } else {
2878 receiver = target === this ? undefined : this._boundTo;
2879 }
2880 }
2881 this._fireEvent("promiseChained", this, promise);
2882 }
2883
2884 var domain = getDomain();
2885 if (!((bitField & 50397184) === 0)) {
2886 var handler, value, settler = target._settlePromiseCtx;
2887 if (((bitField & 33554432) !== 0)) {
2888 value = target._rejectionHandler0;
2889 handler = didFulfill;
2890 } else if (((bitField & 16777216) !== 0)) {
2891 value = target._fulfillmentHandler0;
2892 handler = didReject;
2893 target._unsetRejectionIsUnhandled();
2894 } else {
2895 settler = target._settlePromiseLateCancellationObserver;
2896 value = new CancellationError("late cancellation observer");
2897 target._attachExtraTrace(value);
2898 handler = didReject;
2899 }
2900
2901 async.invoke(settler, target, {
2902 handler: domain === null ? handler
2903 : (typeof handler === "function" && domain.bind(handler)),
2904 promise: promise,
2905 receiver: receiver,
2906 value: value
2907 });
2908 } else {
2909 target._addCallbacks(didFulfill, didReject, promise, receiver, domain);
2910 }
2911
2912 return promise;
2913};
2914
2915Promise.prototype._length = function () {
2916 return this._bitField & 65535;
2917};
2918
2919Promise.prototype._isFateSealed = function () {
2920 return (this._bitField & 117506048) !== 0;
2921};
2922
2923Promise.prototype._isFollowing = function () {
2924 return (this._bitField & 67108864) === 67108864;
2925};
2926
2927Promise.prototype._setLength = function (len) {
2928 this._bitField = (this._bitField & -65536) |
2929 (len & 65535);
2930};
2931
2932Promise.prototype._setFulfilled = function () {
2933 this._bitField = this._bitField | 33554432;
2934 this._fireEvent("promiseFulfilled", this);
2935};
2936
2937Promise.prototype._setRejected = function () {
2938 this._bitField = this._bitField | 16777216;
2939 this._fireEvent("promiseRejected", this);
2940};
2941
2942Promise.prototype._setFollowing = function () {
2943 this._bitField = this._bitField | 67108864;
2944 this._fireEvent("promiseResolved", this);
2945};
2946
2947Promise.prototype._setIsFinal = function () {
2948 this._bitField = this._bitField | 4194304;
2949};
2950
2951Promise.prototype._isFinal = function () {
2952 return (this._bitField & 4194304) > 0;
2953};
2954
2955Promise.prototype._unsetCancelled = function() {
2956 this._bitField = this._bitField & (~65536);
2957};
2958
2959Promise.prototype._setCancelled = function() {
2960 this._bitField = this._bitField | 65536;
2961 this._fireEvent("promiseCancelled", this);
2962};
2963
2964Promise.prototype._setAsyncGuaranteed = function() {
2965 if (async.hasCustomScheduler()) return;
2966 this._bitField = this._bitField | 134217728;
2967};
2968
2969Promise.prototype._receiverAt = function (index) {
2970 var ret = index === 0 ? this._receiver0 : this[
2971 index * 4 - 4 + 3];
2972 if (ret === UNDEFINED_BINDING) {
2973 return undefined;
2974 } else if (ret === undefined && this._isBound()) {
2975 return this._boundValue();
2976 }
2977 return ret;
2978};
2979
2980Promise.prototype._promiseAt = function (index) {
2981 return this[
2982 index * 4 - 4 + 2];
2983};
2984
2985Promise.prototype._fulfillmentHandlerAt = function (index) {
2986 return this[
2987 index * 4 - 4 + 0];
2988};
2989
2990Promise.prototype._rejectionHandlerAt = function (index) {
2991 return this[
2992 index * 4 - 4 + 1];
2993};
2994
2995Promise.prototype._boundValue = function() {};
2996
2997Promise.prototype._migrateCallback0 = function (follower) {
2998 var bitField = follower._bitField;
2999 var fulfill = follower._fulfillmentHandler0;
3000 var reject = follower._rejectionHandler0;
3001 var promise = follower._promise0;
3002 var receiver = follower._receiverAt(0);
3003 if (receiver === undefined) receiver = UNDEFINED_BINDING;
3004 this._addCallbacks(fulfill, reject, promise, receiver, null);
3005};
3006
3007Promise.prototype._migrateCallbackAt = function (follower, index) {
3008 var fulfill = follower._fulfillmentHandlerAt(index);
3009 var reject = follower._rejectionHandlerAt(index);
3010 var promise = follower._promiseAt(index);
3011 var receiver = follower._receiverAt(index);
3012 if (receiver === undefined) receiver = UNDEFINED_BINDING;
3013 this._addCallbacks(fulfill, reject, promise, receiver, null);
3014};
3015
3016Promise.prototype._addCallbacks = function (
3017 fulfill,
3018 reject,
3019 promise,
3020 receiver,
3021 domain
3022) {
3023 var index = this._length();
3024
3025 if (index >= 65535 - 4) {
3026 index = 0;
3027 this._setLength(0);
3028 }
3029
3030 if (index === 0) {
3031 this._promise0 = promise;
3032 this._receiver0 = receiver;
3033 if (typeof fulfill === "function") {
3034 this._fulfillmentHandler0 =
3035 domain === null ? fulfill : domain.bind(fulfill);
3036 }
3037 if (typeof reject === "function") {
3038 this._rejectionHandler0 =
3039 domain === null ? reject : domain.bind(reject);
3040 }
3041 } else {
3042 var base = index * 4 - 4;
3043 this[base + 2] = promise;
3044 this[base + 3] = receiver;
3045 if (typeof fulfill === "function") {
3046 this[base + 0] =
3047 domain === null ? fulfill : domain.bind(fulfill);
3048 }
3049 if (typeof reject === "function") {
3050 this[base + 1] =
3051 domain === null ? reject : domain.bind(reject);
3052 }
3053 }
3054 this._setLength(index + 1);
3055 return index;
3056};
3057
3058Promise.prototype._proxy = function (proxyable, arg) {
3059 this._addCallbacks(undefined, undefined, arg, proxyable, null);
3060};
3061
3062Promise.prototype._resolveCallback = function(value, shouldBind) {
3063 if (((this._bitField & 117506048) !== 0)) return;
3064 if (value === this)
3065 return this._rejectCallback(makeSelfResolutionError(), false);
3066 var maybePromise = tryConvertToPromise(value, this);
3067 if (!(maybePromise instanceof Promise)) return this._fulfill(value);
3068
3069 if (shouldBind) this._propagateFrom(maybePromise, 2);
3070
3071 var promise = maybePromise._target();
3072
3073 if (promise === this) {
3074 this._reject(makeSelfResolutionError());
3075 return;
3076 }
3077
3078 var bitField = promise._bitField;
3079 if (((bitField & 50397184) === 0)) {
3080 var len = this._length();
3081 if (len > 0) promise._migrateCallback0(this);
3082 for (var i = 1; i < len; ++i) {
3083 promise._migrateCallbackAt(this, i);
3084 }
3085 this._setFollowing();
3086 this._setLength(0);
3087 this._setFollowee(promise);
3088 } else if (((bitField & 33554432) !== 0)) {
3089 this._fulfill(promise._value());
3090 } else if (((bitField & 16777216) !== 0)) {
3091 this._reject(promise._reason());
3092 } else {
3093 var reason = new CancellationError("late cancellation observer");
3094 promise._attachExtraTrace(reason);
3095 this._reject(reason);
3096 }
3097};
3098
3099Promise.prototype._rejectCallback =
3100function(reason, synchronous, ignoreNonErrorWarnings) {
3101 var trace = util.ensureErrorObject(reason);
3102 var hasStack = trace === reason;
3103 if (!hasStack && !ignoreNonErrorWarnings && debug.warnings()) {
3104 var message = "a promise was rejected with a non-error: " +
3105 util.classString(reason);
3106 this._warn(message, true);
3107 }
3108 this._attachExtraTrace(trace, synchronous ? hasStack : false);
3109 this._reject(reason);
3110};
3111
3112Promise.prototype._resolveFromExecutor = function (executor) {
3113 var promise = this;
3114 this._captureStackTrace();
3115 this._pushContext();
3116 var synchronous = true;
3117 var r = this._execute(executor, function(value) {
3118 promise._resolveCallback(value);
3119 }, function (reason) {
3120 promise._rejectCallback(reason, synchronous);
3121 });
3122 synchronous = false;
3123 this._popContext();
3124
3125 if (r !== undefined) {
3126 promise._rejectCallback(r, true);
3127 }
3128};
3129
3130Promise.prototype._settlePromiseFromHandler = function (
3131 handler, receiver, value, promise
3132) {
3133 var bitField = promise._bitField;
3134 if (((bitField & 65536) !== 0)) return;
3135 promise._pushContext();
3136 var x;
3137 if (receiver === APPLY) {
3138 if (!value || typeof value.length !== "number") {
3139 x = errorObj;
3140 x.e = new TypeError("cannot .spread() a non-array: " +
3141 util.classString(value));
3142 } else {
3143 x = tryCatch(handler).apply(this._boundValue(), value);
3144 }
3145 } else {
3146 x = tryCatch(handler).call(receiver, value);
3147 }
3148 var promiseCreated = promise._popContext();
3149 bitField = promise._bitField;
3150 if (((bitField & 65536) !== 0)) return;
3151
3152 if (x === NEXT_FILTER) {
3153 promise._reject(value);
3154 } else if (x === errorObj) {
3155 promise._rejectCallback(x.e, false);
3156 } else {
3157 debug.checkForgottenReturns(x, promiseCreated, "", promise, this);
3158 promise._resolveCallback(x);
3159 }
3160};
3161
3162Promise.prototype._target = function() {
3163 var ret = this;
3164 while (ret._isFollowing()) ret = ret._followee();
3165 return ret;
3166};
3167
3168Promise.prototype._followee = function() {
3169 return this._rejectionHandler0;
3170};
3171
3172Promise.prototype._setFollowee = function(promise) {
3173 this._rejectionHandler0 = promise;
3174};
3175
3176Promise.prototype._settlePromise = function(promise, handler, receiver, value) {
3177 var isPromise = promise instanceof Promise;
3178 var bitField = this._bitField;
3179 var asyncGuaranteed = ((bitField & 134217728) !== 0);
3180 if (((bitField & 65536) !== 0)) {
3181 if (isPromise) promise._invokeInternalOnCancel();
3182
3183 if (receiver instanceof PassThroughHandlerContext &&
3184 receiver.isFinallyHandler()) {
3185 receiver.cancelPromise = promise;
3186 if (tryCatch(handler).call(receiver, value) === errorObj) {
3187 promise._reject(errorObj.e);
3188 }
3189 } else if (handler === reflectHandler) {
3190 promise._fulfill(reflectHandler.call(receiver));
3191 } else if (receiver instanceof Proxyable) {
3192 receiver._promiseCancelled(promise);
3193 } else if (isPromise || promise instanceof PromiseArray) {
3194 promise._cancel();
3195 } else {
3196 receiver.cancel();
3197 }
3198 } else if (typeof handler === "function") {
3199 if (!isPromise) {
3200 handler.call(receiver, value, promise);
3201 } else {
3202 if (asyncGuaranteed) promise._setAsyncGuaranteed();
3203 this._settlePromiseFromHandler(handler, receiver, value, promise);
3204 }
3205 } else if (receiver instanceof Proxyable) {
3206 if (!receiver._isResolved()) {
3207 if (((bitField & 33554432) !== 0)) {
3208 receiver._promiseFulfilled(value, promise);
3209 } else {
3210 receiver._promiseRejected(value, promise);
3211 }
3212 }
3213 } else if (isPromise) {
3214 if (asyncGuaranteed) promise._setAsyncGuaranteed();
3215 if (((bitField & 33554432) !== 0)) {
3216 promise._fulfill(value);
3217 } else {
3218 promise._reject(value);
3219 }
3220 }
3221};
3222
3223Promise.prototype._settlePromiseLateCancellationObserver = function(ctx) {
3224 var handler = ctx.handler;
3225 var promise = ctx.promise;
3226 var receiver = ctx.receiver;
3227 var value = ctx.value;
3228 if (typeof handler === "function") {
3229 if (!(promise instanceof Promise)) {
3230 handler.call(receiver, value, promise);
3231 } else {
3232 this._settlePromiseFromHandler(handler, receiver, value, promise);
3233 }
3234 } else if (promise instanceof Promise) {
3235 promise._reject(value);
3236 }
3237};
3238
3239Promise.prototype._settlePromiseCtx = function(ctx) {
3240 this._settlePromise(ctx.promise, ctx.handler, ctx.receiver, ctx.value);
3241};
3242
3243Promise.prototype._settlePromise0 = function(handler, value, bitField) {
3244 var promise = this._promise0;
3245 var receiver = this._receiverAt(0);
3246 this._promise0 = undefined;
3247 this._receiver0 = undefined;
3248 this._settlePromise(promise, handler, receiver, value);
3249};
3250
3251Promise.prototype._clearCallbackDataAtIndex = function(index) {
3252 var base = index * 4 - 4;
3253 this[base + 2] =
3254 this[base + 3] =
3255 this[base + 0] =
3256 this[base + 1] = undefined;
3257};
3258
3259Promise.prototype._fulfill = function (value) {
3260 var bitField = this._bitField;
3261 if (((bitField & 117506048) >>> 16)) return;
3262 if (value === this) {
3263 var err = makeSelfResolutionError();
3264 this._attachExtraTrace(err);
3265 return this._reject(err);
3266 }
3267 this._setFulfilled();
3268 this._rejectionHandler0 = value;
3269
3270 if ((bitField & 65535) > 0) {
3271 if (((bitField & 134217728) !== 0)) {
3272 this._settlePromises();
3273 } else {
3274 async.settlePromises(this);
3275 }
3276 }
3277};
3278
3279Promise.prototype._reject = function (reason) {
3280 var bitField = this._bitField;
3281 if (((bitField & 117506048) >>> 16)) return;
3282 this._setRejected();
3283 this._fulfillmentHandler0 = reason;
3284
3285 if (this._isFinal()) {
3286 return async.fatalError(reason, util.isNode);
3287 }
3288
3289 if ((bitField & 65535) > 0) {
3290 async.settlePromises(this);
3291 } else {
3292 this._ensurePossibleRejectionHandled();
3293 }
3294};
3295
3296Promise.prototype._fulfillPromises = function (len, value) {
3297 for (var i = 1; i < len; i++) {
3298 var handler = this._fulfillmentHandlerAt(i);
3299 var promise = this._promiseAt(i);
3300 var receiver = this._receiverAt(i);
3301 this._clearCallbackDataAtIndex(i);
3302 this._settlePromise(promise, handler, receiver, value);
3303 }
3304};
3305
3306Promise.prototype._rejectPromises = function (len, reason) {
3307 for (var i = 1; i < len; i++) {
3308 var handler = this._rejectionHandlerAt(i);
3309 var promise = this._promiseAt(i);
3310 var receiver = this._receiverAt(i);
3311 this._clearCallbackDataAtIndex(i);
3312 this._settlePromise(promise, handler, receiver, reason);
3313 }
3314};
3315
3316Promise.prototype._settlePromises = function () {
3317 var bitField = this._bitField;
3318 var len = (bitField & 65535);
3319
3320 if (len > 0) {
3321 if (((bitField & 16842752) !== 0)) {
3322 var reason = this._fulfillmentHandler0;
3323 this._settlePromise0(this._rejectionHandler0, reason, bitField);
3324 this._rejectPromises(len, reason);
3325 } else {
3326 var value = this._rejectionHandler0;
3327 this._settlePromise0(this._fulfillmentHandler0, value, bitField);
3328 this._fulfillPromises(len, value);
3329 }
3330 this._setLength(0);
3331 }
3332 this._clearCancellationData();
3333};
3334
3335Promise.prototype._settledValue = function() {
3336 var bitField = this._bitField;
3337 if (((bitField & 33554432) !== 0)) {
3338 return this._rejectionHandler0;
3339 } else if (((bitField & 16777216) !== 0)) {
3340 return this._fulfillmentHandler0;
3341 }
3342};
3343
3344function deferResolve(v) {this.promise._resolveCallback(v);}
3345function deferReject(v) {this.promise._rejectCallback(v, false);}
3346
3347Promise.defer = Promise.pending = function() {
3348 debug.deprecated("Promise.defer", "new Promise");
3349 var promise = new Promise(INTERNAL);
3350 return {
3351 promise: promise,
3352 resolve: deferResolve,
3353 reject: deferReject
3354 };
3355};
3356
3357util.notEnumerableProp(Promise,
3358 "_makeSelfResolutionError",
3359 makeSelfResolutionError);
3360
3361_dereq_("./method")(Promise, INTERNAL, tryConvertToPromise, apiRejection,
3362 debug);
3363_dereq_("./bind")(Promise, INTERNAL, tryConvertToPromise, debug);
3364_dereq_("./cancel")(Promise, PromiseArray, apiRejection, debug);
3365_dereq_("./direct_resolve")(Promise);
3366_dereq_("./synchronous_inspection")(Promise);
3367_dereq_("./join")(
3368 Promise, PromiseArray, tryConvertToPromise, INTERNAL, debug);
3369Promise.Promise = Promise;
3370Promise.version = "3.4.0";
3371_dereq_('./map.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug);
3372_dereq_('./call_get.js')(Promise);
3373_dereq_('./using.js')(Promise, apiRejection, tryConvertToPromise, createContext, INTERNAL, debug);
3374_dereq_('./timers.js')(Promise, INTERNAL, debug);
3375_dereq_('./generators.js')(Promise, apiRejection, INTERNAL, tryConvertToPromise, Proxyable, debug);
3376_dereq_('./nodeify.js')(Promise);
3377_dereq_('./promisify.js')(Promise, INTERNAL);
3378_dereq_('./props.js')(Promise, PromiseArray, tryConvertToPromise, apiRejection);
3379_dereq_('./race.js')(Promise, INTERNAL, tryConvertToPromise, apiRejection);
3380_dereq_('./reduce.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug);
3381_dereq_('./settle.js')(Promise, PromiseArray, debug);
3382_dereq_('./some.js')(Promise, PromiseArray, apiRejection);
3383_dereq_('./filter.js')(Promise, INTERNAL);
3384_dereq_('./each.js')(Promise, INTERNAL);
3385_dereq_('./any.js')(Promise);
3386
3387 util.toFastProperties(Promise);
3388 util.toFastProperties(Promise.prototype);
3389 function fillTypes(value) {
3390 var p = new Promise(INTERNAL);
3391 p._fulfillmentHandler0 = value;
3392 p._rejectionHandler0 = value;
3393 p._promise0 = value;
3394 p._receiver0 = value;
3395 }
3396 // Complete slack tracking, opt out of field-type tracking and
3397 // stabilize map
3398 fillTypes({a: 1});
3399 fillTypes({b: 2});
3400 fillTypes({c: 3});
3401 fillTypes(1);
3402 fillTypes(function(){});
3403 fillTypes(undefined);
3404 fillTypes(false);
3405 fillTypes(new Promise(INTERNAL));
3406 debug.setBounds(Async.firstLineError, util.lastLineError);
3407 return Promise;
3408
3409};
3410
3411},{"./any.js":1,"./async":2,"./bind":3,"./call_get.js":5,"./cancel":6,"./catch_filter":7,"./context":8,"./debuggability":9,"./direct_resolve":10,"./each.js":11,"./errors":12,"./es5":13,"./filter.js":14,"./finally":15,"./generators.js":16,"./join":17,"./map.js":18,"./method":19,"./nodeback":20,"./nodeify.js":21,"./promise_array":23,"./promisify.js":24,"./props.js":25,"./race.js":27,"./reduce.js":28,"./settle.js":30,"./some.js":31,"./synchronous_inspection":32,"./thenables":33,"./timers.js":34,"./using.js":35,"./util":36}],23:[function(_dereq_,module,exports){
3412"use strict";
3413module.exports = function(Promise, INTERNAL, tryConvertToPromise,
3414 apiRejection, Proxyable) {
3415var util = _dereq_("./util");
3416var isArray = util.isArray;
3417
3418function toResolutionValue(val) {
3419 switch(val) {
3420 case -2: return [];
3421 case -3: return {};
3422 }
3423}
3424
3425function PromiseArray(values) {
3426 var promise = this._promise = new Promise(INTERNAL);
3427 if (values instanceof Promise) {
3428 promise._propagateFrom(values, 3);
3429 }
3430 promise._setOnCancel(this);
3431 this._values = values;
3432 this._length = 0;
3433 this._totalResolved = 0;
3434 this._init(undefined, -2);
3435}
3436util.inherits(PromiseArray, Proxyable);
3437
3438PromiseArray.prototype.length = function () {
3439 return this._length;
3440};
3441
3442PromiseArray.prototype.promise = function () {
3443 return this._promise;
3444};
3445
3446PromiseArray.prototype._init = function init(_, resolveValueIfEmpty) {
3447 var values = tryConvertToPromise(this._values, this._promise);
3448 if (values instanceof Promise) {
3449 values = values._target();
3450 var bitField = values._bitField;
3451 ;
3452 this._values = values;
3453
3454 if (((bitField & 50397184) === 0)) {
3455 this._promise._setAsyncGuaranteed();
3456 return values._then(
3457 init,
3458 this._reject,
3459 undefined,
3460 this,
3461 resolveValueIfEmpty
3462 );
3463 } else if (((bitField & 33554432) !== 0)) {
3464 values = values._value();
3465 } else if (((bitField & 16777216) !== 0)) {
3466 return this._reject(values._reason());
3467 } else {
3468 return this._cancel();
3469 }
3470 }
3471 values = util.asArray(values);
3472 if (values === null) {
3473 var err = apiRejection(
3474 "expecting an array or an iterable object but got " + util.classString(values)).reason();
3475 this._promise._rejectCallback(err, false);
3476 return;
3477 }
3478
3479 if (values.length === 0) {
3480 if (resolveValueIfEmpty === -5) {
3481 this._resolveEmptyArray();
3482 }
3483 else {
3484 this._resolve(toResolutionValue(resolveValueIfEmpty));
3485 }
3486 return;
3487 }
3488 this._iterate(values);
3489};
3490
3491PromiseArray.prototype._iterate = function(values) {
3492 var len = this.getActualLength(values.length);
3493 this._length = len;
3494 this._values = this.shouldCopyValues() ? new Array(len) : this._values;
3495 var result = this._promise;
3496 var isResolved = false;
3497 var bitField = null;
3498 for (var i = 0; i < len; ++i) {
3499 var maybePromise = tryConvertToPromise(values[i], result);
3500
3501 if (maybePromise instanceof Promise) {
3502 maybePromise = maybePromise._target();
3503 bitField = maybePromise._bitField;
3504 } else {
3505 bitField = null;
3506 }
3507
3508 if (isResolved) {
3509 if (bitField !== null) {
3510 maybePromise.suppressUnhandledRejections();
3511 }
3512 } else if (bitField !== null) {
3513 if (((bitField & 50397184) === 0)) {
3514 maybePromise._proxy(this, i);
3515 this._values[i] = maybePromise;
3516 } else if (((bitField & 33554432) !== 0)) {
3517 isResolved = this._promiseFulfilled(maybePromise._value(), i);
3518 } else if (((bitField & 16777216) !== 0)) {
3519 isResolved = this._promiseRejected(maybePromise._reason(), i);
3520 } else {
3521 isResolved = this._promiseCancelled(i);
3522 }
3523 } else {
3524 isResolved = this._promiseFulfilled(maybePromise, i);
3525 }
3526 }
3527 if (!isResolved) result._setAsyncGuaranteed();
3528};
3529
3530PromiseArray.prototype._isResolved = function () {
3531 return this._values === null;
3532};
3533
3534PromiseArray.prototype._resolve = function (value) {
3535 this._values = null;
3536 this._promise._fulfill(value);
3537};
3538
3539PromiseArray.prototype._cancel = function() {
3540 if (this._isResolved() || !this._promise.isCancellable()) return;
3541 this._values = null;
3542 this._promise._cancel();
3543};
3544
3545PromiseArray.prototype._reject = function (reason) {
3546 this._values = null;
3547 this._promise._rejectCallback(reason, false);
3548};
3549
3550PromiseArray.prototype._promiseFulfilled = function (value, index) {
3551 this._values[index] = value;
3552 var totalResolved = ++this._totalResolved;
3553 if (totalResolved >= this._length) {
3554 this._resolve(this._values);
3555 return true;
3556 }
3557 return false;
3558};
3559
3560PromiseArray.prototype._promiseCancelled = function() {
3561 this._cancel();
3562 return true;
3563};
3564
3565PromiseArray.prototype._promiseRejected = function (reason) {
3566 this._totalResolved++;
3567 this._reject(reason);
3568 return true;
3569};
3570
3571PromiseArray.prototype._resultCancelled = function() {
3572 if (this._isResolved()) return;
3573 var values = this._values;
3574 this._cancel();
3575 if (values instanceof Promise) {
3576 values.cancel();
3577 } else {
3578 for (var i = 0; i < values.length; ++i) {
3579 if (values[i] instanceof Promise) {
3580 values[i].cancel();
3581 }
3582 }
3583 }
3584};
3585
3586PromiseArray.prototype.shouldCopyValues = function () {
3587 return true;
3588};
3589
3590PromiseArray.prototype.getActualLength = function (len) {
3591 return len;
3592};
3593
3594return PromiseArray;
3595};
3596
3597},{"./util":36}],24:[function(_dereq_,module,exports){
3598"use strict";
3599module.exports = function(Promise, INTERNAL) {
3600var THIS = {};
3601var util = _dereq_("./util");
3602var nodebackForPromise = _dereq_("./nodeback");
3603var withAppended = util.withAppended;
3604var maybeWrapAsError = util.maybeWrapAsError;
3605var canEvaluate = util.canEvaluate;
3606var TypeError = _dereq_("./errors").TypeError;
3607var defaultSuffix = "Async";
3608var defaultPromisified = {__isPromisified__: true};
3609var noCopyProps = [
3610 "arity", "length",
3611 "name",
3612 "arguments",
3613 "caller",
3614 "callee",
3615 "prototype",
3616 "__isPromisified__"
3617];
3618var noCopyPropsPattern = new RegExp("^(?:" + noCopyProps.join("|") + ")$");
3619
3620var defaultFilter = function(name) {
3621 return util.isIdentifier(name) &&
3622 name.charAt(0) !== "_" &&
3623 name !== "constructor";
3624};
3625
3626function propsFilter(key) {
3627 return !noCopyPropsPattern.test(key);
3628}
3629
3630function isPromisified(fn) {
3631 try {
3632 return fn.__isPromisified__ === true;
3633 }
3634 catch (e) {
3635 return false;
3636 }
3637}
3638
3639function hasPromisified(obj, key, suffix) {
3640 var val = util.getDataPropertyOrDefault(obj, key + suffix,
3641 defaultPromisified);
3642 return val ? isPromisified(val) : false;
3643}
3644function checkValid(ret, suffix, suffixRegexp) {
3645 for (var i = 0; i < ret.length; i += 2) {
3646 var key = ret[i];
3647 if (suffixRegexp.test(key)) {
3648 var keyWithoutAsyncSuffix = key.replace(suffixRegexp, "");
3649 for (var j = 0; j < ret.length; j += 2) {
3650 if (ret[j] === keyWithoutAsyncSuffix) {
3651 throw new TypeError("Cannot promisify an API that has normal methods with '%s'-suffix\u000a\u000a See http://goo.gl/MqrFmX\u000a"
3652 .replace("%s", suffix));
3653 }
3654 }
3655 }
3656 }
3657}
3658
3659function promisifiableMethods(obj, suffix, suffixRegexp, filter) {
3660 var keys = util.inheritedDataKeys(obj);
3661 var ret = [];
3662 for (var i = 0; i < keys.length; ++i) {
3663 var key = keys[i];
3664 var value = obj[key];
3665 var passesDefaultFilter = filter === defaultFilter
3666 ? true : defaultFilter(key, value, obj);
3667 if (typeof value === "function" &&
3668 !isPromisified(value) &&
3669 !hasPromisified(obj, key, suffix) &&
3670 filter(key, value, obj, passesDefaultFilter)) {
3671 ret.push(key, value);
3672 }
3673 }
3674 checkValid(ret, suffix, suffixRegexp);
3675 return ret;
3676}
3677
3678var escapeIdentRegex = function(str) {
3679 return str.replace(/([$])/, "\\$");
3680};
3681
3682var makeNodePromisifiedEval;
3683if (!true) {
3684var switchCaseArgumentOrder = function(likelyArgumentCount) {
3685 var ret = [likelyArgumentCount];
3686 var min = Math.max(0, likelyArgumentCount - 1 - 3);
3687 for(var i = likelyArgumentCount - 1; i >= min; --i) {
3688 ret.push(i);
3689 }
3690 for(var i = likelyArgumentCount + 1; i <= 3; ++i) {
3691 ret.push(i);
3692 }
3693 return ret;
3694};
3695
3696var argumentSequence = function(argumentCount) {
3697 return util.filledRange(argumentCount, "_arg", "");
3698};
3699
3700var parameterDeclaration = function(parameterCount) {
3701 return util.filledRange(
3702 Math.max(parameterCount, 3), "_arg", "");
3703};
3704
3705var parameterCount = function(fn) {
3706 if (typeof fn.length === "number") {
3707 return Math.max(Math.min(fn.length, 1023 + 1), 0);
3708 }
3709 return 0;
3710};
3711
3712makeNodePromisifiedEval =
3713function(callback, receiver, originalName, fn, _, multiArgs) {
3714 var newParameterCount = Math.max(0, parameterCount(fn) - 1);
3715 var argumentOrder = switchCaseArgumentOrder(newParameterCount);
3716 var shouldProxyThis = typeof callback === "string" || receiver === THIS;
3717
3718 function generateCallForArgumentCount(count) {
3719 var args = argumentSequence(count).join(", ");
3720 var comma = count > 0 ? ", " : "";
3721 var ret;
3722 if (shouldProxyThis) {
3723 ret = "ret = callback.call(this, {{args}}, nodeback); break;\n";
3724 } else {
3725 ret = receiver === undefined
3726 ? "ret = callback({{args}}, nodeback); break;\n"
3727 : "ret = callback.call(receiver, {{args}}, nodeback); break;\n";
3728 }
3729 return ret.replace("{{args}}", args).replace(", ", comma);
3730 }
3731
3732 function generateArgumentSwitchCase() {
3733 var ret = "";
3734 for (var i = 0; i < argumentOrder.length; ++i) {
3735 ret += "case " + argumentOrder[i] +":" +
3736 generateCallForArgumentCount(argumentOrder[i]);
3737 }
3738
3739 ret += " \n\
3740 default: \n\
3741 var args = new Array(len + 1); \n\
3742 var i = 0; \n\
3743 for (var i = 0; i < len; ++i) { \n\
3744 args[i] = arguments[i]; \n\
3745 } \n\
3746 args[i] = nodeback; \n\
3747 [CodeForCall] \n\
3748 break; \n\
3749 ".replace("[CodeForCall]", (shouldProxyThis
3750 ? "ret = callback.apply(this, args);\n"
3751 : "ret = callback.apply(receiver, args);\n"));
3752 return ret;
3753 }
3754
3755 var getFunctionCode = typeof callback === "string"
3756 ? ("this != null ? this['"+callback+"'] : fn")
3757 : "fn";
3758 var body = "'use strict'; \n\
3759 var ret = function (Parameters) { \n\
3760 'use strict'; \n\
3761 var len = arguments.length; \n\
3762 var promise = new Promise(INTERNAL); \n\
3763 promise._captureStackTrace(); \n\
3764 var nodeback = nodebackForPromise(promise, " + multiArgs + "); \n\
3765 var ret; \n\
3766 var callback = tryCatch([GetFunctionCode]); \n\
3767 switch(len) { \n\
3768 [CodeForSwitchCase] \n\
3769 } \n\
3770 if (ret === errorObj) { \n\
3771 promise._rejectCallback(maybeWrapAsError(ret.e), true, true);\n\
3772 } \n\
3773 if (!promise._isFateSealed()) promise._setAsyncGuaranteed(); \n\
3774 return promise; \n\
3775 }; \n\
3776 notEnumerableProp(ret, '__isPromisified__', true); \n\
3777 return ret; \n\
3778 ".replace("[CodeForSwitchCase]", generateArgumentSwitchCase())
3779 .replace("[GetFunctionCode]", getFunctionCode);
3780 body = body.replace("Parameters", parameterDeclaration(newParameterCount));
3781 return new Function("Promise",
3782 "fn",
3783 "receiver",
3784 "withAppended",
3785 "maybeWrapAsError",
3786 "nodebackForPromise",
3787 "tryCatch",
3788 "errorObj",
3789 "notEnumerableProp",
3790 "INTERNAL",
3791 body)(
3792 Promise,
3793 fn,
3794 receiver,
3795 withAppended,
3796 maybeWrapAsError,
3797 nodebackForPromise,
3798 util.tryCatch,
3799 util.errorObj,
3800 util.notEnumerableProp,
3801 INTERNAL);
3802};
3803}
3804
3805function makeNodePromisifiedClosure(callback, receiver, _, fn, __, multiArgs) {
3806 var defaultThis = (function() {return this;})();
3807 var method = callback;
3808 if (typeof method === "string") {
3809 callback = fn;
3810 }
3811 function promisified() {
3812 var _receiver = receiver;
3813 if (receiver === THIS) _receiver = this;
3814 var promise = new Promise(INTERNAL);
3815 promise._captureStackTrace();
3816 var cb = typeof method === "string" && this !== defaultThis
3817 ? this[method] : callback;
3818 var fn = nodebackForPromise(promise, multiArgs);
3819 try {
3820 cb.apply(_receiver, withAppended(arguments, fn));
3821 } catch(e) {
3822 promise._rejectCallback(maybeWrapAsError(e), true, true);
3823 }
3824 if (!promise._isFateSealed()) promise._setAsyncGuaranteed();
3825 return promise;
3826 }
3827 util.notEnumerableProp(promisified, "__isPromisified__", true);
3828 return promisified;
3829}
3830
3831var makeNodePromisified = canEvaluate
3832 ? makeNodePromisifiedEval
3833 : makeNodePromisifiedClosure;
3834
3835function promisifyAll(obj, suffix, filter, promisifier, multiArgs) {
3836 var suffixRegexp = new RegExp(escapeIdentRegex(suffix) + "$");
3837 var methods =
3838 promisifiableMethods(obj, suffix, suffixRegexp, filter);
3839
3840 for (var i = 0, len = methods.length; i < len; i+= 2) {
3841 var key = methods[i];
3842 var fn = methods[i+1];
3843 var promisifiedKey = key + suffix;
3844 if (promisifier === makeNodePromisified) {
3845 obj[promisifiedKey] =
3846 makeNodePromisified(key, THIS, key, fn, suffix, multiArgs);
3847 } else {
3848 var promisified = promisifier(fn, function() {
3849 return makeNodePromisified(key, THIS, key,
3850 fn, suffix, multiArgs);
3851 });
3852 util.notEnumerableProp(promisified, "__isPromisified__", true);
3853 obj[promisifiedKey] = promisified;
3854 }
3855 }
3856 util.toFastProperties(obj);
3857 return obj;
3858}
3859
3860function promisify(callback, receiver, multiArgs) {
3861 return makeNodePromisified(callback, receiver, undefined,
3862 callback, null, multiArgs);
3863}
3864
3865Promise.promisify = function (fn, options) {
3866 if (typeof fn !== "function") {
3867 throw new TypeError("expecting a function but got " + util.classString(fn));
3868 }
3869 if (isPromisified(fn)) {
3870 return fn;
3871 }
3872 options = Object(options);
3873 var receiver = options.context === undefined ? THIS : options.context;
3874 var multiArgs = !!options.multiArgs;
3875 var ret = promisify(fn, receiver, multiArgs);
3876 util.copyDescriptors(fn, ret, propsFilter);
3877 return ret;
3878};
3879
3880Promise.promisifyAll = function (target, options) {
3881 if (typeof target !== "function" && typeof target !== "object") {
3882 throw new TypeError("the target of promisifyAll must be an object or a function\u000a\u000a See http://goo.gl/MqrFmX\u000a");
3883 }
3884 options = Object(options);
3885 var multiArgs = !!options.multiArgs;
3886 var suffix = options.suffix;
3887 if (typeof suffix !== "string") suffix = defaultSuffix;
3888 var filter = options.filter;
3889 if (typeof filter !== "function") filter = defaultFilter;
3890 var promisifier = options.promisifier;
3891 if (typeof promisifier !== "function") promisifier = makeNodePromisified;
3892
3893 if (!util.isIdentifier(suffix)) {
3894 throw new RangeError("suffix must be a valid identifier\u000a\u000a See http://goo.gl/MqrFmX\u000a");
3895 }
3896
3897 var keys = util.inheritedDataKeys(target);
3898 for (var i = 0; i < keys.length; ++i) {
3899 var value = target[keys[i]];
3900 if (keys[i] !== "constructor" &&
3901 util.isClass(value)) {
3902 promisifyAll(value.prototype, suffix, filter, promisifier,
3903 multiArgs);
3904 promisifyAll(value, suffix, filter, promisifier, multiArgs);
3905 }
3906 }
3907
3908 return promisifyAll(target, suffix, filter, promisifier, multiArgs);
3909};
3910};
3911
3912
3913},{"./errors":12,"./nodeback":20,"./util":36}],25:[function(_dereq_,module,exports){
3914"use strict";
3915module.exports = function(
3916 Promise, PromiseArray, tryConvertToPromise, apiRejection) {
3917var util = _dereq_("./util");
3918var isObject = util.isObject;
3919var es5 = _dereq_("./es5");
3920var Es6Map;
3921if (typeof Map === "function") Es6Map = Map;
3922
3923var mapToEntries = (function() {
3924 var index = 0;
3925 var size = 0;
3926
3927 function extractEntry(value, key) {
3928 this[index] = value;
3929 this[index + size] = key;
3930 index++;
3931 }
3932
3933 return function mapToEntries(map) {
3934 size = map.size;
3935 index = 0;
3936 var ret = new Array(map.size * 2);
3937 map.forEach(extractEntry, ret);
3938 return ret;
3939 };
3940})();
3941
3942var entriesToMap = function(entries) {
3943 var ret = new Es6Map();
3944 var length = entries.length / 2 | 0;
3945 for (var i = 0; i < length; ++i) {
3946 var key = entries[length + i];
3947 var value = entries[i];
3948 ret.set(key, value);
3949 }
3950 return ret;
3951};
3952
3953function PropertiesPromiseArray(obj) {
3954 var isMap = false;
3955 var entries;
3956 if (Es6Map !== undefined && obj instanceof Es6Map) {
3957 entries = mapToEntries(obj);
3958 isMap = true;
3959 } else {
3960 var keys = es5.keys(obj);
3961 var len = keys.length;
3962 entries = new Array(len * 2);
3963 for (var i = 0; i < len; ++i) {
3964 var key = keys[i];
3965 entries[i] = obj[key];
3966 entries[i + len] = key;
3967 }
3968 }
3969 this.constructor$(entries);
3970 this._isMap = isMap;
3971 this._init$(undefined, -3);
3972}
3973util.inherits(PropertiesPromiseArray, PromiseArray);
3974
3975PropertiesPromiseArray.prototype._init = function () {};
3976
3977PropertiesPromiseArray.prototype._promiseFulfilled = function (value, index) {
3978 this._values[index] = value;
3979 var totalResolved = ++this._totalResolved;
3980 if (totalResolved >= this._length) {
3981 var val;
3982 if (this._isMap) {
3983 val = entriesToMap(this._values);
3984 } else {
3985 val = {};
3986 var keyOffset = this.length();
3987 for (var i = 0, len = this.length(); i < len; ++i) {
3988 val[this._values[i + keyOffset]] = this._values[i];
3989 }
3990 }
3991 this._resolve(val);
3992 return true;
3993 }
3994 return false;
3995};
3996
3997PropertiesPromiseArray.prototype.shouldCopyValues = function () {
3998 return false;
3999};
4000
4001PropertiesPromiseArray.prototype.getActualLength = function (len) {
4002 return len >> 1;
4003};
4004
4005function props(promises) {
4006 var ret;
4007 var castValue = tryConvertToPromise(promises);
4008
4009 if (!isObject(castValue)) {
4010 return apiRejection("cannot await properties of a non-object\u000a\u000a See http://goo.gl/MqrFmX\u000a");
4011 } else if (castValue instanceof Promise) {
4012 ret = castValue._then(
4013 Promise.props, undefined, undefined, undefined, undefined);
4014 } else {
4015 ret = new PropertiesPromiseArray(castValue).promise();
4016 }
4017
4018 if (castValue instanceof Promise) {
4019 ret._propagateFrom(castValue, 2);
4020 }
4021 return ret;
4022}
4023
4024Promise.prototype.props = function () {
4025 return props(this);
4026};
4027
4028Promise.props = function (promises) {
4029 return props(promises);
4030};
4031};
4032
4033},{"./es5":13,"./util":36}],26:[function(_dereq_,module,exports){
4034"use strict";
4035function arrayMove(src, srcIndex, dst, dstIndex, len) {
4036 for (var j = 0; j < len; ++j) {
4037 dst[j + dstIndex] = src[j + srcIndex];
4038 src[j + srcIndex] = void 0;
4039 }
4040}
4041
4042function Queue(capacity) {
4043 this._capacity = capacity;
4044 this._length = 0;
4045 this._front = 0;
4046}
4047
4048Queue.prototype._willBeOverCapacity = function (size) {
4049 return this._capacity < size;
4050};
4051
4052Queue.prototype._pushOne = function (arg) {
4053 var length = this.length();
4054 this._checkCapacity(length + 1);
4055 var i = (this._front + length) & (this._capacity - 1);
4056 this[i] = arg;
4057 this._length = length + 1;
4058};
4059
4060Queue.prototype._unshiftOne = function(value) {
4061 var capacity = this._capacity;
4062 this._checkCapacity(this.length() + 1);
4063 var front = this._front;
4064 var i = (((( front - 1 ) &
4065 ( capacity - 1) ) ^ capacity ) - capacity );
4066 this[i] = value;
4067 this._front = i;
4068 this._length = this.length() + 1;
4069};
4070
4071Queue.prototype.unshift = function(fn, receiver, arg) {
4072 this._unshiftOne(arg);
4073 this._unshiftOne(receiver);
4074 this._unshiftOne(fn);
4075};
4076
4077Queue.prototype.push = function (fn, receiver, arg) {
4078 var length = this.length() + 3;
4079 if (this._willBeOverCapacity(length)) {
4080 this._pushOne(fn);
4081 this._pushOne(receiver);
4082 this._pushOne(arg);
4083 return;
4084 }
4085 var j = this._front + length - 3;
4086 this._checkCapacity(length);
4087 var wrapMask = this._capacity - 1;
4088 this[(j + 0) & wrapMask] = fn;
4089 this[(j + 1) & wrapMask] = receiver;
4090 this[(j + 2) & wrapMask] = arg;
4091 this._length = length;
4092};
4093
4094Queue.prototype.shift = function () {
4095 var front = this._front,
4096 ret = this[front];
4097
4098 this[front] = undefined;
4099 this._front = (front + 1) & (this._capacity - 1);
4100 this._length--;
4101 return ret;
4102};
4103
4104Queue.prototype.length = function () {
4105 return this._length;
4106};
4107
4108Queue.prototype._checkCapacity = function (size) {
4109 if (this._capacity < size) {
4110 this._resizeTo(this._capacity << 1);
4111 }
4112};
4113
4114Queue.prototype._resizeTo = function (capacity) {
4115 var oldCapacity = this._capacity;
4116 this._capacity = capacity;
4117 var front = this._front;
4118 var length = this._length;
4119 var moveItemsCount = (front + length) & (oldCapacity - 1);
4120 arrayMove(this, 0, this, oldCapacity, moveItemsCount);
4121};
4122
4123module.exports = Queue;
4124
4125},{}],27:[function(_dereq_,module,exports){
4126"use strict";
4127module.exports = function(
4128 Promise, INTERNAL, tryConvertToPromise, apiRejection) {
4129var util = _dereq_("./util");
4130
4131var raceLater = function (promise) {
4132 return promise.then(function(array) {
4133 return race(array, promise);
4134 });
4135};
4136
4137function race(promises, parent) {
4138 var maybePromise = tryConvertToPromise(promises);
4139
4140 if (maybePromise instanceof Promise) {
4141 return raceLater(maybePromise);
4142 } else {
4143 promises = util.asArray(promises);
4144 if (promises === null)
4145 return apiRejection("expecting an array or an iterable object but got " + util.classString(promises));
4146 }
4147
4148 var ret = new Promise(INTERNAL);
4149 if (parent !== undefined) {
4150 ret._propagateFrom(parent, 3);
4151 }
4152 var fulfill = ret._fulfill;
4153 var reject = ret._reject;
4154 for (var i = 0, len = promises.length; i < len; ++i) {
4155 var val = promises[i];
4156
4157 if (val === undefined && !(i in promises)) {
4158 continue;
4159 }
4160
4161 Promise.cast(val)._then(fulfill, reject, undefined, ret, null);
4162 }
4163 return ret;
4164}
4165
4166Promise.race = function (promises) {
4167 return race(promises, undefined);
4168};
4169
4170Promise.prototype.race = function () {
4171 return race(this, undefined);
4172};
4173
4174};
4175
4176},{"./util":36}],28:[function(_dereq_,module,exports){
4177"use strict";
4178module.exports = function(Promise,
4179 PromiseArray,
4180 apiRejection,
4181 tryConvertToPromise,
4182 INTERNAL,
4183 debug) {
4184var getDomain = Promise._getDomain;
4185var util = _dereq_("./util");
4186var tryCatch = util.tryCatch;
4187
4188function ReductionPromiseArray(promises, fn, initialValue, _each) {
4189 this.constructor$(promises);
4190 var domain = getDomain();
4191 this._fn = domain === null ? fn : domain.bind(fn);
4192 if (initialValue !== undefined) {
4193 initialValue = Promise.resolve(initialValue);
4194 initialValue._attachCancellationCallback(this);
4195 }
4196 this._initialValue = initialValue;
4197 this._currentCancellable = null;
4198 this._eachValues = _each === INTERNAL ? [] : undefined;
4199 this._promise._captureStackTrace();
4200 this._init$(undefined, -5);
4201}
4202util.inherits(ReductionPromiseArray, PromiseArray);
4203
4204ReductionPromiseArray.prototype._gotAccum = function(accum) {
4205 if (this._eachValues !== undefined && accum !== INTERNAL) {
4206 this._eachValues.push(accum);
4207 }
4208};
4209
4210ReductionPromiseArray.prototype._eachComplete = function(value) {
4211 this._eachValues.push(value);
4212 return this._eachValues;
4213};
4214
4215ReductionPromiseArray.prototype._init = function() {};
4216
4217ReductionPromiseArray.prototype._resolveEmptyArray = function() {
4218 this._resolve(this._eachValues !== undefined ? this._eachValues
4219 : this._initialValue);
4220};
4221
4222ReductionPromiseArray.prototype.shouldCopyValues = function () {
4223 return false;
4224};
4225
4226ReductionPromiseArray.prototype._resolve = function(value) {
4227 this._promise._resolveCallback(value);
4228 this._values = null;
4229};
4230
4231ReductionPromiseArray.prototype._resultCancelled = function(sender) {
4232 if (sender === this._initialValue) return this._cancel();
4233 if (this._isResolved()) return;
4234 this._resultCancelled$();
4235 if (this._currentCancellable instanceof Promise) {
4236 this._currentCancellable.cancel();
4237 }
4238 if (this._initialValue instanceof Promise) {
4239 this._initialValue.cancel();
4240 }
4241};
4242
4243ReductionPromiseArray.prototype._iterate = function (values) {
4244 this._values = values;
4245 var value;
4246 var i;
4247 var length = values.length;
4248 if (this._initialValue !== undefined) {
4249 value = this._initialValue;
4250 i = 0;
4251 } else {
4252 value = Promise.resolve(values[0]);
4253 i = 1;
4254 }
4255
4256 this._currentCancellable = value;
4257
4258 if (!value.isRejected()) {
4259 for (; i < length; ++i) {
4260 var ctx = {
4261 accum: null,
4262 value: values[i],
4263 index: i,
4264 length: length,
4265 array: this
4266 };
4267 value = value._then(gotAccum, undefined, undefined, ctx, undefined);
4268 }
4269 }
4270
4271 if (this._eachValues !== undefined) {
4272 value = value
4273 ._then(this._eachComplete, undefined, undefined, this, undefined);
4274 }
4275 value._then(completed, completed, undefined, value, this);
4276};
4277
4278Promise.prototype.reduce = function (fn, initialValue) {
4279 return reduce(this, fn, initialValue, null);
4280};
4281
4282Promise.reduce = function (promises, fn, initialValue, _each) {
4283 return reduce(promises, fn, initialValue, _each);
4284};
4285
4286function completed(valueOrReason, array) {
4287 if (this.isFulfilled()) {
4288 array._resolve(valueOrReason);
4289 } else {
4290 array._reject(valueOrReason);
4291 }
4292}
4293
4294function reduce(promises, fn, initialValue, _each) {
4295 if (typeof fn !== "function") {
4296 return apiRejection("expecting a function but got " + util.classString(fn));
4297 }
4298 var array = new ReductionPromiseArray(promises, fn, initialValue, _each);
4299 return array.promise();
4300}
4301
4302function gotAccum(accum) {
4303 this.accum = accum;
4304 this.array._gotAccum(accum);
4305 var value = tryConvertToPromise(this.value, this.array._promise);
4306 if (value instanceof Promise) {
4307 this.array._currentCancellable = value;
4308 return value._then(gotValue, undefined, undefined, this, undefined);
4309 } else {
4310 return gotValue.call(this, value);
4311 }
4312}
4313
4314function gotValue(value) {
4315 var array = this.array;
4316 var promise = array._promise;
4317 var fn = tryCatch(array._fn);
4318 promise._pushContext();
4319 var ret;
4320 if (array._eachValues !== undefined) {
4321 ret = fn.call(promise._boundValue(), value, this.index, this.length);
4322 } else {
4323 ret = fn.call(promise._boundValue(),
4324 this.accum, value, this.index, this.length);
4325 }
4326 if (ret instanceof Promise) {
4327 array._currentCancellable = ret;
4328 }
4329 var promiseCreated = promise._popContext();
4330 debug.checkForgottenReturns(
4331 ret,
4332 promiseCreated,
4333 array._eachValues !== undefined ? "Promise.each" : "Promise.reduce",
4334 promise
4335 );
4336 return ret;
4337}
4338};
4339
4340},{"./util":36}],29:[function(_dereq_,module,exports){
4341"use strict";
4342var util = _dereq_("./util");
4343var schedule;
4344var noAsyncScheduler = function() {
4345 throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/MqrFmX\u000a");
4346};
4347var NativePromise = util.getNativePromise();
4348if (util.isNode && typeof MutationObserver === "undefined") {
4349 var GlobalSetImmediate = global.setImmediate;
4350 var ProcessNextTick = process.nextTick;
4351 schedule = util.isRecentNode
4352 ? function(fn) { GlobalSetImmediate.call(global, fn); }
4353 : function(fn) { ProcessNextTick.call(process, fn); };
4354} else if (typeof NativePromise === "function") {
4355 var nativePromise = NativePromise.resolve();
4356 schedule = function(fn) {
4357 nativePromise.then(fn);
4358 };
4359} else if ((typeof MutationObserver !== "undefined") &&
4360 !(typeof window !== "undefined" &&
4361 window.navigator &&
4362 window.navigator.standalone)) {
4363 schedule = (function() {
4364 var div = document.createElement("div");
4365 var opts = {attributes: true};
4366 var toggleScheduled = false;
4367 var div2 = document.createElement("div");
4368 var o2 = new MutationObserver(function() {
4369 div.classList.toggle("foo");
4370 toggleScheduled = false;
4371 });
4372 o2.observe(div2, opts);
4373
4374 var scheduleToggle = function() {
4375 if (toggleScheduled) return;
4376 toggleScheduled = true;
4377 div2.classList.toggle("foo");
4378 };
4379
4380 return function schedule(fn) {
4381 var o = new MutationObserver(function() {
4382 o.disconnect();
4383 fn();
4384 });
4385 o.observe(div, opts);
4386 scheduleToggle();
4387 };
4388 })();
4389} else if (typeof setImmediate !== "undefined") {
4390 schedule = function (fn) {
4391 setImmediate(fn);
4392 };
4393} else if (typeof setTimeout !== "undefined") {
4394 schedule = function (fn) {
4395 setTimeout(fn, 0);
4396 };
4397} else {
4398 schedule = noAsyncScheduler;
4399}
4400module.exports = schedule;
4401
4402},{"./util":36}],30:[function(_dereq_,module,exports){
4403"use strict";
4404module.exports =
4405 function(Promise, PromiseArray, debug) {
4406var PromiseInspection = Promise.PromiseInspection;
4407var util = _dereq_("./util");
4408
4409function SettledPromiseArray(values) {
4410 this.constructor$(values);
4411}
4412util.inherits(SettledPromiseArray, PromiseArray);
4413
4414SettledPromiseArray.prototype._promiseResolved = function (index, inspection) {
4415 this._values[index] = inspection;
4416 var totalResolved = ++this._totalResolved;
4417 if (totalResolved >= this._length) {
4418 this._resolve(this._values);
4419 return true;
4420 }
4421 return false;
4422};
4423
4424SettledPromiseArray.prototype._promiseFulfilled = function (value, index) {
4425 var ret = new PromiseInspection();
4426 ret._bitField = 33554432;
4427 ret._settledValueField = value;
4428 return this._promiseResolved(index, ret);
4429};
4430SettledPromiseArray.prototype._promiseRejected = function (reason, index) {
4431 var ret = new PromiseInspection();
4432 ret._bitField = 16777216;
4433 ret._settledValueField = reason;
4434 return this._promiseResolved(index, ret);
4435};
4436
4437Promise.settle = function (promises) {
4438 debug.deprecated(".settle()", ".reflect()");
4439 return new SettledPromiseArray(promises).promise();
4440};
4441
4442Promise.prototype.settle = function () {
4443 return Promise.settle(this);
4444};
4445};
4446
4447},{"./util":36}],31:[function(_dereq_,module,exports){
4448"use strict";
4449module.exports =
4450function(Promise, PromiseArray, apiRejection) {
4451var util = _dereq_("./util");
4452var RangeError = _dereq_("./errors").RangeError;
4453var AggregateError = _dereq_("./errors").AggregateError;
4454var isArray = util.isArray;
4455var CANCELLATION = {};
4456
4457
4458function SomePromiseArray(values) {
4459 this.constructor$(values);
4460 this._howMany = 0;
4461 this._unwrap = false;
4462 this._initialized = false;
4463}
4464util.inherits(SomePromiseArray, PromiseArray);
4465
4466SomePromiseArray.prototype._init = function () {
4467 if (!this._initialized) {
4468 return;
4469 }
4470 if (this._howMany === 0) {
4471 this._resolve([]);
4472 return;
4473 }
4474 this._init$(undefined, -5);
4475 var isArrayResolved = isArray(this._values);
4476 if (!this._isResolved() &&
4477 isArrayResolved &&
4478 this._howMany > this._canPossiblyFulfill()) {
4479 this._reject(this._getRangeError(this.length()));
4480 }
4481};
4482
4483SomePromiseArray.prototype.init = function () {
4484 this._initialized = true;
4485 this._init();
4486};
4487
4488SomePromiseArray.prototype.setUnwrap = function () {
4489 this._unwrap = true;
4490};
4491
4492SomePromiseArray.prototype.howMany = function () {
4493 return this._howMany;
4494};
4495
4496SomePromiseArray.prototype.setHowMany = function (count) {
4497 this._howMany = count;
4498};
4499
4500SomePromiseArray.prototype._promiseFulfilled = function (value) {
4501 this._addFulfilled(value);
4502 if (this._fulfilled() === this.howMany()) {
4503 this._values.length = this.howMany();
4504 if (this.howMany() === 1 && this._unwrap) {
4505 this._resolve(this._values[0]);
4506 } else {
4507 this._resolve(this._values);
4508 }
4509 return true;
4510 }
4511 return false;
4512
4513};
4514SomePromiseArray.prototype._promiseRejected = function (reason) {
4515 this._addRejected(reason);
4516 return this._checkOutcome();
4517};
4518
4519SomePromiseArray.prototype._promiseCancelled = function () {
4520 if (this._values instanceof Promise || this._values == null) {
4521 return this._cancel();
4522 }
4523 this._addRejected(CANCELLATION);
4524 return this._checkOutcome();
4525};
4526
4527SomePromiseArray.prototype._checkOutcome = function() {
4528 if (this.howMany() > this._canPossiblyFulfill()) {
4529 var e = new AggregateError();
4530 for (var i = this.length(); i < this._values.length; ++i) {
4531 if (this._values[i] !== CANCELLATION) {
4532 e.push(this._values[i]);
4533 }
4534 }
4535 if (e.length > 0) {
4536 this._reject(e);
4537 } else {
4538 this._cancel();
4539 }
4540 return true;
4541 }
4542 return false;
4543};
4544
4545SomePromiseArray.prototype._fulfilled = function () {
4546 return this._totalResolved;
4547};
4548
4549SomePromiseArray.prototype._rejected = function () {
4550 return this._values.length - this.length();
4551};
4552
4553SomePromiseArray.prototype._addRejected = function (reason) {
4554 this._values.push(reason);
4555};
4556
4557SomePromiseArray.prototype._addFulfilled = function (value) {
4558 this._values[this._totalResolved++] = value;
4559};
4560
4561SomePromiseArray.prototype._canPossiblyFulfill = function () {
4562 return this.length() - this._rejected();
4563};
4564
4565SomePromiseArray.prototype._getRangeError = function (count) {
4566 var message = "Input array must contain at least " +
4567 this._howMany + " items but contains only " + count + " items";
4568 return new RangeError(message);
4569};
4570
4571SomePromiseArray.prototype._resolveEmptyArray = function () {
4572 this._reject(this._getRangeError(0));
4573};
4574
4575function some(promises, howMany) {
4576 if ((howMany | 0) !== howMany || howMany < 0) {
4577 return apiRejection("expecting a positive integer\u000a\u000a See http://goo.gl/MqrFmX\u000a");
4578 }
4579 var ret = new SomePromiseArray(promises);
4580 var promise = ret.promise();
4581 ret.setHowMany(howMany);
4582 ret.init();
4583 return promise;
4584}
4585
4586Promise.some = function (promises, howMany) {
4587 return some(promises, howMany);
4588};
4589
4590Promise.prototype.some = function (howMany) {
4591 return some(this, howMany);
4592};
4593
4594Promise._SomePromiseArray = SomePromiseArray;
4595};
4596
4597},{"./errors":12,"./util":36}],32:[function(_dereq_,module,exports){
4598"use strict";
4599module.exports = function(Promise) {
4600function PromiseInspection(promise) {
4601 if (promise !== undefined) {
4602 promise = promise._target();
4603 this._bitField = promise._bitField;
4604 this._settledValueField = promise._isFateSealed()
4605 ? promise._settledValue() : undefined;
4606 }
4607 else {
4608 this._bitField = 0;
4609 this._settledValueField = undefined;
4610 }
4611}
4612
4613PromiseInspection.prototype._settledValue = function() {
4614 return this._settledValueField;
4615};
4616
4617var value = PromiseInspection.prototype.value = function () {
4618 if (!this.isFulfilled()) {
4619 throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\u000a\u000a See http://goo.gl/MqrFmX\u000a");
4620 }
4621 return this._settledValue();
4622};
4623
4624var reason = PromiseInspection.prototype.error =
4625PromiseInspection.prototype.reason = function () {
4626 if (!this.isRejected()) {
4627 throw new TypeError("cannot get rejection reason of a non-rejected promise\u000a\u000a See http://goo.gl/MqrFmX\u000a");
4628 }
4629 return this._settledValue();
4630};
4631
4632var isFulfilled = PromiseInspection.prototype.isFulfilled = function() {
4633 return (this._bitField & 33554432) !== 0;
4634};
4635
4636var isRejected = PromiseInspection.prototype.isRejected = function () {
4637 return (this._bitField & 16777216) !== 0;
4638};
4639
4640var isPending = PromiseInspection.prototype.isPending = function () {
4641 return (this._bitField & 50397184) === 0;
4642};
4643
4644var isResolved = PromiseInspection.prototype.isResolved = function () {
4645 return (this._bitField & 50331648) !== 0;
4646};
4647
4648PromiseInspection.prototype.isCancelled =
4649Promise.prototype._isCancelled = function() {
4650 return (this._bitField & 65536) === 65536;
4651};
4652
4653Promise.prototype.isCancelled = function() {
4654 return this._target()._isCancelled();
4655};
4656
4657Promise.prototype.isPending = function() {
4658 return isPending.call(this._target());
4659};
4660
4661Promise.prototype.isRejected = function() {
4662 return isRejected.call(this._target());
4663};
4664
4665Promise.prototype.isFulfilled = function() {
4666 return isFulfilled.call(this._target());
4667};
4668
4669Promise.prototype.isResolved = function() {
4670 return isResolved.call(this._target());
4671};
4672
4673Promise.prototype.value = function() {
4674 return value.call(this._target());
4675};
4676
4677Promise.prototype.reason = function() {
4678 var target = this._target();
4679 target._unsetRejectionIsUnhandled();
4680 return reason.call(target);
4681};
4682
4683Promise.prototype._value = function() {
4684 return this._settledValue();
4685};
4686
4687Promise.prototype._reason = function() {
4688 this._unsetRejectionIsUnhandled();
4689 return this._settledValue();
4690};
4691
4692Promise.PromiseInspection = PromiseInspection;
4693};
4694
4695},{}],33:[function(_dereq_,module,exports){
4696"use strict";
4697module.exports = function(Promise, INTERNAL) {
4698var util = _dereq_("./util");
4699var errorObj = util.errorObj;
4700var isObject = util.isObject;
4701
4702function tryConvertToPromise(obj, context) {
4703 if (isObject(obj)) {
4704 if (obj instanceof Promise) return obj;
4705 var then = getThen(obj);
4706 if (then === errorObj) {
4707 if (context) context._pushContext();
4708 var ret = Promise.reject(then.e);
4709 if (context) context._popContext();
4710 return ret;
4711 } else if (typeof then === "function") {
4712 if (isAnyBluebirdPromise(obj)) {
4713 var ret = new Promise(INTERNAL);
4714 obj._then(
4715 ret._fulfill,
4716 ret._reject,
4717 undefined,
4718 ret,
4719 null
4720 );
4721 return ret;
4722 }
4723 return doThenable(obj, then, context);
4724 }
4725 }
4726 return obj;
4727}
4728
4729function doGetThen(obj) {
4730 return obj.then;
4731}
4732
4733function getThen(obj) {
4734 try {
4735 return doGetThen(obj);
4736 } catch (e) {
4737 errorObj.e = e;
4738 return errorObj;
4739 }
4740}
4741
4742var hasProp = {}.hasOwnProperty;
4743function isAnyBluebirdPromise(obj) {
4744 try {
4745 return hasProp.call(obj, "_promise0");
4746 } catch (e) {
4747 return false;
4748 }
4749}
4750
4751function doThenable(x, then, context) {
4752 var promise = new Promise(INTERNAL);
4753 var ret = promise;
4754 if (context) context._pushContext();
4755 promise._captureStackTrace();
4756 if (context) context._popContext();
4757 var synchronous = true;
4758 var result = util.tryCatch(then).call(x, resolve, reject);
4759 synchronous = false;
4760
4761 if (promise && result === errorObj) {
4762 promise._rejectCallback(result.e, true, true);
4763 promise = null;
4764 }
4765
4766 function resolve(value) {
4767 if (!promise) return;
4768 promise._resolveCallback(value);
4769 promise = null;
4770 }
4771
4772 function reject(reason) {
4773 if (!promise) return;
4774 promise._rejectCallback(reason, synchronous, true);
4775 promise = null;
4776 }
4777 return ret;
4778}
4779
4780return tryConvertToPromise;
4781};
4782
4783},{"./util":36}],34:[function(_dereq_,module,exports){
4784"use strict";
4785module.exports = function(Promise, INTERNAL, debug) {
4786var util = _dereq_("./util");
4787var TimeoutError = Promise.TimeoutError;
4788
4789function HandleWrapper(handle) {
4790 this.handle = handle;
4791}
4792
4793HandleWrapper.prototype._resultCancelled = function() {
4794 clearTimeout(this.handle);
4795};
4796
4797var afterValue = function(value) { return delay(+this).thenReturn(value); };
4798var delay = Promise.delay = function (ms, value) {
4799 var ret;
4800 var handle;
4801 if (value !== undefined) {
4802 ret = Promise.resolve(value)
4803 ._then(afterValue, null, null, ms, undefined);
4804 if (debug.cancellation() && value instanceof Promise) {
4805 ret._setOnCancel(value);
4806 }
4807 } else {
4808 ret = new Promise(INTERNAL);
4809 handle = setTimeout(function() { ret._fulfill(); }, +ms);
4810 if (debug.cancellation()) {
4811 ret._setOnCancel(new HandleWrapper(handle));
4812 }
4813 }
4814 ret._setAsyncGuaranteed();
4815 return ret;
4816};
4817
4818Promise.prototype.delay = function (ms) {
4819 return delay(ms, this);
4820};
4821
4822var afterTimeout = function (promise, message, parent) {
4823 var err;
4824 if (typeof message !== "string") {
4825 if (message instanceof Error) {
4826 err = message;
4827 } else {
4828 err = new TimeoutError("operation timed out");
4829 }
4830 } else {
4831 err = new TimeoutError(message);
4832 }
4833 util.markAsOriginatingFromRejection(err);
4834 promise._attachExtraTrace(err);
4835 promise._reject(err);
4836
4837 if (parent != null) {
4838 parent.cancel();
4839 }
4840};
4841
4842function successClear(value) {
4843 clearTimeout(this.handle);
4844 return value;
4845}
4846
4847function failureClear(reason) {
4848 clearTimeout(this.handle);
4849 throw reason;
4850}
4851
4852Promise.prototype.timeout = function (ms, message) {
4853 ms = +ms;
4854 var ret, parent;
4855
4856 var handleWrapper = new HandleWrapper(setTimeout(function timeoutTimeout() {
4857 if (ret.isPending()) {
4858 afterTimeout(ret, message, parent);
4859 }
4860 }, ms));
4861
4862 if (debug.cancellation()) {
4863 parent = this.then();
4864 ret = parent._then(successClear, failureClear,
4865 undefined, handleWrapper, undefined);
4866 ret._setOnCancel(handleWrapper);
4867 } else {
4868 ret = this._then(successClear, failureClear,
4869 undefined, handleWrapper, undefined);
4870 }
4871
4872 return ret;
4873};
4874
4875};
4876
4877},{"./util":36}],35:[function(_dereq_,module,exports){
4878"use strict";
4879module.exports = function (Promise, apiRejection, tryConvertToPromise,
4880 createContext, INTERNAL, debug) {
4881 var util = _dereq_("./util");
4882 var TypeError = _dereq_("./errors").TypeError;
4883 var inherits = _dereq_("./util").inherits;
4884 var errorObj = util.errorObj;
4885 var tryCatch = util.tryCatch;
4886 var NULL = {};
4887
4888 function thrower(e) {
4889 setTimeout(function(){throw e;}, 0);
4890 }
4891
4892 function castPreservingDisposable(thenable) {
4893 var maybePromise = tryConvertToPromise(thenable);
4894 if (maybePromise !== thenable &&
4895 typeof thenable._isDisposable === "function" &&
4896 typeof thenable._getDisposer === "function" &&
4897 thenable._isDisposable()) {
4898 maybePromise._setDisposable(thenable._getDisposer());
4899 }
4900 return maybePromise;
4901 }
4902 function dispose(resources, inspection) {
4903 var i = 0;
4904 var len = resources.length;
4905 var ret = new Promise(INTERNAL);
4906 function iterator() {
4907 if (i >= len) return ret._fulfill();
4908 var maybePromise = castPreservingDisposable(resources[i++]);
4909 if (maybePromise instanceof Promise &&
4910 maybePromise._isDisposable()) {
4911 try {
4912 maybePromise = tryConvertToPromise(
4913 maybePromise._getDisposer().tryDispose(inspection),
4914 resources.promise);
4915 } catch (e) {
4916 return thrower(e);
4917 }
4918 if (maybePromise instanceof Promise) {
4919 return maybePromise._then(iterator, thrower,
4920 null, null, null);
4921 }
4922 }
4923 iterator();
4924 }
4925 iterator();
4926 return ret;
4927 }
4928
4929 function Disposer(data, promise, context) {
4930 this._data = data;
4931 this._promise = promise;
4932 this._context = context;
4933 }
4934
4935 Disposer.prototype.data = function () {
4936 return this._data;
4937 };
4938
4939 Disposer.prototype.promise = function () {
4940 return this._promise;
4941 };
4942
4943 Disposer.prototype.resource = function () {
4944 if (this.promise().isFulfilled()) {
4945 return this.promise().value();
4946 }
4947 return NULL;
4948 };
4949
4950 Disposer.prototype.tryDispose = function(inspection) {
4951 var resource = this.resource();
4952 var context = this._context;
4953 if (context !== undefined) context._pushContext();
4954 var ret = resource !== NULL
4955 ? this.doDispose(resource, inspection) : null;
4956 if (context !== undefined) context._popContext();
4957 this._promise._unsetDisposable();
4958 this._data = null;
4959 return ret;
4960 };
4961
4962 Disposer.isDisposer = function (d) {
4963 return (d != null &&
4964 typeof d.resource === "function" &&
4965 typeof d.tryDispose === "function");
4966 };
4967
4968 function FunctionDisposer(fn, promise, context) {
4969 this.constructor$(fn, promise, context);
4970 }
4971 inherits(FunctionDisposer, Disposer);
4972
4973 FunctionDisposer.prototype.doDispose = function (resource, inspection) {
4974 var fn = this.data();
4975 return fn.call(resource, resource, inspection);
4976 };
4977
4978 function maybeUnwrapDisposer(value) {
4979 if (Disposer.isDisposer(value)) {
4980 this.resources[this.index]._setDisposable(value);
4981 return value.promise();
4982 }
4983 return value;
4984 }
4985
4986 function ResourceList(length) {
4987 this.length = length;
4988 this.promise = null;
4989 this[length-1] = null;
4990 }
4991
4992 ResourceList.prototype._resultCancelled = function() {
4993 var len = this.length;
4994 for (var i = 0; i < len; ++i) {
4995 var item = this[i];
4996 if (item instanceof Promise) {
4997 item.cancel();
4998 }
4999 }
5000 };
5001
5002 Promise.using = function () {
5003 var len = arguments.length;
5004 if (len < 2) return apiRejection(
5005 "you must pass at least 2 arguments to Promise.using");
5006 var fn = arguments[len - 1];
5007 if (typeof fn !== "function") {
5008 return apiRejection("expecting a function but got " + util.classString(fn));
5009 }
5010 var input;
5011 var spreadArgs = true;
5012 if (len === 2 && Array.isArray(arguments[0])) {
5013 input = arguments[0];
5014 len = input.length;
5015 spreadArgs = false;
5016 } else {
5017 input = arguments;
5018 len--;
5019 }
5020 var resources = new ResourceList(len);
5021 for (var i = 0; i < len; ++i) {
5022 var resource = input[i];
5023 if (Disposer.isDisposer(resource)) {
5024 var disposer = resource;
5025 resource = resource.promise();
5026 resource._setDisposable(disposer);
5027 } else {
5028 var maybePromise = tryConvertToPromise(resource);
5029 if (maybePromise instanceof Promise) {
5030 resource =
5031 maybePromise._then(maybeUnwrapDisposer, null, null, {
5032 resources: resources,
5033 index: i
5034 }, undefined);
5035 }
5036 }
5037 resources[i] = resource;
5038 }
5039
5040 var reflectedResources = new Array(resources.length);
5041 for (var i = 0; i < reflectedResources.length; ++i) {
5042 reflectedResources[i] = Promise.resolve(resources[i]).reflect();
5043 }
5044
5045 var resultPromise = Promise.all(reflectedResources)
5046 .then(function(inspections) {
5047 for (var i = 0; i < inspections.length; ++i) {
5048 var inspection = inspections[i];
5049 if (inspection.isRejected()) {
5050 errorObj.e = inspection.error();
5051 return errorObj;
5052 } else if (!inspection.isFulfilled()) {
5053 resultPromise.cancel();
5054 return;
5055 }
5056 inspections[i] = inspection.value();
5057 }
5058 promise._pushContext();
5059
5060 fn = tryCatch(fn);
5061 var ret = spreadArgs
5062 ? fn.apply(undefined, inspections) : fn(inspections);
5063 var promiseCreated = promise._popContext();
5064 debug.checkForgottenReturns(
5065 ret, promiseCreated, "Promise.using", promise);
5066 return ret;
5067 });
5068
5069 var promise = resultPromise.lastly(function() {
5070 var inspection = new Promise.PromiseInspection(resultPromise);
5071 return dispose(resources, inspection);
5072 });
5073 resources.promise = promise;
5074 promise._setOnCancel(resources);
5075 return promise;
5076 };
5077
5078 Promise.prototype._setDisposable = function (disposer) {
5079 this._bitField = this._bitField | 131072;
5080 this._disposer = disposer;
5081 };
5082
5083 Promise.prototype._isDisposable = function () {
5084 return (this._bitField & 131072) > 0;
5085 };
5086
5087 Promise.prototype._getDisposer = function () {
5088 return this._disposer;
5089 };
5090
5091 Promise.prototype._unsetDisposable = function () {
5092 this._bitField = this._bitField & (~131072);
5093 this._disposer = undefined;
5094 };
5095
5096 Promise.prototype.disposer = function (fn) {
5097 if (typeof fn === "function") {
5098 return new FunctionDisposer(fn, this, createContext());
5099 }
5100 throw new TypeError();
5101 };
5102
5103};
5104
5105},{"./errors":12,"./util":36}],36:[function(_dereq_,module,exports){
5106"use strict";
5107var es5 = _dereq_("./es5");
5108var canEvaluate = typeof navigator == "undefined";
5109
5110var errorObj = {e: {}};
5111var tryCatchTarget;
5112var globalObject = typeof self !== "undefined" ? self :
5113 typeof window !== "undefined" ? window :
5114 typeof global !== "undefined" ? global :
5115 this !== undefined ? this : null;
5116
5117function tryCatcher() {
5118 try {
5119 var target = tryCatchTarget;
5120 tryCatchTarget = null;
5121 return target.apply(this, arguments);
5122 } catch (e) {
5123 errorObj.e = e;
5124 return errorObj;
5125 }
5126}
5127function tryCatch(fn) {
5128 tryCatchTarget = fn;
5129 return tryCatcher;
5130}
5131
5132var inherits = function(Child, Parent) {
5133 var hasProp = {}.hasOwnProperty;
5134
5135 function T() {
5136 this.constructor = Child;
5137 this.constructor$ = Parent;
5138 for (var propertyName in Parent.prototype) {
5139 if (hasProp.call(Parent.prototype, propertyName) &&
5140 propertyName.charAt(propertyName.length-1) !== "$"
5141 ) {
5142 this[propertyName + "$"] = Parent.prototype[propertyName];
5143 }
5144 }
5145 }
5146 T.prototype = Parent.prototype;
5147 Child.prototype = new T();
5148 return Child.prototype;
5149};
5150
5151
5152function isPrimitive(val) {
5153 return val == null || val === true || val === false ||
5154 typeof val === "string" || typeof val === "number";
5155
5156}
5157
5158function isObject(value) {
5159 return typeof value === "function" ||
5160 typeof value === "object" && value !== null;
5161}
5162
5163function maybeWrapAsError(maybeError) {
5164 if (!isPrimitive(maybeError)) return maybeError;
5165
5166 return new Error(safeToString(maybeError));
5167}
5168
5169function withAppended(target, appendee) {
5170 var len = target.length;
5171 var ret = new Array(len + 1);
5172 var i;
5173 for (i = 0; i < len; ++i) {
5174 ret[i] = target[i];
5175 }
5176 ret[i] = appendee;
5177 return ret;
5178}
5179
5180function getDataPropertyOrDefault(obj, key, defaultValue) {
5181 if (es5.isES5) {
5182 var desc = Object.getOwnPropertyDescriptor(obj, key);
5183
5184 if (desc != null) {
5185 return desc.get == null && desc.set == null
5186 ? desc.value
5187 : defaultValue;
5188 }
5189 } else {
5190 return {}.hasOwnProperty.call(obj, key) ? obj[key] : undefined;
5191 }
5192}
5193
5194function notEnumerableProp(obj, name, value) {
5195 if (isPrimitive(obj)) return obj;
5196 var descriptor = {
5197 value: value,
5198 configurable: true,
5199 enumerable: false,
5200 writable: true
5201 };
5202 es5.defineProperty(obj, name, descriptor);
5203 return obj;
5204}
5205
5206function thrower(r) {
5207 throw r;
5208}
5209
5210var inheritedDataKeys = (function() {
5211 var excludedPrototypes = [
5212 Array.prototype,
5213 Object.prototype,
5214 Function.prototype
5215 ];
5216
5217 var isExcludedProto = function(val) {
5218 for (var i = 0; i < excludedPrototypes.length; ++i) {
5219 if (excludedPrototypes[i] === val) {
5220 return true;
5221 }
5222 }
5223 return false;
5224 };
5225
5226 if (es5.isES5) {
5227 var getKeys = Object.getOwnPropertyNames;
5228 return function(obj) {
5229 var ret = [];
5230 var visitedKeys = Object.create(null);
5231 while (obj != null && !isExcludedProto(obj)) {
5232 var keys;
5233 try {
5234 keys = getKeys(obj);
5235 } catch (e) {
5236 return ret;
5237 }
5238 for (var i = 0; i < keys.length; ++i) {
5239 var key = keys[i];
5240 if (visitedKeys[key]) continue;
5241 visitedKeys[key] = true;
5242 var desc = Object.getOwnPropertyDescriptor(obj, key);
5243 if (desc != null && desc.get == null && desc.set == null) {
5244 ret.push(key);
5245 }
5246 }
5247 obj = es5.getPrototypeOf(obj);
5248 }
5249 return ret;
5250 };
5251 } else {
5252 var hasProp = {}.hasOwnProperty;
5253 return function(obj) {
5254 if (isExcludedProto(obj)) return [];
5255 var ret = [];
5256
5257 /*jshint forin:false */
5258 enumeration: for (var key in obj) {
5259 if (hasProp.call(obj, key)) {
5260 ret.push(key);
5261 } else {
5262 for (var i = 0; i < excludedPrototypes.length; ++i) {
5263 if (hasProp.call(excludedPrototypes[i], key)) {
5264 continue enumeration;
5265 }
5266 }
5267 ret.push(key);
5268 }
5269 }
5270 return ret;
5271 };
5272 }
5273
5274})();
5275
5276var thisAssignmentPattern = /this\s*\.\s*\S+\s*=/;
5277function isClass(fn) {
5278 try {
5279 if (typeof fn === "function") {
5280 var keys = es5.names(fn.prototype);
5281
5282 var hasMethods = es5.isES5 && keys.length > 1;
5283 var hasMethodsOtherThanConstructor = keys.length > 0 &&
5284 !(keys.length === 1 && keys[0] === "constructor");
5285 var hasThisAssignmentAndStaticMethods =
5286 thisAssignmentPattern.test(fn + "") && es5.names(fn).length > 0;
5287
5288 if (hasMethods || hasMethodsOtherThanConstructor ||
5289 hasThisAssignmentAndStaticMethods) {
5290 return true;
5291 }
5292 }
5293 return false;
5294 } catch (e) {
5295 return false;
5296 }
5297}
5298
5299function toFastProperties(obj) {
5300 /*jshint -W027,-W055,-W031*/
5301 function FakeConstructor() {}
5302 FakeConstructor.prototype = obj;
5303 var l = 8;
5304 while (l--) new FakeConstructor();
5305 return obj;
5306 eval(obj);
5307}
5308
5309var rident = /^[a-z$_][a-z$_0-9]*$/i;
5310function isIdentifier(str) {
5311 return rident.test(str);
5312}
5313
5314function filledRange(count, prefix, suffix) {
5315 var ret = new Array(count);
5316 for(var i = 0; i < count; ++i) {
5317 ret[i] = prefix + i + suffix;
5318 }
5319 return ret;
5320}
5321
5322function safeToString(obj) {
5323 try {
5324 return obj + "";
5325 } catch (e) {
5326 return "[no string representation]";
5327 }
5328}
5329
5330function isError(obj) {
5331 return obj !== null &&
5332 typeof obj === "object" &&
5333 typeof obj.message === "string" &&
5334 typeof obj.name === "string";
5335}
5336
5337function markAsOriginatingFromRejection(e) {
5338 try {
5339 notEnumerableProp(e, "isOperational", true);
5340 }
5341 catch(ignore) {}
5342}
5343
5344function originatesFromRejection(e) {
5345 if (e == null) return false;
5346 return ((e instanceof Error["__BluebirdErrorTypes__"].OperationalError) ||
5347 e["isOperational"] === true);
5348}
5349
5350function canAttachTrace(obj) {
5351 return isError(obj) && es5.propertyIsWritable(obj, "stack");
5352}
5353
5354var ensureErrorObject = (function() {
5355 if (!("stack" in new Error())) {
5356 return function(value) {
5357 if (canAttachTrace(value)) return value;
5358 try {throw new Error(safeToString(value));}
5359 catch(err) {return err;}
5360 };
5361 } else {
5362 return function(value) {
5363 if (canAttachTrace(value)) return value;
5364 return new Error(safeToString(value));
5365 };
5366 }
5367})();
5368
5369function classString(obj) {
5370 return {}.toString.call(obj);
5371}
5372
5373function copyDescriptors(from, to, filter) {
5374 var keys = es5.names(from);
5375 for (var i = 0; i < keys.length; ++i) {
5376 var key = keys[i];
5377 if (filter(key)) {
5378 try {
5379 es5.defineProperty(to, key, es5.getDescriptor(from, key));
5380 } catch (ignore) {}
5381 }
5382 }
5383}
5384
5385var asArray = function(v) {
5386 if (es5.isArray(v)) {
5387 return v;
5388 }
5389 return null;
5390};
5391
5392if (typeof Symbol !== "undefined" && Symbol.iterator) {
5393 var ArrayFrom = typeof Array.from === "function" ? function(v) {
5394 return Array.from(v);
5395 } : function(v) {
5396 var ret = [];
5397 var it = v[Symbol.iterator]();
5398 var itResult;
5399 while (!((itResult = it.next()).done)) {
5400 ret.push(itResult.value);
5401 }
5402 return ret;
5403 };
5404
5405 asArray = function(v) {
5406 if (es5.isArray(v)) {
5407 return v;
5408 } else if (v != null && typeof v[Symbol.iterator] === "function") {
5409 return ArrayFrom(v);
5410 }
5411 return null;
5412 };
5413}
5414
5415var isNode = typeof process !== "undefined" &&
5416 classString(process).toLowerCase() === "[object process]";
5417
5418function env(key, def) {
5419 return isNode ? process.env[key] : def;
5420}
5421
5422function getNativePromise() {
5423 if (typeof Promise === "function") {
5424 try {
5425 var promise = new Promise(function(){});
5426 if ({}.toString.call(promise) === "[object Promise]") {
5427 return Promise;
5428 }
5429 } catch (e) {}
5430 }
5431}
5432
5433var ret = {
5434 isClass: isClass,
5435 isIdentifier: isIdentifier,
5436 inheritedDataKeys: inheritedDataKeys,
5437 getDataPropertyOrDefault: getDataPropertyOrDefault,
5438 thrower: thrower,
5439 isArray: es5.isArray,
5440 asArray: asArray,
5441 notEnumerableProp: notEnumerableProp,
5442 isPrimitive: isPrimitive,
5443 isObject: isObject,
5444 isError: isError,
5445 canEvaluate: canEvaluate,
5446 errorObj: errorObj,
5447 tryCatch: tryCatch,
5448 inherits: inherits,
5449 withAppended: withAppended,
5450 maybeWrapAsError: maybeWrapAsError,
5451 toFastProperties: toFastProperties,
5452 filledRange: filledRange,
5453 toString: safeToString,
5454 canAttachTrace: canAttachTrace,
5455 ensureErrorObject: ensureErrorObject,
5456 originatesFromRejection: originatesFromRejection,
5457 markAsOriginatingFromRejection: markAsOriginatingFromRejection,
5458 classString: classString,
5459 copyDescriptors: copyDescriptors,
5460 hasDevTools: typeof chrome !== "undefined" && chrome &&
5461 typeof chrome.loadTimes === "function",
5462 isNode: isNode,
5463 env: env,
5464 global: globalObject,
5465 getNativePromise: getNativePromise
5466};
5467ret.isRecentNode = ret.isNode && (function() {
5468 var version = process.versions.node.split(".").map(Number);
5469 return (version[0] === 0 && version[1] > 10) || (version[0] > 0);
5470})();
5471
5472if (ret.isNode) ret.toFastProperties(process);
5473
5474try {throw new Error(); } catch (e) {ret.lastLineError = e;}
5475module.exports = ret;
5476
5477},{"./es5":13}]},{},[4])(4)
5478}); ;if (typeof window !== 'undefined' && window !== null) { window.P = window.Promise; } else if (typeof self !== 'undefined' && self !== null) { self.P = self.Promise; }
5479}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
5480},{"_process":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/browserify/node_modules/process/browser.js"}],"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/browser-request/index.js":[function(require,module,exports){
5481// Browser Request
5482//
5483// Licensed under the Apache License, Version 2.0 (the "License");
5484// you may not use this file except in compliance with the License.
5485// You may obtain a copy of the License at
5486//
5487// http://www.apache.org/licenses/LICENSE-2.0
5488//
5489// Unless required by applicable law or agreed to in writing, software
5490// distributed under the License is distributed on an "AS IS" BASIS,
5491// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5492// See the License for the specific language governing permissions and
5493// limitations under the License.
5494
5495// UMD HEADER START
5496(function (root, factory) {
5497 if (typeof define === 'function' && define.amd) {
5498 // AMD. Register as an anonymous module.
5499 define([], factory);
5500 } else if (typeof exports === 'object') {
5501 // Node. Does not work with strict CommonJS, but
5502 // only CommonJS-like enviroments that support module.exports,
5503 // like Node.
5504 module.exports = factory();
5505 } else {
5506 // Browser globals (root is window)
5507 root.returnExports = factory();
5508 }
5509}(this, function () {
5510// UMD HEADER END
5511
5512var XHR = XMLHttpRequest
5513if (!XHR) throw new Error('missing XMLHttpRequest')
5514request.log = {
5515 'trace': noop, 'debug': noop, 'info': noop, 'warn': noop, 'error': noop
5516}
5517
5518var DEFAULT_TIMEOUT = 3 * 60 * 1000 // 3 minutes
5519
5520//
5521// request
5522//
5523
5524function request(options, callback) {
5525 // The entry-point to the API: prep the options object and pass the real work to run_xhr.
5526 if(typeof callback !== 'function')
5527 throw new Error('Bad callback given: ' + callback)
5528
5529 if(!options)
5530 throw new Error('No options given')
5531
5532 var options_onResponse = options.onResponse; // Save this for later.
5533
5534 if(typeof options === 'string')
5535 options = {'uri':options};
5536 else
5537 options = JSON.parse(JSON.stringify(options)); // Use a duplicate for mutating.
5538
5539 options.onResponse = options_onResponse // And put it back.
5540
5541 if (options.verbose) request.log = getLogger();
5542
5543 if(options.url) {
5544 options.uri = options.url;
5545 delete options.url;
5546 }
5547
5548 if(!options.uri && options.uri !== "")
5549 throw new Error("options.uri is a required argument");
5550
5551 if(typeof options.uri != "string")
5552 throw new Error("options.uri must be a string");
5553
5554 var unsupported_options = ['proxy', '_redirectsFollowed', 'maxRedirects', 'followRedirect']
5555 for (var i = 0; i < unsupported_options.length; i++)
5556 if(options[ unsupported_options[i] ])
5557 throw new Error("options." + unsupported_options[i] + " is not supported")
5558
5559 options.callback = callback
5560 options.method = options.method || 'GET';
5561 options.headers = options.headers || {};
5562 options.body = options.body || null
5563 options.timeout = options.timeout || request.DEFAULT_TIMEOUT
5564
5565 if(options.headers.host)
5566 throw new Error("Options.headers.host is not supported");
5567
5568 if(options.json) {
5569 options.headers.accept = options.headers.accept || 'application/json'
5570 if(options.method !== 'GET')
5571 options.headers['content-type'] = 'application/json'
5572
5573 if(typeof options.json !== 'boolean')
5574 options.body = JSON.stringify(options.json)
5575 else if(typeof options.body !== 'string')
5576 options.body = JSON.stringify(options.body)
5577 }
5578
5579 //BEGIN QS Hack
5580 var serialize = function(obj) {
5581 var str = [];
5582 for(var p in obj)
5583 if (obj.hasOwnProperty(p)) {
5584 str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
5585 }
5586 return str.join("&");
5587 }
5588
5589 if(options.qs){
5590 var qs = (typeof options.qs == 'string')? options.qs : serialize(options.qs);
5591 if(options.uri.indexOf('?') !== -1){ //no get params
5592 options.uri = options.uri+'&'+qs;
5593 }else{ //existing get params
5594 options.uri = options.uri+'?'+qs;
5595 }
5596 }
5597 //END QS Hack
5598
5599 //BEGIN FORM Hack
5600 var multipart = function(obj) {
5601 //todo: support file type (useful?)
5602 var result = {};
5603 result.boundry = '-------------------------------'+Math.floor(Math.random()*1000000000);
5604 var lines = [];
5605 for(var p in obj){
5606 if (obj.hasOwnProperty(p)) {
5607 lines.push(
5608 '--'+result.boundry+"\n"+
5609 'Content-Disposition: form-data; name="'+p+'"'+"\n"+
5610 "\n"+
5611 obj[p]+"\n"
5612 );
5613 }
5614 }
5615 lines.push( '--'+result.boundry+'--' );
5616 result.body = lines.join('');
5617 result.length = result.body.length;
5618 result.type = 'multipart/form-data; boundary='+result.boundry;
5619 return result;
5620 }
5621
5622 if(options.form){
5623 if(typeof options.form == 'string') throw('form name unsupported');
5624 if(options.method === 'POST'){
5625 var encoding = (options.encoding || 'application/x-www-form-urlencoded').toLowerCase();
5626 options.headers['content-type'] = encoding;
5627 switch(encoding){
5628 case 'application/x-www-form-urlencoded':
5629 options.body = serialize(options.form).replace(/%20/g, "+");
5630 break;
5631 case 'multipart/form-data':
5632 var multi = multipart(options.form);
5633 //options.headers['content-length'] = multi.length;
5634 options.body = multi.body;
5635 options.headers['content-type'] = multi.type;
5636 break;
5637 default : throw new Error('unsupported encoding:'+encoding);
5638 }
5639 }
5640 }
5641 //END FORM Hack
5642
5643 // If onResponse is boolean true, call back immediately when the response is known,
5644 // not when the full request is complete.
5645 options.onResponse = options.onResponse || noop
5646 if(options.onResponse === true) {
5647 options.onResponse = callback
5648 options.callback = noop
5649 }
5650
5651 // XXX Browsers do not like this.
5652 //if(options.body)
5653 // options.headers['content-length'] = options.body.length;
5654
5655 // HTTP basic authentication
5656 if(!options.headers.authorization && options.auth)
5657 options.headers.authorization = 'Basic ' + b64_enc(options.auth.username + ':' + options.auth.password);
5658
5659 return run_xhr(options)
5660}
5661
5662var req_seq = 0
5663function run_xhr(options) {
5664 var xhr = new XHR
5665 , timed_out = false
5666 , is_cors = is_crossDomain(options.uri)
5667 , supports_cors = ('withCredentials' in xhr)
5668
5669 req_seq += 1
5670 xhr.seq_id = req_seq
5671 xhr.id = req_seq + ': ' + options.method + ' ' + options.uri
5672 xhr._id = xhr.id // I know I will type "_id" from habit all the time.
5673
5674 if(is_cors && !supports_cors) {
5675 var cors_err = new Error('Browser does not support cross-origin request: ' + options.uri)
5676 cors_err.cors = 'unsupported'
5677 return options.callback(cors_err, xhr)
5678 }
5679
5680 xhr.timeoutTimer = setTimeout(too_late, options.timeout)
5681 function too_late() {
5682 timed_out = true
5683 var er = new Error('ETIMEDOUT')
5684 er.code = 'ETIMEDOUT'
5685 er.duration = options.timeout
5686
5687 request.log.error('Timeout', { 'id':xhr._id, 'milliseconds':options.timeout })
5688 return options.callback(er, xhr)
5689 }
5690
5691 // Some states can be skipped over, so remember what is still incomplete.
5692 var did = {'response':false, 'loading':false, 'end':false}
5693
5694 xhr.onreadystatechange = on_state_change
5695 xhr.open(options.method, options.uri, true) // asynchronous
5696 if(is_cors)
5697 xhr.withCredentials = !! options.withCredentials
5698 xhr.send(options.body)
5699 return xhr
5700
5701 function on_state_change(event) {
5702 if(timed_out)
5703 return request.log.debug('Ignoring timed out state change', {'state':xhr.readyState, 'id':xhr.id})
5704
5705 request.log.debug('State change', {'state':xhr.readyState, 'id':xhr.id, 'timed_out':timed_out})
5706
5707 if(xhr.readyState === XHR.OPENED) {
5708 request.log.debug('Request started', {'id':xhr.id})
5709 for (var key in options.headers)
5710 xhr.setRequestHeader(key, options.headers[key])
5711 }
5712
5713 else if(xhr.readyState === XHR.HEADERS_RECEIVED)
5714 on_response()
5715
5716 else if(xhr.readyState === XHR.LOADING) {
5717 on_response()
5718 on_loading()
5719 }
5720
5721 else if(xhr.readyState === XHR.DONE) {
5722 on_response()
5723 on_loading()
5724 on_end()
5725 }
5726 }
5727
5728 function on_response() {
5729 if(did.response)
5730 return
5731
5732 did.response = true
5733 request.log.debug('Got response', {'id':xhr.id, 'status':xhr.status})
5734 clearTimeout(xhr.timeoutTimer)
5735 xhr.statusCode = xhr.status // Node request compatibility
5736
5737 // Detect failed CORS requests.
5738 if(is_cors && xhr.statusCode == 0) {
5739 var cors_err = new Error('CORS request rejected: ' + options.uri)
5740 cors_err.cors = 'rejected'
5741
5742 // Do not process this request further.
5743 did.loading = true
5744 did.end = true
5745
5746 return options.callback(cors_err, xhr)
5747 }
5748
5749 options.onResponse(null, xhr)
5750 }
5751
5752 function on_loading() {
5753 if(did.loading)
5754 return
5755
5756 did.loading = true
5757 request.log.debug('Response body loading', {'id':xhr.id})
5758 // TODO: Maybe simulate "data" events by watching xhr.responseText
5759 }
5760
5761 function on_end() {
5762 if(did.end)
5763 return
5764
5765 did.end = true
5766 request.log.debug('Request done', {'id':xhr.id})
5767
5768 xhr.body = xhr.responseText
5769 if(options.json) {
5770 try { xhr.body = JSON.parse(xhr.responseText) }
5771 catch (er) { return options.callback(er, xhr) }
5772 }
5773
5774 options.callback(null, xhr, xhr.body)
5775 }
5776
5777} // request
5778
5779request.withCredentials = false;
5780request.DEFAULT_TIMEOUT = DEFAULT_TIMEOUT;
5781
5782//
5783// defaults
5784//
5785
5786request.defaults = function(options, requester) {
5787 var def = function (method) {
5788 var d = function (params, callback) {
5789 if(typeof params === 'string')
5790 params = {'uri': params};
5791 else {
5792 params = JSON.parse(JSON.stringify(params));
5793 }
5794 for (var i in options) {
5795 if (params[i] === undefined) params[i] = options[i]
5796 }
5797 return method(params, callback)
5798 }
5799 return d
5800 }
5801 var de = def(request)
5802 de.get = def(request.get)
5803 de.post = def(request.post)
5804 de.put = def(request.put)
5805 de.head = def(request.head)
5806 return de
5807}
5808
5809//
5810// HTTP method shortcuts
5811//
5812
5813var shortcuts = [ 'get', 'put', 'post', 'head' ];
5814shortcuts.forEach(function(shortcut) {
5815 var method = shortcut.toUpperCase();
5816 var func = shortcut.toLowerCase();
5817
5818 request[func] = function(opts) {
5819 if(typeof opts === 'string')
5820 opts = {'method':method, 'uri':opts};
5821 else {
5822 opts = JSON.parse(JSON.stringify(opts));
5823 opts.method = method;
5824 }
5825
5826 var args = [opts].concat(Array.prototype.slice.apply(arguments, [1]));
5827 return request.apply(this, args);
5828 }
5829})
5830
5831//
5832// CouchDB shortcut
5833//
5834
5835request.couch = function(options, callback) {
5836 if(typeof options === 'string')
5837 options = {'uri':options}
5838
5839 // Just use the request API to do JSON.
5840 options.json = true
5841 if(options.body)
5842 options.json = options.body
5843 delete options.body
5844
5845 callback = callback || noop
5846
5847 var xhr = request(options, couch_handler)
5848 return xhr
5849
5850 function couch_handler(er, resp, body) {
5851 if(er)
5852 return callback(er, resp, body)
5853
5854 if((resp.statusCode < 200 || resp.statusCode > 299) && body.error) {
5855 // The body is a Couch JSON object indicating the error.
5856 er = new Error('CouchDB error: ' + (body.error.reason || body.error.error))
5857 for (var key in body)
5858 er[key] = body[key]
5859 return callback(er, resp, body);
5860 }
5861
5862 return callback(er, resp, body);
5863 }
5864}
5865
5866//
5867// Utility
5868//
5869
5870function noop() {}
5871
5872function getLogger() {
5873 var logger = {}
5874 , levels = ['trace', 'debug', 'info', 'warn', 'error']
5875 , level, i
5876
5877 for(i = 0; i < levels.length; i++) {
5878 level = levels[i]
5879
5880 logger[level] = noop
5881 if(typeof console !== 'undefined' && console && console[level])
5882 logger[level] = formatted(console, level)
5883 }
5884
5885 return logger
5886}
5887
5888function formatted(obj, method) {
5889 return formatted_logger
5890
5891 function formatted_logger(str, context) {
5892 if(typeof context === 'object')
5893 str += ' ' + JSON.stringify(context)
5894
5895 return obj[method].call(obj, str)
5896 }
5897}
5898
5899// Return whether a URL is a cross-domain request.
5900function is_crossDomain(url) {
5901 var rurl = /^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/
5902
5903 // jQuery #8138, IE may throw an exception when accessing
5904 // a field from window.location if document.domain has been set
5905 var ajaxLocation
5906 try { ajaxLocation = location.href }
5907 catch (e) {
5908 // Use the href attribute of an A element since IE will modify it given document.location
5909 ajaxLocation = document.createElement( "a" );
5910 ajaxLocation.href = "";
5911 ajaxLocation = ajaxLocation.href;
5912 }
5913
5914 var ajaxLocParts = rurl.exec(ajaxLocation.toLowerCase()) || []
5915 , parts = rurl.exec(url.toLowerCase() )
5916
5917 var result = !!(
5918 parts &&
5919 ( parts[1] != ajaxLocParts[1]
5920 || parts[2] != ajaxLocParts[2]
5921 || (parts[3] || (parts[1] === "http:" ? 80 : 443)) != (ajaxLocParts[3] || (ajaxLocParts[1] === "http:" ? 80 : 443))
5922 )
5923 )
5924
5925 //console.debug('is_crossDomain('+url+') -> ' + result)
5926 return result
5927}
5928
5929// MIT License from http://phpjs.org/functions/base64_encode:358
5930function b64_enc (data) {
5931 // Encodes string using MIME base64 algorithm
5932 var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
5933 var o1, o2, o3, h1, h2, h3, h4, bits, i = 0, ac = 0, enc="", tmp_arr = [];
5934
5935 if (!data) {
5936 return data;
5937 }
5938
5939 // assume utf8 data
5940 // data = this.utf8_encode(data+'');
5941
5942 do { // pack three octets into four hexets
5943 o1 = data.charCodeAt(i++);
5944 o2 = data.charCodeAt(i++);
5945 o3 = data.charCodeAt(i++);
5946
5947 bits = o1<<16 | o2<<8 | o3;
5948
5949 h1 = bits>>18 & 0x3f;
5950 h2 = bits>>12 & 0x3f;
5951 h3 = bits>>6 & 0x3f;
5952 h4 = bits & 0x3f;
5953
5954 // use hexets to index into b64, and append result to encoded string
5955 tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
5956 } while (i < data.length);
5957
5958 enc = tmp_arr.join('');
5959
5960 switch (data.length % 3) {
5961 case 1:
5962 enc = enc.slice(0, -2) + '==';
5963 break;
5964 case 2:
5965 enc = enc.slice(0, -1) + '=';
5966 break;
5967 }
5968
5969 return enc;
5970}
5971 return request;
5972//UMD FOOTER START
5973}));
5974//UMD FOOTER END
5975
5976},{}],"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/browserify/node_modules/browser-resolve/empty.js":[function(require,module,exports){
5977
5978},{}],"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/browserify/node_modules/buffer/index.js":[function(require,module,exports){
5979(function (global){
5980/*!
5981 * The buffer module from node.js, for the browser.
5982 *
5983 * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
5984 * @license MIT
5985 */
5986/* eslint-disable no-proto */
5987
5988'use strict'
5989
5990var base64 = require('base64-js')
5991var ieee754 = require('ieee754')
5992var isArray = require('isarray')
5993
5994exports.Buffer = Buffer
5995exports.SlowBuffer = SlowBuffer
5996exports.INSPECT_MAX_BYTES = 50
5997Buffer.poolSize = 8192 // not used by this implementation
5998
5999var rootParent = {}
6000
6001/**
6002 * If `Buffer.TYPED_ARRAY_SUPPORT`:
6003 * === true Use Uint8Array implementation (fastest)
6004 * === false Use Object implementation (most compatible, even IE6)
6005 *
6006 * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
6007 * Opera 11.6+, iOS 4.2+.
6008 *
6009 * Due to various browser bugs, sometimes the Object implementation will be used even
6010 * when the browser supports typed arrays.
6011 *
6012 * Note:
6013 *
6014 * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
6015 * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
6016 *
6017 * - Safari 5-7 lacks support for changing the `Object.prototype.constructor` property
6018 * on objects.
6019 *
6020 * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
6021 *
6022 * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
6023 * incorrect length in some situations.
6024
6025 * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
6026 * get the Object implementation, which is slower but behaves correctly.
6027 */
6028Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined
6029 ? global.TYPED_ARRAY_SUPPORT
6030 : typedArraySupport()
6031
6032function typedArraySupport () {
6033 function Bar () {}
6034 try {
6035 var arr = new Uint8Array(1)
6036 arr.foo = function () { return 42 }
6037 arr.constructor = Bar
6038 return arr.foo() === 42 && // typed array instances can be augmented
6039 arr.constructor === Bar && // constructor can be set
6040 typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`
6041 arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`
6042 } catch (e) {
6043 return false
6044 }
6045}
6046
6047function kMaxLength () {
6048 return Buffer.TYPED_ARRAY_SUPPORT
6049 ? 0x7fffffff
6050 : 0x3fffffff
6051}
6052
6053/**
6054 * Class: Buffer
6055 * =============
6056 *
6057 * The Buffer constructor returns instances of `Uint8Array` that are augmented
6058 * with function properties for all the node `Buffer` API functions. We use
6059 * `Uint8Array` so that square bracket notation works as expected -- it returns
6060 * a single octet.
6061 *
6062 * By augmenting the instances, we can avoid modifying the `Uint8Array`
6063 * prototype.
6064 */
6065function Buffer (arg) {
6066 if (!(this instanceof Buffer)) {
6067 // Avoid going through an ArgumentsAdaptorTrampoline in the common case.
6068 if (arguments.length > 1) return new Buffer(arg, arguments[1])
6069 return new Buffer(arg)
6070 }
6071
6072 if (!Buffer.TYPED_ARRAY_SUPPORT) {
6073 this.length = 0
6074 this.parent = undefined
6075 }
6076
6077 // Common case.
6078 if (typeof arg === 'number') {
6079 return fromNumber(this, arg)
6080 }
6081
6082 // Slightly less common case.
6083 if (typeof arg === 'string') {
6084 return fromString(this, arg, arguments.length > 1 ? arguments[1] : 'utf8')
6085 }
6086
6087 // Unusual.
6088 return fromObject(this, arg)
6089}
6090
6091function fromNumber (that, length) {
6092 that = allocate(that, length < 0 ? 0 : checked(length) | 0)
6093 if (!Buffer.TYPED_ARRAY_SUPPORT) {
6094 for (var i = 0; i < length; i++) {
6095 that[i] = 0
6096 }
6097 }
6098 return that
6099}
6100
6101function fromString (that, string, encoding) {
6102 if (typeof encoding !== 'string' || encoding === '') encoding = 'utf8'
6103
6104 // Assumption: byteLength() return value is always < kMaxLength.
6105 var length = byteLength(string, encoding) | 0
6106 that = allocate(that, length)
6107
6108 that.write(string, encoding)
6109 return that
6110}
6111
6112function fromObject (that, object) {
6113 if (Buffer.isBuffer(object)) return fromBuffer(that, object)
6114
6115 if (isArray(object)) return fromArray(that, object)
6116
6117 if (object == null) {
6118 throw new TypeError('must start with number, buffer, array or string')
6119 }
6120
6121 if (typeof ArrayBuffer !== 'undefined') {
6122 if (object.buffer instanceof ArrayBuffer) {
6123 return fromTypedArray(that, object)
6124 }
6125 if (object instanceof ArrayBuffer) {
6126 return fromArrayBuffer(that, object)
6127 }
6128 }
6129
6130 if (object.length) return fromArrayLike(that, object)
6131
6132 return fromJsonObject(that, object)
6133}
6134
6135function fromBuffer (that, buffer) {
6136 var length = checked(buffer.length) | 0
6137 that = allocate(that, length)
6138 buffer.copy(that, 0, 0, length)
6139 return that
6140}
6141
6142function fromArray (that, array) {
6143 var length = checked(array.length) | 0
6144 that = allocate(that, length)
6145 for (var i = 0; i < length; i += 1) {
6146 that[i] = array[i] & 255
6147 }
6148 return that
6149}
6150
6151// Duplicate of fromArray() to keep fromArray() monomorphic.
6152function fromTypedArray (that, array) {
6153 var length = checked(array.length) | 0
6154 that = allocate(that, length)
6155 // Truncating the elements is probably not what people expect from typed
6156 // arrays with BYTES_PER_ELEMENT > 1 but it's compatible with the behavior
6157 // of the old Buffer constructor.
6158 for (var i = 0; i < length; i += 1) {
6159 that[i] = array[i] & 255
6160 }
6161 return that
6162}
6163
6164function fromArrayBuffer (that, array) {
6165 if (Buffer.TYPED_ARRAY_SUPPORT) {
6166 // Return an augmented `Uint8Array` instance, for best performance
6167 array.byteLength
6168 that = Buffer._augment(new Uint8Array(array))
6169 } else {
6170 // Fallback: Return an object instance of the Buffer class
6171 that = fromTypedArray(that, new Uint8Array(array))
6172 }
6173 return that
6174}
6175
6176function fromArrayLike (that, array) {
6177 var length = checked(array.length) | 0
6178 that = allocate(that, length)
6179 for (var i = 0; i < length; i += 1) {
6180 that[i] = array[i] & 255
6181 }
6182 return that
6183}
6184
6185// Deserialize { type: 'Buffer', data: [1,2,3,...] } into a Buffer object.
6186// Returns a zero-length buffer for inputs that don't conform to the spec.
6187function fromJsonObject (that, object) {
6188 var array
6189 var length = 0
6190
6191 if (object.type === 'Buffer' && isArray(object.data)) {
6192 array = object.data
6193 length = checked(array.length) | 0
6194 }
6195 that = allocate(that, length)
6196
6197 for (var i = 0; i < length; i += 1) {
6198 that[i] = array[i] & 255
6199 }
6200 return that
6201}
6202
6203if (Buffer.TYPED_ARRAY_SUPPORT) {
6204 Buffer.prototype.__proto__ = Uint8Array.prototype
6205 Buffer.__proto__ = Uint8Array
6206} else {
6207 // pre-set for values that may exist in the future
6208 Buffer.prototype.length = undefined
6209 Buffer.prototype.parent = undefined
6210}
6211
6212function allocate (that, length) {
6213 if (Buffer.TYPED_ARRAY_SUPPORT) {
6214 // Return an augmented `Uint8Array` instance, for best performance
6215 that = Buffer._augment(new Uint8Array(length))
6216 that.__proto__ = Buffer.prototype
6217 } else {
6218 // Fallback: Return an object instance of the Buffer class
6219 that.length = length
6220 that._isBuffer = true
6221 }
6222
6223 var fromPool = length !== 0 && length <= Buffer.poolSize >>> 1
6224 if (fromPool) that.parent = rootParent
6225
6226 return that
6227}
6228
6229function checked (length) {
6230 // Note: cannot use `length < kMaxLength` here because that fails when
6231 // length is NaN (which is otherwise coerced to zero.)
6232 if (length >= kMaxLength()) {
6233 throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
6234 'size: 0x' + kMaxLength().toString(16) + ' bytes')
6235 }
6236 return length | 0
6237}
6238
6239function SlowBuffer (subject, encoding) {
6240 if (!(this instanceof SlowBuffer)) return new SlowBuffer(subject, encoding)
6241
6242 var buf = new Buffer(subject, encoding)
6243 delete buf.parent
6244 return buf
6245}
6246
6247Buffer.isBuffer = function isBuffer (b) {
6248 return !!(b != null && b._isBuffer)
6249}
6250
6251Buffer.compare = function compare (a, b) {
6252 if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
6253 throw new TypeError('Arguments must be Buffers')
6254 }
6255
6256 if (a === b) return 0
6257
6258 var x = a.length
6259 var y = b.length
6260
6261 var i = 0
6262 var len = Math.min(x, y)
6263 while (i < len) {
6264 if (a[i] !== b[i]) break
6265
6266 ++i
6267 }
6268
6269 if (i !== len) {
6270 x = a[i]
6271 y = b[i]
6272 }
6273
6274 if (x < y) return -1
6275 if (y < x) return 1
6276 return 0
6277}
6278
6279Buffer.isEncoding = function isEncoding (encoding) {
6280 switch (String(encoding).toLowerCase()) {
6281 case 'hex':
6282 case 'utf8':
6283 case 'utf-8':
6284 case 'ascii':
6285 case 'binary':
6286 case 'base64':
6287 case 'raw':
6288 case 'ucs2':
6289 case 'ucs-2':
6290 case 'utf16le':
6291 case 'utf-16le':
6292 return true
6293 default:
6294 return false
6295 }
6296}
6297
6298Buffer.concat = function concat (list, length) {
6299 if (!isArray(list)) throw new TypeError('list argument must be an Array of Buffers.')
6300
6301 if (list.length === 0) {
6302 return new Buffer(0)
6303 }
6304
6305 var i
6306 if (length === undefined) {
6307 length = 0
6308 for (i = 0; i < list.length; i++) {
6309 length += list[i].length
6310 }
6311 }
6312
6313 var buf = new Buffer(length)
6314 var pos = 0
6315 for (i = 0; i < list.length; i++) {
6316 var item = list[i]
6317 item.copy(buf, pos)
6318 pos += item.length
6319 }
6320 return buf
6321}
6322
6323function byteLength (string, encoding) {
6324 if (typeof string !== 'string') string = '' + string
6325
6326 var len = string.length
6327 if (len === 0) return 0
6328
6329 // Use a for loop to avoid recursion
6330 var loweredCase = false
6331 for (;;) {
6332 switch (encoding) {
6333 case 'ascii':
6334 case 'binary':
6335 // Deprecated
6336 case 'raw':
6337 case 'raws':
6338 return len
6339 case 'utf8':
6340 case 'utf-8':
6341 return utf8ToBytes(string).length
6342 case 'ucs2':
6343 case 'ucs-2':
6344 case 'utf16le':
6345 case 'utf-16le':
6346 return len * 2
6347 case 'hex':
6348 return len >>> 1
6349 case 'base64':
6350 return base64ToBytes(string).length
6351 default:
6352 if (loweredCase) return utf8ToBytes(string).length // assume utf8
6353 encoding = ('' + encoding).toLowerCase()
6354 loweredCase = true
6355 }
6356 }
6357}
6358Buffer.byteLength = byteLength
6359
6360function slowToString (encoding, start, end) {
6361 var loweredCase = false
6362
6363 start = start | 0
6364 end = end === undefined || end === Infinity ? this.length : end | 0
6365
6366 if (!encoding) encoding = 'utf8'
6367 if (start < 0) start = 0
6368 if (end > this.length) end = this.length
6369 if (end <= start) return ''
6370
6371 while (true) {
6372 switch (encoding) {
6373 case 'hex':
6374 return hexSlice(this, start, end)
6375
6376 case 'utf8':
6377 case 'utf-8':
6378 return utf8Slice(this, start, end)
6379
6380 case 'ascii':
6381 return asciiSlice(this, start, end)
6382
6383 case 'binary':
6384 return binarySlice(this, start, end)
6385
6386 case 'base64':
6387 return base64Slice(this, start, end)
6388
6389 case 'ucs2':
6390 case 'ucs-2':
6391 case 'utf16le':
6392 case 'utf-16le':
6393 return utf16leSlice(this, start, end)
6394
6395 default:
6396 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
6397 encoding = (encoding + '').toLowerCase()
6398 loweredCase = true
6399 }
6400 }
6401}
6402
6403Buffer.prototype.toString = function toString () {
6404 var length = this.length | 0
6405 if (length === 0) return ''
6406 if (arguments.length === 0) return utf8Slice(this, 0, length)
6407 return slowToString.apply(this, arguments)
6408}
6409
6410Buffer.prototype.equals = function equals (b) {
6411 if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
6412 if (this === b) return true
6413 return Buffer.compare(this, b) === 0
6414}
6415
6416Buffer.prototype.inspect = function inspect () {
6417 var str = ''
6418 var max = exports.INSPECT_MAX_BYTES
6419 if (this.length > 0) {
6420 str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
6421 if (this.length > max) str += ' ... '
6422 }
6423 return '<Buffer ' + str + '>'
6424}
6425
6426Buffer.prototype.compare = function compare (b) {
6427 if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
6428 if (this === b) return 0
6429 return Buffer.compare(this, b)
6430}
6431
6432Buffer.prototype.indexOf = function indexOf (val, byteOffset) {
6433 if (byteOffset > 0x7fffffff) byteOffset = 0x7fffffff
6434 else if (byteOffset < -0x80000000) byteOffset = -0x80000000
6435 byteOffset >>= 0
6436
6437 if (this.length === 0) return -1
6438 if (byteOffset >= this.length) return -1
6439
6440 // Negative offsets start from the end of the buffer
6441 if (byteOffset < 0) byteOffset = Math.max(this.length + byteOffset, 0)
6442
6443 if (typeof val === 'string') {
6444 if (val.length === 0) return -1 // special case: looking for empty string always fails
6445 return String.prototype.indexOf.call(this, val, byteOffset)
6446 }
6447 if (Buffer.isBuffer(val)) {
6448 return arrayIndexOf(this, val, byteOffset)
6449 }
6450 if (typeof val === 'number') {
6451 if (Buffer.TYPED_ARRAY_SUPPORT && Uint8Array.prototype.indexOf === 'function') {
6452 return Uint8Array.prototype.indexOf.call(this, val, byteOffset)
6453 }
6454 return arrayIndexOf(this, [ val ], byteOffset)
6455 }
6456
6457 function arrayIndexOf (arr, val, byteOffset) {
6458 var foundIndex = -1
6459 for (var i = 0; byteOffset + i < arr.length; i++) {
6460 if (arr[byteOffset + i] === val[foundIndex === -1 ? 0 : i - foundIndex]) {
6461 if (foundIndex === -1) foundIndex = i
6462 if (i - foundIndex + 1 === val.length) return byteOffset + foundIndex
6463 } else {
6464 foundIndex = -1
6465 }
6466 }
6467 return -1
6468 }
6469
6470 throw new TypeError('val must be string, number or Buffer')
6471}
6472
6473// `get` is deprecated
6474Buffer.prototype.get = function get (offset) {
6475 console.log('.get() is deprecated. Access using array indexes instead.')
6476 return this.readUInt8(offset)
6477}
6478
6479// `set` is deprecated
6480Buffer.prototype.set = function set (v, offset) {
6481 console.log('.set() is deprecated. Access using array indexes instead.')
6482 return this.writeUInt8(v, offset)
6483}
6484
6485function hexWrite (buf, string, offset, length) {
6486 offset = Number(offset) || 0
6487 var remaining = buf.length - offset
6488 if (!length) {
6489 length = remaining
6490 } else {
6491 length = Number(length)
6492 if (length > remaining) {
6493 length = remaining
6494 }
6495 }
6496
6497 // must be an even number of digits
6498 var strLen = string.length
6499 if (strLen % 2 !== 0) throw new Error('Invalid hex string')
6500
6501 if (length > strLen / 2) {
6502 length = strLen / 2
6503 }
6504 for (var i = 0; i < length; i++) {
6505 var parsed = parseInt(string.substr(i * 2, 2), 16)
6506 if (isNaN(parsed)) throw new Error('Invalid hex string')
6507 buf[offset + i] = parsed
6508 }
6509 return i
6510}
6511
6512function utf8Write (buf, string, offset, length) {
6513 return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
6514}
6515
6516function asciiWrite (buf, string, offset, length) {
6517 return blitBuffer(asciiToBytes(string), buf, offset, length)
6518}
6519
6520function binaryWrite (buf, string, offset, length) {
6521 return asciiWrite(buf, string, offset, length)
6522}
6523
6524function base64Write (buf, string, offset, length) {
6525 return blitBuffer(base64ToBytes(string), buf, offset, length)
6526}
6527
6528function ucs2Write (buf, string, offset, length) {
6529 return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
6530}
6531
6532Buffer.prototype.write = function write (string, offset, length, encoding) {
6533 // Buffer#write(string)
6534 if (offset === undefined) {
6535 encoding = 'utf8'
6536 length = this.length
6537 offset = 0
6538 // Buffer#write(string, encoding)
6539 } else if (length === undefined && typeof offset === 'string') {
6540 encoding = offset
6541 length = this.length
6542 offset = 0
6543 // Buffer#write(string, offset[, length][, encoding])
6544 } else if (isFinite(offset)) {
6545 offset = offset | 0
6546 if (isFinite(length)) {
6547 length = length | 0
6548 if (encoding === undefined) encoding = 'utf8'
6549 } else {
6550 encoding = length
6551 length = undefined
6552 }
6553 // legacy write(string, encoding, offset, length) - remove in v0.13
6554 } else {
6555 var swap = encoding
6556 encoding = offset
6557 offset = length | 0
6558 length = swap
6559 }
6560
6561 var remaining = this.length - offset
6562 if (length === undefined || length > remaining) length = remaining
6563
6564 if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
6565 throw new RangeError('attempt to write outside buffer bounds')
6566 }
6567
6568 if (!encoding) encoding = 'utf8'
6569
6570 var loweredCase = false
6571 for (;;) {
6572 switch (encoding) {
6573 case 'hex':
6574 return hexWrite(this, string, offset, length)
6575
6576 case 'utf8':
6577 case 'utf-8':
6578 return utf8Write(this, string, offset, length)
6579
6580 case 'ascii':
6581 return asciiWrite(this, string, offset, length)
6582
6583 case 'binary':
6584 return binaryWrite(this, string, offset, length)
6585
6586 case 'base64':
6587 // Warning: maxLength not taken into account in base64Write
6588 return base64Write(this, string, offset, length)
6589
6590 case 'ucs2':
6591 case 'ucs-2':
6592 case 'utf16le':
6593 case 'utf-16le':
6594 return ucs2Write(this, string, offset, length)
6595
6596 default:
6597 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
6598 encoding = ('' + encoding).toLowerCase()
6599 loweredCase = true
6600 }
6601 }
6602}
6603
6604Buffer.prototype.toJSON = function toJSON () {
6605 return {
6606 type: 'Buffer',
6607 data: Array.prototype.slice.call(this._arr || this, 0)
6608 }
6609}
6610
6611function base64Slice (buf, start, end) {
6612 if (start === 0 && end === buf.length) {
6613 return base64.fromByteArray(buf)
6614 } else {
6615 return base64.fromByteArray(buf.slice(start, end))
6616 }
6617}
6618
6619function utf8Slice (buf, start, end) {
6620 end = Math.min(buf.length, end)
6621 var res = []
6622
6623 var i = start
6624 while (i < end) {
6625 var firstByte = buf[i]
6626 var codePoint = null
6627 var bytesPerSequence = (firstByte > 0xEF) ? 4
6628 : (firstByte > 0xDF) ? 3
6629 : (firstByte > 0xBF) ? 2
6630 : 1
6631
6632 if (i + bytesPerSequence <= end) {
6633 var secondByte, thirdByte, fourthByte, tempCodePoint
6634
6635 switch (bytesPerSequence) {
6636 case 1:
6637 if (firstByte < 0x80) {
6638 codePoint = firstByte
6639 }
6640 break
6641 case 2:
6642 secondByte = buf[i + 1]
6643 if ((secondByte & 0xC0) === 0x80) {
6644 tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
6645 if (tempCodePoint > 0x7F) {
6646 codePoint = tempCodePoint
6647 }
6648 }
6649 break
6650 case 3:
6651 secondByte = buf[i + 1]
6652 thirdByte = buf[i + 2]
6653 if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
6654 tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
6655 if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
6656 codePoint = tempCodePoint
6657 }
6658 }
6659 break
6660 case 4:
6661 secondByte = buf[i + 1]
6662 thirdByte = buf[i + 2]
6663 fourthByte = buf[i + 3]
6664 if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
6665 tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
6666 if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
6667 codePoint = tempCodePoint
6668 }
6669 }
6670 }
6671 }
6672
6673 if (codePoint === null) {
6674 // we did not generate a valid codePoint so insert a
6675 // replacement char (U+FFFD) and advance only 1 byte
6676 codePoint = 0xFFFD
6677 bytesPerSequence = 1
6678 } else if (codePoint > 0xFFFF) {
6679 // encode to utf16 (surrogate pair dance)
6680 codePoint -= 0x10000
6681 res.push(codePoint >>> 10 & 0x3FF | 0xD800)
6682 codePoint = 0xDC00 | codePoint & 0x3FF
6683 }
6684
6685 res.push(codePoint)
6686 i += bytesPerSequence
6687 }
6688
6689 return decodeCodePointsArray(res)
6690}
6691
6692// Based on http://stackoverflow.com/a/22747272/680742, the browser with
6693// the lowest limit is Chrome, with 0x10000 args.
6694// We go 1 magnitude less, for safety
6695var MAX_ARGUMENTS_LENGTH = 0x1000
6696
6697function decodeCodePointsArray (codePoints) {
6698 var len = codePoints.length
6699 if (len <= MAX_ARGUMENTS_LENGTH) {
6700 return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
6701 }
6702
6703 // Decode in chunks to avoid "call stack size exceeded".
6704 var res = ''
6705 var i = 0
6706 while (i < len) {
6707 res += String.fromCharCode.apply(
6708 String,
6709 codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
6710 )
6711 }
6712 return res
6713}
6714
6715function asciiSlice (buf, start, end) {
6716 var ret = ''
6717 end = Math.min(buf.length, end)
6718
6719 for (var i = start; i < end; i++) {
6720 ret += String.fromCharCode(buf[i] & 0x7F)
6721 }
6722 return ret
6723}
6724
6725function binarySlice (buf, start, end) {
6726 var ret = ''
6727 end = Math.min(buf.length, end)
6728
6729 for (var i = start; i < end; i++) {
6730 ret += String.fromCharCode(buf[i])
6731 }
6732 return ret
6733}
6734
6735function hexSlice (buf, start, end) {
6736 var len = buf.length
6737
6738 if (!start || start < 0) start = 0
6739 if (!end || end < 0 || end > len) end = len
6740
6741 var out = ''
6742 for (var i = start; i < end; i++) {
6743 out += toHex(buf[i])
6744 }
6745 return out
6746}
6747
6748function utf16leSlice (buf, start, end) {
6749 var bytes = buf.slice(start, end)
6750 var res = ''
6751 for (var i = 0; i < bytes.length; i += 2) {
6752 res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)
6753 }
6754 return res
6755}
6756
6757Buffer.prototype.slice = function slice (start, end) {
6758 var len = this.length
6759 start = ~~start
6760 end = end === undefined ? len : ~~end
6761
6762 if (start < 0) {
6763 start += len
6764 if (start < 0) start = 0
6765 } else if (start > len) {
6766 start = len
6767 }
6768
6769 if (end < 0) {
6770 end += len
6771 if (end < 0) end = 0
6772 } else if (end > len) {
6773 end = len
6774 }
6775
6776 if (end < start) end = start
6777
6778 var newBuf
6779 if (Buffer.TYPED_ARRAY_SUPPORT) {
6780 newBuf = Buffer._augment(this.subarray(start, end))
6781 } else {
6782 var sliceLen = end - start
6783 newBuf = new Buffer(sliceLen, undefined)
6784 for (var i = 0; i < sliceLen; i++) {
6785 newBuf[i] = this[i + start]
6786 }
6787 }
6788
6789 if (newBuf.length) newBuf.parent = this.parent || this
6790
6791 return newBuf
6792}
6793
6794/*
6795 * Need to make sure that buffer isn't trying to write out of bounds.
6796 */
6797function checkOffset (offset, ext, length) {
6798 if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
6799 if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
6800}
6801
6802Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
6803 offset = offset | 0
6804 byteLength = byteLength | 0
6805 if (!noAssert) checkOffset(offset, byteLength, this.length)
6806
6807 var val = this[offset]
6808 var mul = 1
6809 var i = 0
6810 while (++i < byteLength && (mul *= 0x100)) {
6811 val += this[offset + i] * mul
6812 }
6813
6814 return val
6815}
6816
6817Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
6818 offset = offset | 0
6819 byteLength = byteLength | 0
6820 if (!noAssert) {
6821 checkOffset(offset, byteLength, this.length)
6822 }
6823
6824 var val = this[offset + --byteLength]
6825 var mul = 1
6826 while (byteLength > 0 && (mul *= 0x100)) {
6827 val += this[offset + --byteLength] * mul
6828 }
6829
6830 return val
6831}
6832
6833Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
6834 if (!noAssert) checkOffset(offset, 1, this.length)
6835 return this[offset]
6836}
6837
6838Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
6839 if (!noAssert) checkOffset(offset, 2, this.length)
6840 return this[offset] | (this[offset + 1] << 8)
6841}
6842
6843Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
6844 if (!noAssert) checkOffset(offset, 2, this.length)
6845 return (this[offset] << 8) | this[offset + 1]
6846}
6847
6848Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
6849 if (!noAssert) checkOffset(offset, 4, this.length)
6850
6851 return ((this[offset]) |
6852 (this[offset + 1] << 8) |
6853 (this[offset + 2] << 16)) +
6854 (this[offset + 3] * 0x1000000)
6855}
6856
6857Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
6858 if (!noAssert) checkOffset(offset, 4, this.length)
6859
6860 return (this[offset] * 0x1000000) +
6861 ((this[offset + 1] << 16) |
6862 (this[offset + 2] << 8) |
6863 this[offset + 3])
6864}
6865
6866Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
6867 offset = offset | 0
6868 byteLength = byteLength | 0
6869 if (!noAssert) checkOffset(offset, byteLength, this.length)
6870
6871 var val = this[offset]
6872 var mul = 1
6873 var i = 0
6874 while (++i < byteLength && (mul *= 0x100)) {
6875 val += this[offset + i] * mul
6876 }
6877 mul *= 0x80
6878
6879 if (val >= mul) val -= Math.pow(2, 8 * byteLength)
6880
6881 return val
6882}
6883
6884Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
6885 offset = offset | 0
6886 byteLength = byteLength | 0
6887 if (!noAssert) checkOffset(offset, byteLength, this.length)
6888
6889 var i = byteLength
6890 var mul = 1
6891 var val = this[offset + --i]
6892 while (i > 0 && (mul *= 0x100)) {
6893 val += this[offset + --i] * mul
6894 }
6895 mul *= 0x80
6896
6897 if (val >= mul) val -= Math.pow(2, 8 * byteLength)
6898
6899 return val
6900}
6901
6902Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
6903 if (!noAssert) checkOffset(offset, 1, this.length)
6904 if (!(this[offset] & 0x80)) return (this[offset])
6905 return ((0xff - this[offset] + 1) * -1)
6906}
6907
6908Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
6909 if (!noAssert) checkOffset(offset, 2, this.length)
6910 var val = this[offset] | (this[offset + 1] << 8)
6911 return (val & 0x8000) ? val | 0xFFFF0000 : val
6912}
6913
6914Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
6915 if (!noAssert) checkOffset(offset, 2, this.length)
6916 var val = this[offset + 1] | (this[offset] << 8)
6917 return (val & 0x8000) ? val | 0xFFFF0000 : val
6918}
6919
6920Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
6921 if (!noAssert) checkOffset(offset, 4, this.length)
6922
6923 return (this[offset]) |
6924 (this[offset + 1] << 8) |
6925 (this[offset + 2] << 16) |
6926 (this[offset + 3] << 24)
6927}
6928
6929Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
6930 if (!noAssert) checkOffset(offset, 4, this.length)
6931
6932 return (this[offset] << 24) |
6933 (this[offset + 1] << 16) |
6934 (this[offset + 2] << 8) |
6935 (this[offset + 3])
6936}
6937
6938Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
6939 if (!noAssert) checkOffset(offset, 4, this.length)
6940 return ieee754.read(this, offset, true, 23, 4)
6941}
6942
6943Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
6944 if (!noAssert) checkOffset(offset, 4, this.length)
6945 return ieee754.read(this, offset, false, 23, 4)
6946}
6947
6948Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
6949 if (!noAssert) checkOffset(offset, 8, this.length)
6950 return ieee754.read(this, offset, true, 52, 8)
6951}
6952
6953Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
6954 if (!noAssert) checkOffset(offset, 8, this.length)
6955 return ieee754.read(this, offset, false, 52, 8)
6956}
6957
6958function checkInt (buf, value, offset, ext, max, min) {
6959 if (!Buffer.isBuffer(buf)) throw new TypeError('buffer must be a Buffer instance')
6960 if (value > max || value < min) throw new RangeError('value is out of bounds')
6961 if (offset + ext > buf.length) throw new RangeError('index out of range')
6962}
6963
6964Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
6965 value = +value
6966 offset = offset | 0
6967 byteLength = byteLength | 0
6968 if (!noAssert) checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0)
6969
6970 var mul = 1
6971 var i = 0
6972 this[offset] = value & 0xFF
6973 while (++i < byteLength && (mul *= 0x100)) {
6974 this[offset + i] = (value / mul) & 0xFF
6975 }
6976
6977 return offset + byteLength
6978}
6979
6980Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
6981 value = +value
6982 offset = offset | 0
6983 byteLength = byteLength | 0
6984 if (!noAssert) checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0)
6985
6986 var i = byteLength - 1
6987 var mul = 1
6988 this[offset + i] = value & 0xFF
6989 while (--i >= 0 && (mul *= 0x100)) {
6990 this[offset + i] = (value / mul) & 0xFF
6991 }
6992
6993 return offset + byteLength
6994}
6995
6996Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
6997 value = +value
6998 offset = offset | 0
6999 if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
7000 if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
7001 this[offset] = (value & 0xff)
7002 return offset + 1
7003}
7004
7005function objectWriteUInt16 (buf, value, offset, littleEndian) {
7006 if (value < 0) value = 0xffff + value + 1
7007 for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; i++) {
7008 buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
7009 (littleEndian ? i : 1 - i) * 8
7010 }
7011}
7012
7013Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
7014 value = +value
7015 offset = offset | 0
7016 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
7017 if (Buffer.TYPED_ARRAY_SUPPORT) {
7018 this[offset] = (value & 0xff)
7019 this[offset + 1] = (value >>> 8)
7020 } else {
7021 objectWriteUInt16(this, value, offset, true)
7022 }
7023 return offset + 2
7024}
7025
7026Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
7027 value = +value
7028 offset = offset | 0
7029 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
7030 if (Buffer.TYPED_ARRAY_SUPPORT) {
7031 this[offset] = (value >>> 8)
7032 this[offset + 1] = (value & 0xff)
7033 } else {
7034 objectWriteUInt16(this, value, offset, false)
7035 }
7036 return offset + 2
7037}
7038
7039function objectWriteUInt32 (buf, value, offset, littleEndian) {
7040 if (value < 0) value = 0xffffffff + value + 1
7041 for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; i++) {
7042 buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff
7043 }
7044}
7045
7046Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
7047 value = +value
7048 offset = offset | 0
7049 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
7050 if (Buffer.TYPED_ARRAY_SUPPORT) {
7051 this[offset + 3] = (value >>> 24)
7052 this[offset + 2] = (value >>> 16)
7053 this[offset + 1] = (value >>> 8)
7054 this[offset] = (value & 0xff)
7055 } else {
7056 objectWriteUInt32(this, value, offset, true)
7057 }
7058 return offset + 4
7059}
7060
7061Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
7062 value = +value
7063 offset = offset | 0
7064 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
7065 if (Buffer.TYPED_ARRAY_SUPPORT) {
7066 this[offset] = (value >>> 24)
7067 this[offset + 1] = (value >>> 16)
7068 this[offset + 2] = (value >>> 8)
7069 this[offset + 3] = (value & 0xff)
7070 } else {
7071 objectWriteUInt32(this, value, offset, false)
7072 }
7073 return offset + 4
7074}
7075
7076Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
7077 value = +value
7078 offset = offset | 0
7079 if (!noAssert) {
7080 var limit = Math.pow(2, 8 * byteLength - 1)
7081
7082 checkInt(this, value, offset, byteLength, limit - 1, -limit)
7083 }
7084
7085 var i = 0
7086 var mul = 1
7087 var sub = value < 0 ? 1 : 0
7088 this[offset] = value & 0xFF
7089 while (++i < byteLength && (mul *= 0x100)) {
7090 this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
7091 }
7092
7093 return offset + byteLength
7094}
7095
7096Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
7097 value = +value
7098 offset = offset | 0
7099 if (!noAssert) {
7100 var limit = Math.pow(2, 8 * byteLength - 1)
7101
7102 checkInt(this, value, offset, byteLength, limit - 1, -limit)
7103 }
7104
7105 var i = byteLength - 1
7106 var mul = 1
7107 var sub = value < 0 ? 1 : 0
7108 this[offset + i] = value & 0xFF
7109 while (--i >= 0 && (mul *= 0x100)) {
7110 this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
7111 }
7112
7113 return offset + byteLength
7114}
7115
7116Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
7117 value = +value
7118 offset = offset | 0
7119 if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
7120 if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
7121 if (value < 0) value = 0xff + value + 1
7122 this[offset] = (value & 0xff)
7123 return offset + 1
7124}
7125
7126Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
7127 value = +value
7128 offset = offset | 0
7129 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
7130 if (Buffer.TYPED_ARRAY_SUPPORT) {
7131 this[offset] = (value & 0xff)
7132 this[offset + 1] = (value >>> 8)
7133 } else {
7134 objectWriteUInt16(this, value, offset, true)
7135 }
7136 return offset + 2
7137}
7138
7139Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
7140 value = +value
7141 offset = offset | 0
7142 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
7143 if (Buffer.TYPED_ARRAY_SUPPORT) {
7144 this[offset] = (value >>> 8)
7145 this[offset + 1] = (value & 0xff)
7146 } else {
7147 objectWriteUInt16(this, value, offset, false)
7148 }
7149 return offset + 2
7150}
7151
7152Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
7153 value = +value
7154 offset = offset | 0
7155 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
7156 if (Buffer.TYPED_ARRAY_SUPPORT) {
7157 this[offset] = (value & 0xff)
7158 this[offset + 1] = (value >>> 8)
7159 this[offset + 2] = (value >>> 16)
7160 this[offset + 3] = (value >>> 24)
7161 } else {
7162 objectWriteUInt32(this, value, offset, true)
7163 }
7164 return offset + 4
7165}
7166
7167Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
7168 value = +value
7169 offset = offset | 0
7170 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
7171 if (value < 0) value = 0xffffffff + value + 1
7172 if (Buffer.TYPED_ARRAY_SUPPORT) {
7173 this[offset] = (value >>> 24)
7174 this[offset + 1] = (value >>> 16)
7175 this[offset + 2] = (value >>> 8)
7176 this[offset + 3] = (value & 0xff)
7177 } else {
7178 objectWriteUInt32(this, value, offset, false)
7179 }
7180 return offset + 4
7181}
7182
7183function checkIEEE754 (buf, value, offset, ext, max, min) {
7184 if (value > max || value < min) throw new RangeError('value is out of bounds')
7185 if (offset + ext > buf.length) throw new RangeError('index out of range')
7186 if (offset < 0) throw new RangeError('index out of range')
7187}
7188
7189function writeFloat (buf, value, offset, littleEndian, noAssert) {
7190 if (!noAssert) {
7191 checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
7192 }
7193 ieee754.write(buf, value, offset, littleEndian, 23, 4)
7194 return offset + 4
7195}
7196
7197Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
7198 return writeFloat(this, value, offset, true, noAssert)
7199}
7200
7201Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
7202 return writeFloat(this, value, offset, false, noAssert)
7203}
7204
7205function writeDouble (buf, value, offset, littleEndian, noAssert) {
7206 if (!noAssert) {
7207 checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
7208 }
7209 ieee754.write(buf, value, offset, littleEndian, 52, 8)
7210 return offset + 8
7211}
7212
7213Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
7214 return writeDouble(this, value, offset, true, noAssert)
7215}
7216
7217Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
7218 return writeDouble(this, value, offset, false, noAssert)
7219}
7220
7221// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
7222Buffer.prototype.copy = function copy (target, targetStart, start, end) {
7223 if (!start) start = 0
7224 if (!end && end !== 0) end = this.length
7225 if (targetStart >= target.length) targetStart = target.length
7226 if (!targetStart) targetStart = 0
7227 if (end > 0 && end < start) end = start
7228
7229 // Copy 0 bytes; we're done
7230 if (end === start) return 0
7231 if (target.length === 0 || this.length === 0) return 0
7232
7233 // Fatal error conditions
7234 if (targetStart < 0) {
7235 throw new RangeError('targetStart out of bounds')
7236 }
7237 if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
7238 if (end < 0) throw new RangeError('sourceEnd out of bounds')
7239
7240 // Are we oob?
7241 if (end > this.length) end = this.length
7242 if (target.length - targetStart < end - start) {
7243 end = target.length - targetStart + start
7244 }
7245
7246 var len = end - start
7247 var i
7248
7249 if (this === target && start < targetStart && targetStart < end) {
7250 // descending copy from end
7251 for (i = len - 1; i >= 0; i--) {
7252 target[i + targetStart] = this[i + start]
7253 }
7254 } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
7255 // ascending copy from start
7256 for (i = 0; i < len; i++) {
7257 target[i + targetStart] = this[i + start]
7258 }
7259 } else {
7260 target._set(this.subarray(start, start + len), targetStart)
7261 }
7262
7263 return len
7264}
7265
7266// fill(value, start=0, end=buffer.length)
7267Buffer.prototype.fill = function fill (value, start, end) {
7268 if (!value) value = 0
7269 if (!start) start = 0
7270 if (!end) end = this.length
7271
7272 if (end < start) throw new RangeError('end < start')
7273
7274 // Fill 0 bytes; we're done
7275 if (end === start) return
7276 if (this.length === 0) return
7277
7278 if (start < 0 || start >= this.length) throw new RangeError('start out of bounds')
7279 if (end < 0 || end > this.length) throw new RangeError('end out of bounds')
7280
7281 var i
7282 if (typeof value === 'number') {
7283 for (i = start; i < end; i++) {
7284 this[i] = value
7285 }
7286 } else {
7287 var bytes = utf8ToBytes(value.toString())
7288 var len = bytes.length
7289 for (i = start; i < end; i++) {
7290 this[i] = bytes[i % len]
7291 }
7292 }
7293
7294 return this
7295}
7296
7297/**
7298 * Creates a new `ArrayBuffer` with the *copied* memory of the buffer instance.
7299 * Added in Node 0.12. Only available in browsers that support ArrayBuffer.
7300 */
7301Buffer.prototype.toArrayBuffer = function toArrayBuffer () {
7302 if (typeof Uint8Array !== 'undefined') {
7303 if (Buffer.TYPED_ARRAY_SUPPORT) {
7304 return (new Buffer(this)).buffer
7305 } else {
7306 var buf = new Uint8Array(this.length)
7307 for (var i = 0, len = buf.length; i < len; i += 1) {
7308 buf[i] = this[i]
7309 }
7310 return buf.buffer
7311 }
7312 } else {
7313 throw new TypeError('Buffer.toArrayBuffer not supported in this browser')
7314 }
7315}
7316
7317// HELPER FUNCTIONS
7318// ================
7319
7320var BP = Buffer.prototype
7321
7322/**
7323 * Augment a Uint8Array *instance* (not the Uint8Array class!) with Buffer methods
7324 */
7325Buffer._augment = function _augment (arr) {
7326 arr.constructor = Buffer
7327 arr._isBuffer = true
7328
7329 // save reference to original Uint8Array set method before overwriting
7330 arr._set = arr.set
7331
7332 // deprecated
7333 arr.get = BP.get
7334 arr.set = BP.set
7335
7336 arr.write = BP.write
7337 arr.toString = BP.toString
7338 arr.toLocaleString = BP.toString
7339 arr.toJSON = BP.toJSON
7340 arr.equals = BP.equals
7341 arr.compare = BP.compare
7342 arr.indexOf = BP.indexOf
7343 arr.copy = BP.copy
7344 arr.slice = BP.slice
7345 arr.readUIntLE = BP.readUIntLE
7346 arr.readUIntBE = BP.readUIntBE
7347 arr.readUInt8 = BP.readUInt8
7348 arr.readUInt16LE = BP.readUInt16LE
7349 arr.readUInt16BE = BP.readUInt16BE
7350 arr.readUInt32LE = BP.readUInt32LE
7351 arr.readUInt32BE = BP.readUInt32BE
7352 arr.readIntLE = BP.readIntLE
7353 arr.readIntBE = BP.readIntBE
7354 arr.readInt8 = BP.readInt8
7355 arr.readInt16LE = BP.readInt16LE
7356 arr.readInt16BE = BP.readInt16BE
7357 arr.readInt32LE = BP.readInt32LE
7358 arr.readInt32BE = BP.readInt32BE
7359 arr.readFloatLE = BP.readFloatLE
7360 arr.readFloatBE = BP.readFloatBE
7361 arr.readDoubleLE = BP.readDoubleLE
7362 arr.readDoubleBE = BP.readDoubleBE
7363 arr.writeUInt8 = BP.writeUInt8
7364 arr.writeUIntLE = BP.writeUIntLE
7365 arr.writeUIntBE = BP.writeUIntBE
7366 arr.writeUInt16LE = BP.writeUInt16LE
7367 arr.writeUInt16BE = BP.writeUInt16BE
7368 arr.writeUInt32LE = BP.writeUInt32LE
7369 arr.writeUInt32BE = BP.writeUInt32BE
7370 arr.writeIntLE = BP.writeIntLE
7371 arr.writeIntBE = BP.writeIntBE
7372 arr.writeInt8 = BP.writeInt8
7373 arr.writeInt16LE = BP.writeInt16LE
7374 arr.writeInt16BE = BP.writeInt16BE
7375 arr.writeInt32LE = BP.writeInt32LE
7376 arr.writeInt32BE = BP.writeInt32BE
7377 arr.writeFloatLE = BP.writeFloatLE
7378 arr.writeFloatBE = BP.writeFloatBE
7379 arr.writeDoubleLE = BP.writeDoubleLE
7380 arr.writeDoubleBE = BP.writeDoubleBE
7381 arr.fill = BP.fill
7382 arr.inspect = BP.inspect
7383 arr.toArrayBuffer = BP.toArrayBuffer
7384
7385 return arr
7386}
7387
7388var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g
7389
7390function base64clean (str) {
7391 // Node strips out invalid characters like \n and \t from the string, base64-js does not
7392 str = stringtrim(str).replace(INVALID_BASE64_RE, '')
7393 // Node converts strings with length < 2 to ''
7394 if (str.length < 2) return ''
7395 // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
7396 while (str.length % 4 !== 0) {
7397 str = str + '='
7398 }
7399 return str
7400}
7401
7402function stringtrim (str) {
7403 if (str.trim) return str.trim()
7404 return str.replace(/^\s+|\s+$/g, '')
7405}
7406
7407function toHex (n) {
7408 if (n < 16) return '0' + n.toString(16)
7409 return n.toString(16)
7410}
7411
7412function utf8ToBytes (string, units) {
7413 units = units || Infinity
7414 var codePoint
7415 var length = string.length
7416 var leadSurrogate = null
7417 var bytes = []
7418
7419 for (var i = 0; i < length; i++) {
7420 codePoint = string.charCodeAt(i)
7421
7422 // is surrogate component
7423 if (codePoint > 0xD7FF && codePoint < 0xE000) {
7424 // last char was a lead
7425 if (!leadSurrogate) {
7426 // no lead yet
7427 if (codePoint > 0xDBFF) {
7428 // unexpected trail
7429 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
7430 continue
7431 } else if (i + 1 === length) {
7432 // unpaired lead
7433 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
7434 continue
7435 }
7436
7437 // valid lead
7438 leadSurrogate = codePoint
7439
7440 continue
7441 }
7442
7443 // 2 leads in a row
7444 if (codePoint < 0xDC00) {
7445 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
7446 leadSurrogate = codePoint
7447 continue
7448 }
7449
7450 // valid surrogate pair
7451 codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
7452 } else if (leadSurrogate) {
7453 // valid bmp char, but last char was a lead
7454 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
7455 }
7456
7457 leadSurrogate = null
7458
7459 // encode utf8
7460 if (codePoint < 0x80) {
7461 if ((units -= 1) < 0) break
7462 bytes.push(codePoint)
7463 } else if (codePoint < 0x800) {
7464 if ((units -= 2) < 0) break
7465 bytes.push(
7466 codePoint >> 0x6 | 0xC0,
7467 codePoint & 0x3F | 0x80
7468 )
7469 } else if (codePoint < 0x10000) {
7470 if ((units -= 3) < 0) break
7471 bytes.push(
7472 codePoint >> 0xC | 0xE0,
7473 codePoint >> 0x6 & 0x3F | 0x80,
7474 codePoint & 0x3F | 0x80
7475 )
7476 } else if (codePoint < 0x110000) {
7477 if ((units -= 4) < 0) break
7478 bytes.push(
7479 codePoint >> 0x12 | 0xF0,
7480 codePoint >> 0xC & 0x3F | 0x80,
7481 codePoint >> 0x6 & 0x3F | 0x80,
7482 codePoint & 0x3F | 0x80
7483 )
7484 } else {
7485 throw new Error('Invalid code point')
7486 }
7487 }
7488
7489 return bytes
7490}
7491
7492function asciiToBytes (str) {
7493 var byteArray = []
7494 for (var i = 0; i < str.length; i++) {
7495 // Node's code seems to be doing this and not & 0x7F..
7496 byteArray.push(str.charCodeAt(i) & 0xFF)
7497 }
7498 return byteArray
7499}
7500
7501function utf16leToBytes (str, units) {
7502 var c, hi, lo
7503 var byteArray = []
7504 for (var i = 0; i < str.length; i++) {
7505 if ((units -= 2) < 0) break
7506
7507 c = str.charCodeAt(i)
7508 hi = c >> 8
7509 lo = c % 256
7510 byteArray.push(lo)
7511 byteArray.push(hi)
7512 }
7513
7514 return byteArray
7515}
7516
7517function base64ToBytes (str) {
7518 return base64.toByteArray(base64clean(str))
7519}
7520
7521function blitBuffer (src, dst, offset, length) {
7522 for (var i = 0; i < length; i++) {
7523 if ((i + offset >= dst.length) || (i >= src.length)) break
7524 dst[i + offset] = src[i]
7525 }
7526 return i
7527}
7528
7529}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
7530},{"base64-js":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/browserify/node_modules/buffer/node_modules/base64-js/lib/b64.js","ieee754":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/browserify/node_modules/buffer/node_modules/ieee754/index.js","isarray":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/browserify/node_modules/buffer/node_modules/isarray/index.js"}],"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/browserify/node_modules/buffer/node_modules/base64-js/lib/b64.js":[function(require,module,exports){
7531var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
7532
7533;(function (exports) {
7534 'use strict';
7535
7536 var Arr = (typeof Uint8Array !== 'undefined')
7537 ? Uint8Array
7538 : Array
7539
7540 var PLUS = '+'.charCodeAt(0)
7541 var SLASH = '/'.charCodeAt(0)
7542 var NUMBER = '0'.charCodeAt(0)
7543 var LOWER = 'a'.charCodeAt(0)
7544 var UPPER = 'A'.charCodeAt(0)
7545 var PLUS_URL_SAFE = '-'.charCodeAt(0)
7546 var SLASH_URL_SAFE = '_'.charCodeAt(0)
7547
7548 function decode (elt) {
7549 var code = elt.charCodeAt(0)
7550 if (code === PLUS ||
7551 code === PLUS_URL_SAFE)
7552 return 62 // '+'
7553 if (code === SLASH ||
7554 code === SLASH_URL_SAFE)
7555 return 63 // '/'
7556 if (code < NUMBER)
7557 return -1 //no match
7558 if (code < NUMBER + 10)
7559 return code - NUMBER + 26 + 26
7560 if (code < UPPER + 26)
7561 return code - UPPER
7562 if (code < LOWER + 26)
7563 return code - LOWER + 26
7564 }
7565
7566 function b64ToByteArray (b64) {
7567 var i, j, l, tmp, placeHolders, arr
7568
7569 if (b64.length % 4 > 0) {
7570 throw new Error('Invalid string. Length must be a multiple of 4')
7571 }
7572
7573 // the number of equal signs (place holders)
7574 // if there are two placeholders, than the two characters before it
7575 // represent one byte
7576 // if there is only one, then the three characters before it represent 2 bytes
7577 // this is just a cheap hack to not do indexOf twice
7578 var len = b64.length
7579 placeHolders = '=' === b64.charAt(len - 2) ? 2 : '=' === b64.charAt(len - 1) ? 1 : 0
7580
7581 // base64 is 4/3 + up to two characters of the original data
7582 arr = new Arr(b64.length * 3 / 4 - placeHolders)
7583
7584 // if there are placeholders, only get up to the last complete 4 chars
7585 l = placeHolders > 0 ? b64.length - 4 : b64.length
7586
7587 var L = 0
7588
7589 function push (v) {
7590 arr[L++] = v
7591 }
7592
7593 for (i = 0, j = 0; i < l; i += 4, j += 3) {
7594 tmp = (decode(b64.charAt(i)) << 18) | (decode(b64.charAt(i + 1)) << 12) | (decode(b64.charAt(i + 2)) << 6) | decode(b64.charAt(i + 3))
7595 push((tmp & 0xFF0000) >> 16)
7596 push((tmp & 0xFF00) >> 8)
7597 push(tmp & 0xFF)
7598 }
7599
7600 if (placeHolders === 2) {
7601 tmp = (decode(b64.charAt(i)) << 2) | (decode(b64.charAt(i + 1)) >> 4)
7602 push(tmp & 0xFF)
7603 } else if (placeHolders === 1) {
7604 tmp = (decode(b64.charAt(i)) << 10) | (decode(b64.charAt(i + 1)) << 4) | (decode(b64.charAt(i + 2)) >> 2)
7605 push((tmp >> 8) & 0xFF)
7606 push(tmp & 0xFF)
7607 }
7608
7609 return arr
7610 }
7611
7612 function uint8ToBase64 (uint8) {
7613 var i,
7614 extraBytes = uint8.length % 3, // if we have 1 byte left, pad 2 bytes
7615 output = "",
7616 temp, length
7617
7618 function encode (num) {
7619 return lookup.charAt(num)
7620 }
7621
7622 function tripletToBase64 (num) {
7623 return encode(num >> 18 & 0x3F) + encode(num >> 12 & 0x3F) + encode(num >> 6 & 0x3F) + encode(num & 0x3F)
7624 }
7625
7626 // go through the array every three bytes, we'll deal with trailing stuff later
7627 for (i = 0, length = uint8.length - extraBytes; i < length; i += 3) {
7628 temp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])
7629 output += tripletToBase64(temp)
7630 }
7631
7632 // pad the end with zeros, but make sure to not forget the extra bytes
7633 switch (extraBytes) {
7634 case 1:
7635 temp = uint8[uint8.length - 1]
7636 output += encode(temp >> 2)
7637 output += encode((temp << 4) & 0x3F)
7638 output += '=='
7639 break
7640 case 2:
7641 temp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1])
7642 output += encode(temp >> 10)
7643 output += encode((temp >> 4) & 0x3F)
7644 output += encode((temp << 2) & 0x3F)
7645 output += '='
7646 break
7647 }
7648
7649 return output
7650 }
7651
7652 exports.toByteArray = b64ToByteArray
7653 exports.fromByteArray = uint8ToBase64
7654}(typeof exports === 'undefined' ? (this.base64js = {}) : exports))
7655
7656},{}],"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/browserify/node_modules/buffer/node_modules/ieee754/index.js":[function(require,module,exports){
7657exports.read = function (buffer, offset, isLE, mLen, nBytes) {
7658 var e, m
7659 var eLen = nBytes * 8 - mLen - 1
7660 var eMax = (1 << eLen) - 1
7661 var eBias = eMax >> 1
7662 var nBits = -7
7663 var i = isLE ? (nBytes - 1) : 0
7664 var d = isLE ? -1 : 1
7665 var s = buffer[offset + i]
7666
7667 i += d
7668
7669 e = s & ((1 << (-nBits)) - 1)
7670 s >>= (-nBits)
7671 nBits += eLen
7672 for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
7673
7674 m = e & ((1 << (-nBits)) - 1)
7675 e >>= (-nBits)
7676 nBits += mLen
7677 for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
7678
7679 if (e === 0) {
7680 e = 1 - eBias
7681 } else if (e === eMax) {
7682 return m ? NaN : ((s ? -1 : 1) * Infinity)
7683 } else {
7684 m = m + Math.pow(2, mLen)
7685 e = e - eBias
7686 }
7687 return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
7688}
7689
7690exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
7691 var e, m, c
7692 var eLen = nBytes * 8 - mLen - 1
7693 var eMax = (1 << eLen) - 1
7694 var eBias = eMax >> 1
7695 var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
7696 var i = isLE ? 0 : (nBytes - 1)
7697 var d = isLE ? 1 : -1
7698 var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
7699
7700 value = Math.abs(value)
7701
7702 if (isNaN(value) || value === Infinity) {
7703 m = isNaN(value) ? 1 : 0
7704 e = eMax
7705 } else {
7706 e = Math.floor(Math.log(value) / Math.LN2)
7707 if (value * (c = Math.pow(2, -e)) < 1) {
7708 e--
7709 c *= 2
7710 }
7711 if (e + eBias >= 1) {
7712 value += rt / c
7713 } else {
7714 value += rt * Math.pow(2, 1 - eBias)
7715 }
7716 if (value * c >= 2) {
7717 e++
7718 c /= 2
7719 }
7720
7721 if (e + eBias >= eMax) {
7722 m = 0
7723 e = eMax
7724 } else if (e + eBias >= 1) {
7725 m = (value * c - 1) * Math.pow(2, mLen)
7726 e = e + eBias
7727 } else {
7728 m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
7729 e = 0
7730 }
7731 }
7732
7733 for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
7734
7735 e = (e << mLen) | m
7736 eLen += mLen
7737 for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
7738
7739 buffer[offset + i - d] |= s * 128
7740}
7741
7742},{}],"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/browserify/node_modules/buffer/node_modules/isarray/index.js":[function(require,module,exports){
7743var toString = {}.toString;
7744
7745module.exports = Array.isArray || function (arr) {
7746 return toString.call(arr) == '[object Array]';
7747};
7748
7749},{}],"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/browserify/node_modules/events/events.js":[function(require,module,exports){
7750// Copyright Joyent, Inc. and other Node contributors.
7751//
7752// Permission is hereby granted, free of charge, to any person obtaining a
7753// copy of this software and associated documentation files (the
7754// "Software"), to deal in the Software without restriction, including
7755// without limitation the rights to use, copy, modify, merge, publish,
7756// distribute, sublicense, and/or sell copies of the Software, and to permit
7757// persons to whom the Software is furnished to do so, subject to the
7758// following conditions:
7759//
7760// The above copyright notice and this permission notice shall be included
7761// in all copies or substantial portions of the Software.
7762//
7763// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
7764// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
7765// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
7766// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
7767// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
7768// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
7769// USE OR OTHER DEALINGS IN THE SOFTWARE.
7770
7771function EventEmitter() {
7772 this._events = this._events || {};
7773 this._maxListeners = this._maxListeners || undefined;
7774}
7775module.exports = EventEmitter;
7776
7777// Backwards-compat with node 0.10.x
7778EventEmitter.EventEmitter = EventEmitter;
7779
7780EventEmitter.prototype._events = undefined;
7781EventEmitter.prototype._maxListeners = undefined;
7782
7783// By default EventEmitters will print a warning if more than 10 listeners are
7784// added to it. This is a useful default which helps finding memory leaks.
7785EventEmitter.defaultMaxListeners = 10;
7786
7787// Obviously not all Emitters should be limited to 10. This function allows
7788// that to be increased. Set to zero for unlimited.
7789EventEmitter.prototype.setMaxListeners = function(n) {
7790 if (!isNumber(n) || n < 0 || isNaN(n))
7791 throw TypeError('n must be a positive number');
7792 this._maxListeners = n;
7793 return this;
7794};
7795
7796EventEmitter.prototype.emit = function(type) {
7797 var er, handler, len, args, i, listeners;
7798
7799 if (!this._events)
7800 this._events = {};
7801
7802 // If there is no 'error' event listener then throw.
7803 if (type === 'error') {
7804 if (!this._events.error ||
7805 (isObject(this._events.error) && !this._events.error.length)) {
7806 er = arguments[1];
7807 if (er instanceof Error) {
7808 throw er; // Unhandled 'error' event
7809 }
7810 throw TypeError('Uncaught, unspecified "error" event.');
7811 }
7812 }
7813
7814 handler = this._events[type];
7815
7816 if (isUndefined(handler))
7817 return false;
7818
7819 if (isFunction(handler)) {
7820 switch (arguments.length) {
7821 // fast cases
7822 case 1:
7823 handler.call(this);
7824 break;
7825 case 2:
7826 handler.call(this, arguments[1]);
7827 break;
7828 case 3:
7829 handler.call(this, arguments[1], arguments[2]);
7830 break;
7831 // slower
7832 default:
7833 len = arguments.length;
7834 args = new Array(len - 1);
7835 for (i = 1; i < len; i++)
7836 args[i - 1] = arguments[i];
7837 handler.apply(this, args);
7838 }
7839 } else if (isObject(handler)) {
7840 len = arguments.length;
7841 args = new Array(len - 1);
7842 for (i = 1; i < len; i++)
7843 args[i - 1] = arguments[i];
7844
7845 listeners = handler.slice();
7846 len = listeners.length;
7847 for (i = 0; i < len; i++)
7848 listeners[i].apply(this, args);
7849 }
7850
7851 return true;
7852};
7853
7854EventEmitter.prototype.addListener = function(type, listener) {
7855 var m;
7856
7857 if (!isFunction(listener))
7858 throw TypeError('listener must be a function');
7859
7860 if (!this._events)
7861 this._events = {};
7862
7863 // To avoid recursion in the case that type === "newListener"! Before
7864 // adding it to the listeners, first emit "newListener".
7865 if (this._events.newListener)
7866 this.emit('newListener', type,
7867 isFunction(listener.listener) ?
7868 listener.listener : listener);
7869
7870 if (!this._events[type])
7871 // Optimize the case of one listener. Don't need the extra array object.
7872 this._events[type] = listener;
7873 else if (isObject(this._events[type]))
7874 // If we've already got an array, just append.
7875 this._events[type].push(listener);
7876 else
7877 // Adding the second element, need to change to array.
7878 this._events[type] = [this._events[type], listener];
7879
7880 // Check for listener leak
7881 if (isObject(this._events[type]) && !this._events[type].warned) {
7882 var m;
7883 if (!isUndefined(this._maxListeners)) {
7884 m = this._maxListeners;
7885 } else {
7886 m = EventEmitter.defaultMaxListeners;
7887 }
7888
7889 if (m && m > 0 && this._events[type].length > m) {
7890 this._events[type].warned = true;
7891 console.error('(node) warning: possible EventEmitter memory ' +
7892 'leak detected. %d listeners added. ' +
7893 'Use emitter.setMaxListeners() to increase limit.',
7894 this._events[type].length);
7895 if (typeof console.trace === 'function') {
7896 // not supported in IE 10
7897 console.trace();
7898 }
7899 }
7900 }
7901
7902 return this;
7903};
7904
7905EventEmitter.prototype.on = EventEmitter.prototype.addListener;
7906
7907EventEmitter.prototype.once = function(type, listener) {
7908 if (!isFunction(listener))
7909 throw TypeError('listener must be a function');
7910
7911 var fired = false;
7912
7913 function g() {
7914 this.removeListener(type, g);
7915
7916 if (!fired) {
7917 fired = true;
7918 listener.apply(this, arguments);
7919 }
7920 }
7921
7922 g.listener = listener;
7923 this.on(type, g);
7924
7925 return this;
7926};
7927
7928// emits a 'removeListener' event iff the listener was removed
7929EventEmitter.prototype.removeListener = function(type, listener) {
7930 var list, position, length, i;
7931
7932 if (!isFunction(listener))
7933 throw TypeError('listener must be a function');
7934
7935 if (!this._events || !this._events[type])
7936 return this;
7937
7938 list = this._events[type];
7939 length = list.length;
7940 position = -1;
7941
7942 if (list === listener ||
7943 (isFunction(list.listener) && list.listener === listener)) {
7944 delete this._events[type];
7945 if (this._events.removeListener)
7946 this.emit('removeListener', type, listener);
7947
7948 } else if (isObject(list)) {
7949 for (i = length; i-- > 0;) {
7950 if (list[i] === listener ||
7951 (list[i].listener && list[i].listener === listener)) {
7952 position = i;
7953 break;
7954 }
7955 }
7956
7957 if (position < 0)
7958 return this;
7959
7960 if (list.length === 1) {
7961 list.length = 0;
7962 delete this._events[type];
7963 } else {
7964 list.splice(position, 1);
7965 }
7966
7967 if (this._events.removeListener)
7968 this.emit('removeListener', type, listener);
7969 }
7970
7971 return this;
7972};
7973
7974EventEmitter.prototype.removeAllListeners = function(type) {
7975 var key, listeners;
7976
7977 if (!this._events)
7978 return this;
7979
7980 // not listening for removeListener, no need to emit
7981 if (!this._events.removeListener) {
7982 if (arguments.length === 0)
7983 this._events = {};
7984 else if (this._events[type])
7985 delete this._events[type];
7986 return this;
7987 }
7988
7989 // emit removeListener for all listeners on all events
7990 if (arguments.length === 0) {
7991 for (key in this._events) {
7992 if (key === 'removeListener') continue;
7993 this.removeAllListeners(key);
7994 }
7995 this.removeAllListeners('removeListener');
7996 this._events = {};
7997 return this;
7998 }
7999
8000 listeners = this._events[type];
8001
8002 if (isFunction(listeners)) {
8003 this.removeListener(type, listeners);
8004 } else {
8005 // LIFO order
8006 while (listeners.length)
8007 this.removeListener(type, listeners[listeners.length - 1]);
8008 }
8009 delete this._events[type];
8010
8011 return this;
8012};
8013
8014EventEmitter.prototype.listeners = function(type) {
8015 var ret;
8016 if (!this._events || !this._events[type])
8017 ret = [];
8018 else if (isFunction(this._events[type]))
8019 ret = [this._events[type]];
8020 else
8021 ret = this._events[type].slice();
8022 return ret;
8023};
8024
8025EventEmitter.listenerCount = function(emitter, type) {
8026 var ret;
8027 if (!emitter._events || !emitter._events[type])
8028 ret = 0;
8029 else if (isFunction(emitter._events[type]))
8030 ret = 1;
8031 else
8032 ret = emitter._events[type].length;
8033 return ret;
8034};
8035
8036function isFunction(arg) {
8037 return typeof arg === 'function';
8038}
8039
8040function isNumber(arg) {
8041 return typeof arg === 'number';
8042}
8043
8044function isObject(arg) {
8045 return typeof arg === 'object' && arg !== null;
8046}
8047
8048function isUndefined(arg) {
8049 return arg === void 0;
8050}
8051
8052},{}],"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/browserify/node_modules/process/browser.js":[function(require,module,exports){
8053// shim for using process in browser
8054var process = module.exports = {};
8055
8056// cached from whatever global is present so that test runners that stub it
8057// don't break things. But we need to wrap it in a try catch in case it is
8058// wrapped in strict mode code which doesn't define any globals. It's inside a
8059// function because try/catches deoptimize in certain engines.
8060
8061var cachedSetTimeout;
8062var cachedClearTimeout;
8063
8064(function () {
8065 try {
8066 cachedSetTimeout = setTimeout;
8067 } catch (e) {
8068 cachedSetTimeout = function () {
8069 throw new Error('setTimeout is not defined');
8070 }
8071 }
8072 try {
8073 cachedClearTimeout = clearTimeout;
8074 } catch (e) {
8075 cachedClearTimeout = function () {
8076 throw new Error('clearTimeout is not defined');
8077 }
8078 }
8079} ())
8080function runTimeout(fun) {
8081 if (cachedSetTimeout === setTimeout) {
8082 //normal enviroments in sane situations
8083 return setTimeout(fun, 0);
8084 }
8085 try {
8086 // when when somebody has screwed with setTimeout but no I.E. maddness
8087 return cachedSetTimeout(fun, 0);
8088 } catch(e){
8089 try {
8090 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
8091 return cachedSetTimeout.call(null, fun, 0);
8092 } catch(e){
8093 // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
8094 return cachedSetTimeout.call(this, fun, 0);
8095 }
8096 }
8097
8098
8099}
8100function runClearTimeout(marker) {
8101 if (cachedClearTimeout === clearTimeout) {
8102 //normal enviroments in sane situations
8103 return clearTimeout(marker);
8104 }
8105 try {
8106 // when when somebody has screwed with setTimeout but no I.E. maddness
8107 return cachedClearTimeout(marker);
8108 } catch (e){
8109 try {
8110 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
8111 return cachedClearTimeout.call(null, marker);
8112 } catch (e){
8113 // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
8114 // Some versions of I.E. have different rules for clearTimeout vs setTimeout
8115 return cachedClearTimeout.call(this, marker);
8116 }
8117 }
8118
8119
8120
8121}
8122var queue = [];
8123var draining = false;
8124var currentQueue;
8125var queueIndex = -1;
8126
8127function cleanUpNextTick() {
8128 if (!draining || !currentQueue) {
8129 return;
8130 }
8131 draining = false;
8132 if (currentQueue.length) {
8133 queue = currentQueue.concat(queue);
8134 } else {
8135 queueIndex = -1;
8136 }
8137 if (queue.length) {
8138 drainQueue();
8139 }
8140}
8141
8142function drainQueue() {
8143 if (draining) {
8144 return;
8145 }
8146 var timeout = runTimeout(cleanUpNextTick);
8147 draining = true;
8148
8149 var len = queue.length;
8150 while(len) {
8151 currentQueue = queue;
8152 queue = [];
8153 while (++queueIndex < len) {
8154 if (currentQueue) {
8155 currentQueue[queueIndex].run();
8156 }
8157 }
8158 queueIndex = -1;
8159 len = queue.length;
8160 }
8161 currentQueue = null;
8162 draining = false;
8163 runClearTimeout(timeout);
8164}
8165
8166process.nextTick = function (fun) {
8167 var args = new Array(arguments.length - 1);
8168 if (arguments.length > 1) {
8169 for (var i = 1; i < arguments.length; i++) {
8170 args[i - 1] = arguments[i];
8171 }
8172 }
8173 queue.push(new Item(fun, args));
8174 if (queue.length === 1 && !draining) {
8175 runTimeout(drainQueue);
8176 }
8177};
8178
8179// v8 likes predictible objects
8180function Item(fun, array) {
8181 this.fun = fun;
8182 this.array = array;
8183}
8184Item.prototype.run = function () {
8185 this.fun.apply(null, this.array);
8186};
8187process.title = 'browser';
8188process.browser = true;
8189process.env = {};
8190process.argv = [];
8191process.version = ''; // empty string to avoid regexp issues
8192process.versions = {};
8193
8194function noop() {}
8195
8196process.on = noop;
8197process.addListener = noop;
8198process.once = noop;
8199process.off = noop;
8200process.removeListener = noop;
8201process.removeAllListeners = noop;
8202process.emit = noop;
8203
8204process.binding = function (name) {
8205 throw new Error('process.binding is not supported');
8206};
8207
8208process.cwd = function () { return '/' };
8209process.chdir = function (dir) {
8210 throw new Error('process.chdir is not supported');
8211};
8212process.umask = function() { return 0; };
8213
8214},{}],"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/inherits/inherits_browser.js":[function(require,module,exports){
8215if (typeof Object.create === 'function') {
8216 // implementation from standard node.js 'util' module
8217 module.exports = function inherits(ctor, superCtor) {
8218 ctor.super_ = superCtor
8219 ctor.prototype = Object.create(superCtor.prototype, {
8220 constructor: {
8221 value: ctor,
8222 enumerable: false,
8223 writable: true,
8224 configurable: true
8225 }
8226 });
8227 };
8228} else {
8229 // old school shim for old browsers
8230 module.exports = function inherits(ctor, superCtor) {
8231 ctor.super_ = superCtor
8232 var TempCtor = function () {}
8233 TempCtor.prototype = superCtor.prototype
8234 ctor.prototype = new TempCtor()
8235 ctor.prototype.constructor = ctor
8236 }
8237}
8238
8239},{}],"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/lodash/index.js":[function(require,module,exports){
8240(function (global){
8241/**
8242 * @license
8243 * lodash 3.10.1 (Custom Build) <https://lodash.com/>
8244 * Build: `lodash modern -d -o ./index.js`
8245 * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
8246 * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
8247 * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
8248 * Available under MIT license <https://lodash.com/license>
8249 */
8250;(function() {
8251
8252 /** Used as a safe reference for `undefined` in pre-ES5 environments. */
8253 var undefined;
8254
8255 /** Used as the semantic version number. */
8256 var VERSION = '3.10.1';
8257
8258 /** Used to compose bitmasks for wrapper metadata. */
8259 var BIND_FLAG = 1,
8260 BIND_KEY_FLAG = 2,
8261 CURRY_BOUND_FLAG = 4,
8262 CURRY_FLAG = 8,
8263 CURRY_RIGHT_FLAG = 16,
8264 PARTIAL_FLAG = 32,
8265 PARTIAL_RIGHT_FLAG = 64,
8266 ARY_FLAG = 128,
8267 REARG_FLAG = 256;
8268
8269 /** Used as default options for `_.trunc`. */
8270 var DEFAULT_TRUNC_LENGTH = 30,
8271 DEFAULT_TRUNC_OMISSION = '...';
8272
8273 /** Used to detect when a function becomes hot. */
8274 var HOT_COUNT = 150,
8275 HOT_SPAN = 16;
8276
8277 /** Used as the size to enable large array optimizations. */
8278 var LARGE_ARRAY_SIZE = 200;
8279
8280 /** Used to indicate the type of lazy iteratees. */
8281 var LAZY_FILTER_FLAG = 1,
8282 LAZY_MAP_FLAG = 2;
8283
8284 /** Used as the `TypeError` message for "Functions" methods. */
8285 var FUNC_ERROR_TEXT = 'Expected a function';
8286
8287 /** Used as the internal argument placeholder. */
8288 var PLACEHOLDER = '__lodash_placeholder__';
8289
8290 /** `Object#toString` result references. */
8291 var argsTag = '[object Arguments]',
8292 arrayTag = '[object Array]',
8293 boolTag = '[object Boolean]',
8294 dateTag = '[object Date]',
8295 errorTag = '[object Error]',
8296 funcTag = '[object Function]',
8297 mapTag = '[object Map]',
8298 numberTag = '[object Number]',
8299 objectTag = '[object Object]',
8300 regexpTag = '[object RegExp]',
8301 setTag = '[object Set]',
8302 stringTag = '[object String]',
8303 weakMapTag = '[object WeakMap]';
8304
8305 var arrayBufferTag = '[object ArrayBuffer]',
8306 float32Tag = '[object Float32Array]',
8307 float64Tag = '[object Float64Array]',
8308 int8Tag = '[object Int8Array]',
8309 int16Tag = '[object Int16Array]',
8310 int32Tag = '[object Int32Array]',
8311 uint8Tag = '[object Uint8Array]',
8312 uint8ClampedTag = '[object Uint8ClampedArray]',
8313 uint16Tag = '[object Uint16Array]',
8314 uint32Tag = '[object Uint32Array]';
8315
8316 /** Used to match empty string literals in compiled template source. */
8317 var reEmptyStringLeading = /\b__p \+= '';/g,
8318 reEmptyStringMiddle = /\b(__p \+=) '' \+/g,
8319 reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g;
8320
8321 /** Used to match HTML entities and HTML characters. */
8322 var reEscapedHtml = /&(?:amp|lt|gt|quot|#39|#96);/g,
8323 reUnescapedHtml = /[&<>"'`]/g,
8324 reHasEscapedHtml = RegExp(reEscapedHtml.source),
8325 reHasUnescapedHtml = RegExp(reUnescapedHtml.source);
8326
8327 /** Used to match template delimiters. */
8328 var reEscape = /<%-([\s\S]+?)%>/g,
8329 reEvaluate = /<%([\s\S]+?)%>/g,
8330 reInterpolate = /<%=([\s\S]+?)%>/g;
8331
8332 /** Used to match property names within property paths. */
8333 var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\n\\]|\\.)*?\1)\]/,
8334 reIsPlainProp = /^\w*$/,
8335 rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\n\\]|\\.)*?)\2)\]/g;
8336
8337 /**
8338 * Used to match `RegExp` [syntax characters](http://ecma-international.org/ecma-262/6.0/#sec-patterns)
8339 * and those outlined by [`EscapeRegExpPattern`](http://ecma-international.org/ecma-262/6.0/#sec-escaperegexppattern).
8340 */
8341 var reRegExpChars = /^[:!,]|[\\^$.*+?()[\]{}|\/]|(^[0-9a-fA-Fnrtuvx])|([\n\r\u2028\u2029])/g,
8342 reHasRegExpChars = RegExp(reRegExpChars.source);
8343
8344 /** Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks). */
8345 var reComboMark = /[\u0300-\u036f\ufe20-\ufe23]/g;
8346
8347 /** Used to match backslashes in property paths. */
8348 var reEscapeChar = /\\(\\)?/g;
8349
8350 /** Used to match [ES template delimiters](http://ecma-international.org/ecma-262/6.0/#sec-template-literal-lexical-components). */
8351 var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g;
8352
8353 /** Used to match `RegExp` flags from their coerced string values. */
8354 var reFlags = /\w*$/;
8355
8356 /** Used to detect hexadecimal string values. */
8357 var reHasHexPrefix = /^0[xX]/;
8358
8359 /** Used to detect host constructors (Safari > 5). */
8360 var reIsHostCtor = /^\[object .+?Constructor\]$/;
8361
8362 /** Used to detect unsigned integer values. */
8363 var reIsUint = /^\d+$/;
8364
8365 /** Used to match latin-1 supplementary letters (excluding mathematical operators). */
8366 var reLatin1 = /[\xc0-\xd6\xd8-\xde\xdf-\xf6\xf8-\xff]/g;
8367
8368 /** Used to ensure capturing order of template delimiters. */
8369 var reNoMatch = /($^)/;
8370
8371 /** Used to match unescaped characters in compiled string literals. */
8372 var reUnescapedString = /['\n\r\u2028\u2029\\]/g;
8373
8374 /** Used to match words to create compound words. */
8375 var reWords = (function() {
8376 var upper = '[A-Z\\xc0-\\xd6\\xd8-\\xde]',
8377 lower = '[a-z\\xdf-\\xf6\\xf8-\\xff]+';
8378
8379 return RegExp(upper + '+(?=' + upper + lower + ')|' + upper + '?' + lower + '|' + upper + '+|[0-9]+', 'g');
8380 }());
8381
8382 /** Used to assign default `context` object properties. */
8383 var contextProps = [
8384 'Array', 'ArrayBuffer', 'Date', 'Error', 'Float32Array', 'Float64Array',
8385 'Function', 'Int8Array', 'Int16Array', 'Int32Array', 'Math', 'Number',
8386 'Object', 'RegExp', 'Set', 'String', '_', 'clearTimeout', 'isFinite',
8387 'parseFloat', 'parseInt', 'setTimeout', 'TypeError', 'Uint8Array',
8388 'Uint8ClampedArray', 'Uint16Array', 'Uint32Array', 'WeakMap'
8389 ];
8390
8391 /** Used to make template sourceURLs easier to identify. */
8392 var templateCounter = -1;
8393
8394 /** Used to identify `toStringTag` values of typed arrays. */
8395 var typedArrayTags = {};
8396 typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =
8397 typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =
8398 typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =
8399 typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =
8400 typedArrayTags[uint32Tag] = true;
8401 typedArrayTags[argsTag] = typedArrayTags[arrayTag] =
8402 typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =
8403 typedArrayTags[dateTag] = typedArrayTags[errorTag] =
8404 typedArrayTags[funcTag] = typedArrayTags[mapTag] =
8405 typedArrayTags[numberTag] = typedArrayTags[objectTag] =
8406 typedArrayTags[regexpTag] = typedArrayTags[setTag] =
8407 typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false;
8408
8409 /** Used to identify `toStringTag` values supported by `_.clone`. */
8410 var cloneableTags = {};
8411 cloneableTags[argsTag] = cloneableTags[arrayTag] =
8412 cloneableTags[arrayBufferTag] = cloneableTags[boolTag] =
8413 cloneableTags[dateTag] = cloneableTags[float32Tag] =
8414 cloneableTags[float64Tag] = cloneableTags[int8Tag] =
8415 cloneableTags[int16Tag] = cloneableTags[int32Tag] =
8416 cloneableTags[numberTag] = cloneableTags[objectTag] =
8417 cloneableTags[regexpTag] = cloneableTags[stringTag] =
8418 cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] =
8419 cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true;
8420 cloneableTags[errorTag] = cloneableTags[funcTag] =
8421 cloneableTags[mapTag] = cloneableTags[setTag] =
8422 cloneableTags[weakMapTag] = false;
8423
8424 /** Used to map latin-1 supplementary letters to basic latin letters. */
8425 var deburredLetters = {
8426 '\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A',
8427 '\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a',
8428 '\xc7': 'C', '\xe7': 'c',
8429 '\xd0': 'D', '\xf0': 'd',
8430 '\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E',
8431 '\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e',
8432 '\xcC': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I',
8433 '\xeC': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i',
8434 '\xd1': 'N', '\xf1': 'n',
8435 '\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O',
8436 '\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o',
8437 '\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U',
8438 '\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u',
8439 '\xdd': 'Y', '\xfd': 'y', '\xff': 'y',
8440 '\xc6': 'Ae', '\xe6': 'ae',
8441 '\xde': 'Th', '\xfe': 'th',
8442 '\xdf': 'ss'
8443 };
8444
8445 /** Used to map characters to HTML entities. */
8446 var htmlEscapes = {
8447 '&': '&amp;',
8448 '<': '&lt;',
8449 '>': '&gt;',
8450 '"': '&quot;',
8451 "'": '&#39;',
8452 '`': '&#96;'
8453 };
8454
8455 /** Used to map HTML entities to characters. */
8456 var htmlUnescapes = {
8457 '&amp;': '&',
8458 '&lt;': '<',
8459 '&gt;': '>',
8460 '&quot;': '"',
8461 '&#39;': "'",
8462 '&#96;': '`'
8463 };
8464
8465 /** Used to determine if values are of the language type `Object`. */
8466 var objectTypes = {
8467 'function': true,
8468 'object': true
8469 };
8470
8471 /** Used to escape characters for inclusion in compiled regexes. */
8472 var regexpEscapes = {
8473 '0': 'x30', '1': 'x31', '2': 'x32', '3': 'x33', '4': 'x34',
8474 '5': 'x35', '6': 'x36', '7': 'x37', '8': 'x38', '9': 'x39',
8475 'A': 'x41', 'B': 'x42', 'C': 'x43', 'D': 'x44', 'E': 'x45', 'F': 'x46',
8476 'a': 'x61', 'b': 'x62', 'c': 'x63', 'd': 'x64', 'e': 'x65', 'f': 'x66',
8477 'n': 'x6e', 'r': 'x72', 't': 'x74', 'u': 'x75', 'v': 'x76', 'x': 'x78'
8478 };
8479
8480 /** Used to escape characters for inclusion in compiled string literals. */
8481 var stringEscapes = {
8482 '\\': '\\',
8483 "'": "'",
8484 '\n': 'n',
8485 '\r': 'r',
8486 '\u2028': 'u2028',
8487 '\u2029': 'u2029'
8488 };
8489
8490 /** Detect free variable `exports`. */
8491 var freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports;
8492
8493 /** Detect free variable `module`. */
8494 var freeModule = objectTypes[typeof module] && module && !module.nodeType && module;
8495
8496 /** Detect free variable `global` from Node.js. */
8497 var freeGlobal = freeExports && freeModule && typeof global == 'object' && global && global.Object && global;
8498
8499 /** Detect free variable `self`. */
8500 var freeSelf = objectTypes[typeof self] && self && self.Object && self;
8501
8502 /** Detect free variable `window`. */
8503 var freeWindow = objectTypes[typeof window] && window && window.Object && window;
8504
8505 /** Detect the popular CommonJS extension `module.exports`. */
8506 var moduleExports = freeModule && freeModule.exports === freeExports && freeExports;
8507
8508 /**
8509 * Used as a reference to the global object.
8510 *
8511 * The `this` value is used if it's the global object to avoid Greasemonkey's
8512 * restricted `window` object, otherwise the `window` object is used.
8513 */
8514 var root = freeGlobal || ((freeWindow !== (this && this.window)) && freeWindow) || freeSelf || this;
8515
8516 /*--------------------------------------------------------------------------*/
8517
8518 /**
8519 * The base implementation of `compareAscending` which compares values and
8520 * sorts them in ascending order without guaranteeing a stable sort.
8521 *
8522 * @private
8523 * @param {*} value The value to compare.
8524 * @param {*} other The other value to compare.
8525 * @returns {number} Returns the sort order indicator for `value`.
8526 */
8527 function baseCompareAscending(value, other) {
8528 if (value !== other) {
8529 var valIsNull = value === null,
8530 valIsUndef = value === undefined,
8531 valIsReflexive = value === value;
8532
8533 var othIsNull = other === null,
8534 othIsUndef = other === undefined,
8535 othIsReflexive = other === other;
8536
8537 if ((value > other && !othIsNull) || !valIsReflexive ||
8538 (valIsNull && !othIsUndef && othIsReflexive) ||
8539 (valIsUndef && othIsReflexive)) {
8540 return 1;
8541 }
8542 if ((value < other && !valIsNull) || !othIsReflexive ||
8543 (othIsNull && !valIsUndef && valIsReflexive) ||
8544 (othIsUndef && valIsReflexive)) {
8545 return -1;
8546 }
8547 }
8548 return 0;
8549 }
8550
8551 /**
8552 * The base implementation of `_.findIndex` and `_.findLastIndex` without
8553 * support for callback shorthands and `this` binding.
8554 *
8555 * @private
8556 * @param {Array} array The array to search.
8557 * @param {Function} predicate The function invoked per iteration.
8558 * @param {boolean} [fromRight] Specify iterating from right to left.
8559 * @returns {number} Returns the index of the matched value, else `-1`.
8560 */
8561 function baseFindIndex(array, predicate, fromRight) {
8562 var length = array.length,
8563 index = fromRight ? length : -1;
8564
8565 while ((fromRight ? index-- : ++index < length)) {
8566 if (predicate(array[index], index, array)) {
8567 return index;
8568 }
8569 }
8570 return -1;
8571 }
8572
8573 /**
8574 * The base implementation of `_.indexOf` without support for binary searches.
8575 *
8576 * @private
8577 * @param {Array} array The array to search.
8578 * @param {*} value The value to search for.
8579 * @param {number} fromIndex The index to search from.
8580 * @returns {number} Returns the index of the matched value, else `-1`.
8581 */
8582 function baseIndexOf(array, value, fromIndex) {
8583 if (value !== value) {
8584 return indexOfNaN(array, fromIndex);
8585 }
8586 var index = fromIndex - 1,
8587 length = array.length;
8588
8589 while (++index < length) {
8590 if (array[index] === value) {
8591 return index;
8592 }
8593 }
8594 return -1;
8595 }
8596
8597 /**
8598 * The base implementation of `_.isFunction` without support for environments
8599 * with incorrect `typeof` results.
8600 *
8601 * @private
8602 * @param {*} value The value to check.
8603 * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
8604 */
8605 function baseIsFunction(value) {
8606 // Avoid a Chakra JIT bug in compatibility modes of IE 11.
8607 // See https://github.com/jashkenas/underscore/issues/1621 for more details.
8608 return typeof value == 'function' || false;
8609 }
8610
8611 /**
8612 * Converts `value` to a string if it's not one. An empty string is returned
8613 * for `null` or `undefined` values.
8614 *
8615 * @private
8616 * @param {*} value The value to process.
8617 * @returns {string} Returns the string.
8618 */
8619 function baseToString(value) {
8620 return value == null ? '' : (value + '');
8621 }
8622
8623 /**
8624 * Used by `_.trim` and `_.trimLeft` to get the index of the first character
8625 * of `string` that is not found in `chars`.
8626 *
8627 * @private
8628 * @param {string} string The string to inspect.
8629 * @param {string} chars The characters to find.
8630 * @returns {number} Returns the index of the first character not found in `chars`.
8631 */
8632 function charsLeftIndex(string, chars) {
8633 var index = -1,
8634 length = string.length;
8635
8636 while (++index < length && chars.indexOf(string.charAt(index)) > -1) {}
8637 return index;
8638 }
8639
8640 /**
8641 * Used by `_.trim` and `_.trimRight` to get the index of the last character
8642 * of `string` that is not found in `chars`.
8643 *
8644 * @private
8645 * @param {string} string The string to inspect.
8646 * @param {string} chars The characters to find.
8647 * @returns {number} Returns the index of the last character not found in `chars`.
8648 */
8649 function charsRightIndex(string, chars) {
8650 var index = string.length;
8651
8652 while (index-- && chars.indexOf(string.charAt(index)) > -1) {}
8653 return index;
8654 }
8655
8656 /**
8657 * Used by `_.sortBy` to compare transformed elements of a collection and stable
8658 * sort them in ascending order.
8659 *
8660 * @private
8661 * @param {Object} object The object to compare.
8662 * @param {Object} other The other object to compare.
8663 * @returns {number} Returns the sort order indicator for `object`.
8664 */
8665 function compareAscending(object, other) {
8666 return baseCompareAscending(object.criteria, other.criteria) || (object.index - other.index);
8667 }
8668
8669 /**
8670 * Used by `_.sortByOrder` to compare multiple properties of a value to another
8671 * and stable sort them.
8672 *
8673 * If `orders` is unspecified, all valuess are sorted in ascending order. Otherwise,
8674 * a value is sorted in ascending order if its corresponding order is "asc", and
8675 * descending if "desc".
8676 *
8677 * @private
8678 * @param {Object} object The object to compare.
8679 * @param {Object} other The other object to compare.
8680 * @param {boolean[]} orders The order to sort by for each property.
8681 * @returns {number} Returns the sort order indicator for `object`.
8682 */
8683 function compareMultiple(object, other, orders) {
8684 var index = -1,
8685 objCriteria = object.criteria,
8686 othCriteria = other.criteria,
8687 length = objCriteria.length,
8688 ordersLength = orders.length;
8689
8690 while (++index < length) {
8691 var result = baseCompareAscending(objCriteria[index], othCriteria[index]);
8692 if (result) {
8693 if (index >= ordersLength) {
8694 return result;
8695 }
8696 var order = orders[index];
8697 return result * ((order === 'asc' || order === true) ? 1 : -1);
8698 }
8699 }
8700 // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications
8701 // that causes it, under certain circumstances, to provide the same value for
8702 // `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247
8703 // for more details.
8704 //
8705 // This also ensures a stable sort in V8 and other engines.
8706 // See https://code.google.com/p/v8/issues/detail?id=90 for more details.
8707 return object.index - other.index;
8708 }
8709
8710 /**
8711 * Used by `_.deburr` to convert latin-1 supplementary letters to basic latin letters.
8712 *
8713 * @private
8714 * @param {string} letter The matched letter to deburr.
8715 * @returns {string} Returns the deburred letter.
8716 */
8717 function deburrLetter(letter) {
8718 return deburredLetters[letter];
8719 }
8720
8721 /**
8722 * Used by `_.escape` to convert characters to HTML entities.
8723 *
8724 * @private
8725 * @param {string} chr The matched character to escape.
8726 * @returns {string} Returns the escaped character.
8727 */
8728 function escapeHtmlChar(chr) {
8729 return htmlEscapes[chr];
8730 }
8731
8732 /**
8733 * Used by `_.escapeRegExp` to escape characters for inclusion in compiled regexes.
8734 *
8735 * @private
8736 * @param {string} chr The matched character to escape.
8737 * @param {string} leadingChar The capture group for a leading character.
8738 * @param {string} whitespaceChar The capture group for a whitespace character.
8739 * @returns {string} Returns the escaped character.
8740 */
8741 function escapeRegExpChar(chr, leadingChar, whitespaceChar) {
8742 if (leadingChar) {
8743 chr = regexpEscapes[chr];
8744 } else if (whitespaceChar) {
8745 chr = stringEscapes[chr];
8746 }
8747 return '\\' + chr;
8748 }
8749
8750 /**
8751 * Used by `_.template` to escape characters for inclusion in compiled string literals.
8752 *
8753 * @private
8754 * @param {string} chr The matched character to escape.
8755 * @returns {string} Returns the escaped character.
8756 */
8757 function escapeStringChar(chr) {
8758 return '\\' + stringEscapes[chr];
8759 }
8760
8761 /**
8762 * Gets the index at which the first occurrence of `NaN` is found in `array`.
8763 *
8764 * @private
8765 * @param {Array} array The array to search.
8766 * @param {number} fromIndex The index to search from.
8767 * @param {boolean} [fromRight] Specify iterating from right to left.
8768 * @returns {number} Returns the index of the matched `NaN`, else `-1`.
8769 */
8770 function indexOfNaN(array, fromIndex, fromRight) {
8771 var length = array.length,
8772 index = fromIndex + (fromRight ? 0 : -1);
8773
8774 while ((fromRight ? index-- : ++index < length)) {
8775 var other = array[index];
8776 if (other !== other) {
8777 return index;
8778 }
8779 }
8780 return -1;
8781 }
8782
8783 /**
8784 * Checks if `value` is object-like.
8785 *
8786 * @private
8787 * @param {*} value The value to check.
8788 * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
8789 */
8790 function isObjectLike(value) {
8791 return !!value && typeof value == 'object';
8792 }
8793
8794 /**
8795 * Used by `trimmedLeftIndex` and `trimmedRightIndex` to determine if a
8796 * character code is whitespace.
8797 *
8798 * @private
8799 * @param {number} charCode The character code to inspect.
8800 * @returns {boolean} Returns `true` if `charCode` is whitespace, else `false`.
8801 */
8802 function isSpace(charCode) {
8803 return ((charCode <= 160 && (charCode >= 9 && charCode <= 13) || charCode == 32 || charCode == 160) || charCode == 5760 || charCode == 6158 ||
8804 (charCode >= 8192 && (charCode <= 8202 || charCode == 8232 || charCode == 8233 || charCode == 8239 || charCode == 8287 || charCode == 12288 || charCode == 65279)));
8805 }
8806
8807 /**
8808 * Replaces all `placeholder` elements in `array` with an internal placeholder
8809 * and returns an array of their indexes.
8810 *
8811 * @private
8812 * @param {Array} array The array to modify.
8813 * @param {*} placeholder The placeholder to replace.
8814 * @returns {Array} Returns the new array of placeholder indexes.
8815 */
8816 function replaceHolders(array, placeholder) {
8817 var index = -1,
8818 length = array.length,
8819 resIndex = -1,
8820 result = [];
8821
8822 while (++index < length) {
8823 if (array[index] === placeholder) {
8824 array[index] = PLACEHOLDER;
8825 result[++resIndex] = index;
8826 }
8827 }
8828 return result;
8829 }
8830
8831 /**
8832 * An implementation of `_.uniq` optimized for sorted arrays without support
8833 * for callback shorthands and `this` binding.
8834 *
8835 * @private
8836 * @param {Array} array The array to inspect.
8837 * @param {Function} [iteratee] The function invoked per iteration.
8838 * @returns {Array} Returns the new duplicate-value-free array.
8839 */
8840 function sortedUniq(array, iteratee) {
8841 var seen,
8842 index = -1,
8843 length = array.length,
8844 resIndex = -1,
8845 result = [];
8846
8847 while (++index < length) {
8848 var value = array[index],
8849 computed = iteratee ? iteratee(value, index, array) : value;
8850
8851 if (!index || seen !== computed) {
8852 seen = computed;
8853 result[++resIndex] = value;
8854 }
8855 }
8856 return result;
8857 }
8858
8859 /**
8860 * Used by `_.trim` and `_.trimLeft` to get the index of the first non-whitespace
8861 * character of `string`.
8862 *
8863 * @private
8864 * @param {string} string The string to inspect.
8865 * @returns {number} Returns the index of the first non-whitespace character.
8866 */
8867 function trimmedLeftIndex(string) {
8868 var index = -1,
8869 length = string.length;
8870
8871 while (++index < length && isSpace(string.charCodeAt(index))) {}
8872 return index;
8873 }
8874
8875 /**
8876 * Used by `_.trim` and `_.trimRight` to get the index of the last non-whitespace
8877 * character of `string`.
8878 *
8879 * @private
8880 * @param {string} string The string to inspect.
8881 * @returns {number} Returns the index of the last non-whitespace character.
8882 */
8883 function trimmedRightIndex(string) {
8884 var index = string.length;
8885
8886 while (index-- && isSpace(string.charCodeAt(index))) {}
8887 return index;
8888 }
8889
8890 /**
8891 * Used by `_.unescape` to convert HTML entities to characters.
8892 *
8893 * @private
8894 * @param {string} chr The matched character to unescape.
8895 * @returns {string} Returns the unescaped character.
8896 */
8897 function unescapeHtmlChar(chr) {
8898 return htmlUnescapes[chr];
8899 }
8900
8901 /*--------------------------------------------------------------------------*/
8902
8903 /**
8904 * Create a new pristine `lodash` function using the given `context` object.
8905 *
8906 * @static
8907 * @memberOf _
8908 * @category Utility
8909 * @param {Object} [context=root] The context object.
8910 * @returns {Function} Returns a new `lodash` function.
8911 * @example
8912 *
8913 * _.mixin({ 'foo': _.constant('foo') });
8914 *
8915 * var lodash = _.runInContext();
8916 * lodash.mixin({ 'bar': lodash.constant('bar') });
8917 *
8918 * _.isFunction(_.foo);
8919 * // => true
8920 * _.isFunction(_.bar);
8921 * // => false
8922 *
8923 * lodash.isFunction(lodash.foo);
8924 * // => false
8925 * lodash.isFunction(lodash.bar);
8926 * // => true
8927 *
8928 * // using `context` to mock `Date#getTime` use in `_.now`
8929 * var mock = _.runInContext({
8930 * 'Date': function() {
8931 * return { 'getTime': getTimeMock };
8932 * }
8933 * });
8934 *
8935 * // or creating a suped-up `defer` in Node.js
8936 * var defer = _.runInContext({ 'setTimeout': setImmediate }).defer;
8937 */
8938 function runInContext(context) {
8939 // Avoid issues with some ES3 environments that attempt to use values, named
8940 // after built-in constructors like `Object`, for the creation of literals.
8941 // ES5 clears this up by stating that literals must use built-in constructors.
8942 // See https://es5.github.io/#x11.1.5 for more details.
8943 context = context ? _.defaults(root.Object(), context, _.pick(root, contextProps)) : root;
8944
8945 /** Native constructor references. */
8946 var Array = context.Array,
8947 Date = context.Date,
8948 Error = context.Error,
8949 Function = context.Function,
8950 Math = context.Math,
8951 Number = context.Number,
8952 Object = context.Object,
8953 RegExp = context.RegExp,
8954 String = context.String,
8955 TypeError = context.TypeError;
8956
8957 /** Used for native method references. */
8958 var arrayProto = Array.prototype,
8959 objectProto = Object.prototype,
8960 stringProto = String.prototype;
8961
8962 /** Used to resolve the decompiled source of functions. */
8963 var fnToString = Function.prototype.toString;
8964
8965 /** Used to check objects for own properties. */
8966 var hasOwnProperty = objectProto.hasOwnProperty;
8967
8968 /** Used to generate unique IDs. */
8969 var idCounter = 0;
8970
8971 /**
8972 * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
8973 * of values.
8974 */
8975 var objToString = objectProto.toString;
8976
8977 /** Used to restore the original `_` reference in `_.noConflict`. */
8978 var oldDash = root._;
8979
8980 /** Used to detect if a method is native. */
8981 var reIsNative = RegExp('^' +
8982 fnToString.call(hasOwnProperty).replace(/[\\^$.*+?()[\]{}|]/g, '\\$&')
8983 .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
8984 );
8985
8986 /** Native method references. */
8987 var ArrayBuffer = context.ArrayBuffer,
8988 clearTimeout = context.clearTimeout,
8989 parseFloat = context.parseFloat,
8990 pow = Math.pow,
8991 propertyIsEnumerable = objectProto.propertyIsEnumerable,
8992 Set = getNative(context, 'Set'),
8993 setTimeout = context.setTimeout,
8994 splice = arrayProto.splice,
8995 Uint8Array = context.Uint8Array,
8996 WeakMap = getNative(context, 'WeakMap');
8997
8998 /* Native method references for those with the same name as other `lodash` methods. */
8999 var nativeCeil = Math.ceil,
9000 nativeCreate = getNative(Object, 'create'),
9001 nativeFloor = Math.floor,
9002 nativeIsArray = getNative(Array, 'isArray'),
9003 nativeIsFinite = context.isFinite,
9004 nativeKeys = getNative(Object, 'keys'),
9005 nativeMax = Math.max,
9006 nativeMin = Math.min,
9007 nativeNow = getNative(Date, 'now'),
9008 nativeParseInt = context.parseInt,
9009 nativeRandom = Math.random;
9010
9011 /** Used as references for `-Infinity` and `Infinity`. */
9012 var NEGATIVE_INFINITY = Number.NEGATIVE_INFINITY,
9013 POSITIVE_INFINITY = Number.POSITIVE_INFINITY;
9014
9015 /** Used as references for the maximum length and index of an array. */
9016 var MAX_ARRAY_LENGTH = 4294967295,
9017 MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1,
9018 HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1;
9019
9020 /**
9021 * Used as the [maximum length](http://ecma-international.org/ecma-262/6.0/#sec-number.max_safe_integer)
9022 * of an array-like value.
9023 */
9024 var MAX_SAFE_INTEGER = 9007199254740991;
9025
9026 /** Used to store function metadata. */
9027 var metaMap = WeakMap && new WeakMap;
9028
9029 /** Used to lookup unminified function names. */
9030 var realNames = {};
9031
9032 /*------------------------------------------------------------------------*/
9033
9034 /**
9035 * Creates a `lodash` object which wraps `value` to enable implicit chaining.
9036 * Methods that operate on and return arrays, collections, and functions can
9037 * be chained together. Methods that retrieve a single value or may return a
9038 * primitive value will automatically end the chain returning the unwrapped
9039 * value. Explicit chaining may be enabled using `_.chain`. The execution of
9040 * chained methods is lazy, that is, execution is deferred until `_#value`
9041 * is implicitly or explicitly called.
9042 *
9043 * Lazy evaluation allows several methods to support shortcut fusion. Shortcut
9044 * fusion is an optimization strategy which merge iteratee calls; this can help
9045 * to avoid the creation of intermediate data structures and greatly reduce the
9046 * number of iteratee executions.
9047 *
9048 * Chaining is supported in custom builds as long as the `_#value` method is
9049 * directly or indirectly included in the build.
9050 *
9051 * In addition to lodash methods, wrappers have `Array` and `String` methods.
9052 *
9053 * The wrapper `Array` methods are:
9054 * `concat`, `join`, `pop`, `push`, `reverse`, `shift`, `slice`, `sort`,
9055 * `splice`, and `unshift`
9056 *
9057 * The wrapper `String` methods are:
9058 * `replace` and `split`
9059 *
9060 * The wrapper methods that support shortcut fusion are:
9061 * `compact`, `drop`, `dropRight`, `dropRightWhile`, `dropWhile`, `filter`,
9062 * `first`, `initial`, `last`, `map`, `pluck`, `reject`, `rest`, `reverse`,
9063 * `slice`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, `toArray`,
9064 * and `where`
9065 *
9066 * The chainable wrapper methods are:
9067 * `after`, `ary`, `assign`, `at`, `before`, `bind`, `bindAll`, `bindKey`,
9068 * `callback`, `chain`, `chunk`, `commit`, `compact`, `concat`, `constant`,
9069 * `countBy`, `create`, `curry`, `debounce`, `defaults`, `defaultsDeep`,
9070 * `defer`, `delay`, `difference`, `drop`, `dropRight`, `dropRightWhile`,
9071 * `dropWhile`, `fill`, `filter`, `flatten`, `flattenDeep`, `flow`, `flowRight`,
9072 * `forEach`, `forEachRight`, `forIn`, `forInRight`, `forOwn`, `forOwnRight`,
9073 * `functions`, `groupBy`, `indexBy`, `initial`, `intersection`, `invert`,
9074 * `invoke`, `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`,
9075 * `matchesProperty`, `memoize`, `merge`, `method`, `methodOf`, `mixin`,
9076 * `modArgs`, `negate`, `omit`, `once`, `pairs`, `partial`, `partialRight`,
9077 * `partition`, `pick`, `plant`, `pluck`, `property`, `propertyOf`, `pull`,
9078 * `pullAt`, `push`, `range`, `rearg`, `reject`, `remove`, `rest`, `restParam`,
9079 * `reverse`, `set`, `shuffle`, `slice`, `sort`, `sortBy`, `sortByAll`,
9080 * `sortByOrder`, `splice`, `spread`, `take`, `takeRight`, `takeRightWhile`,
9081 * `takeWhile`, `tap`, `throttle`, `thru`, `times`, `toArray`, `toPlainObject`,
9082 * `transform`, `union`, `uniq`, `unshift`, `unzip`, `unzipWith`, `values`,
9083 * `valuesIn`, `where`, `without`, `wrap`, `xor`, `zip`, `zipObject`, `zipWith`
9084 *
9085 * The wrapper methods that are **not** chainable by default are:
9086 * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clone`, `cloneDeep`,
9087 * `deburr`, `endsWith`, `escape`, `escapeRegExp`, `every`, `find`, `findIndex`,
9088 * `findKey`, `findLast`, `findLastIndex`, `findLastKey`, `findWhere`, `first`,
9089 * `floor`, `get`, `gt`, `gte`, `has`, `identity`, `includes`, `indexOf`,
9090 * `inRange`, `isArguments`, `isArray`, `isBoolean`, `isDate`, `isElement`,
9091 * `isEmpty`, `isEqual`, `isError`, `isFinite` `isFunction`, `isMatch`,
9092 * `isNative`, `isNaN`, `isNull`, `isNumber`, `isObject`, `isPlainObject`,
9093 * `isRegExp`, `isString`, `isUndefined`, `isTypedArray`, `join`, `kebabCase`,
9094 * `last`, `lastIndexOf`, `lt`, `lte`, `max`, `min`, `noConflict`, `noop`,
9095 * `now`, `pad`, `padLeft`, `padRight`, `parseInt`, `pop`, `random`, `reduce`,
9096 * `reduceRight`, `repeat`, `result`, `round`, `runInContext`, `shift`, `size`,
9097 * `snakeCase`, `some`, `sortedIndex`, `sortedLastIndex`, `startCase`,
9098 * `startsWith`, `sum`, `template`, `trim`, `trimLeft`, `trimRight`, `trunc`,
9099 * `unescape`, `uniqueId`, `value`, and `words`
9100 *
9101 * The wrapper method `sample` will return a wrapped value when `n` is provided,
9102 * otherwise an unwrapped value is returned.
9103 *
9104 * @name _
9105 * @constructor
9106 * @category Chain
9107 * @param {*} value The value to wrap in a `lodash` instance.
9108 * @returns {Object} Returns the new `lodash` wrapper instance.
9109 * @example
9110 *
9111 * var wrapped = _([1, 2, 3]);
9112 *
9113 * // returns an unwrapped value
9114 * wrapped.reduce(function(total, n) {
9115 * return total + n;
9116 * });
9117 * // => 6
9118 *
9119 * // returns a wrapped value
9120 * var squares = wrapped.map(function(n) {
9121 * return n * n;
9122 * });
9123 *
9124 * _.isArray(squares);
9125 * // => false
9126 *
9127 * _.isArray(squares.value());
9128 * // => true
9129 */
9130 function lodash(value) {
9131 if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) {
9132 if (value instanceof LodashWrapper) {
9133 return value;
9134 }
9135 if (hasOwnProperty.call(value, '__chain__') && hasOwnProperty.call(value, '__wrapped__')) {
9136 return wrapperClone(value);
9137 }
9138 }
9139 return new LodashWrapper(value);
9140 }
9141
9142 /**
9143 * The function whose prototype all chaining wrappers inherit from.
9144 *
9145 * @private
9146 */
9147 function baseLodash() {
9148 // No operation performed.
9149 }
9150
9151 /**
9152 * The base constructor for creating `lodash` wrapper objects.
9153 *
9154 * @private
9155 * @param {*} value The value to wrap.
9156 * @param {boolean} [chainAll] Enable chaining for all wrapper methods.
9157 * @param {Array} [actions=[]] Actions to peform to resolve the unwrapped value.
9158 */
9159 function LodashWrapper(value, chainAll, actions) {
9160 this.__wrapped__ = value;
9161 this.__actions__ = actions || [];
9162 this.__chain__ = !!chainAll;
9163 }
9164
9165 /**
9166 * An object environment feature flags.
9167 *
9168 * @static
9169 * @memberOf _
9170 * @type Object
9171 */
9172 var support = lodash.support = {};
9173
9174 /**
9175 * By default, the template delimiters used by lodash are like those in
9176 * embedded Ruby (ERB). Change the following template settings to use
9177 * alternative delimiters.
9178 *
9179 * @static
9180 * @memberOf _
9181 * @type Object
9182 */
9183 lodash.templateSettings = {
9184
9185 /**
9186 * Used to detect `data` property values to be HTML-escaped.
9187 *
9188 * @memberOf _.templateSettings
9189 * @type RegExp
9190 */
9191 'escape': reEscape,
9192
9193 /**
9194 * Used to detect code to be evaluated.
9195 *
9196 * @memberOf _.templateSettings
9197 * @type RegExp
9198 */
9199 'evaluate': reEvaluate,
9200
9201 /**
9202 * Used to detect `data` property values to inject.
9203 *
9204 * @memberOf _.templateSettings
9205 * @type RegExp
9206 */
9207 'interpolate': reInterpolate,
9208
9209 /**
9210 * Used to reference the data object in the template text.
9211 *
9212 * @memberOf _.templateSettings
9213 * @type string
9214 */
9215 'variable': '',
9216
9217 /**
9218 * Used to import variables into the compiled template.
9219 *
9220 * @memberOf _.templateSettings
9221 * @type Object
9222 */
9223 'imports': {
9224
9225 /**
9226 * A reference to the `lodash` function.
9227 *
9228 * @memberOf _.templateSettings.imports
9229 * @type Function
9230 */
9231 '_': lodash
9232 }
9233 };
9234
9235 /*------------------------------------------------------------------------*/
9236
9237 /**
9238 * Creates a lazy wrapper object which wraps `value` to enable lazy evaluation.
9239 *
9240 * @private
9241 * @param {*} value The value to wrap.
9242 */
9243 function LazyWrapper(value) {
9244 this.__wrapped__ = value;
9245 this.__actions__ = [];
9246 this.__dir__ = 1;
9247 this.__filtered__ = false;
9248 this.__iteratees__ = [];
9249 this.__takeCount__ = POSITIVE_INFINITY;
9250 this.__views__ = [];
9251 }
9252
9253 /**
9254 * Creates a clone of the lazy wrapper object.
9255 *
9256 * @private
9257 * @name clone
9258 * @memberOf LazyWrapper
9259 * @returns {Object} Returns the cloned `LazyWrapper` object.
9260 */
9261 function lazyClone() {
9262 var result = new LazyWrapper(this.__wrapped__);
9263 result.__actions__ = arrayCopy(this.__actions__);
9264 result.__dir__ = this.__dir__;
9265 result.__filtered__ = this.__filtered__;
9266 result.__iteratees__ = arrayCopy(this.__iteratees__);
9267 result.__takeCount__ = this.__takeCount__;
9268 result.__views__ = arrayCopy(this.__views__);
9269 return result;
9270 }
9271
9272 /**
9273 * Reverses the direction of lazy iteration.
9274 *
9275 * @private
9276 * @name reverse
9277 * @memberOf LazyWrapper
9278 * @returns {Object} Returns the new reversed `LazyWrapper` object.
9279 */
9280 function lazyReverse() {
9281 if (this.__filtered__) {
9282 var result = new LazyWrapper(this);
9283 result.__dir__ = -1;
9284 result.__filtered__ = true;
9285 } else {
9286 result = this.clone();
9287 result.__dir__ *= -1;
9288 }
9289 return result;
9290 }
9291
9292 /**
9293 * Extracts the unwrapped value from its lazy wrapper.
9294 *
9295 * @private
9296 * @name value
9297 * @memberOf LazyWrapper
9298 * @returns {*} Returns the unwrapped value.
9299 */
9300 function lazyValue() {
9301 var array = this.__wrapped__.value(),
9302 dir = this.__dir__,
9303 isArr = isArray(array),
9304 isRight = dir < 0,
9305 arrLength = isArr ? array.length : 0,
9306 view = getView(0, arrLength, this.__views__),
9307 start = view.start,
9308 end = view.end,
9309 length = end - start,
9310 index = isRight ? end : (start - 1),
9311 iteratees = this.__iteratees__,
9312 iterLength = iteratees.length,
9313 resIndex = 0,
9314 takeCount = nativeMin(length, this.__takeCount__);
9315
9316 if (!isArr || arrLength < LARGE_ARRAY_SIZE || (arrLength == length && takeCount == length)) {
9317 return baseWrapperValue((isRight && isArr) ? array.reverse() : array, this.__actions__);
9318 }
9319 var result = [];
9320
9321 outer:
9322 while (length-- && resIndex < takeCount) {
9323 index += dir;
9324
9325 var iterIndex = -1,
9326 value = array[index];
9327
9328 while (++iterIndex < iterLength) {
9329 var data = iteratees[iterIndex],
9330 iteratee = data.iteratee,
9331 type = data.type,
9332 computed = iteratee(value);
9333
9334 if (type == LAZY_MAP_FLAG) {
9335 value = computed;
9336 } else if (!computed) {
9337 if (type == LAZY_FILTER_FLAG) {
9338 continue outer;
9339 } else {
9340 break outer;
9341 }
9342 }
9343 }
9344 result[resIndex++] = value;
9345 }
9346 return result;
9347 }
9348
9349 /*------------------------------------------------------------------------*/
9350
9351 /**
9352 * Creates a cache object to store key/value pairs.
9353 *
9354 * @private
9355 * @static
9356 * @name Cache
9357 * @memberOf _.memoize
9358 */
9359 function MapCache() {
9360 this.__data__ = {};
9361 }
9362
9363 /**
9364 * Removes `key` and its value from the cache.
9365 *
9366 * @private
9367 * @name delete
9368 * @memberOf _.memoize.Cache
9369 * @param {string} key The key of the value to remove.
9370 * @returns {boolean} Returns `true` if the entry was removed successfully, else `false`.
9371 */
9372 function mapDelete(key) {
9373 return this.has(key) && delete this.__data__[key];
9374 }
9375
9376 /**
9377 * Gets the cached value for `key`.
9378 *
9379 * @private
9380 * @name get
9381 * @memberOf _.memoize.Cache
9382 * @param {string} key The key of the value to get.
9383 * @returns {*} Returns the cached value.
9384 */
9385 function mapGet(key) {
9386 return key == '__proto__' ? undefined : this.__data__[key];
9387 }
9388
9389 /**
9390 * Checks if a cached value for `key` exists.
9391 *
9392 * @private
9393 * @name has
9394 * @memberOf _.memoize.Cache
9395 * @param {string} key The key of the entry to check.
9396 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
9397 */
9398 function mapHas(key) {
9399 return key != '__proto__' && hasOwnProperty.call(this.__data__, key);
9400 }
9401
9402 /**
9403 * Sets `value` to `key` of the cache.
9404 *
9405 * @private
9406 * @name set
9407 * @memberOf _.memoize.Cache
9408 * @param {string} key The key of the value to cache.
9409 * @param {*} value The value to cache.
9410 * @returns {Object} Returns the cache object.
9411 */
9412 function mapSet(key, value) {
9413 if (key != '__proto__') {
9414 this.__data__[key] = value;
9415 }
9416 return this;
9417 }
9418
9419 /*------------------------------------------------------------------------*/
9420
9421 /**
9422 *
9423 * Creates a cache object to store unique values.
9424 *
9425 * @private
9426 * @param {Array} [values] The values to cache.
9427 */
9428 function SetCache(values) {
9429 var length = values ? values.length : 0;
9430
9431 this.data = { 'hash': nativeCreate(null), 'set': new Set };
9432 while (length--) {
9433 this.push(values[length]);
9434 }
9435 }
9436
9437 /**
9438 * Checks if `value` is in `cache` mimicking the return signature of
9439 * `_.indexOf` by returning `0` if the value is found, else `-1`.
9440 *
9441 * @private
9442 * @param {Object} cache The cache to search.
9443 * @param {*} value The value to search for.
9444 * @returns {number} Returns `0` if `value` is found, else `-1`.
9445 */
9446 function cacheIndexOf(cache, value) {
9447 var data = cache.data,
9448 result = (typeof value == 'string' || isObject(value)) ? data.set.has(value) : data.hash[value];
9449
9450 return result ? 0 : -1;
9451 }
9452
9453 /**
9454 * Adds `value` to the cache.
9455 *
9456 * @private
9457 * @name push
9458 * @memberOf SetCache
9459 * @param {*} value The value to cache.
9460 */
9461 function cachePush(value) {
9462 var data = this.data;
9463 if (typeof value == 'string' || isObject(value)) {
9464 data.set.add(value);
9465 } else {
9466 data.hash[value] = true;
9467 }
9468 }
9469
9470 /*------------------------------------------------------------------------*/
9471
9472 /**
9473 * Creates a new array joining `array` with `other`.
9474 *
9475 * @private
9476 * @param {Array} array The array to join.
9477 * @param {Array} other The other array to join.
9478 * @returns {Array} Returns the new concatenated array.
9479 */
9480 function arrayConcat(array, other) {
9481 var index = -1,
9482 length = array.length,
9483 othIndex = -1,
9484 othLength = other.length,
9485 result = Array(length + othLength);
9486
9487 while (++index < length) {
9488 result[index] = array[index];
9489 }
9490 while (++othIndex < othLength) {
9491 result[index++] = other[othIndex];
9492 }
9493 return result;
9494 }
9495
9496 /**
9497 * Copies the values of `source` to `array`.
9498 *
9499 * @private
9500 * @param {Array} source The array to copy values from.
9501 * @param {Array} [array=[]] The array to copy values to.
9502 * @returns {Array} Returns `array`.
9503 */
9504 function arrayCopy(source, array) {
9505 var index = -1,
9506 length = source.length;
9507
9508 array || (array = Array(length));
9509 while (++index < length) {
9510 array[index] = source[index];
9511 }
9512 return array;
9513 }
9514
9515 /**
9516 * A specialized version of `_.forEach` for arrays without support for callback
9517 * shorthands and `this` binding.
9518 *
9519 * @private
9520 * @param {Array} array The array to iterate over.
9521 * @param {Function} iteratee The function invoked per iteration.
9522 * @returns {Array} Returns `array`.
9523 */
9524 function arrayEach(array, iteratee) {
9525 var index = -1,
9526 length = array.length;
9527
9528 while (++index < length) {
9529 if (iteratee(array[index], index, array) === false) {
9530 break;
9531 }
9532 }
9533 return array;
9534 }
9535
9536 /**
9537 * A specialized version of `_.forEachRight` for arrays without support for
9538 * callback shorthands and `this` binding.
9539 *
9540 * @private
9541 * @param {Array} array The array to iterate over.
9542 * @param {Function} iteratee The function invoked per iteration.
9543 * @returns {Array} Returns `array`.
9544 */
9545 function arrayEachRight(array, iteratee) {
9546 var length = array.length;
9547
9548 while (length--) {
9549 if (iteratee(array[length], length, array) === false) {
9550 break;
9551 }
9552 }
9553 return array;
9554 }
9555
9556 /**
9557 * A specialized version of `_.every` for arrays without support for callback
9558 * shorthands and `this` binding.
9559 *
9560 * @private
9561 * @param {Array} array The array to iterate over.
9562 * @param {Function} predicate The function invoked per iteration.
9563 * @returns {boolean} Returns `true` if all elements pass the predicate check,
9564 * else `false`.
9565 */
9566 function arrayEvery(array, predicate) {
9567 var index = -1,
9568 length = array.length;
9569
9570 while (++index < length) {
9571 if (!predicate(array[index], index, array)) {
9572 return false;
9573 }
9574 }
9575 return true;
9576 }
9577
9578 /**
9579 * A specialized version of `baseExtremum` for arrays which invokes `iteratee`
9580 * with one argument: (value).
9581 *
9582 * @private
9583 * @param {Array} array The array to iterate over.
9584 * @param {Function} iteratee The function invoked per iteration.
9585 * @param {Function} comparator The function used to compare values.
9586 * @param {*} exValue The initial extremum value.
9587 * @returns {*} Returns the extremum value.
9588 */
9589 function arrayExtremum(array, iteratee, comparator, exValue) {
9590 var index = -1,
9591 length = array.length,
9592 computed = exValue,
9593 result = computed;
9594
9595 while (++index < length) {
9596 var value = array[index],
9597 current = +iteratee(value);
9598
9599 if (comparator(current, computed)) {
9600 computed = current;
9601 result = value;
9602 }
9603 }
9604 return result;
9605 }
9606
9607 /**
9608 * A specialized version of `_.filter` for arrays without support for callback
9609 * shorthands and `this` binding.
9610 *
9611 * @private
9612 * @param {Array} array The array to iterate over.
9613 * @param {Function} predicate The function invoked per iteration.
9614 * @returns {Array} Returns the new filtered array.
9615 */
9616 function arrayFilter(array, predicate) {
9617 var index = -1,
9618 length = array.length,
9619 resIndex = -1,
9620 result = [];
9621
9622 while (++index < length) {
9623 var value = array[index];
9624 if (predicate(value, index, array)) {
9625 result[++resIndex] = value;
9626 }
9627 }
9628 return result;
9629 }
9630
9631 /**
9632 * A specialized version of `_.map` for arrays without support for callback
9633 * shorthands and `this` binding.
9634 *
9635 * @private
9636 * @param {Array} array The array to iterate over.
9637 * @param {Function} iteratee The function invoked per iteration.
9638 * @returns {Array} Returns the new mapped array.
9639 */
9640 function arrayMap(array, iteratee) {
9641 var index = -1,
9642 length = array.length,
9643 result = Array(length);
9644
9645 while (++index < length) {
9646 result[index] = iteratee(array[index], index, array);
9647 }
9648 return result;
9649 }
9650
9651 /**
9652 * Appends the elements of `values` to `array`.
9653 *
9654 * @private
9655 * @param {Array} array The array to modify.
9656 * @param {Array} values The values to append.
9657 * @returns {Array} Returns `array`.
9658 */
9659 function arrayPush(array, values) {
9660 var index = -1,
9661 length = values.length,
9662 offset = array.length;
9663
9664 while (++index < length) {
9665 array[offset + index] = values[index];
9666 }
9667 return array;
9668 }
9669
9670 /**
9671 * A specialized version of `_.reduce` for arrays without support for callback
9672 * shorthands and `this` binding.
9673 *
9674 * @private
9675 * @param {Array} array The array to iterate over.
9676 * @param {Function} iteratee The function invoked per iteration.
9677 * @param {*} [accumulator] The initial value.
9678 * @param {boolean} [initFromArray] Specify using the first element of `array`
9679 * as the initial value.
9680 * @returns {*} Returns the accumulated value.
9681 */
9682 function arrayReduce(array, iteratee, accumulator, initFromArray) {
9683 var index = -1,
9684 length = array.length;
9685
9686 if (initFromArray && length) {
9687 accumulator = array[++index];
9688 }
9689 while (++index < length) {
9690 accumulator = iteratee(accumulator, array[index], index, array);
9691 }
9692 return accumulator;
9693 }
9694
9695 /**
9696 * A specialized version of `_.reduceRight` for arrays without support for
9697 * callback shorthands and `this` binding.
9698 *
9699 * @private
9700 * @param {Array} array The array to iterate over.
9701 * @param {Function} iteratee The function invoked per iteration.
9702 * @param {*} [accumulator] The initial value.
9703 * @param {boolean} [initFromArray] Specify using the last element of `array`
9704 * as the initial value.
9705 * @returns {*} Returns the accumulated value.
9706 */
9707 function arrayReduceRight(array, iteratee, accumulator, initFromArray) {
9708 var length = array.length;
9709 if (initFromArray && length) {
9710 accumulator = array[--length];
9711 }
9712 while (length--) {
9713 accumulator = iteratee(accumulator, array[length], length, array);
9714 }
9715 return accumulator;
9716 }
9717
9718 /**
9719 * A specialized version of `_.some` for arrays without support for callback
9720 * shorthands and `this` binding.
9721 *
9722 * @private
9723 * @param {Array} array The array to iterate over.
9724 * @param {Function} predicate The function invoked per iteration.
9725 * @returns {boolean} Returns `true` if any element passes the predicate check,
9726 * else `false`.
9727 */
9728 function arraySome(array, predicate) {
9729 var index = -1,
9730 length = array.length;
9731
9732 while (++index < length) {
9733 if (predicate(array[index], index, array)) {
9734 return true;
9735 }
9736 }
9737 return false;
9738 }
9739
9740 /**
9741 * A specialized version of `_.sum` for arrays without support for callback
9742 * shorthands and `this` binding..
9743 *
9744 * @private
9745 * @param {Array} array The array to iterate over.
9746 * @param {Function} iteratee The function invoked per iteration.
9747 * @returns {number} Returns the sum.
9748 */
9749 function arraySum(array, iteratee) {
9750 var length = array.length,
9751 result = 0;
9752
9753 while (length--) {
9754 result += +iteratee(array[length]) || 0;
9755 }
9756 return result;
9757 }
9758
9759 /**
9760 * Used by `_.defaults` to customize its `_.assign` use.
9761 *
9762 * @private
9763 * @param {*} objectValue The destination object property value.
9764 * @param {*} sourceValue The source object property value.
9765 * @returns {*} Returns the value to assign to the destination object.
9766 */
9767 function assignDefaults(objectValue, sourceValue) {
9768 return objectValue === undefined ? sourceValue : objectValue;
9769 }
9770
9771 /**
9772 * Used by `_.template` to customize its `_.assign` use.
9773 *
9774 * **Note:** This function is like `assignDefaults` except that it ignores
9775 * inherited property values when checking if a property is `undefined`.
9776 *
9777 * @private
9778 * @param {*} objectValue The destination object property value.
9779 * @param {*} sourceValue The source object property value.
9780 * @param {string} key The key associated with the object and source values.
9781 * @param {Object} object The destination object.
9782 * @returns {*} Returns the value to assign to the destination object.
9783 */
9784 function assignOwnDefaults(objectValue, sourceValue, key, object) {
9785 return (objectValue === undefined || !hasOwnProperty.call(object, key))
9786 ? sourceValue
9787 : objectValue;
9788 }
9789
9790 /**
9791 * A specialized version of `_.assign` for customizing assigned values without
9792 * support for argument juggling, multiple sources, and `this` binding `customizer`
9793 * functions.
9794 *
9795 * @private
9796 * @param {Object} object The destination object.
9797 * @param {Object} source The source object.
9798 * @param {Function} customizer The function to customize assigned values.
9799 * @returns {Object} Returns `object`.
9800 */
9801 function assignWith(object, source, customizer) {
9802 var index = -1,
9803 props = keys(source),
9804 length = props.length;
9805
9806 while (++index < length) {
9807 var key = props[index],
9808 value = object[key],
9809 result = customizer(value, source[key], key, object, source);
9810
9811 if ((result === result ? (result !== value) : (value === value)) ||
9812 (value === undefined && !(key in object))) {
9813 object[key] = result;
9814 }
9815 }
9816 return object;
9817 }
9818
9819 /**
9820 * The base implementation of `_.assign` without support for argument juggling,
9821 * multiple sources, and `customizer` functions.
9822 *
9823 * @private
9824 * @param {Object} object The destination object.
9825 * @param {Object} source The source object.
9826 * @returns {Object} Returns `object`.
9827 */
9828 function baseAssign(object, source) {
9829 return source == null
9830 ? object
9831 : baseCopy(source, keys(source), object);
9832 }
9833
9834 /**
9835 * The base implementation of `_.at` without support for string collections
9836 * and individual key arguments.
9837 *
9838 * @private
9839 * @param {Array|Object} collection The collection to iterate over.
9840 * @param {number[]|string[]} props The property names or indexes of elements to pick.
9841 * @returns {Array} Returns the new array of picked elements.
9842 */
9843 function baseAt(collection, props) {
9844 var index = -1,
9845 isNil = collection == null,
9846 isArr = !isNil && isArrayLike(collection),
9847 length = isArr ? collection.length : 0,
9848 propsLength = props.length,
9849 result = Array(propsLength);
9850
9851 while(++index < propsLength) {
9852 var key = props[index];
9853 if (isArr) {
9854 result[index] = isIndex(key, length) ? collection[key] : undefined;
9855 } else {
9856 result[index] = isNil ? undefined : collection[key];
9857 }
9858 }
9859 return result;
9860 }
9861
9862 /**
9863 * Copies properties of `source` to `object`.
9864 *
9865 * @private
9866 * @param {Object} source The object to copy properties from.
9867 * @param {Array} props The property names to copy.
9868 * @param {Object} [object={}] The object to copy properties to.
9869 * @returns {Object} Returns `object`.
9870 */
9871 function baseCopy(source, props, object) {
9872 object || (object = {});
9873
9874 var index = -1,
9875 length = props.length;
9876
9877 while (++index < length) {
9878 var key = props[index];
9879 object[key] = source[key];
9880 }
9881 return object;
9882 }
9883
9884 /**
9885 * The base implementation of `_.callback` which supports specifying the
9886 * number of arguments to provide to `func`.
9887 *
9888 * @private
9889 * @param {*} [func=_.identity] The value to convert to a callback.
9890 * @param {*} [thisArg] The `this` binding of `func`.
9891 * @param {number} [argCount] The number of arguments to provide to `func`.
9892 * @returns {Function} Returns the callback.
9893 */
9894 function baseCallback(func, thisArg, argCount) {
9895 var type = typeof func;
9896 if (type == 'function') {
9897 return thisArg === undefined
9898 ? func
9899 : bindCallback(func, thisArg, argCount);
9900 }
9901 if (func == null) {
9902 return identity;
9903 }
9904 if (type == 'object') {
9905 return baseMatches(func);
9906 }
9907 return thisArg === undefined
9908 ? property(func)
9909 : baseMatchesProperty(func, thisArg);
9910 }
9911
9912 /**
9913 * The base implementation of `_.clone` without support for argument juggling
9914 * and `this` binding `customizer` functions.
9915 *
9916 * @private
9917 * @param {*} value The value to clone.
9918 * @param {boolean} [isDeep] Specify a deep clone.
9919 * @param {Function} [customizer] The function to customize cloning values.
9920 * @param {string} [key] The key of `value`.
9921 * @param {Object} [object] The object `value` belongs to.
9922 * @param {Array} [stackA=[]] Tracks traversed source objects.
9923 * @param {Array} [stackB=[]] Associates clones with source counterparts.
9924 * @returns {*} Returns the cloned value.
9925 */
9926 function baseClone(value, isDeep, customizer, key, object, stackA, stackB) {
9927 var result;
9928 if (customizer) {
9929 result = object ? customizer(value, key, object) : customizer(value);
9930 }
9931 if (result !== undefined) {
9932 return result;
9933 }
9934 if (!isObject(value)) {
9935 return value;
9936 }
9937 var isArr = isArray(value);
9938 if (isArr) {
9939 result = initCloneArray(value);
9940 if (!isDeep) {
9941 return arrayCopy(value, result);
9942 }
9943 } else {
9944 var tag = objToString.call(value),
9945 isFunc = tag == funcTag;
9946
9947 if (tag == objectTag || tag == argsTag || (isFunc && !object)) {
9948 result = initCloneObject(isFunc ? {} : value);
9949 if (!isDeep) {
9950 return baseAssign(result, value);
9951 }
9952 } else {
9953 return cloneableTags[tag]
9954 ? initCloneByTag(value, tag, isDeep)
9955 : (object ? value : {});
9956 }
9957 }
9958 // Check for circular references and return its corresponding clone.
9959 stackA || (stackA = []);
9960 stackB || (stackB = []);
9961
9962 var length = stackA.length;
9963 while (length--) {
9964 if (stackA[length] == value) {
9965 return stackB[length];
9966 }
9967 }
9968 // Add the source value to the stack of traversed objects and associate it with its clone.
9969 stackA.push(value);
9970 stackB.push(result);
9971
9972 // Recursively populate clone (susceptible to call stack limits).
9973 (isArr ? arrayEach : baseForOwn)(value, function(subValue, key) {
9974 result[key] = baseClone(subValue, isDeep, customizer, key, value, stackA, stackB);
9975 });
9976 return result;
9977 }
9978
9979 /**
9980 * The base implementation of `_.create` without support for assigning
9981 * properties to the created object.
9982 *
9983 * @private
9984 * @param {Object} prototype The object to inherit from.
9985 * @returns {Object} Returns the new object.
9986 */
9987 var baseCreate = (function() {
9988 function object() {}
9989 return function(prototype) {
9990 if (isObject(prototype)) {
9991 object.prototype = prototype;
9992 var result = new object;
9993 object.prototype = undefined;
9994 }
9995 return result || {};
9996 };
9997 }());
9998
9999 /**
10000 * The base implementation of `_.delay` and `_.defer` which accepts an index
10001 * of where to slice the arguments to provide to `func`.
10002 *
10003 * @private
10004 * @param {Function} func The function to delay.
10005 * @param {number} wait The number of milliseconds to delay invocation.
10006 * @param {Object} args The arguments provide to `func`.
10007 * @returns {number} Returns the timer id.
10008 */
10009 function baseDelay(func, wait, args) {
10010 if (typeof func != 'function') {
10011 throw new TypeError(FUNC_ERROR_TEXT);
10012 }
10013 return setTimeout(function() { func.apply(undefined, args); }, wait);
10014 }
10015
10016 /**
10017 * The base implementation of `_.difference` which accepts a single array
10018 * of values to exclude.
10019 *
10020 * @private
10021 * @param {Array} array The array to inspect.
10022 * @param {Array} values The values to exclude.
10023 * @returns {Array} Returns the new array of filtered values.
10024 */
10025 function baseDifference(array, values) {
10026 var length = array ? array.length : 0,
10027 result = [];
10028
10029 if (!length) {
10030 return result;
10031 }
10032 var index = -1,
10033 indexOf = getIndexOf(),
10034 isCommon = indexOf == baseIndexOf,
10035 cache = (isCommon && values.length >= LARGE_ARRAY_SIZE) ? createCache(values) : null,
10036 valuesLength = values.length;
10037
10038 if (cache) {
10039 indexOf = cacheIndexOf;
10040 isCommon = false;
10041 values = cache;
10042 }
10043 outer:
10044 while (++index < length) {
10045 var value = array[index];
10046
10047 if (isCommon && value === value) {
10048 var valuesIndex = valuesLength;
10049 while (valuesIndex--) {
10050 if (values[valuesIndex] === value) {
10051 continue outer;
10052 }
10053 }
10054 result.push(value);
10055 }
10056 else if (indexOf(values, value, 0) < 0) {
10057 result.push(value);
10058 }
10059 }
10060 return result;
10061 }
10062
10063 /**
10064 * The base implementation of `_.forEach` without support for callback
10065 * shorthands and `this` binding.
10066 *
10067 * @private
10068 * @param {Array|Object|string} collection The collection to iterate over.
10069 * @param {Function} iteratee The function invoked per iteration.
10070 * @returns {Array|Object|string} Returns `collection`.
10071 */
10072 var baseEach = createBaseEach(baseForOwn);
10073
10074 /**
10075 * The base implementation of `_.forEachRight` without support for callback
10076 * shorthands and `this` binding.
10077 *
10078 * @private
10079 * @param {Array|Object|string} collection The collection to iterate over.
10080 * @param {Function} iteratee The function invoked per iteration.
10081 * @returns {Array|Object|string} Returns `collection`.
10082 */
10083 var baseEachRight = createBaseEach(baseForOwnRight, true);
10084
10085 /**
10086 * The base implementation of `_.every` without support for callback
10087 * shorthands and `this` binding.
10088 *
10089 * @private
10090 * @param {Array|Object|string} collection The collection to iterate over.
10091 * @param {Function} predicate The function invoked per iteration.
10092 * @returns {boolean} Returns `true` if all elements pass the predicate check,
10093 * else `false`
10094 */
10095 function baseEvery(collection, predicate) {
10096 var result = true;
10097 baseEach(collection, function(value, index, collection) {
10098 result = !!predicate(value, index, collection);
10099 return result;
10100 });
10101 return result;
10102 }
10103
10104 /**
10105 * Gets the extremum value of `collection` invoking `iteratee` for each value
10106 * in `collection` to generate the criterion by which the value is ranked.
10107 * The `iteratee` is invoked with three arguments: (value, index|key, collection).
10108 *
10109 * @private
10110 * @param {Array|Object|string} collection The collection to iterate over.
10111 * @param {Function} iteratee The function invoked per iteration.
10112 * @param {Function} comparator The function used to compare values.
10113 * @param {*} exValue The initial extremum value.
10114 * @returns {*} Returns the extremum value.
10115 */
10116 function baseExtremum(collection, iteratee, comparator, exValue) {
10117 var computed = exValue,
10118 result = computed;
10119
10120 baseEach(collection, function(value, index, collection) {
10121 var current = +iteratee(value, index, collection);
10122 if (comparator(current, computed) || (current === exValue && current === result)) {
10123 computed = current;
10124 result = value;
10125 }
10126 });
10127 return result;
10128 }
10129
10130 /**
10131 * The base implementation of `_.fill` without an iteratee call guard.
10132 *
10133 * @private
10134 * @param {Array} array The array to fill.
10135 * @param {*} value The value to fill `array` with.
10136 * @param {number} [start=0] The start position.
10137 * @param {number} [end=array.length] The end position.
10138 * @returns {Array} Returns `array`.
10139 */
10140 function baseFill(array, value, start, end) {
10141 var length = array.length;
10142
10143 start = start == null ? 0 : (+start || 0);
10144 if (start < 0) {
10145 start = -start > length ? 0 : (length + start);
10146 }
10147 end = (end === undefined || end > length) ? length : (+end || 0);
10148 if (end < 0) {
10149 end += length;
10150 }
10151 length = start > end ? 0 : (end >>> 0);
10152 start >>>= 0;
10153
10154 while (start < length) {
10155 array[start++] = value;
10156 }
10157 return array;
10158 }
10159
10160 /**
10161 * The base implementation of `_.filter` without support for callback
10162 * shorthands and `this` binding.
10163 *
10164 * @private
10165 * @param {Array|Object|string} collection The collection to iterate over.
10166 * @param {Function} predicate The function invoked per iteration.
10167 * @returns {Array} Returns the new filtered array.
10168 */
10169 function baseFilter(collection, predicate) {
10170 var result = [];
10171 baseEach(collection, function(value, index, collection) {
10172 if (predicate(value, index, collection)) {
10173 result.push(value);
10174 }
10175 });
10176 return result;
10177 }
10178
10179 /**
10180 * The base implementation of `_.find`, `_.findLast`, `_.findKey`, and `_.findLastKey`,
10181 * without support for callback shorthands and `this` binding, which iterates
10182 * over `collection` using the provided `eachFunc`.
10183 *
10184 * @private
10185 * @param {Array|Object|string} collection The collection to search.
10186 * @param {Function} predicate The function invoked per iteration.
10187 * @param {Function} eachFunc The function to iterate over `collection`.
10188 * @param {boolean} [retKey] Specify returning the key of the found element
10189 * instead of the element itself.
10190 * @returns {*} Returns the found element or its key, else `undefined`.
10191 */
10192 function baseFind(collection, predicate, eachFunc, retKey) {
10193 var result;
10194 eachFunc(collection, function(value, key, collection) {
10195 if (predicate(value, key, collection)) {
10196 result = retKey ? key : value;
10197 return false;
10198 }
10199 });
10200 return result;
10201 }
10202
10203 /**
10204 * The base implementation of `_.flatten` with added support for restricting
10205 * flattening and specifying the start index.
10206 *
10207 * @private
10208 * @param {Array} array The array to flatten.
10209 * @param {boolean} [isDeep] Specify a deep flatten.
10210 * @param {boolean} [isStrict] Restrict flattening to arrays-like objects.
10211 * @param {Array} [result=[]] The initial result value.
10212 * @returns {Array} Returns the new flattened array.
10213 */
10214 function baseFlatten(array, isDeep, isStrict, result) {
10215 result || (result = []);
10216
10217 var index = -1,
10218 length = array.length;
10219
10220 while (++index < length) {
10221 var value = array[index];
10222 if (isObjectLike(value) && isArrayLike(value) &&
10223 (isStrict || isArray(value) || isArguments(value))) {
10224 if (isDeep) {
10225 // Recursively flatten arrays (susceptible to call stack limits).
10226 baseFlatten(value, isDeep, isStrict, result);
10227 } else {
10228 arrayPush(result, value);
10229 }
10230 } else if (!isStrict) {
10231 result[result.length] = value;
10232 }
10233 }
10234 return result;
10235 }
10236
10237 /**
10238 * The base implementation of `baseForIn` and `baseForOwn` which iterates
10239 * over `object` properties returned by `keysFunc` invoking `iteratee` for
10240 * each property. Iteratee functions may exit iteration early by explicitly
10241 * returning `false`.
10242 *
10243 * @private
10244 * @param {Object} object The object to iterate over.
10245 * @param {Function} iteratee The function invoked per iteration.
10246 * @param {Function} keysFunc The function to get the keys of `object`.
10247 * @returns {Object} Returns `object`.
10248 */
10249 var baseFor = createBaseFor();
10250
10251 /**
10252 * This function is like `baseFor` except that it iterates over properties
10253 * in the opposite order.
10254 *
10255 * @private
10256 * @param {Object} object The object to iterate over.
10257 * @param {Function} iteratee The function invoked per iteration.
10258 * @param {Function} keysFunc The function to get the keys of `object`.
10259 * @returns {Object} Returns `object`.
10260 */
10261 var baseForRight = createBaseFor(true);
10262
10263 /**
10264 * The base implementation of `_.forIn` without support for callback
10265 * shorthands and `this` binding.
10266 *
10267 * @private
10268 * @param {Object} object The object to iterate over.
10269 * @param {Function} iteratee The function invoked per iteration.
10270 * @returns {Object} Returns `object`.
10271 */
10272 function baseForIn(object, iteratee) {
10273 return baseFor(object, iteratee, keysIn);
10274 }
10275
10276 /**
10277 * The base implementation of `_.forOwn` without support for callback
10278 * shorthands and `this` binding.
10279 *
10280 * @private
10281 * @param {Object} object The object to iterate over.
10282 * @param {Function} iteratee The function invoked per iteration.
10283 * @returns {Object} Returns `object`.
10284 */
10285 function baseForOwn(object, iteratee) {
10286 return baseFor(object, iteratee, keys);
10287 }
10288
10289 /**
10290 * The base implementation of `_.forOwnRight` without support for callback
10291 * shorthands and `this` binding.
10292 *
10293 * @private
10294 * @param {Object} object The object to iterate over.
10295 * @param {Function} iteratee The function invoked per iteration.
10296 * @returns {Object} Returns `object`.
10297 */
10298 function baseForOwnRight(object, iteratee) {
10299 return baseForRight(object, iteratee, keys);
10300 }
10301
10302 /**
10303 * The base implementation of `_.functions` which creates an array of
10304 * `object` function property names filtered from those provided.
10305 *
10306 * @private
10307 * @param {Object} object The object to inspect.
10308 * @param {Array} props The property names to filter.
10309 * @returns {Array} Returns the new array of filtered property names.
10310 */
10311 function baseFunctions(object, props) {
10312 var index = -1,
10313 length = props.length,
10314 resIndex = -1,
10315 result = [];
10316
10317 while (++index < length) {
10318 var key = props[index];
10319 if (isFunction(object[key])) {
10320 result[++resIndex] = key;
10321 }
10322 }
10323 return result;
10324 }
10325
10326 /**
10327 * The base implementation of `get` without support for string paths
10328 * and default values.
10329 *
10330 * @private
10331 * @param {Object} object The object to query.
10332 * @param {Array} path The path of the property to get.
10333 * @param {string} [pathKey] The key representation of path.
10334 * @returns {*} Returns the resolved value.
10335 */
10336 function baseGet(object, path, pathKey) {
10337 if (object == null) {
10338 return;
10339 }
10340 if (pathKey !== undefined && pathKey in toObject(object)) {
10341 path = [pathKey];
10342 }
10343 var index = 0,
10344 length = path.length;
10345
10346 while (object != null && index < length) {
10347 object = object[path[index++]];
10348 }
10349 return (index && index == length) ? object : undefined;
10350 }
10351
10352 /**
10353 * The base implementation of `_.isEqual` without support for `this` binding
10354 * `customizer` functions.
10355 *
10356 * @private
10357 * @param {*} value The value to compare.
10358 * @param {*} other The other value to compare.
10359 * @param {Function} [customizer] The function to customize comparing values.
10360 * @param {boolean} [isLoose] Specify performing partial comparisons.
10361 * @param {Array} [stackA] Tracks traversed `value` objects.
10362 * @param {Array} [stackB] Tracks traversed `other` objects.
10363 * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
10364 */
10365 function baseIsEqual(value, other, customizer, isLoose, stackA, stackB) {
10366 if (value === other) {
10367 return true;
10368 }
10369 if (value == null || other == null || (!isObject(value) && !isObjectLike(other))) {
10370 return value !== value && other !== other;
10371 }
10372 return baseIsEqualDeep(value, other, baseIsEqual, customizer, isLoose, stackA, stackB);
10373 }
10374
10375 /**
10376 * A specialized version of `baseIsEqual` for arrays and objects which performs
10377 * deep comparisons and tracks traversed objects enabling objects with circular
10378 * references to be compared.
10379 *
10380 * @private
10381 * @param {Object} object The object to compare.
10382 * @param {Object} other The other object to compare.
10383 * @param {Function} equalFunc The function to determine equivalents of values.
10384 * @param {Function} [customizer] The function to customize comparing objects.
10385 * @param {boolean} [isLoose] Specify performing partial comparisons.
10386 * @param {Array} [stackA=[]] Tracks traversed `value` objects.
10387 * @param {Array} [stackB=[]] Tracks traversed `other` objects.
10388 * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
10389 */
10390 function baseIsEqualDeep(object, other, equalFunc, customizer, isLoose, stackA, stackB) {
10391 var objIsArr = isArray(object),
10392 othIsArr = isArray(other),
10393 objTag = arrayTag,
10394 othTag = arrayTag;
10395
10396 if (!objIsArr) {
10397 objTag = objToString.call(object);
10398 if (objTag == argsTag) {
10399 objTag = objectTag;
10400 } else if (objTag != objectTag) {
10401 objIsArr = isTypedArray(object);
10402 }
10403 }
10404 if (!othIsArr) {
10405 othTag = objToString.call(other);
10406 if (othTag == argsTag) {
10407 othTag = objectTag;
10408 } else if (othTag != objectTag) {
10409 othIsArr = isTypedArray(other);
10410 }
10411 }
10412 var objIsObj = objTag == objectTag,
10413 othIsObj = othTag == objectTag,
10414 isSameTag = objTag == othTag;
10415
10416 if (isSameTag && !(objIsArr || objIsObj)) {
10417 return equalByTag(object, other, objTag);
10418 }
10419 if (!isLoose) {
10420 var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),
10421 othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');
10422
10423 if (objIsWrapped || othIsWrapped) {
10424 return equalFunc(objIsWrapped ? object.value() : object, othIsWrapped ? other.value() : other, customizer, isLoose, stackA, stackB);
10425 }
10426 }
10427 if (!isSameTag) {
10428 return false;
10429 }
10430 // Assume cyclic values are equal.
10431 // For more information on detecting circular references see https://es5.github.io/#JO.
10432 stackA || (stackA = []);
10433 stackB || (stackB = []);
10434
10435 var length = stackA.length;
10436 while (length--) {
10437 if (stackA[length] == object) {
10438 return stackB[length] == other;
10439 }
10440 }
10441 // Add `object` and `other` to the stack of traversed objects.
10442 stackA.push(object);
10443 stackB.push(other);
10444
10445 var result = (objIsArr ? equalArrays : equalObjects)(object, other, equalFunc, customizer, isLoose, stackA, stackB);
10446
10447 stackA.pop();
10448 stackB.pop();
10449
10450 return result;
10451 }
10452
10453 /**
10454 * The base implementation of `_.isMatch` without support for callback
10455 * shorthands and `this` binding.
10456 *
10457 * @private
10458 * @param {Object} object The object to inspect.
10459 * @param {Array} matchData The propery names, values, and compare flags to match.
10460 * @param {Function} [customizer] The function to customize comparing objects.
10461 * @returns {boolean} Returns `true` if `object` is a match, else `false`.
10462 */
10463 function baseIsMatch(object, matchData, customizer) {
10464 var index = matchData.length,
10465 length = index,
10466 noCustomizer = !customizer;
10467
10468 if (object == null) {
10469 return !length;
10470 }
10471 object = toObject(object);
10472 while (index--) {
10473 var data = matchData[index];
10474 if ((noCustomizer && data[2])
10475 ? data[1] !== object[data[0]]
10476 : !(data[0] in object)
10477 ) {
10478 return false;
10479 }
10480 }
10481 while (++index < length) {
10482 data = matchData[index];
10483 var key = data[0],
10484 objValue = object[key],
10485 srcValue = data[1];
10486
10487 if (noCustomizer && data[2]) {
10488 if (objValue === undefined && !(key in object)) {
10489 return false;
10490 }
10491 } else {
10492 var result = customizer ? customizer(objValue, srcValue, key) : undefined;
10493 if (!(result === undefined ? baseIsEqual(srcValue, objValue, customizer, true) : result)) {
10494 return false;
10495 }
10496 }
10497 }
10498 return true;
10499 }
10500
10501 /**
10502 * The base implementation of `_.map` without support for callback shorthands
10503 * and `this` binding.
10504 *
10505 * @private
10506 * @param {Array|Object|string} collection The collection to iterate over.
10507 * @param {Function} iteratee The function invoked per iteration.
10508 * @returns {Array} Returns the new mapped array.
10509 */
10510 function baseMap(collection, iteratee) {
10511 var index = -1,
10512 result = isArrayLike(collection) ? Array(collection.length) : [];
10513
10514 baseEach(collection, function(value, key, collection) {
10515 result[++index] = iteratee(value, key, collection);
10516 });
10517 return result;
10518 }
10519
10520 /**
10521 * The base implementation of `_.matches` which does not clone `source`.
10522 *
10523 * @private
10524 * @param {Object} source The object of property values to match.
10525 * @returns {Function} Returns the new function.
10526 */
10527 function baseMatches(source) {
10528 var matchData = getMatchData(source);
10529 if (matchData.length == 1 && matchData[0][2]) {
10530 var key = matchData[0][0],
10531 value = matchData[0][1];
10532
10533 return function(object) {
10534 if (object == null) {
10535 return false;
10536 }
10537 return object[key] === value && (value !== undefined || (key in toObject(object)));
10538 };
10539 }
10540 return function(object) {
10541 return baseIsMatch(object, matchData);
10542 };
10543 }
10544
10545 /**
10546 * The base implementation of `_.matchesProperty` which does not clone `srcValue`.
10547 *
10548 * @private
10549 * @param {string} path The path of the property to get.
10550 * @param {*} srcValue The value to compare.
10551 * @returns {Function} Returns the new function.
10552 */
10553 function baseMatchesProperty(path, srcValue) {
10554 var isArr = isArray(path),
10555 isCommon = isKey(path) && isStrictComparable(srcValue),
10556 pathKey = (path + '');
10557
10558 path = toPath(path);
10559 return function(object) {
10560 if (object == null) {
10561 return false;
10562 }
10563 var key = pathKey;
10564 object = toObject(object);
10565 if ((isArr || !isCommon) && !(key in object)) {
10566 object = path.length == 1 ? object : baseGet(object, baseSlice(path, 0, -1));
10567 if (object == null) {
10568 return false;
10569 }
10570 key = last(path);
10571 object = toObject(object);
10572 }
10573 return object[key] === srcValue
10574 ? (srcValue !== undefined || (key in object))
10575 : baseIsEqual(srcValue, object[key], undefined, true);
10576 };
10577 }
10578
10579 /**
10580 * The base implementation of `_.merge` without support for argument juggling,
10581 * multiple sources, and `this` binding `customizer` functions.
10582 *
10583 * @private
10584 * @param {Object} object The destination object.
10585 * @param {Object} source The source object.
10586 * @param {Function} [customizer] The function to customize merged values.
10587 * @param {Array} [stackA=[]] Tracks traversed source objects.
10588 * @param {Array} [stackB=[]] Associates values with source counterparts.
10589 * @returns {Object} Returns `object`.
10590 */
10591 function baseMerge(object, source, customizer, stackA, stackB) {
10592 if (!isObject(object)) {
10593 return object;
10594 }
10595 var isSrcArr = isArrayLike(source) && (isArray(source) || isTypedArray(source)),
10596 props = isSrcArr ? undefined : keys(source);
10597
10598 arrayEach(props || source, function(srcValue, key) {
10599 if (props) {
10600 key = srcValue;
10601 srcValue = source[key];
10602 }
10603 if (isObjectLike(srcValue)) {
10604 stackA || (stackA = []);
10605 stackB || (stackB = []);
10606 baseMergeDeep(object, source, key, baseMerge, customizer, stackA, stackB);
10607 }
10608 else {
10609 var value = object[key],
10610 result = customizer ? customizer(value, srcValue, key, object, source) : undefined,
10611 isCommon = result === undefined;
10612
10613 if (isCommon) {
10614 result = srcValue;
10615 }
10616 if ((result !== undefined || (isSrcArr && !(key in object))) &&
10617 (isCommon || (result === result ? (result !== value) : (value === value)))) {
10618 object[key] = result;
10619 }
10620 }
10621 });
10622 return object;
10623 }
10624
10625 /**
10626 * A specialized version of `baseMerge` for arrays and objects which performs
10627 * deep merges and tracks traversed objects enabling objects with circular
10628 * references to be merged.
10629 *
10630 * @private
10631 * @param {Object} object The destination object.
10632 * @param {Object} source The source object.
10633 * @param {string} key The key of the value to merge.
10634 * @param {Function} mergeFunc The function to merge values.
10635 * @param {Function} [customizer] The function to customize merged values.
10636 * @param {Array} [stackA=[]] Tracks traversed source objects.
10637 * @param {Array} [stackB=[]] Associates values with source counterparts.
10638 * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
10639 */
10640 function baseMergeDeep(object, source, key, mergeFunc, customizer, stackA, stackB) {
10641 var length = stackA.length,
10642 srcValue = source[key];
10643
10644 while (length--) {
10645 if (stackA[length] == srcValue) {
10646 object[key] = stackB[length];
10647 return;
10648 }
10649 }
10650 var value = object[key],
10651 result = customizer ? customizer(value, srcValue, key, object, source) : undefined,
10652 isCommon = result === undefined;
10653
10654 if (isCommon) {
10655 result = srcValue;
10656 if (isArrayLike(srcValue) && (isArray(srcValue) || isTypedArray(srcValue))) {
10657 result = isArray(value)
10658 ? value
10659 : (isArrayLike(value) ? arrayCopy(value) : []);
10660 }
10661 else if (isPlainObject(srcValue) || isArguments(srcValue)) {
10662 result = isArguments(value)
10663 ? toPlainObject(value)
10664 : (isPlainObject(value) ? value : {});
10665 }
10666 else {
10667 isCommon = false;
10668 }
10669 }
10670 // Add the source value to the stack of traversed objects and associate
10671 // it with its merged value.
10672 stackA.push(srcValue);
10673 stackB.push(result);
10674
10675 if (isCommon) {
10676 // Recursively merge objects and arrays (susceptible to call stack limits).
10677 object[key] = mergeFunc(result, srcValue, customizer, stackA, stackB);
10678 } else if (result === result ? (result !== value) : (value === value)) {
10679 object[key] = result;
10680 }
10681 }
10682
10683 /**
10684 * The base implementation of `_.property` without support for deep paths.
10685 *
10686 * @private
10687 * @param {string} key The key of the property to get.
10688 * @returns {Function} Returns the new function.
10689 */
10690 function baseProperty(key) {
10691 return function(object) {
10692 return object == null ? undefined : object[key];
10693 };
10694 }
10695
10696 /**
10697 * A specialized version of `baseProperty` which supports deep paths.
10698 *
10699 * @private
10700 * @param {Array|string} path The path of the property to get.
10701 * @returns {Function} Returns the new function.
10702 */
10703 function basePropertyDeep(path) {
10704 var pathKey = (path + '');
10705 path = toPath(path);
10706 return function(object) {
10707 return baseGet(object, path, pathKey);
10708 };
10709 }
10710
10711 /**
10712 * The base implementation of `_.pullAt` without support for individual
10713 * index arguments and capturing the removed elements.
10714 *
10715 * @private
10716 * @param {Array} array The array to modify.
10717 * @param {number[]} indexes The indexes of elements to remove.
10718 * @returns {Array} Returns `array`.
10719 */
10720 function basePullAt(array, indexes) {
10721 var length = array ? indexes.length : 0;
10722 while (length--) {
10723 var index = indexes[length];
10724 if (index != previous && isIndex(index)) {
10725 var previous = index;
10726 splice.call(array, index, 1);
10727 }
10728 }
10729 return array;
10730 }
10731
10732 /**
10733 * The base implementation of `_.random` without support for argument juggling
10734 * and returning floating-point numbers.
10735 *
10736 * @private
10737 * @param {number} min The minimum possible value.
10738 * @param {number} max The maximum possible value.
10739 * @returns {number} Returns the random number.
10740 */
10741 function baseRandom(min, max) {
10742 return min + nativeFloor(nativeRandom() * (max - min + 1));
10743 }
10744
10745 /**
10746 * The base implementation of `_.reduce` and `_.reduceRight` without support
10747 * for callback shorthands and `this` binding, which iterates over `collection`
10748 * using the provided `eachFunc`.
10749 *
10750 * @private
10751 * @param {Array|Object|string} collection The collection to iterate over.
10752 * @param {Function} iteratee The function invoked per iteration.
10753 * @param {*} accumulator The initial value.
10754 * @param {boolean} initFromCollection Specify using the first or last element
10755 * of `collection` as the initial value.
10756 * @param {Function} eachFunc The function to iterate over `collection`.
10757 * @returns {*} Returns the accumulated value.
10758 */
10759 function baseReduce(collection, iteratee, accumulator, initFromCollection, eachFunc) {
10760 eachFunc(collection, function(value, index, collection) {
10761 accumulator = initFromCollection
10762 ? (initFromCollection = false, value)
10763 : iteratee(accumulator, value, index, collection);
10764 });
10765 return accumulator;
10766 }
10767
10768 /**
10769 * The base implementation of `setData` without support for hot loop detection.
10770 *
10771 * @private
10772 * @param {Function} func The function to associate metadata with.
10773 * @param {*} data The metadata.
10774 * @returns {Function} Returns `func`.
10775 */
10776 var baseSetData = !metaMap ? identity : function(func, data) {
10777 metaMap.set(func, data);
10778 return func;
10779 };
10780
10781 /**
10782 * The base implementation of `_.slice` without an iteratee call guard.
10783 *
10784 * @private
10785 * @param {Array} array The array to slice.
10786 * @param {number} [start=0] The start position.
10787 * @param {number} [end=array.length] The end position.
10788 * @returns {Array} Returns the slice of `array`.
10789 */
10790 function baseSlice(array, start, end) {
10791 var index = -1,
10792 length = array.length;
10793
10794 start = start == null ? 0 : (+start || 0);
10795 if (start < 0) {
10796 start = -start > length ? 0 : (length + start);
10797 }
10798 end = (end === undefined || end > length) ? length : (+end || 0);
10799 if (end < 0) {
10800 end += length;
10801 }
10802 length = start > end ? 0 : ((end - start) >>> 0);
10803 start >>>= 0;
10804
10805 var result = Array(length);
10806 while (++index < length) {
10807 result[index] = array[index + start];
10808 }
10809 return result;
10810 }
10811
10812 /**
10813 * The base implementation of `_.some` without support for callback shorthands
10814 * and `this` binding.
10815 *
10816 * @private
10817 * @param {Array|Object|string} collection The collection to iterate over.
10818 * @param {Function} predicate The function invoked per iteration.
10819 * @returns {boolean} Returns `true` if any element passes the predicate check,
10820 * else `false`.
10821 */
10822 function baseSome(collection, predicate) {
10823 var result;
10824
10825 baseEach(collection, function(value, index, collection) {
10826 result = predicate(value, index, collection);
10827 return !result;
10828 });
10829 return !!result;
10830 }
10831
10832 /**
10833 * The base implementation of `_.sortBy` which uses `comparer` to define
10834 * the sort order of `array` and replaces criteria objects with their
10835 * corresponding values.
10836 *
10837 * @private
10838 * @param {Array} array The array to sort.
10839 * @param {Function} comparer The function to define sort order.
10840 * @returns {Array} Returns `array`.
10841 */
10842 function baseSortBy(array, comparer) {
10843 var length = array.length;
10844
10845 array.sort(comparer);
10846 while (length--) {
10847 array[length] = array[length].value;
10848 }
10849 return array;
10850 }
10851
10852 /**
10853 * The base implementation of `_.sortByOrder` without param guards.
10854 *
10855 * @private
10856 * @param {Array|Object|string} collection The collection to iterate over.
10857 * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by.
10858 * @param {boolean[]} orders The sort orders of `iteratees`.
10859 * @returns {Array} Returns the new sorted array.
10860 */
10861 function baseSortByOrder(collection, iteratees, orders) {
10862 var callback = getCallback(),
10863 index = -1;
10864
10865 iteratees = arrayMap(iteratees, function(iteratee) { return callback(iteratee); });
10866
10867 var result = baseMap(collection, function(value) {
10868 var criteria = arrayMap(iteratees, function(iteratee) { return iteratee(value); });
10869 return { 'criteria': criteria, 'index': ++index, 'value': value };
10870 });
10871
10872 return baseSortBy(result, function(object, other) {
10873 return compareMultiple(object, other, orders);
10874 });
10875 }
10876
10877 /**
10878 * The base implementation of `_.sum` without support for callback shorthands
10879 * and `this` binding.
10880 *
10881 * @private
10882 * @param {Array|Object|string} collection The collection to iterate over.
10883 * @param {Function} iteratee The function invoked per iteration.
10884 * @returns {number} Returns the sum.
10885 */
10886 function baseSum(collection, iteratee) {
10887 var result = 0;
10888 baseEach(collection, function(value, index, collection) {
10889 result += +iteratee(value, index, collection) || 0;
10890 });
10891 return result;
10892 }
10893
10894 /**
10895 * The base implementation of `_.uniq` without support for callback shorthands
10896 * and `this` binding.
10897 *
10898 * @private
10899 * @param {Array} array The array to inspect.
10900 * @param {Function} [iteratee] The function invoked per iteration.
10901 * @returns {Array} Returns the new duplicate-value-free array.
10902 */
10903 function baseUniq(array, iteratee) {
10904 var index = -1,
10905 indexOf = getIndexOf(),
10906 length = array.length,
10907 isCommon = indexOf == baseIndexOf,
10908 isLarge = isCommon && length >= LARGE_ARRAY_SIZE,
10909 seen = isLarge ? createCache() : null,
10910 result = [];
10911
10912 if (seen) {
10913 indexOf = cacheIndexOf;
10914 isCommon = false;
10915 } else {
10916 isLarge = false;
10917 seen = iteratee ? [] : result;
10918 }
10919 outer:
10920 while (++index < length) {
10921 var value = array[index],
10922 computed = iteratee ? iteratee(value, index, array) : value;
10923
10924 if (isCommon && value === value) {
10925 var seenIndex = seen.length;
10926 while (seenIndex--) {
10927 if (seen[seenIndex] === computed) {
10928 continue outer;
10929 }
10930 }
10931 if (iteratee) {
10932 seen.push(computed);
10933 }
10934 result.push(value);
10935 }
10936 else if (indexOf(seen, computed, 0) < 0) {
10937 if (iteratee || isLarge) {
10938 seen.push(computed);
10939 }
10940 result.push(value);
10941 }
10942 }
10943 return result;
10944 }
10945
10946 /**
10947 * The base implementation of `_.values` and `_.valuesIn` which creates an
10948 * array of `object` property values corresponding to the property names
10949 * of `props`.
10950 *
10951 * @private
10952 * @param {Object} object The object to query.
10953 * @param {Array} props The property names to get values for.
10954 * @returns {Object} Returns the array of property values.
10955 */
10956 function baseValues(object, props) {
10957 var index = -1,
10958 length = props.length,
10959 result = Array(length);
10960
10961 while (++index < length) {
10962 result[index] = object[props[index]];
10963 }
10964 return result;
10965 }
10966
10967 /**
10968 * The base implementation of `_.dropRightWhile`, `_.dropWhile`, `_.takeRightWhile`,
10969 * and `_.takeWhile` without support for callback shorthands and `this` binding.
10970 *
10971 * @private
10972 * @param {Array} array The array to query.
10973 * @param {Function} predicate The function invoked per iteration.
10974 * @param {boolean} [isDrop] Specify dropping elements instead of taking them.
10975 * @param {boolean} [fromRight] Specify iterating from right to left.
10976 * @returns {Array} Returns the slice of `array`.
10977 */
10978 function baseWhile(array, predicate, isDrop, fromRight) {
10979 var length = array.length,
10980 index = fromRight ? length : -1;
10981
10982 while ((fromRight ? index-- : ++index < length) && predicate(array[index], index, array)) {}
10983 return isDrop
10984 ? baseSlice(array, (fromRight ? 0 : index), (fromRight ? index + 1 : length))
10985 : baseSlice(array, (fromRight ? index + 1 : 0), (fromRight ? length : index));
10986 }
10987
10988 /**
10989 * The base implementation of `wrapperValue` which returns the result of
10990 * performing a sequence of actions on the unwrapped `value`, where each
10991 * successive action is supplied the return value of the previous.
10992 *
10993 * @private
10994 * @param {*} value The unwrapped value.
10995 * @param {Array} actions Actions to peform to resolve the unwrapped value.
10996 * @returns {*} Returns the resolved value.
10997 */
10998 function baseWrapperValue(value, actions) {
10999 var result = value;
11000 if (result instanceof LazyWrapper) {
11001 result = result.value();
11002 }
11003 var index = -1,
11004 length = actions.length;
11005
11006 while (++index < length) {
11007 var action = actions[index];
11008 result = action.func.apply(action.thisArg, arrayPush([result], action.args));
11009 }
11010 return result;
11011 }
11012
11013 /**
11014 * Performs a binary search of `array` to determine the index at which `value`
11015 * should be inserted into `array` in order to maintain its sort order.
11016 *
11017 * @private
11018 * @param {Array} array The sorted array to inspect.
11019 * @param {*} value The value to evaluate.
11020 * @param {boolean} [retHighest] Specify returning the highest qualified index.
11021 * @returns {number} Returns the index at which `value` should be inserted
11022 * into `array`.
11023 */
11024 function binaryIndex(array, value, retHighest) {
11025 var low = 0,
11026 high = array ? array.length : low;
11027
11028 if (typeof value == 'number' && value === value && high <= HALF_MAX_ARRAY_LENGTH) {
11029 while (low < high) {
11030 var mid = (low + high) >>> 1,
11031 computed = array[mid];
11032
11033 if ((retHighest ? (computed <= value) : (computed < value)) && computed !== null) {
11034 low = mid + 1;
11035 } else {
11036 high = mid;
11037 }
11038 }
11039 return high;
11040 }
11041 return binaryIndexBy(array, value, identity, retHighest);
11042 }
11043
11044 /**
11045 * This function is like `binaryIndex` except that it invokes `iteratee` for
11046 * `value` and each element of `array` to compute their sort ranking. The
11047 * iteratee is invoked with one argument; (value).
11048 *
11049 * @private
11050 * @param {Array} array The sorted array to inspect.
11051 * @param {*} value The value to evaluate.
11052 * @param {Function} iteratee The function invoked per iteration.
11053 * @param {boolean} [retHighest] Specify returning the highest qualified index.
11054 * @returns {number} Returns the index at which `value` should be inserted
11055 * into `array`.
11056 */
11057 function binaryIndexBy(array, value, iteratee, retHighest) {
11058 value = iteratee(value);
11059
11060 var low = 0,
11061 high = array ? array.length : 0,
11062 valIsNaN = value !== value,
11063 valIsNull = value === null,
11064 valIsUndef = value === undefined;
11065
11066 while (low < high) {
11067 var mid = nativeFloor((low + high) / 2),
11068 computed = iteratee(array[mid]),
11069 isDef = computed !== undefined,
11070 isReflexive = computed === computed;
11071
11072 if (valIsNaN) {
11073 var setLow = isReflexive || retHighest;
11074 } else if (valIsNull) {
11075 setLow = isReflexive && isDef && (retHighest || computed != null);
11076 } else if (valIsUndef) {
11077 setLow = isReflexive && (retHighest || isDef);
11078 } else if (computed == null) {
11079 setLow = false;
11080 } else {
11081 setLow = retHighest ? (computed <= value) : (computed < value);
11082 }
11083 if (setLow) {
11084 low = mid + 1;
11085 } else {
11086 high = mid;
11087 }
11088 }
11089 return nativeMin(high, MAX_ARRAY_INDEX);
11090 }
11091
11092 /**
11093 * A specialized version of `baseCallback` which only supports `this` binding
11094 * and specifying the number of arguments to provide to `func`.
11095 *
11096 * @private
11097 * @param {Function} func The function to bind.
11098 * @param {*} thisArg The `this` binding of `func`.
11099 * @param {number} [argCount] The number of arguments to provide to `func`.
11100 * @returns {Function} Returns the callback.
11101 */
11102 function bindCallback(func, thisArg, argCount) {
11103 if (typeof func != 'function') {
11104 return identity;
11105 }
11106 if (thisArg === undefined) {
11107 return func;
11108 }
11109 switch (argCount) {
11110 case 1: return function(value) {
11111 return func.call(thisArg, value);
11112 };
11113 case 3: return function(value, index, collection) {
11114 return func.call(thisArg, value, index, collection);
11115 };
11116 case 4: return function(accumulator, value, index, collection) {
11117 return func.call(thisArg, accumulator, value, index, collection);
11118 };
11119 case 5: return function(value, other, key, object, source) {
11120 return func.call(thisArg, value, other, key, object, source);
11121 };
11122 }
11123 return function() {
11124 return func.apply(thisArg, arguments);
11125 };
11126 }
11127
11128 /**
11129 * Creates a clone of the given array buffer.
11130 *
11131 * @private
11132 * @param {ArrayBuffer} buffer The array buffer to clone.
11133 * @returns {ArrayBuffer} Returns the cloned array buffer.
11134 */
11135 function bufferClone(buffer) {
11136 var result = new ArrayBuffer(buffer.byteLength),
11137 view = new Uint8Array(result);
11138
11139 view.set(new Uint8Array(buffer));
11140 return result;
11141 }
11142
11143 /**
11144 * Creates an array that is the composition of partially applied arguments,
11145 * placeholders, and provided arguments into a single array of arguments.
11146 *
11147 * @private
11148 * @param {Array|Object} args The provided arguments.
11149 * @param {Array} partials The arguments to prepend to those provided.
11150 * @param {Array} holders The `partials` placeholder indexes.
11151 * @returns {Array} Returns the new array of composed arguments.
11152 */
11153 function composeArgs(args, partials, holders) {
11154 var holdersLength = holders.length,
11155 argsIndex = -1,
11156 argsLength = nativeMax(args.length - holdersLength, 0),
11157 leftIndex = -1,
11158 leftLength = partials.length,
11159 result = Array(leftLength + argsLength);
11160
11161 while (++leftIndex < leftLength) {
11162 result[leftIndex] = partials[leftIndex];
11163 }
11164 while (++argsIndex < holdersLength) {
11165 result[holders[argsIndex]] = args[argsIndex];
11166 }
11167 while (argsLength--) {
11168 result[leftIndex++] = args[argsIndex++];
11169 }
11170 return result;
11171 }
11172
11173 /**
11174 * This function is like `composeArgs` except that the arguments composition
11175 * is tailored for `_.partialRight`.
11176 *
11177 * @private
11178 * @param {Array|Object} args The provided arguments.
11179 * @param {Array} partials The arguments to append to those provided.
11180 * @param {Array} holders The `partials` placeholder indexes.
11181 * @returns {Array} Returns the new array of composed arguments.
11182 */
11183 function composeArgsRight(args, partials, holders) {
11184 var holdersIndex = -1,
11185 holdersLength = holders.length,
11186 argsIndex = -1,
11187 argsLength = nativeMax(args.length - holdersLength, 0),
11188 rightIndex = -1,
11189 rightLength = partials.length,
11190 result = Array(argsLength + rightLength);
11191
11192 while (++argsIndex < argsLength) {
11193 result[argsIndex] = args[argsIndex];
11194 }
11195 var offset = argsIndex;
11196 while (++rightIndex < rightLength) {
11197 result[offset + rightIndex] = partials[rightIndex];
11198 }
11199 while (++holdersIndex < holdersLength) {
11200 result[offset + holders[holdersIndex]] = args[argsIndex++];
11201 }
11202 return result;
11203 }
11204
11205 /**
11206 * Creates a `_.countBy`, `_.groupBy`, `_.indexBy`, or `_.partition` function.
11207 *
11208 * @private
11209 * @param {Function} setter The function to set keys and values of the accumulator object.
11210 * @param {Function} [initializer] The function to initialize the accumulator object.
11211 * @returns {Function} Returns the new aggregator function.
11212 */
11213 function createAggregator(setter, initializer) {
11214 return function(collection, iteratee, thisArg) {
11215 var result = initializer ? initializer() : {};
11216 iteratee = getCallback(iteratee, thisArg, 3);
11217
11218 if (isArray(collection)) {
11219 var index = -1,
11220 length = collection.length;
11221
11222 while (++index < length) {
11223 var value = collection[index];
11224 setter(result, value, iteratee(value, index, collection), collection);
11225 }
11226 } else {
11227 baseEach(collection, function(value, key, collection) {
11228 setter(result, value, iteratee(value, key, collection), collection);
11229 });
11230 }
11231 return result;
11232 };
11233 }
11234
11235 /**
11236 * Creates a `_.assign`, `_.defaults`, or `_.merge` function.
11237 *
11238 * @private
11239 * @param {Function} assigner The function to assign values.
11240 * @returns {Function} Returns the new assigner function.
11241 */
11242 function createAssigner(assigner) {
11243 return restParam(function(object, sources) {
11244 var index = -1,
11245 length = object == null ? 0 : sources.length,
11246 customizer = length > 2 ? sources[length - 2] : undefined,
11247 guard = length > 2 ? sources[2] : undefined,
11248 thisArg = length > 1 ? sources[length - 1] : undefined;
11249
11250 if (typeof customizer == 'function') {
11251 customizer = bindCallback(customizer, thisArg, 5);
11252 length -= 2;
11253 } else {
11254 customizer = typeof thisArg == 'function' ? thisArg : undefined;
11255 length -= (customizer ? 1 : 0);
11256 }
11257 if (guard && isIterateeCall(sources[0], sources[1], guard)) {
11258 customizer = length < 3 ? undefined : customizer;
11259 length = 1;
11260 }
11261 while (++index < length) {
11262 var source = sources[index];
11263 if (source) {
11264 assigner(object, source, customizer);
11265 }
11266 }
11267 return object;
11268 });
11269 }
11270
11271 /**
11272 * Creates a `baseEach` or `baseEachRight` function.
11273 *
11274 * @private
11275 * @param {Function} eachFunc The function to iterate over a collection.
11276 * @param {boolean} [fromRight] Specify iterating from right to left.
11277 * @returns {Function} Returns the new base function.
11278 */
11279 function createBaseEach(eachFunc, fromRight) {
11280 return function(collection, iteratee) {
11281 var length = collection ? getLength(collection) : 0;
11282 if (!isLength(length)) {
11283 return eachFunc(collection, iteratee);
11284 }
11285 var index = fromRight ? length : -1,
11286 iterable = toObject(collection);
11287
11288 while ((fromRight ? index-- : ++index < length)) {
11289 if (iteratee(iterable[index], index, iterable) === false) {
11290 break;
11291 }
11292 }
11293 return collection;
11294 };
11295 }
11296
11297 /**
11298 * Creates a base function for `_.forIn` or `_.forInRight`.
11299 *
11300 * @private
11301 * @param {boolean} [fromRight] Specify iterating from right to left.
11302 * @returns {Function} Returns the new base function.
11303 */
11304 function createBaseFor(fromRight) {
11305 return function(object, iteratee, keysFunc) {
11306 var iterable = toObject(object),
11307 props = keysFunc(object),
11308 length = props.length,
11309 index = fromRight ? length : -1;
11310
11311 while ((fromRight ? index-- : ++index < length)) {
11312 var key = props[index];
11313 if (iteratee(iterable[key], key, iterable) === false) {
11314 break;
11315 }
11316 }
11317 return object;
11318 };
11319 }
11320
11321 /**
11322 * Creates a function that wraps `func` and invokes it with the `this`
11323 * binding of `thisArg`.
11324 *
11325 * @private
11326 * @param {Function} func The function to bind.
11327 * @param {*} [thisArg] The `this` binding of `func`.
11328 * @returns {Function} Returns the new bound function.
11329 */
11330 function createBindWrapper(func, thisArg) {
11331 var Ctor = createCtorWrapper(func);
11332
11333 function wrapper() {
11334 var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;
11335 return fn.apply(thisArg, arguments);
11336 }
11337 return wrapper;
11338 }
11339
11340 /**
11341 * Creates a `Set` cache object to optimize linear searches of large arrays.
11342 *
11343 * @private
11344 * @param {Array} [values] The values to cache.
11345 * @returns {null|Object} Returns the new cache object if `Set` is supported, else `null`.
11346 */
11347 function createCache(values) {
11348 return (nativeCreate && Set) ? new SetCache(values) : null;
11349 }
11350
11351 /**
11352 * Creates a function that produces compound words out of the words in a
11353 * given string.
11354 *
11355 * @private
11356 * @param {Function} callback The function to combine each word.
11357 * @returns {Function} Returns the new compounder function.
11358 */
11359 function createCompounder(callback) {
11360 return function(string) {
11361 var index = -1,
11362 array = words(deburr(string)),
11363 length = array.length,
11364 result = '';
11365
11366 while (++index < length) {
11367 result = callback(result, array[index], index);
11368 }
11369 return result;
11370 };
11371 }
11372
11373 /**
11374 * Creates a function that produces an instance of `Ctor` regardless of
11375 * whether it was invoked as part of a `new` expression or by `call` or `apply`.
11376 *
11377 * @private
11378 * @param {Function} Ctor The constructor to wrap.
11379 * @returns {Function} Returns the new wrapped function.
11380 */
11381 function createCtorWrapper(Ctor) {
11382 return function() {
11383 // Use a `switch` statement to work with class constructors.
11384 // See http://ecma-international.org/ecma-262/6.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist
11385 // for more details.
11386 var args = arguments;
11387 switch (args.length) {
11388 case 0: return new Ctor;
11389 case 1: return new Ctor(args[0]);
11390 case 2: return new Ctor(args[0], args[1]);
11391 case 3: return new Ctor(args[0], args[1], args[2]);
11392 case 4: return new Ctor(args[0], args[1], args[2], args[3]);
11393 case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]);
11394 case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]);
11395 case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]);
11396 }
11397 var thisBinding = baseCreate(Ctor.prototype),
11398 result = Ctor.apply(thisBinding, args);
11399
11400 // Mimic the constructor's `return` behavior.
11401 // See https://es5.github.io/#x13.2.2 for more details.
11402 return isObject(result) ? result : thisBinding;
11403 };
11404 }
11405
11406 /**
11407 * Creates a `_.curry` or `_.curryRight` function.
11408 *
11409 * @private
11410 * @param {boolean} flag The curry bit flag.
11411 * @returns {Function} Returns the new curry function.
11412 */
11413 function createCurry(flag) {
11414 function curryFunc(func, arity, guard) {
11415 if (guard && isIterateeCall(func, arity, guard)) {
11416 arity = undefined;
11417 }
11418 var result = createWrapper(func, flag, undefined, undefined, undefined, undefined, undefined, arity);
11419 result.placeholder = curryFunc.placeholder;
11420 return result;
11421 }
11422 return curryFunc;
11423 }
11424
11425 /**
11426 * Creates a `_.defaults` or `_.defaultsDeep` function.
11427 *
11428 * @private
11429 * @param {Function} assigner The function to assign values.
11430 * @param {Function} customizer The function to customize assigned values.
11431 * @returns {Function} Returns the new defaults function.
11432 */
11433 function createDefaults(assigner, customizer) {
11434 return restParam(function(args) {
11435 var object = args[0];
11436 if (object == null) {
11437 return object;
11438 }
11439 args.push(customizer);
11440 return assigner.apply(undefined, args);
11441 });
11442 }
11443
11444 /**
11445 * Creates a `_.max` or `_.min` function.
11446 *
11447 * @private
11448 * @param {Function} comparator The function used to compare values.
11449 * @param {*} exValue The initial extremum value.
11450 * @returns {Function} Returns the new extremum function.
11451 */
11452 function createExtremum(comparator, exValue) {
11453 return function(collection, iteratee, thisArg) {
11454 if (thisArg && isIterateeCall(collection, iteratee, thisArg)) {
11455 iteratee = undefined;
11456 }
11457 iteratee = getCallback(iteratee, thisArg, 3);
11458 if (iteratee.length == 1) {
11459 collection = isArray(collection) ? collection : toIterable(collection);
11460 var result = arrayExtremum(collection, iteratee, comparator, exValue);
11461 if (!(collection.length && result === exValue)) {
11462 return result;
11463 }
11464 }
11465 return baseExtremum(collection, iteratee, comparator, exValue);
11466 };
11467 }
11468
11469 /**
11470 * Creates a `_.find` or `_.findLast` function.
11471 *
11472 * @private
11473 * @param {Function} eachFunc The function to iterate over a collection.
11474 * @param {boolean} [fromRight] Specify iterating from right to left.
11475 * @returns {Function} Returns the new find function.
11476 */
11477 function createFind(eachFunc, fromRight) {
11478 return function(collection, predicate, thisArg) {
11479 predicate = getCallback(predicate, thisArg, 3);
11480 if (isArray(collection)) {
11481 var index = baseFindIndex(collection, predicate, fromRight);
11482 return index > -1 ? collection[index] : undefined;
11483 }
11484 return baseFind(collection, predicate, eachFunc);
11485 };
11486 }
11487
11488 /**
11489 * Creates a `_.findIndex` or `_.findLastIndex` function.
11490 *
11491 * @private
11492 * @param {boolean} [fromRight] Specify iterating from right to left.
11493 * @returns {Function} Returns the new find function.
11494 */
11495 function createFindIndex(fromRight) {
11496 return function(array, predicate, thisArg) {
11497 if (!(array && array.length)) {
11498 return -1;
11499 }
11500 predicate = getCallback(predicate, thisArg, 3);
11501 return baseFindIndex(array, predicate, fromRight);
11502 };
11503 }
11504
11505 /**
11506 * Creates a `_.findKey` or `_.findLastKey` function.
11507 *
11508 * @private
11509 * @param {Function} objectFunc The function to iterate over an object.
11510 * @returns {Function} Returns the new find function.
11511 */
11512 function createFindKey(objectFunc) {
11513 return function(object, predicate, thisArg) {
11514 predicate = getCallback(predicate, thisArg, 3);
11515 return baseFind(object, predicate, objectFunc, true);
11516 };
11517 }
11518
11519 /**
11520 * Creates a `_.flow` or `_.flowRight` function.
11521 *
11522 * @private
11523 * @param {boolean} [fromRight] Specify iterating from right to left.
11524 * @returns {Function} Returns the new flow function.
11525 */
11526 function createFlow(fromRight) {
11527 return function() {
11528 var wrapper,
11529 length = arguments.length,
11530 index = fromRight ? length : -1,
11531 leftIndex = 0,
11532 funcs = Array(length);
11533
11534 while ((fromRight ? index-- : ++index < length)) {
11535 var func = funcs[leftIndex++] = arguments[index];
11536 if (typeof func != 'function') {
11537 throw new TypeError(FUNC_ERROR_TEXT);
11538 }
11539 if (!wrapper && LodashWrapper.prototype.thru && getFuncName(func) == 'wrapper') {
11540 wrapper = new LodashWrapper([], true);
11541 }
11542 }
11543 index = wrapper ? -1 : length;
11544 while (++index < length) {
11545 func = funcs[index];
11546
11547 var funcName = getFuncName(func),
11548 data = funcName == 'wrapper' ? getData(func) : undefined;
11549
11550 if (data && isLaziable(data[0]) && data[1] == (ARY_FLAG | CURRY_FLAG | PARTIAL_FLAG | REARG_FLAG) && !data[4].length && data[9] == 1) {
11551 wrapper = wrapper[getFuncName(data[0])].apply(wrapper, data[3]);
11552 } else {
11553 wrapper = (func.length == 1 && isLaziable(func)) ? wrapper[funcName]() : wrapper.thru(func);
11554 }
11555 }
11556 return function() {
11557 var args = arguments,
11558 value = args[0];
11559
11560 if (wrapper && args.length == 1 && isArray(value) && value.length >= LARGE_ARRAY_SIZE) {
11561 return wrapper.plant(value).value();
11562 }
11563 var index = 0,
11564 result = length ? funcs[index].apply(this, args) : value;
11565
11566 while (++index < length) {
11567 result = funcs[index].call(this, result);
11568 }
11569 return result;
11570 };
11571 };
11572 }
11573
11574 /**
11575 * Creates a function for `_.forEach` or `_.forEachRight`.
11576 *
11577 * @private
11578 * @param {Function} arrayFunc The function to iterate over an array.
11579 * @param {Function} eachFunc The function to iterate over a collection.
11580 * @returns {Function} Returns the new each function.
11581 */
11582 function createForEach(arrayFunc, eachFunc) {
11583 return function(collection, iteratee, thisArg) {
11584 return (typeof iteratee == 'function' && thisArg === undefined && isArray(collection))
11585 ? arrayFunc(collection, iteratee)
11586 : eachFunc(collection, bindCallback(iteratee, thisArg, 3));
11587 };
11588 }
11589
11590 /**
11591 * Creates a function for `_.forIn` or `_.forInRight`.
11592 *
11593 * @private
11594 * @param {Function} objectFunc The function to iterate over an object.
11595 * @returns {Function} Returns the new each function.
11596 */
11597 function createForIn(objectFunc) {
11598 return function(object, iteratee, thisArg) {
11599 if (typeof iteratee != 'function' || thisArg !== undefined) {
11600 iteratee = bindCallback(iteratee, thisArg, 3);
11601 }
11602 return objectFunc(object, iteratee, keysIn);
11603 };
11604 }
11605
11606 /**
11607 * Creates a function for `_.forOwn` or `_.forOwnRight`.
11608 *
11609 * @private
11610 * @param {Function} objectFunc The function to iterate over an object.
11611 * @returns {Function} Returns the new each function.
11612 */
11613 function createForOwn(objectFunc) {
11614 return function(object, iteratee, thisArg) {
11615 if (typeof iteratee != 'function' || thisArg !== undefined) {
11616 iteratee = bindCallback(iteratee, thisArg, 3);
11617 }
11618 return objectFunc(object, iteratee);
11619 };
11620 }
11621
11622 /**
11623 * Creates a function for `_.mapKeys` or `_.mapValues`.
11624 *
11625 * @private
11626 * @param {boolean} [isMapKeys] Specify mapping keys instead of values.
11627 * @returns {Function} Returns the new map function.
11628 */
11629 function createObjectMapper(isMapKeys) {
11630 return function(object, iteratee, thisArg) {
11631 var result = {};
11632 iteratee = getCallback(iteratee, thisArg, 3);
11633
11634 baseForOwn(object, function(value, key, object) {
11635 var mapped = iteratee(value, key, object);
11636 key = isMapKeys ? mapped : key;
11637 value = isMapKeys ? value : mapped;
11638 result[key] = value;
11639 });
11640 return result;
11641 };
11642 }
11643
11644 /**
11645 * Creates a function for `_.padLeft` or `_.padRight`.
11646 *
11647 * @private
11648 * @param {boolean} [fromRight] Specify padding from the right.
11649 * @returns {Function} Returns the new pad function.
11650 */
11651 function createPadDir(fromRight) {
11652 return function(string, length, chars) {
11653 string = baseToString(string);
11654 return (fromRight ? string : '') + createPadding(string, length, chars) + (fromRight ? '' : string);
11655 };
11656 }
11657
11658 /**
11659 * Creates a `_.partial` or `_.partialRight` function.
11660 *
11661 * @private
11662 * @param {boolean} flag The partial bit flag.
11663 * @returns {Function} Returns the new partial function.
11664 */
11665 function createPartial(flag) {
11666 var partialFunc = restParam(function(func, partials) {
11667 var holders = replaceHolders(partials, partialFunc.placeholder);
11668 return createWrapper(func, flag, undefined, partials, holders);
11669 });
11670 return partialFunc;
11671 }
11672
11673 /**
11674 * Creates a function for `_.reduce` or `_.reduceRight`.
11675 *
11676 * @private
11677 * @param {Function} arrayFunc The function to iterate over an array.
11678 * @param {Function} eachFunc The function to iterate over a collection.
11679 * @returns {Function} Returns the new each function.
11680 */
11681 function createReduce(arrayFunc, eachFunc) {
11682 return function(collection, iteratee, accumulator, thisArg) {
11683 var initFromArray = arguments.length < 3;
11684 return (typeof iteratee == 'function' && thisArg === undefined && isArray(collection))
11685 ? arrayFunc(collection, iteratee, accumulator, initFromArray)
11686 : baseReduce(collection, getCallback(iteratee, thisArg, 4), accumulator, initFromArray, eachFunc);
11687 };
11688 }
11689
11690 /**
11691 * Creates a function that wraps `func` and invokes it with optional `this`
11692 * binding of, partial application, and currying.
11693 *
11694 * @private
11695 * @param {Function|string} func The function or method name to reference.
11696 * @param {number} bitmask The bitmask of flags. See `createWrapper` for more details.
11697 * @param {*} [thisArg] The `this` binding of `func`.
11698 * @param {Array} [partials] The arguments to prepend to those provided to the new function.
11699 * @param {Array} [holders] The `partials` placeholder indexes.
11700 * @param {Array} [partialsRight] The arguments to append to those provided to the new function.
11701 * @param {Array} [holdersRight] The `partialsRight` placeholder indexes.
11702 * @param {Array} [argPos] The argument positions of the new function.
11703 * @param {number} [ary] The arity cap of `func`.
11704 * @param {number} [arity] The arity of `func`.
11705 * @returns {Function} Returns the new wrapped function.
11706 */
11707 function createHybridWrapper(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) {
11708 var isAry = bitmask & ARY_FLAG,
11709 isBind = bitmask & BIND_FLAG,
11710 isBindKey = bitmask & BIND_KEY_FLAG,
11711 isCurry = bitmask & CURRY_FLAG,
11712 isCurryBound = bitmask & CURRY_BOUND_FLAG,
11713 isCurryRight = bitmask & CURRY_RIGHT_FLAG,
11714 Ctor = isBindKey ? undefined : createCtorWrapper(func);
11715
11716 function wrapper() {
11717 // Avoid `arguments` object use disqualifying optimizations by
11718 // converting it to an array before providing it to other functions.
11719 var length = arguments.length,
11720 index = length,
11721 args = Array(length);
11722
11723 while (index--) {
11724 args[index] = arguments[index];
11725 }
11726 if (partials) {
11727 args = composeArgs(args, partials, holders);
11728 }
11729 if (partialsRight) {
11730 args = composeArgsRight(args, partialsRight, holdersRight);
11731 }
11732 if (isCurry || isCurryRight) {
11733 var placeholder = wrapper.placeholder,
11734 argsHolders = replaceHolders(args, placeholder);
11735
11736 length -= argsHolders.length;
11737 if (length < arity) {
11738 var newArgPos = argPos ? arrayCopy(argPos) : undefined,
11739 newArity = nativeMax(arity - length, 0),
11740 newsHolders = isCurry ? argsHolders : undefined,
11741 newHoldersRight = isCurry ? undefined : argsHolders,
11742 newPartials = isCurry ? args : undefined,
11743 newPartialsRight = isCurry ? undefined : args;
11744
11745 bitmask |= (isCurry ? PARTIAL_FLAG : PARTIAL_RIGHT_FLAG);
11746 bitmask &= ~(isCurry ? PARTIAL_RIGHT_FLAG : PARTIAL_FLAG);
11747
11748 if (!isCurryBound) {
11749 bitmask &= ~(BIND_FLAG | BIND_KEY_FLAG);
11750 }
11751 var newData = [func, bitmask, thisArg, newPartials, newsHolders, newPartialsRight, newHoldersRight, newArgPos, ary, newArity],
11752 result = createHybridWrapper.apply(undefined, newData);
11753
11754 if (isLaziable(func)) {
11755 setData(result, newData);
11756 }
11757 result.placeholder = placeholder;
11758 return result;
11759 }
11760 }
11761 var thisBinding = isBind ? thisArg : this,
11762 fn = isBindKey ? thisBinding[func] : func;
11763
11764 if (argPos) {
11765 args = reorder(args, argPos);
11766 }
11767 if (isAry && ary < args.length) {
11768 args.length = ary;
11769 }
11770 if (this && this !== root && this instanceof wrapper) {
11771 fn = Ctor || createCtorWrapper(func);
11772 }
11773 return fn.apply(thisBinding, args);
11774 }
11775 return wrapper;
11776 }
11777
11778 /**
11779 * Creates the padding required for `string` based on the given `length`.
11780 * The `chars` string is truncated if the number of characters exceeds `length`.
11781 *
11782 * @private
11783 * @param {string} string The string to create padding for.
11784 * @param {number} [length=0] The padding length.
11785 * @param {string} [chars=' '] The string used as padding.
11786 * @returns {string} Returns the pad for `string`.
11787 */
11788 function createPadding(string, length, chars) {
11789 var strLength = string.length;
11790 length = +length;
11791
11792 if (strLength >= length || !nativeIsFinite(length)) {
11793 return '';
11794 }
11795 var padLength = length - strLength;
11796 chars = chars == null ? ' ' : (chars + '');
11797 return repeat(chars, nativeCeil(padLength / chars.length)).slice(0, padLength);
11798 }
11799
11800 /**
11801 * Creates a function that wraps `func` and invokes it with the optional `this`
11802 * binding of `thisArg` and the `partials` prepended to those provided to
11803 * the wrapper.
11804 *
11805 * @private
11806 * @param {Function} func The function to partially apply arguments to.
11807 * @param {number} bitmask The bitmask of flags. See `createWrapper` for more details.
11808 * @param {*} thisArg The `this` binding of `func`.
11809 * @param {Array} partials The arguments to prepend to those provided to the new function.
11810 * @returns {Function} Returns the new bound function.
11811 */
11812 function createPartialWrapper(func, bitmask, thisArg, partials) {
11813 var isBind = bitmask & BIND_FLAG,
11814 Ctor = createCtorWrapper(func);
11815
11816 function wrapper() {
11817 // Avoid `arguments` object use disqualifying optimizations by
11818 // converting it to an array before providing it `func`.
11819 var argsIndex = -1,
11820 argsLength = arguments.length,
11821 leftIndex = -1,
11822 leftLength = partials.length,
11823 args = Array(leftLength + argsLength);
11824
11825 while (++leftIndex < leftLength) {
11826 args[leftIndex] = partials[leftIndex];
11827 }
11828 while (argsLength--) {
11829 args[leftIndex++] = arguments[++argsIndex];
11830 }
11831 var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;
11832 return fn.apply(isBind ? thisArg : this, args);
11833 }
11834 return wrapper;
11835 }
11836
11837 /**
11838 * Creates a `_.ceil`, `_.floor`, or `_.round` function.
11839 *
11840 * @private
11841 * @param {string} methodName The name of the `Math` method to use when rounding.
11842 * @returns {Function} Returns the new round function.
11843 */
11844 function createRound(methodName) {
11845 var func = Math[methodName];
11846 return function(number, precision) {
11847 precision = precision === undefined ? 0 : (+precision || 0);
11848 if (precision) {
11849 precision = pow(10, precision);
11850 return func(number * precision) / precision;
11851 }
11852 return func(number);
11853 };
11854 }
11855
11856 /**
11857 * Creates a `_.sortedIndex` or `_.sortedLastIndex` function.
11858 *
11859 * @private
11860 * @param {boolean} [retHighest] Specify returning the highest qualified index.
11861 * @returns {Function} Returns the new index function.
11862 */
11863 function createSortedIndex(retHighest) {
11864 return function(array, value, iteratee, thisArg) {
11865 var callback = getCallback(iteratee);
11866 return (iteratee == null && callback === baseCallback)
11867 ? binaryIndex(array, value, retHighest)
11868 : binaryIndexBy(array, value, callback(iteratee, thisArg, 1), retHighest);
11869 };
11870 }
11871
11872 /**
11873 * Creates a function that either curries or invokes `func` with optional
11874 * `this` binding and partially applied arguments.
11875 *
11876 * @private
11877 * @param {Function|string} func The function or method name to reference.
11878 * @param {number} bitmask The bitmask of flags.
11879 * The bitmask may be composed of the following flags:
11880 * 1 - `_.bind`
11881 * 2 - `_.bindKey`
11882 * 4 - `_.curry` or `_.curryRight` of a bound function
11883 * 8 - `_.curry`
11884 * 16 - `_.curryRight`
11885 * 32 - `_.partial`
11886 * 64 - `_.partialRight`
11887 * 128 - `_.rearg`
11888 * 256 - `_.ary`
11889 * @param {*} [thisArg] The `this` binding of `func`.
11890 * @param {Array} [partials] The arguments to be partially applied.
11891 * @param {Array} [holders] The `partials` placeholder indexes.
11892 * @param {Array} [argPos] The argument positions of the new function.
11893 * @param {number} [ary] The arity cap of `func`.
11894 * @param {number} [arity] The arity of `func`.
11895 * @returns {Function} Returns the new wrapped function.
11896 */
11897 function createWrapper(func, bitmask, thisArg, partials, holders, argPos, ary, arity) {
11898 var isBindKey = bitmask & BIND_KEY_FLAG;
11899 if (!isBindKey && typeof func != 'function') {
11900 throw new TypeError(FUNC_ERROR_TEXT);
11901 }
11902 var length = partials ? partials.length : 0;
11903 if (!length) {
11904 bitmask &= ~(PARTIAL_FLAG | PARTIAL_RIGHT_FLAG);
11905 partials = holders = undefined;
11906 }
11907 length -= (holders ? holders.length : 0);
11908 if (bitmask & PARTIAL_RIGHT_FLAG) {
11909 var partialsRight = partials,
11910 holdersRight = holders;
11911
11912 partials = holders = undefined;
11913 }
11914 var data = isBindKey ? undefined : getData(func),
11915 newData = [func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity];
11916
11917 if (data) {
11918 mergeData(newData, data);
11919 bitmask = newData[1];
11920 arity = newData[9];
11921 }
11922 newData[9] = arity == null
11923 ? (isBindKey ? 0 : func.length)
11924 : (nativeMax(arity - length, 0) || 0);
11925
11926 if (bitmask == BIND_FLAG) {
11927 var result = createBindWrapper(newData[0], newData[2]);
11928 } else if ((bitmask == PARTIAL_FLAG || bitmask == (BIND_FLAG | PARTIAL_FLAG)) && !newData[4].length) {
11929 result = createPartialWrapper.apply(undefined, newData);
11930 } else {
11931 result = createHybridWrapper.apply(undefined, newData);
11932 }
11933 var setter = data ? baseSetData : setData;
11934 return setter(result, newData);
11935 }
11936
11937 /**
11938 * A specialized version of `baseIsEqualDeep` for arrays with support for
11939 * partial deep comparisons.
11940 *
11941 * @private
11942 * @param {Array} array The array to compare.
11943 * @param {Array} other The other array to compare.
11944 * @param {Function} equalFunc The function to determine equivalents of values.
11945 * @param {Function} [customizer] The function to customize comparing arrays.
11946 * @param {boolean} [isLoose] Specify performing partial comparisons.
11947 * @param {Array} [stackA] Tracks traversed `value` objects.
11948 * @param {Array} [stackB] Tracks traversed `other` objects.
11949 * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.
11950 */
11951 function equalArrays(array, other, equalFunc, customizer, isLoose, stackA, stackB) {
11952 var index = -1,
11953 arrLength = array.length,
11954 othLength = other.length;
11955
11956 if (arrLength != othLength && !(isLoose && othLength > arrLength)) {
11957 return false;
11958 }
11959 // Ignore non-index properties.
11960 while (++index < arrLength) {
11961 var arrValue = array[index],
11962 othValue = other[index],
11963 result = customizer ? customizer(isLoose ? othValue : arrValue, isLoose ? arrValue : othValue, index) : undefined;
11964
11965 if (result !== undefined) {
11966 if (result) {
11967 continue;
11968 }
11969 return false;
11970 }
11971 // Recursively compare arrays (susceptible to call stack limits).
11972 if (isLoose) {
11973 if (!arraySome(other, function(othValue) {
11974 return arrValue === othValue || equalFunc(arrValue, othValue, customizer, isLoose, stackA, stackB);
11975 })) {
11976 return false;
11977 }
11978 } else if (!(arrValue === othValue || equalFunc(arrValue, othValue, customizer, isLoose, stackA, stackB))) {
11979 return false;
11980 }
11981 }
11982 return true;
11983 }
11984
11985 /**
11986 * A specialized version of `baseIsEqualDeep` for comparing objects of
11987 * the same `toStringTag`.
11988 *
11989 * **Note:** This function only supports comparing values with tags of
11990 * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
11991 *
11992 * @private
11993 * @param {Object} object The object to compare.
11994 * @param {Object} other The other object to compare.
11995 * @param {string} tag The `toStringTag` of the objects to compare.
11996 * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
11997 */
11998 function equalByTag(object, other, tag) {
11999 switch (tag) {
12000 case boolTag:
12001 case dateTag:
12002 // Coerce dates and booleans to numbers, dates to milliseconds and booleans
12003 // to `1` or `0` treating invalid dates coerced to `NaN` as not equal.
12004 return +object == +other;
12005
12006 case errorTag:
12007 return object.name == other.name && object.message == other.message;
12008
12009 case numberTag:
12010 // Treat `NaN` vs. `NaN` as equal.
12011 return (object != +object)
12012 ? other != +other
12013 : object == +other;
12014
12015 case regexpTag:
12016 case stringTag:
12017 // Coerce regexes to strings and treat strings primitives and string
12018 // objects as equal. See https://es5.github.io/#x15.10.6.4 for more details.
12019 return object == (other + '');
12020 }
12021 return false;
12022 }
12023
12024 /**
12025 * A specialized version of `baseIsEqualDeep` for objects with support for
12026 * partial deep comparisons.
12027 *
12028 * @private
12029 * @param {Object} object The object to compare.
12030 * @param {Object} other The other object to compare.
12031 * @param {Function} equalFunc The function to determine equivalents of values.
12032 * @param {Function} [customizer] The function to customize comparing values.
12033 * @param {boolean} [isLoose] Specify performing partial comparisons.
12034 * @param {Array} [stackA] Tracks traversed `value` objects.
12035 * @param {Array} [stackB] Tracks traversed `other` objects.
12036 * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
12037 */
12038 function equalObjects(object, other, equalFunc, customizer, isLoose, stackA, stackB) {
12039 var objProps = keys(object),
12040 objLength = objProps.length,
12041 othProps = keys(other),
12042 othLength = othProps.length;
12043
12044 if (objLength != othLength && !isLoose) {
12045 return false;
12046 }
12047 var index = objLength;
12048 while (index--) {
12049 var key = objProps[index];
12050 if (!(isLoose ? key in other : hasOwnProperty.call(other, key))) {
12051 return false;
12052 }
12053 }
12054 var skipCtor = isLoose;
12055 while (++index < objLength) {
12056 key = objProps[index];
12057 var objValue = object[key],
12058 othValue = other[key],
12059 result = customizer ? customizer(isLoose ? othValue : objValue, isLoose? objValue : othValue, key) : undefined;
12060
12061 // Recursively compare objects (susceptible to call stack limits).
12062 if (!(result === undefined ? equalFunc(objValue, othValue, customizer, isLoose, stackA, stackB) : result)) {
12063 return false;
12064 }
12065 skipCtor || (skipCtor = key == 'constructor');
12066 }
12067 if (!skipCtor) {
12068 var objCtor = object.constructor,
12069 othCtor = other.constructor;
12070
12071 // Non `Object` object instances with different constructors are not equal.
12072 if (objCtor != othCtor &&
12073 ('constructor' in object && 'constructor' in other) &&
12074 !(typeof objCtor == 'function' && objCtor instanceof objCtor &&
12075 typeof othCtor == 'function' && othCtor instanceof othCtor)) {
12076 return false;
12077 }
12078 }
12079 return true;
12080 }
12081
12082 /**
12083 * Gets the appropriate "callback" function. If the `_.callback` method is
12084 * customized this function returns the custom method, otherwise it returns
12085 * the `baseCallback` function. If arguments are provided the chosen function
12086 * is invoked with them and its result is returned.
12087 *
12088 * @private
12089 * @returns {Function} Returns the chosen function or its result.
12090 */
12091 function getCallback(func, thisArg, argCount) {
12092 var result = lodash.callback || callback;
12093 result = result === callback ? baseCallback : result;
12094 return argCount ? result(func, thisArg, argCount) : result;
12095 }
12096
12097 /**
12098 * Gets metadata for `func`.
12099 *
12100 * @private
12101 * @param {Function} func The function to query.
12102 * @returns {*} Returns the metadata for `func`.
12103 */
12104 var getData = !metaMap ? noop : function(func) {
12105 return metaMap.get(func);
12106 };
12107
12108 /**
12109 * Gets the name of `func`.
12110 *
12111 * @private
12112 * @param {Function} func The function to query.
12113 * @returns {string} Returns the function name.
12114 */
12115 function getFuncName(func) {
12116 var result = func.name,
12117 array = realNames[result],
12118 length = array ? array.length : 0;
12119
12120 while (length--) {
12121 var data = array[length],
12122 otherFunc = data.func;
12123 if (otherFunc == null || otherFunc == func) {
12124 return data.name;
12125 }
12126 }
12127 return result;
12128 }
12129
12130 /**
12131 * Gets the appropriate "indexOf" function. If the `_.indexOf` method is
12132 * customized this function returns the custom method, otherwise it returns
12133 * the `baseIndexOf` function. If arguments are provided the chosen function
12134 * is invoked with them and its result is returned.
12135 *
12136 * @private
12137 * @returns {Function|number} Returns the chosen function or its result.
12138 */
12139 function getIndexOf(collection, target, fromIndex) {
12140 var result = lodash.indexOf || indexOf;
12141 result = result === indexOf ? baseIndexOf : result;
12142 return collection ? result(collection, target, fromIndex) : result;
12143 }
12144
12145 /**
12146 * Gets the "length" property value of `object`.
12147 *
12148 * **Note:** This function is used to avoid a [JIT bug](https://bugs.webkit.org/show_bug.cgi?id=142792)
12149 * that affects Safari on at least iOS 8.1-8.3 ARM64.
12150 *
12151 * @private
12152 * @param {Object} object The object to query.
12153 * @returns {*} Returns the "length" value.
12154 */
12155 var getLength = baseProperty('length');
12156
12157 /**
12158 * Gets the propery names, values, and compare flags of `object`.
12159 *
12160 * @private
12161 * @param {Object} object The object to query.
12162 * @returns {Array} Returns the match data of `object`.
12163 */
12164 function getMatchData(object) {
12165 var result = pairs(object),
12166 length = result.length;
12167
12168 while (length--) {
12169 result[length][2] = isStrictComparable(result[length][1]);
12170 }
12171 return result;
12172 }
12173
12174 /**
12175 * Gets the native function at `key` of `object`.
12176 *
12177 * @private
12178 * @param {Object} object The object to query.
12179 * @param {string} key The key of the method to get.
12180 * @returns {*} Returns the function if it's native, else `undefined`.
12181 */
12182 function getNative(object, key) {
12183 var value = object == null ? undefined : object[key];
12184 return isNative(value) ? value : undefined;
12185 }
12186
12187 /**
12188 * Gets the view, applying any `transforms` to the `start` and `end` positions.
12189 *
12190 * @private
12191 * @param {number} start The start of the view.
12192 * @param {number} end The end of the view.
12193 * @param {Array} transforms The transformations to apply to the view.
12194 * @returns {Object} Returns an object containing the `start` and `end`
12195 * positions of the view.
12196 */
12197 function getView(start, end, transforms) {
12198 var index = -1,
12199 length = transforms.length;
12200
12201 while (++index < length) {
12202 var data = transforms[index],
12203 size = data.size;
12204
12205 switch (data.type) {
12206 case 'drop': start += size; break;
12207 case 'dropRight': end -= size; break;
12208 case 'take': end = nativeMin(end, start + size); break;
12209 case 'takeRight': start = nativeMax(start, end - size); break;
12210 }
12211 }
12212 return { 'start': start, 'end': end };
12213 }
12214
12215 /**
12216 * Initializes an array clone.
12217 *
12218 * @private
12219 * @param {Array} array The array to clone.
12220 * @returns {Array} Returns the initialized clone.
12221 */
12222 function initCloneArray(array) {
12223 var length = array.length,
12224 result = new array.constructor(length);
12225
12226 // Add array properties assigned by `RegExp#exec`.
12227 if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) {
12228 result.index = array.index;
12229 result.input = array.input;
12230 }
12231 return result;
12232 }
12233
12234 /**
12235 * Initializes an object clone.
12236 *
12237 * @private
12238 * @param {Object} object The object to clone.
12239 * @returns {Object} Returns the initialized clone.
12240 */
12241 function initCloneObject(object) {
12242 var Ctor = object.constructor;
12243 if (!(typeof Ctor == 'function' && Ctor instanceof Ctor)) {
12244 Ctor = Object;
12245 }
12246 return new Ctor;
12247 }
12248
12249 /**
12250 * Initializes an object clone based on its `toStringTag`.
12251 *
12252 * **Note:** This function only supports cloning values with tags of
12253 * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
12254 *
12255 * @private
12256 * @param {Object} object The object to clone.
12257 * @param {string} tag The `toStringTag` of the object to clone.
12258 * @param {boolean} [isDeep] Specify a deep clone.
12259 * @returns {Object} Returns the initialized clone.
12260 */
12261 function initCloneByTag(object, tag, isDeep) {
12262 var Ctor = object.constructor;
12263 switch (tag) {
12264 case arrayBufferTag:
12265 return bufferClone(object);
12266
12267 case boolTag:
12268 case dateTag:
12269 return new Ctor(+object);
12270
12271 case float32Tag: case float64Tag:
12272 case int8Tag: case int16Tag: case int32Tag:
12273 case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag:
12274 var buffer = object.buffer;
12275 return new Ctor(isDeep ? bufferClone(buffer) : buffer, object.byteOffset, object.length);
12276
12277 case numberTag:
12278 case stringTag:
12279 return new Ctor(object);
12280
12281 case regexpTag:
12282 var result = new Ctor(object.source, reFlags.exec(object));
12283 result.lastIndex = object.lastIndex;
12284 }
12285 return result;
12286 }
12287
12288 /**
12289 * Invokes the method at `path` on `object`.
12290 *
12291 * @private
12292 * @param {Object} object The object to query.
12293 * @param {Array|string} path The path of the method to invoke.
12294 * @param {Array} args The arguments to invoke the method with.
12295 * @returns {*} Returns the result of the invoked method.
12296 */
12297 function invokePath(object, path, args) {
12298 if (object != null && !isKey(path, object)) {
12299 path = toPath(path);
12300 object = path.length == 1 ? object : baseGet(object, baseSlice(path, 0, -1));
12301 path = last(path);
12302 }
12303 var func = object == null ? object : object[path];
12304 return func == null ? undefined : func.apply(object, args);
12305 }
12306
12307 /**
12308 * Checks if `value` is array-like.
12309 *
12310 * @private
12311 * @param {*} value The value to check.
12312 * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
12313 */
12314 function isArrayLike(value) {
12315 return value != null && isLength(getLength(value));
12316 }
12317
12318 /**
12319 * Checks if `value` is a valid array-like index.
12320 *
12321 * @private
12322 * @param {*} value The value to check.
12323 * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
12324 * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
12325 */
12326 function isIndex(value, length) {
12327 value = (typeof value == 'number' || reIsUint.test(value)) ? +value : -1;
12328 length = length == null ? MAX_SAFE_INTEGER : length;
12329 return value > -1 && value % 1 == 0 && value < length;
12330 }
12331
12332 /**
12333 * Checks if the provided arguments are from an iteratee call.
12334 *
12335 * @private
12336 * @param {*} value The potential iteratee value argument.
12337 * @param {*} index The potential iteratee index or key argument.
12338 * @param {*} object The potential iteratee object argument.
12339 * @returns {boolean} Returns `true` if the arguments are from an iteratee call, else `false`.
12340 */
12341 function isIterateeCall(value, index, object) {
12342 if (!isObject(object)) {
12343 return false;
12344 }
12345 var type = typeof index;
12346 if (type == 'number'
12347 ? (isArrayLike(object) && isIndex(index, object.length))
12348 : (type == 'string' && index in object)) {
12349 var other = object[index];
12350 return value === value ? (value === other) : (other !== other);
12351 }
12352 return false;
12353 }
12354
12355 /**
12356 * Checks if `value` is a property name and not a property path.
12357 *
12358 * @private
12359 * @param {*} value The value to check.
12360 * @param {Object} [object] The object to query keys on.
12361 * @returns {boolean} Returns `true` if `value` is a property name, else `false`.
12362 */
12363 function isKey(value, object) {
12364 var type = typeof value;
12365 if ((type == 'string' && reIsPlainProp.test(value)) || type == 'number') {
12366 return true;
12367 }
12368 if (isArray(value)) {
12369 return false;
12370 }
12371 var result = !reIsDeepProp.test(value);
12372 return result || (object != null && value in toObject(object));
12373 }
12374
12375 /**
12376 * Checks if `func` has a lazy counterpart.
12377 *
12378 * @private
12379 * @param {Function} func The function to check.
12380 * @returns {boolean} Returns `true` if `func` has a lazy counterpart, else `false`.
12381 */
12382 function isLaziable(func) {
12383 var funcName = getFuncName(func);
12384 if (!(funcName in LazyWrapper.prototype)) {
12385 return false;
12386 }
12387 var other = lodash[funcName];
12388 if (func === other) {
12389 return true;
12390 }
12391 var data = getData(other);
12392 return !!data && func === data[0];
12393 }
12394
12395 /**
12396 * Checks if `value` is a valid array-like length.
12397 *
12398 * **Note:** This function is based on [`ToLength`](http://ecma-international.org/ecma-262/6.0/#sec-tolength).
12399 *
12400 * @private
12401 * @param {*} value The value to check.
12402 * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
12403 */
12404 function isLength(value) {
12405 return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
12406 }
12407
12408 /**
12409 * Checks if `value` is suitable for strict equality comparisons, i.e. `===`.
12410 *
12411 * @private
12412 * @param {*} value The value to check.
12413 * @returns {boolean} Returns `true` if `value` if suitable for strict
12414 * equality comparisons, else `false`.
12415 */
12416 function isStrictComparable(value) {
12417 return value === value && !isObject(value);
12418 }
12419
12420 /**
12421 * Merges the function metadata of `source` into `data`.
12422 *
12423 * Merging metadata reduces the number of wrappers required to invoke a function.
12424 * This is possible because methods like `_.bind`, `_.curry`, and `_.partial`
12425 * may be applied regardless of execution order. Methods like `_.ary` and `_.rearg`
12426 * augment function arguments, making the order in which they are executed important,
12427 * preventing the merging of metadata. However, we make an exception for a safe
12428 * common case where curried functions have `_.ary` and or `_.rearg` applied.
12429 *
12430 * @private
12431 * @param {Array} data The destination metadata.
12432 * @param {Array} source The source metadata.
12433 * @returns {Array} Returns `data`.
12434 */
12435 function mergeData(data, source) {
12436 var bitmask = data[1],
12437 srcBitmask = source[1],
12438 newBitmask = bitmask | srcBitmask,
12439 isCommon = newBitmask < ARY_FLAG;
12440
12441 var isCombo =
12442 (srcBitmask == ARY_FLAG && bitmask == CURRY_FLAG) ||
12443 (srcBitmask == ARY_FLAG && bitmask == REARG_FLAG && data[7].length <= source[8]) ||
12444 (srcBitmask == (ARY_FLAG | REARG_FLAG) && bitmask == CURRY_FLAG);
12445
12446 // Exit early if metadata can't be merged.
12447 if (!(isCommon || isCombo)) {
12448 return data;
12449 }
12450 // Use source `thisArg` if available.
12451 if (srcBitmask & BIND_FLAG) {
12452 data[2] = source[2];
12453 // Set when currying a bound function.
12454 newBitmask |= (bitmask & BIND_FLAG) ? 0 : CURRY_BOUND_FLAG;
12455 }
12456 // Compose partial arguments.
12457 var value = source[3];
12458 if (value) {
12459 var partials = data[3];
12460 data[3] = partials ? composeArgs(partials, value, source[4]) : arrayCopy(value);
12461 data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : arrayCopy(source[4]);
12462 }
12463 // Compose partial right arguments.
12464 value = source[5];
12465 if (value) {
12466 partials = data[5];
12467 data[5] = partials ? composeArgsRight(partials, value, source[6]) : arrayCopy(value);
12468 data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : arrayCopy(source[6]);
12469 }
12470 // Use source `argPos` if available.
12471 value = source[7];
12472 if (value) {
12473 data[7] = arrayCopy(value);
12474 }
12475 // Use source `ary` if it's smaller.
12476 if (srcBitmask & ARY_FLAG) {
12477 data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]);
12478 }
12479 // Use source `arity` if one is not provided.
12480 if (data[9] == null) {
12481 data[9] = source[9];
12482 }
12483 // Use source `func` and merge bitmasks.
12484 data[0] = source[0];
12485 data[1] = newBitmask;
12486
12487 return data;
12488 }
12489
12490 /**
12491 * Used by `_.defaultsDeep` to customize its `_.merge` use.
12492 *
12493 * @private
12494 * @param {*} objectValue The destination object property value.
12495 * @param {*} sourceValue The source object property value.
12496 * @returns {*} Returns the value to assign to the destination object.
12497 */
12498 function mergeDefaults(objectValue, sourceValue) {
12499 return objectValue === undefined ? sourceValue : merge(objectValue, sourceValue, mergeDefaults);
12500 }
12501
12502 /**
12503 * A specialized version of `_.pick` which picks `object` properties specified
12504 * by `props`.
12505 *
12506 * @private
12507 * @param {Object} object The source object.
12508 * @param {string[]} props The property names to pick.
12509 * @returns {Object} Returns the new object.
12510 */
12511 function pickByArray(object, props) {
12512 object = toObject(object);
12513
12514 var index = -1,
12515 length = props.length,
12516 result = {};
12517
12518 while (++index < length) {
12519 var key = props[index];
12520 if (key in object) {
12521 result[key] = object[key];
12522 }
12523 }
12524 return result;
12525 }
12526
12527 /**
12528 * A specialized version of `_.pick` which picks `object` properties `predicate`
12529 * returns truthy for.
12530 *
12531 * @private
12532 * @param {Object} object The source object.
12533 * @param {Function} predicate The function invoked per iteration.
12534 * @returns {Object} Returns the new object.
12535 */
12536 function pickByCallback(object, predicate) {
12537 var result = {};
12538 baseForIn(object, function(value, key, object) {
12539 if (predicate(value, key, object)) {
12540 result[key] = value;
12541 }
12542 });
12543 return result;
12544 }
12545
12546 /**
12547 * Reorder `array` according to the specified indexes where the element at
12548 * the first index is assigned as the first element, the element at
12549 * the second index is assigned as the second element, and so on.
12550 *
12551 * @private
12552 * @param {Array} array The array to reorder.
12553 * @param {Array} indexes The arranged array indexes.
12554 * @returns {Array} Returns `array`.
12555 */
12556 function reorder(array, indexes) {
12557 var arrLength = array.length,
12558 length = nativeMin(indexes.length, arrLength),
12559 oldArray = arrayCopy(array);
12560
12561 while (length--) {
12562 var index = indexes[length];
12563 array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined;
12564 }
12565 return array;
12566 }
12567
12568 /**
12569 * Sets metadata for `func`.
12570 *
12571 * **Note:** If this function becomes hot, i.e. is invoked a lot in a short
12572 * period of time, it will trip its breaker and transition to an identity function
12573 * to avoid garbage collection pauses in V8. See [V8 issue 2070](https://code.google.com/p/v8/issues/detail?id=2070)
12574 * for more details.
12575 *
12576 * @private
12577 * @param {Function} func The function to associate metadata with.
12578 * @param {*} data The metadata.
12579 * @returns {Function} Returns `func`.
12580 */
12581 var setData = (function() {
12582 var count = 0,
12583 lastCalled = 0;
12584
12585 return function(key, value) {
12586 var stamp = now(),
12587 remaining = HOT_SPAN - (stamp - lastCalled);
12588
12589 lastCalled = stamp;
12590 if (remaining > 0) {
12591 if (++count >= HOT_COUNT) {
12592 return key;
12593 }
12594 } else {
12595 count = 0;
12596 }
12597 return baseSetData(key, value);
12598 };
12599 }());
12600
12601 /**
12602 * A fallback implementation of `Object.keys` which creates an array of the
12603 * own enumerable property names of `object`.
12604 *
12605 * @private
12606 * @param {Object} object The object to query.
12607 * @returns {Array} Returns the array of property names.
12608 */
12609 function shimKeys(object) {
12610 var props = keysIn(object),
12611 propsLength = props.length,
12612 length = propsLength && object.length;
12613
12614 var allowIndexes = !!length && isLength(length) &&
12615 (isArray(object) || isArguments(object));
12616
12617 var index = -1,
12618 result = [];
12619
12620 while (++index < propsLength) {
12621 var key = props[index];
12622 if ((allowIndexes && isIndex(key, length)) || hasOwnProperty.call(object, key)) {
12623 result.push(key);
12624 }
12625 }
12626 return result;
12627 }
12628
12629 /**
12630 * Converts `value` to an array-like object if it's not one.
12631 *
12632 * @private
12633 * @param {*} value The value to process.
12634 * @returns {Array|Object} Returns the array-like object.
12635 */
12636 function toIterable(value) {
12637 if (value == null) {
12638 return [];
12639 }
12640 if (!isArrayLike(value)) {
12641 return values(value);
12642 }
12643 return isObject(value) ? value : Object(value);
12644 }
12645
12646 /**
12647 * Converts `value` to an object if it's not one.
12648 *
12649 * @private
12650 * @param {*} value The value to process.
12651 * @returns {Object} Returns the object.
12652 */
12653 function toObject(value) {
12654 return isObject(value) ? value : Object(value);
12655 }
12656
12657 /**
12658 * Converts `value` to property path array if it's not one.
12659 *
12660 * @private
12661 * @param {*} value The value to process.
12662 * @returns {Array} Returns the property path array.
12663 */
12664 function toPath(value) {
12665 if (isArray(value)) {
12666 return value;
12667 }
12668 var result = [];
12669 baseToString(value).replace(rePropName, function(match, number, quote, string) {
12670 result.push(quote ? string.replace(reEscapeChar, '$1') : (number || match));
12671 });
12672 return result;
12673 }
12674
12675 /**
12676 * Creates a clone of `wrapper`.
12677 *
12678 * @private
12679 * @param {Object} wrapper The wrapper to clone.
12680 * @returns {Object} Returns the cloned wrapper.
12681 */
12682 function wrapperClone(wrapper) {
12683 return wrapper instanceof LazyWrapper
12684 ? wrapper.clone()
12685 : new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__, arrayCopy(wrapper.__actions__));
12686 }
12687
12688 /*------------------------------------------------------------------------*/
12689
12690 /**
12691 * Creates an array of elements split into groups the length of `size`.
12692 * If `collection` can't be split evenly, the final chunk will be the remaining
12693 * elements.
12694 *
12695 * @static
12696 * @memberOf _
12697 * @category Array
12698 * @param {Array} array The array to process.
12699 * @param {number} [size=1] The length of each chunk.
12700 * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
12701 * @returns {Array} Returns the new array containing chunks.
12702 * @example
12703 *
12704 * _.chunk(['a', 'b', 'c', 'd'], 2);
12705 * // => [['a', 'b'], ['c', 'd']]
12706 *
12707 * _.chunk(['a', 'b', 'c', 'd'], 3);
12708 * // => [['a', 'b', 'c'], ['d']]
12709 */
12710 function chunk(array, size, guard) {
12711 if (guard ? isIterateeCall(array, size, guard) : size == null) {
12712 size = 1;
12713 } else {
12714 size = nativeMax(nativeFloor(size) || 1, 1);
12715 }
12716 var index = 0,
12717 length = array ? array.length : 0,
12718 resIndex = -1,
12719 result = Array(nativeCeil(length / size));
12720
12721 while (index < length) {
12722 result[++resIndex] = baseSlice(array, index, (index += size));
12723 }
12724 return result;
12725 }
12726
12727 /**
12728 * Creates an array with all falsey values removed. The values `false`, `null`,
12729 * `0`, `""`, `undefined`, and `NaN` are falsey.
12730 *
12731 * @static
12732 * @memberOf _
12733 * @category Array
12734 * @param {Array} array The array to compact.
12735 * @returns {Array} Returns the new array of filtered values.
12736 * @example
12737 *
12738 * _.compact([0, 1, false, 2, '', 3]);
12739 * // => [1, 2, 3]
12740 */
12741 function compact(array) {
12742 var index = -1,
12743 length = array ? array.length : 0,
12744 resIndex = -1,
12745 result = [];
12746
12747 while (++index < length) {
12748 var value = array[index];
12749 if (value) {
12750 result[++resIndex] = value;
12751 }
12752 }
12753 return result;
12754 }
12755
12756 /**
12757 * Creates an array of unique `array` values not included in the other
12758 * provided arrays using [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
12759 * for equality comparisons.
12760 *
12761 * @static
12762 * @memberOf _
12763 * @category Array
12764 * @param {Array} array The array to inspect.
12765 * @param {...Array} [values] The arrays of values to exclude.
12766 * @returns {Array} Returns the new array of filtered values.
12767 * @example
12768 *
12769 * _.difference([1, 2, 3], [4, 2]);
12770 * // => [1, 3]
12771 */
12772 var difference = restParam(function(array, values) {
12773 return (isObjectLike(array) && isArrayLike(array))
12774 ? baseDifference(array, baseFlatten(values, false, true))
12775 : [];
12776 });
12777
12778 /**
12779 * Creates a slice of `array` with `n` elements dropped from the beginning.
12780 *
12781 * @static
12782 * @memberOf _
12783 * @category Array
12784 * @param {Array} array The array to query.
12785 * @param {number} [n=1] The number of elements to drop.
12786 * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
12787 * @returns {Array} Returns the slice of `array`.
12788 * @example
12789 *
12790 * _.drop([1, 2, 3]);
12791 * // => [2, 3]
12792 *
12793 * _.drop([1, 2, 3], 2);
12794 * // => [3]
12795 *
12796 * _.drop([1, 2, 3], 5);
12797 * // => []
12798 *
12799 * _.drop([1, 2, 3], 0);
12800 * // => [1, 2, 3]
12801 */
12802 function drop(array, n, guard) {
12803 var length = array ? array.length : 0;
12804 if (!length) {
12805 return [];
12806 }
12807 if (guard ? isIterateeCall(array, n, guard) : n == null) {
12808 n = 1;
12809 }
12810 return baseSlice(array, n < 0 ? 0 : n);
12811 }
12812
12813 /**
12814 * Creates a slice of `array` with `n` elements dropped from the end.
12815 *
12816 * @static
12817 * @memberOf _
12818 * @category Array
12819 * @param {Array} array The array to query.
12820 * @param {number} [n=1] The number of elements to drop.
12821 * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
12822 * @returns {Array} Returns the slice of `array`.
12823 * @example
12824 *
12825 * _.dropRight([1, 2, 3]);
12826 * // => [1, 2]
12827 *
12828 * _.dropRight([1, 2, 3], 2);
12829 * // => [1]
12830 *
12831 * _.dropRight([1, 2, 3], 5);
12832 * // => []
12833 *
12834 * _.dropRight([1, 2, 3], 0);
12835 * // => [1, 2, 3]
12836 */
12837 function dropRight(array, n, guard) {
12838 var length = array ? array.length : 0;
12839 if (!length) {
12840 return [];
12841 }
12842 if (guard ? isIterateeCall(array, n, guard) : n == null) {
12843 n = 1;
12844 }
12845 n = length - (+n || 0);
12846 return baseSlice(array, 0, n < 0 ? 0 : n);
12847 }
12848
12849 /**
12850 * Creates a slice of `array` excluding elements dropped from the end.
12851 * Elements are dropped until `predicate` returns falsey. The predicate is
12852 * bound to `thisArg` and invoked with three arguments: (value, index, array).
12853 *
12854 * If a property name is provided for `predicate` the created `_.property`
12855 * style callback returns the property value of the given element.
12856 *
12857 * If a value is also provided for `thisArg` the created `_.matchesProperty`
12858 * style callback returns `true` for elements that have a matching property
12859 * value, else `false`.
12860 *
12861 * If an object is provided for `predicate` the created `_.matches` style
12862 * callback returns `true` for elements that match the properties of the given
12863 * object, else `false`.
12864 *
12865 * @static
12866 * @memberOf _
12867 * @category Array
12868 * @param {Array} array The array to query.
12869 * @param {Function|Object|string} [predicate=_.identity] The function invoked
12870 * per iteration.
12871 * @param {*} [thisArg] The `this` binding of `predicate`.
12872 * @returns {Array} Returns the slice of `array`.
12873 * @example
12874 *
12875 * _.dropRightWhile([1, 2, 3], function(n) {
12876 * return n > 1;
12877 * });
12878 * // => [1]
12879 *
12880 * var users = [
12881 * { 'user': 'barney', 'active': true },
12882 * { 'user': 'fred', 'active': false },
12883 * { 'user': 'pebbles', 'active': false }
12884 * ];
12885 *
12886 * // using the `_.matches` callback shorthand
12887 * _.pluck(_.dropRightWhile(users, { 'user': 'pebbles', 'active': false }), 'user');
12888 * // => ['barney', 'fred']
12889 *
12890 * // using the `_.matchesProperty` callback shorthand
12891 * _.pluck(_.dropRightWhile(users, 'active', false), 'user');
12892 * // => ['barney']
12893 *
12894 * // using the `_.property` callback shorthand
12895 * _.pluck(_.dropRightWhile(users, 'active'), 'user');
12896 * // => ['barney', 'fred', 'pebbles']
12897 */
12898 function dropRightWhile(array, predicate, thisArg) {
12899 return (array && array.length)
12900 ? baseWhile(array, getCallback(predicate, thisArg, 3), true, true)
12901 : [];
12902 }
12903
12904 /**
12905 * Creates a slice of `array` excluding elements dropped from the beginning.
12906 * Elements are dropped until `predicate` returns falsey. The predicate is
12907 * bound to `thisArg` and invoked with three arguments: (value, index, array).
12908 *
12909 * If a property name is provided for `predicate` the created `_.property`
12910 * style callback returns the property value of the given element.
12911 *
12912 * If a value is also provided for `thisArg` the created `_.matchesProperty`
12913 * style callback returns `true` for elements that have a matching property
12914 * value, else `false`.
12915 *
12916 * If an object is provided for `predicate` the created `_.matches` style
12917 * callback returns `true` for elements that have the properties of the given
12918 * object, else `false`.
12919 *
12920 * @static
12921 * @memberOf _
12922 * @category Array
12923 * @param {Array} array The array to query.
12924 * @param {Function|Object|string} [predicate=_.identity] The function invoked
12925 * per iteration.
12926 * @param {*} [thisArg] The `this` binding of `predicate`.
12927 * @returns {Array} Returns the slice of `array`.
12928 * @example
12929 *
12930 * _.dropWhile([1, 2, 3], function(n) {
12931 * return n < 3;
12932 * });
12933 * // => [3]
12934 *
12935 * var users = [
12936 * { 'user': 'barney', 'active': false },
12937 * { 'user': 'fred', 'active': false },
12938 * { 'user': 'pebbles', 'active': true }
12939 * ];
12940 *
12941 * // using the `_.matches` callback shorthand
12942 * _.pluck(_.dropWhile(users, { 'user': 'barney', 'active': false }), 'user');
12943 * // => ['fred', 'pebbles']
12944 *
12945 * // using the `_.matchesProperty` callback shorthand
12946 * _.pluck(_.dropWhile(users, 'active', false), 'user');
12947 * // => ['pebbles']
12948 *
12949 * // using the `_.property` callback shorthand
12950 * _.pluck(_.dropWhile(users, 'active'), 'user');
12951 * // => ['barney', 'fred', 'pebbles']
12952 */
12953 function dropWhile(array, predicate, thisArg) {
12954 return (array && array.length)
12955 ? baseWhile(array, getCallback(predicate, thisArg, 3), true)
12956 : [];
12957 }
12958
12959 /**
12960 * Fills elements of `array` with `value` from `start` up to, but not
12961 * including, `end`.
12962 *
12963 * **Note:** This method mutates `array`.
12964 *
12965 * @static
12966 * @memberOf _
12967 * @category Array
12968 * @param {Array} array The array to fill.
12969 * @param {*} value The value to fill `array` with.
12970 * @param {number} [start=0] The start position.
12971 * @param {number} [end=array.length] The end position.
12972 * @returns {Array} Returns `array`.
12973 * @example
12974 *
12975 * var array = [1, 2, 3];
12976 *
12977 * _.fill(array, 'a');
12978 * console.log(array);
12979 * // => ['a', 'a', 'a']
12980 *
12981 * _.fill(Array(3), 2);
12982 * // => [2, 2, 2]
12983 *
12984 * _.fill([4, 6, 8], '*', 1, 2);
12985 * // => [4, '*', 8]
12986 */
12987 function fill(array, value, start, end) {
12988 var length = array ? array.length : 0;
12989 if (!length) {
12990 return [];
12991 }
12992 if (start && typeof start != 'number' && isIterateeCall(array, value, start)) {
12993 start = 0;
12994 end = length;
12995 }
12996 return baseFill(array, value, start, end);
12997 }
12998
12999 /**
13000 * This method is like `_.find` except that it returns the index of the first
13001 * element `predicate` returns truthy for instead of the element itself.
13002 *
13003 * If a property name is provided for `predicate` the created `_.property`
13004 * style callback returns the property value of the given element.
13005 *
13006 * If a value is also provided for `thisArg` the created `_.matchesProperty`
13007 * style callback returns `true` for elements that have a matching property
13008 * value, else `false`.
13009 *
13010 * If an object is provided for `predicate` the created `_.matches` style
13011 * callback returns `true` for elements that have the properties of the given
13012 * object, else `false`.
13013 *
13014 * @static
13015 * @memberOf _
13016 * @category Array
13017 * @param {Array} array The array to search.
13018 * @param {Function|Object|string} [predicate=_.identity] The function invoked
13019 * per iteration.
13020 * @param {*} [thisArg] The `this` binding of `predicate`.
13021 * @returns {number} Returns the index of the found element, else `-1`.
13022 * @example
13023 *
13024 * var users = [
13025 * { 'user': 'barney', 'active': false },
13026 * { 'user': 'fred', 'active': false },
13027 * { 'user': 'pebbles', 'active': true }
13028 * ];
13029 *
13030 * _.findIndex(users, function(chr) {
13031 * return chr.user == 'barney';
13032 * });
13033 * // => 0
13034 *
13035 * // using the `_.matches` callback shorthand
13036 * _.findIndex(users, { 'user': 'fred', 'active': false });
13037 * // => 1
13038 *
13039 * // using the `_.matchesProperty` callback shorthand
13040 * _.findIndex(users, 'active', false);
13041 * // => 0
13042 *
13043 * // using the `_.property` callback shorthand
13044 * _.findIndex(users, 'active');
13045 * // => 2
13046 */
13047 var findIndex = createFindIndex();
13048
13049 /**
13050 * This method is like `_.findIndex` except that it iterates over elements
13051 * of `collection` from right to left.
13052 *
13053 * If a property name is provided for `predicate` the created `_.property`
13054 * style callback returns the property value of the given element.
13055 *
13056 * If a value is also provided for `thisArg` the created `_.matchesProperty`
13057 * style callback returns `true` for elements that have a matching property
13058 * value, else `false`.
13059 *
13060 * If an object is provided for `predicate` the created `_.matches` style
13061 * callback returns `true` for elements that have the properties of the given
13062 * object, else `false`.
13063 *
13064 * @static
13065 * @memberOf _
13066 * @category Array
13067 * @param {Array} array The array to search.
13068 * @param {Function|Object|string} [predicate=_.identity] The function invoked
13069 * per iteration.
13070 * @param {*} [thisArg] The `this` binding of `predicate`.
13071 * @returns {number} Returns the index of the found element, else `-1`.
13072 * @example
13073 *
13074 * var users = [
13075 * { 'user': 'barney', 'active': true },
13076 * { 'user': 'fred', 'active': false },
13077 * { 'user': 'pebbles', 'active': false }
13078 * ];
13079 *
13080 * _.findLastIndex(users, function(chr) {
13081 * return chr.user == 'pebbles';
13082 * });
13083 * // => 2
13084 *
13085 * // using the `_.matches` callback shorthand
13086 * _.findLastIndex(users, { 'user': 'barney', 'active': true });
13087 * // => 0
13088 *
13089 * // using the `_.matchesProperty` callback shorthand
13090 * _.findLastIndex(users, 'active', false);
13091 * // => 2
13092 *
13093 * // using the `_.property` callback shorthand
13094 * _.findLastIndex(users, 'active');
13095 * // => 0
13096 */
13097 var findLastIndex = createFindIndex(true);
13098
13099 /**
13100 * Gets the first element of `array`.
13101 *
13102 * @static
13103 * @memberOf _
13104 * @alias head
13105 * @category Array
13106 * @param {Array} array The array to query.
13107 * @returns {*} Returns the first element of `array`.
13108 * @example
13109 *
13110 * _.first([1, 2, 3]);
13111 * // => 1
13112 *
13113 * _.first([]);
13114 * // => undefined
13115 */
13116 function first(array) {
13117 return array ? array[0] : undefined;
13118 }
13119
13120 /**
13121 * Flattens a nested array. If `isDeep` is `true` the array is recursively
13122 * flattened, otherwise it is only flattened a single level.
13123 *
13124 * @static
13125 * @memberOf _
13126 * @category Array
13127 * @param {Array} array The array to flatten.
13128 * @param {boolean} [isDeep] Specify a deep flatten.
13129 * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
13130 * @returns {Array} Returns the new flattened array.
13131 * @example
13132 *
13133 * _.flatten([1, [2, 3, [4]]]);
13134 * // => [1, 2, 3, [4]]
13135 *
13136 * // using `isDeep`
13137 * _.flatten([1, [2, 3, [4]]], true);
13138 * // => [1, 2, 3, 4]
13139 */
13140 function flatten(array, isDeep, guard) {
13141 var length = array ? array.length : 0;
13142 if (guard && isIterateeCall(array, isDeep, guard)) {
13143 isDeep = false;
13144 }
13145 return length ? baseFlatten(array, isDeep) : [];
13146 }
13147
13148 /**
13149 * Recursively flattens a nested array.
13150 *
13151 * @static
13152 * @memberOf _
13153 * @category Array
13154 * @param {Array} array The array to recursively flatten.
13155 * @returns {Array} Returns the new flattened array.
13156 * @example
13157 *
13158 * _.flattenDeep([1, [2, 3, [4]]]);
13159 * // => [1, 2, 3, 4]
13160 */
13161 function flattenDeep(array) {
13162 var length = array ? array.length : 0;
13163 return length ? baseFlatten(array, true) : [];
13164 }
13165
13166 /**
13167 * Gets the index at which the first occurrence of `value` is found in `array`
13168 * using [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
13169 * for equality comparisons. If `fromIndex` is negative, it is used as the offset
13170 * from the end of `array`. If `array` is sorted providing `true` for `fromIndex`
13171 * performs a faster binary search.
13172 *
13173 * @static
13174 * @memberOf _
13175 * @category Array
13176 * @param {Array} array The array to search.
13177 * @param {*} value The value to search for.
13178 * @param {boolean|number} [fromIndex=0] The index to search from or `true`
13179 * to perform a binary search on a sorted array.
13180 * @returns {number} Returns the index of the matched value, else `-1`.
13181 * @example
13182 *
13183 * _.indexOf([1, 2, 1, 2], 2);
13184 * // => 1
13185 *
13186 * // using `fromIndex`
13187 * _.indexOf([1, 2, 1, 2], 2, 2);
13188 * // => 3
13189 *
13190 * // performing a binary search
13191 * _.indexOf([1, 1, 2, 2], 2, true);
13192 * // => 2
13193 */
13194 function indexOf(array, value, fromIndex) {
13195 var length = array ? array.length : 0;
13196 if (!length) {
13197 return -1;
13198 }
13199 if (typeof fromIndex == 'number') {
13200 fromIndex = fromIndex < 0 ? nativeMax(length + fromIndex, 0) : fromIndex;
13201 } else if (fromIndex) {
13202 var index = binaryIndex(array, value);
13203 if (index < length &&
13204 (value === value ? (value === array[index]) : (array[index] !== array[index]))) {
13205 return index;
13206 }
13207 return -1;
13208 }
13209 return baseIndexOf(array, value, fromIndex || 0);
13210 }
13211
13212 /**
13213 * Gets all but the last element of `array`.
13214 *
13215 * @static
13216 * @memberOf _
13217 * @category Array
13218 * @param {Array} array The array to query.
13219 * @returns {Array} Returns the slice of `array`.
13220 * @example
13221 *
13222 * _.initial([1, 2, 3]);
13223 * // => [1, 2]
13224 */
13225 function initial(array) {
13226 return dropRight(array, 1);
13227 }
13228
13229 /**
13230 * Creates an array of unique values that are included in all of the provided
13231 * arrays using [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
13232 * for equality comparisons.
13233 *
13234 * @static
13235 * @memberOf _
13236 * @category Array
13237 * @param {...Array} [arrays] The arrays to inspect.
13238 * @returns {Array} Returns the new array of shared values.
13239 * @example
13240 * _.intersection([1, 2], [4, 2], [2, 1]);
13241 * // => [2]
13242 */
13243 var intersection = restParam(function(arrays) {
13244 var othLength = arrays.length,
13245 othIndex = othLength,
13246 caches = Array(length),
13247 indexOf = getIndexOf(),
13248 isCommon = indexOf == baseIndexOf,
13249 result = [];
13250
13251 while (othIndex--) {
13252 var value = arrays[othIndex] = isArrayLike(value = arrays[othIndex]) ? value : [];
13253 caches[othIndex] = (isCommon && value.length >= 120) ? createCache(othIndex && value) : null;
13254 }
13255 var array = arrays[0],
13256 index = -1,
13257 length = array ? array.length : 0,
13258 seen = caches[0];
13259
13260 outer:
13261 while (++index < length) {
13262 value = array[index];
13263 if ((seen ? cacheIndexOf(seen, value) : indexOf(result, value, 0)) < 0) {
13264 var othIndex = othLength;
13265 while (--othIndex) {
13266 var cache = caches[othIndex];
13267 if ((cache ? cacheIndexOf(cache, value) : indexOf(arrays[othIndex], value, 0)) < 0) {
13268 continue outer;
13269 }
13270 }
13271 if (seen) {
13272 seen.push(value);
13273 }
13274 result.push(value);
13275 }
13276 }
13277 return result;
13278 });
13279
13280 /**
13281 * Gets the last element of `array`.
13282 *
13283 * @static
13284 * @memberOf _
13285 * @category Array
13286 * @param {Array} array The array to query.
13287 * @returns {*} Returns the last element of `array`.
13288 * @example
13289 *
13290 * _.last([1, 2, 3]);
13291 * // => 3
13292 */
13293 function last(array) {
13294 var length = array ? array.length : 0;
13295 return length ? array[length - 1] : undefined;
13296 }
13297
13298 /**
13299 * This method is like `_.indexOf` except that it iterates over elements of
13300 * `array` from right to left.
13301 *
13302 * @static
13303 * @memberOf _
13304 * @category Array
13305 * @param {Array} array The array to search.
13306 * @param {*} value The value to search for.
13307 * @param {boolean|number} [fromIndex=array.length-1] The index to search from
13308 * or `true` to perform a binary search on a sorted array.
13309 * @returns {number} Returns the index of the matched value, else `-1`.
13310 * @example
13311 *
13312 * _.lastIndexOf([1, 2, 1, 2], 2);
13313 * // => 3
13314 *
13315 * // using `fromIndex`
13316 * _.lastIndexOf([1, 2, 1, 2], 2, 2);
13317 * // => 1
13318 *
13319 * // performing a binary search
13320 * _.lastIndexOf([1, 1, 2, 2], 2, true);
13321 * // => 3
13322 */
13323 function lastIndexOf(array, value, fromIndex) {
13324 var length = array ? array.length : 0;
13325 if (!length) {
13326 return -1;
13327 }
13328 var index = length;
13329 if (typeof fromIndex == 'number') {
13330 index = (fromIndex < 0 ? nativeMax(length + fromIndex, 0) : nativeMin(fromIndex || 0, length - 1)) + 1;
13331 } else if (fromIndex) {
13332 index = binaryIndex(array, value, true) - 1;
13333 var other = array[index];
13334 if (value === value ? (value === other) : (other !== other)) {
13335 return index;
13336 }
13337 return -1;
13338 }
13339 if (value !== value) {
13340 return indexOfNaN(array, index, true);
13341 }
13342 while (index--) {
13343 if (array[index] === value) {
13344 return index;
13345 }
13346 }
13347 return -1;
13348 }
13349
13350 /**
13351 * Removes all provided values from `array` using
13352 * [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
13353 * for equality comparisons.
13354 *
13355 * **Note:** Unlike `_.without`, this method mutates `array`.
13356 *
13357 * @static
13358 * @memberOf _
13359 * @category Array
13360 * @param {Array} array The array to modify.
13361 * @param {...*} [values] The values to remove.
13362 * @returns {Array} Returns `array`.
13363 * @example
13364 *
13365 * var array = [1, 2, 3, 1, 2, 3];
13366 *
13367 * _.pull(array, 2, 3);
13368 * console.log(array);
13369 * // => [1, 1]
13370 */
13371 function pull() {
13372 var args = arguments,
13373 array = args[0];
13374
13375 if (!(array && array.length)) {
13376 return array;
13377 }
13378 var index = 0,
13379 indexOf = getIndexOf(),
13380 length = args.length;
13381
13382 while (++index < length) {
13383 var fromIndex = 0,
13384 value = args[index];
13385
13386 while ((fromIndex = indexOf(array, value, fromIndex)) > -1) {
13387 splice.call(array, fromIndex, 1);
13388 }
13389 }
13390 return array;
13391 }
13392
13393 /**
13394 * Removes elements from `array` corresponding to the given indexes and returns
13395 * an array of the removed elements. Indexes may be specified as an array of
13396 * indexes or as individual arguments.
13397 *
13398 * **Note:** Unlike `_.at`, this method mutates `array`.
13399 *
13400 * @static
13401 * @memberOf _
13402 * @category Array
13403 * @param {Array} array The array to modify.
13404 * @param {...(number|number[])} [indexes] The indexes of elements to remove,
13405 * specified as individual indexes or arrays of indexes.
13406 * @returns {Array} Returns the new array of removed elements.
13407 * @example
13408 *
13409 * var array = [5, 10, 15, 20];
13410 * var evens = _.pullAt(array, 1, 3);
13411 *
13412 * console.log(array);
13413 * // => [5, 15]
13414 *
13415 * console.log(evens);
13416 * // => [10, 20]
13417 */
13418 var pullAt = restParam(function(array, indexes) {
13419 indexes = baseFlatten(indexes);
13420
13421 var result = baseAt(array, indexes);
13422 basePullAt(array, indexes.sort(baseCompareAscending));
13423 return result;
13424 });
13425
13426 /**
13427 * Removes all elements from `array` that `predicate` returns truthy for
13428 * and returns an array of the removed elements. The predicate is bound to
13429 * `thisArg` and invoked with three arguments: (value, index, array).
13430 *
13431 * If a property name is provided for `predicate` the created `_.property`
13432 * style callback returns the property value of the given element.
13433 *
13434 * If a value is also provided for `thisArg` the created `_.matchesProperty`
13435 * style callback returns `true` for elements that have a matching property
13436 * value, else `false`.
13437 *
13438 * If an object is provided for `predicate` the created `_.matches` style
13439 * callback returns `true` for elements that have the properties of the given
13440 * object, else `false`.
13441 *
13442 * **Note:** Unlike `_.filter`, this method mutates `array`.
13443 *
13444 * @static
13445 * @memberOf _
13446 * @category Array
13447 * @param {Array} array The array to modify.
13448 * @param {Function|Object|string} [predicate=_.identity] The function invoked
13449 * per iteration.
13450 * @param {*} [thisArg] The `this` binding of `predicate`.
13451 * @returns {Array} Returns the new array of removed elements.
13452 * @example
13453 *
13454 * var array = [1, 2, 3, 4];
13455 * var evens = _.remove(array, function(n) {
13456 * return n % 2 == 0;
13457 * });
13458 *
13459 * console.log(array);
13460 * // => [1, 3]
13461 *
13462 * console.log(evens);
13463 * // => [2, 4]
13464 */
13465 function remove(array, predicate, thisArg) {
13466 var result = [];
13467 if (!(array && array.length)) {
13468 return result;
13469 }
13470 var index = -1,
13471 indexes = [],
13472 length = array.length;
13473
13474 predicate = getCallback(predicate, thisArg, 3);
13475 while (++index < length) {
13476 var value = array[index];
13477 if (predicate(value, index, array)) {
13478 result.push(value);
13479 indexes.push(index);
13480 }
13481 }
13482 basePullAt(array, indexes);
13483 return result;
13484 }
13485
13486 /**
13487 * Gets all but the first element of `array`.
13488 *
13489 * @static
13490 * @memberOf _
13491 * @alias tail
13492 * @category Array
13493 * @param {Array} array The array to query.
13494 * @returns {Array} Returns the slice of `array`.
13495 * @example
13496 *
13497 * _.rest([1, 2, 3]);
13498 * // => [2, 3]
13499 */
13500 function rest(array) {
13501 return drop(array, 1);
13502 }
13503
13504 /**
13505 * Creates a slice of `array` from `start` up to, but not including, `end`.
13506 *
13507 * **Note:** This method is used instead of `Array#slice` to support node
13508 * lists in IE < 9 and to ensure dense arrays are returned.
13509 *
13510 * @static
13511 * @memberOf _
13512 * @category Array
13513 * @param {Array} array The array to slice.
13514 * @param {number} [start=0] The start position.
13515 * @param {number} [end=array.length] The end position.
13516 * @returns {Array} Returns the slice of `array`.
13517 */
13518 function slice(array, start, end) {
13519 var length = array ? array.length : 0;
13520 if (!length) {
13521 return [];
13522 }
13523 if (end && typeof end != 'number' && isIterateeCall(array, start, end)) {
13524 start = 0;
13525 end = length;
13526 }
13527 return baseSlice(array, start, end);
13528 }
13529
13530 /**
13531 * Uses a binary search to determine the lowest index at which `value` should
13532 * be inserted into `array` in order to maintain its sort order. If an iteratee
13533 * function is provided it is invoked for `value` and each element of `array`
13534 * to compute their sort ranking. The iteratee is bound to `thisArg` and
13535 * invoked with one argument; (value).
13536 *
13537 * If a property name is provided for `iteratee` the created `_.property`
13538 * style callback returns the property value of the given element.
13539 *
13540 * If a value is also provided for `thisArg` the created `_.matchesProperty`
13541 * style callback returns `true` for elements that have a matching property
13542 * value, else `false`.
13543 *
13544 * If an object is provided for `iteratee` the created `_.matches` style
13545 * callback returns `true` for elements that have the properties of the given
13546 * object, else `false`.
13547 *
13548 * @static
13549 * @memberOf _
13550 * @category Array
13551 * @param {Array} array The sorted array to inspect.
13552 * @param {*} value The value to evaluate.
13553 * @param {Function|Object|string} [iteratee=_.identity] The function invoked
13554 * per iteration.
13555 * @param {*} [thisArg] The `this` binding of `iteratee`.
13556 * @returns {number} Returns the index at which `value` should be inserted
13557 * into `array`.
13558 * @example
13559 *
13560 * _.sortedIndex([30, 50], 40);
13561 * // => 1
13562 *
13563 * _.sortedIndex([4, 4, 5, 5], 5);
13564 * // => 2
13565 *
13566 * var dict = { 'data': { 'thirty': 30, 'forty': 40, 'fifty': 50 } };
13567 *
13568 * // using an iteratee function
13569 * _.sortedIndex(['thirty', 'fifty'], 'forty', function(word) {
13570 * return this.data[word];
13571 * }, dict);
13572 * // => 1
13573 *
13574 * // using the `_.property` callback shorthand
13575 * _.sortedIndex([{ 'x': 30 }, { 'x': 50 }], { 'x': 40 }, 'x');
13576 * // => 1
13577 */
13578 var sortedIndex = createSortedIndex();
13579
13580 /**
13581 * This method is like `_.sortedIndex` except that it returns the highest
13582 * index at which `value` should be inserted into `array` in order to
13583 * maintain its sort order.
13584 *
13585 * @static
13586 * @memberOf _
13587 * @category Array
13588 * @param {Array} array The sorted array to inspect.
13589 * @param {*} value The value to evaluate.
13590 * @param {Function|Object|string} [iteratee=_.identity] The function invoked
13591 * per iteration.
13592 * @param {*} [thisArg] The `this` binding of `iteratee`.
13593 * @returns {number} Returns the index at which `value` should be inserted
13594 * into `array`.
13595 * @example
13596 *
13597 * _.sortedLastIndex([4, 4, 5, 5], 5);
13598 * // => 4
13599 */
13600 var sortedLastIndex = createSortedIndex(true);
13601
13602 /**
13603 * Creates a slice of `array` with `n` elements taken from the beginning.
13604 *
13605 * @static
13606 * @memberOf _
13607 * @category Array
13608 * @param {Array} array The array to query.
13609 * @param {number} [n=1] The number of elements to take.
13610 * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
13611 * @returns {Array} Returns the slice of `array`.
13612 * @example
13613 *
13614 * _.take([1, 2, 3]);
13615 * // => [1]
13616 *
13617 * _.take([1, 2, 3], 2);
13618 * // => [1, 2]
13619 *
13620 * _.take([1, 2, 3], 5);
13621 * // => [1, 2, 3]
13622 *
13623 * _.take([1, 2, 3], 0);
13624 * // => []
13625 */
13626 function take(array, n, guard) {
13627 var length = array ? array.length : 0;
13628 if (!length) {
13629 return [];
13630 }
13631 if (guard ? isIterateeCall(array, n, guard) : n == null) {
13632 n = 1;
13633 }
13634 return baseSlice(array, 0, n < 0 ? 0 : n);
13635 }
13636
13637 /**
13638 * Creates a slice of `array` with `n` elements taken from the end.
13639 *
13640 * @static
13641 * @memberOf _
13642 * @category Array
13643 * @param {Array} array The array to query.
13644 * @param {number} [n=1] The number of elements to take.
13645 * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
13646 * @returns {Array} Returns the slice of `array`.
13647 * @example
13648 *
13649 * _.takeRight([1, 2, 3]);
13650 * // => [3]
13651 *
13652 * _.takeRight([1, 2, 3], 2);
13653 * // => [2, 3]
13654 *
13655 * _.takeRight([1, 2, 3], 5);
13656 * // => [1, 2, 3]
13657 *
13658 * _.takeRight([1, 2, 3], 0);
13659 * // => []
13660 */
13661 function takeRight(array, n, guard) {
13662 var length = array ? array.length : 0;
13663 if (!length) {
13664 return [];
13665 }
13666 if (guard ? isIterateeCall(array, n, guard) : n == null) {
13667 n = 1;
13668 }
13669 n = length - (+n || 0);
13670 return baseSlice(array, n < 0 ? 0 : n);
13671 }
13672
13673 /**
13674 * Creates a slice of `array` with elements taken from the end. Elements are
13675 * taken until `predicate` returns falsey. The predicate is bound to `thisArg`
13676 * and invoked with three arguments: (value, index, array).
13677 *
13678 * If a property name is provided for `predicate` the created `_.property`
13679 * style callback returns the property value of the given element.
13680 *
13681 * If a value is also provided for `thisArg` the created `_.matchesProperty`
13682 * style callback returns `true` for elements that have a matching property
13683 * value, else `false`.
13684 *
13685 * If an object is provided for `predicate` the created `_.matches` style
13686 * callback returns `true` for elements that have the properties of the given
13687 * object, else `false`.
13688 *
13689 * @static
13690 * @memberOf _
13691 * @category Array
13692 * @param {Array} array The array to query.
13693 * @param {Function|Object|string} [predicate=_.identity] The function invoked
13694 * per iteration.
13695 * @param {*} [thisArg] The `this` binding of `predicate`.
13696 * @returns {Array} Returns the slice of `array`.
13697 * @example
13698 *
13699 * _.takeRightWhile([1, 2, 3], function(n) {
13700 * return n > 1;
13701 * });
13702 * // => [2, 3]
13703 *
13704 * var users = [
13705 * { 'user': 'barney', 'active': true },
13706 * { 'user': 'fred', 'active': false },
13707 * { 'user': 'pebbles', 'active': false }
13708 * ];
13709 *
13710 * // using the `_.matches` callback shorthand
13711 * _.pluck(_.takeRightWhile(users, { 'user': 'pebbles', 'active': false }), 'user');
13712 * // => ['pebbles']
13713 *
13714 * // using the `_.matchesProperty` callback shorthand
13715 * _.pluck(_.takeRightWhile(users, 'active', false), 'user');
13716 * // => ['fred', 'pebbles']
13717 *
13718 * // using the `_.property` callback shorthand
13719 * _.pluck(_.takeRightWhile(users, 'active'), 'user');
13720 * // => []
13721 */
13722 function takeRightWhile(array, predicate, thisArg) {
13723 return (array && array.length)
13724 ? baseWhile(array, getCallback(predicate, thisArg, 3), false, true)
13725 : [];
13726 }
13727
13728 /**
13729 * Creates a slice of `array` with elements taken from the beginning. Elements
13730 * are taken until `predicate` returns falsey. The predicate is bound to
13731 * `thisArg` and invoked with three arguments: (value, index, array).
13732 *
13733 * If a property name is provided for `predicate` the created `_.property`
13734 * style callback returns the property value of the given element.
13735 *
13736 * If a value is also provided for `thisArg` the created `_.matchesProperty`
13737 * style callback returns `true` for elements that have a matching property
13738 * value, else `false`.
13739 *
13740 * If an object is provided for `predicate` the created `_.matches` style
13741 * callback returns `true` for elements that have the properties of the given
13742 * object, else `false`.
13743 *
13744 * @static
13745 * @memberOf _
13746 * @category Array
13747 * @param {Array} array The array to query.
13748 * @param {Function|Object|string} [predicate=_.identity] The function invoked
13749 * per iteration.
13750 * @param {*} [thisArg] The `this` binding of `predicate`.
13751 * @returns {Array} Returns the slice of `array`.
13752 * @example
13753 *
13754 * _.takeWhile([1, 2, 3], function(n) {
13755 * return n < 3;
13756 * });
13757 * // => [1, 2]
13758 *
13759 * var users = [
13760 * { 'user': 'barney', 'active': false },
13761 * { 'user': 'fred', 'active': false},
13762 * { 'user': 'pebbles', 'active': true }
13763 * ];
13764 *
13765 * // using the `_.matches` callback shorthand
13766 * _.pluck(_.takeWhile(users, { 'user': 'barney', 'active': false }), 'user');
13767 * // => ['barney']
13768 *
13769 * // using the `_.matchesProperty` callback shorthand
13770 * _.pluck(_.takeWhile(users, 'active', false), 'user');
13771 * // => ['barney', 'fred']
13772 *
13773 * // using the `_.property` callback shorthand
13774 * _.pluck(_.takeWhile(users, 'active'), 'user');
13775 * // => []
13776 */
13777 function takeWhile(array, predicate, thisArg) {
13778 return (array && array.length)
13779 ? baseWhile(array, getCallback(predicate, thisArg, 3))
13780 : [];
13781 }
13782
13783 /**
13784 * Creates an array of unique values, in order, from all of the provided arrays
13785 * using [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
13786 * for equality comparisons.
13787 *
13788 * @static
13789 * @memberOf _
13790 * @category Array
13791 * @param {...Array} [arrays] The arrays to inspect.
13792 * @returns {Array} Returns the new array of combined values.
13793 * @example
13794 *
13795 * _.union([1, 2], [4, 2], [2, 1]);
13796 * // => [1, 2, 4]
13797 */
13798 var union = restParam(function(arrays) {
13799 return baseUniq(baseFlatten(arrays, false, true));
13800 });
13801
13802 /**
13803 * Creates a duplicate-free version of an array, using
13804 * [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
13805 * for equality comparisons, in which only the first occurence of each element
13806 * is kept. Providing `true` for `isSorted` performs a faster search algorithm
13807 * for sorted arrays. If an iteratee function is provided it is invoked for
13808 * each element in the array to generate the criterion by which uniqueness
13809 * is computed. The `iteratee` is bound to `thisArg` and invoked with three
13810 * arguments: (value, index, array).
13811 *
13812 * If a property name is provided for `iteratee` the created `_.property`
13813 * style callback returns the property value of the given element.
13814 *
13815 * If a value is also provided for `thisArg` the created `_.matchesProperty`
13816 * style callback returns `true` for elements that have a matching property
13817 * value, else `false`.
13818 *
13819 * If an object is provided for `iteratee` the created `_.matches` style
13820 * callback returns `true` for elements that have the properties of the given
13821 * object, else `false`.
13822 *
13823 * @static
13824 * @memberOf _
13825 * @alias unique
13826 * @category Array
13827 * @param {Array} array The array to inspect.
13828 * @param {boolean} [isSorted] Specify the array is sorted.
13829 * @param {Function|Object|string} [iteratee] The function invoked per iteration.
13830 * @param {*} [thisArg] The `this` binding of `iteratee`.
13831 * @returns {Array} Returns the new duplicate-value-free array.
13832 * @example
13833 *
13834 * _.uniq([2, 1, 2]);
13835 * // => [2, 1]
13836 *
13837 * // using `isSorted`
13838 * _.uniq([1, 1, 2], true);
13839 * // => [1, 2]
13840 *
13841 * // using an iteratee function
13842 * _.uniq([1, 2.5, 1.5, 2], function(n) {
13843 * return this.floor(n);
13844 * }, Math);
13845 * // => [1, 2.5]
13846 *
13847 * // using the `_.property` callback shorthand
13848 * _.uniq([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x');
13849 * // => [{ 'x': 1 }, { 'x': 2 }]
13850 */
13851 function uniq(array, isSorted, iteratee, thisArg) {
13852 var length = array ? array.length : 0;
13853 if (!length) {
13854 return [];
13855 }
13856 if (isSorted != null && typeof isSorted != 'boolean') {
13857 thisArg = iteratee;
13858 iteratee = isIterateeCall(array, isSorted, thisArg) ? undefined : isSorted;
13859 isSorted = false;
13860 }
13861 var callback = getCallback();
13862 if (!(iteratee == null && callback === baseCallback)) {
13863 iteratee = callback(iteratee, thisArg, 3);
13864 }
13865 return (isSorted && getIndexOf() == baseIndexOf)
13866 ? sortedUniq(array, iteratee)
13867 : baseUniq(array, iteratee);
13868 }
13869
13870 /**
13871 * This method is like `_.zip` except that it accepts an array of grouped
13872 * elements and creates an array regrouping the elements to their pre-zip
13873 * configuration.
13874 *
13875 * @static
13876 * @memberOf _
13877 * @category Array
13878 * @param {Array} array The array of grouped elements to process.
13879 * @returns {Array} Returns the new array of regrouped elements.
13880 * @example
13881 *
13882 * var zipped = _.zip(['fred', 'barney'], [30, 40], [true, false]);
13883 * // => [['fred', 30, true], ['barney', 40, false]]
13884 *
13885 * _.unzip(zipped);
13886 * // => [['fred', 'barney'], [30, 40], [true, false]]
13887 */
13888 function unzip(array) {
13889 if (!(array && array.length)) {
13890 return [];
13891 }
13892 var index = -1,
13893 length = 0;
13894
13895 array = arrayFilter(array, function(group) {
13896 if (isArrayLike(group)) {
13897 length = nativeMax(group.length, length);
13898 return true;
13899 }
13900 });
13901 var result = Array(length);
13902 while (++index < length) {
13903 result[index] = arrayMap(array, baseProperty(index));
13904 }
13905 return result;
13906 }
13907
13908 /**
13909 * This method is like `_.unzip` except that it accepts an iteratee to specify
13910 * how regrouped values should be combined. The `iteratee` is bound to `thisArg`
13911 * and invoked with four arguments: (accumulator, value, index, group).
13912 *
13913 * @static
13914 * @memberOf _
13915 * @category Array
13916 * @param {Array} array The array of grouped elements to process.
13917 * @param {Function} [iteratee] The function to combine regrouped values.
13918 * @param {*} [thisArg] The `this` binding of `iteratee`.
13919 * @returns {Array} Returns the new array of regrouped elements.
13920 * @example
13921 *
13922 * var zipped = _.zip([1, 2], [10, 20], [100, 200]);
13923 * // => [[1, 10, 100], [2, 20, 200]]
13924 *
13925 * _.unzipWith(zipped, _.add);
13926 * // => [3, 30, 300]
13927 */
13928 function unzipWith(array, iteratee, thisArg) {
13929 var length = array ? array.length : 0;
13930 if (!length) {
13931 return [];
13932 }
13933 var result = unzip(array);
13934 if (iteratee == null) {
13935 return result;
13936 }
13937 iteratee = bindCallback(iteratee, thisArg, 4);
13938 return arrayMap(result, function(group) {
13939 return arrayReduce(group, iteratee, undefined, true);
13940 });
13941 }
13942
13943 /**
13944 * Creates an array excluding all provided values using
13945 * [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
13946 * for equality comparisons.
13947 *
13948 * @static
13949 * @memberOf _
13950 * @category Array
13951 * @param {Array} array The array to filter.
13952 * @param {...*} [values] The values to exclude.
13953 * @returns {Array} Returns the new array of filtered values.
13954 * @example
13955 *
13956 * _.without([1, 2, 1, 3], 1, 2);
13957 * // => [3]
13958 */
13959 var without = restParam(function(array, values) {
13960 return isArrayLike(array)
13961 ? baseDifference(array, values)
13962 : [];
13963 });
13964
13965 /**
13966 * Creates an array of unique values that is the [symmetric difference](https://en.wikipedia.org/wiki/Symmetric_difference)
13967 * of the provided arrays.
13968 *
13969 * @static
13970 * @memberOf _
13971 * @category Array
13972 * @param {...Array} [arrays] The arrays to inspect.
13973 * @returns {Array} Returns the new array of values.
13974 * @example
13975 *
13976 * _.xor([1, 2], [4, 2]);
13977 * // => [1, 4]
13978 */
13979 function xor() {
13980 var index = -1,
13981 length = arguments.length;
13982
13983 while (++index < length) {
13984 var array = arguments[index];
13985 if (isArrayLike(array)) {
13986 var result = result
13987 ? arrayPush(baseDifference(result, array), baseDifference(array, result))
13988 : array;
13989 }
13990 }
13991 return result ? baseUniq(result) : [];
13992 }
13993
13994 /**
13995 * Creates an array of grouped elements, the first of which contains the first
13996 * elements of the given arrays, the second of which contains the second elements
13997 * of the given arrays, and so on.
13998 *
13999 * @static
14000 * @memberOf _
14001 * @category Array
14002 * @param {...Array} [arrays] The arrays to process.
14003 * @returns {Array} Returns the new array of grouped elements.
14004 * @example
14005 *
14006 * _.zip(['fred', 'barney'], [30, 40], [true, false]);
14007 * // => [['fred', 30, true], ['barney', 40, false]]
14008 */
14009 var zip = restParam(unzip);
14010
14011 /**
14012 * The inverse of `_.pairs`; this method returns an object composed from arrays
14013 * of property names and values. Provide either a single two dimensional array,
14014 * e.g. `[[key1, value1], [key2, value2]]` or two arrays, one of property names
14015 * and one of corresponding values.
14016 *
14017 * @static
14018 * @memberOf _
14019 * @alias object
14020 * @category Array
14021 * @param {Array} props The property names.
14022 * @param {Array} [values=[]] The property values.
14023 * @returns {Object} Returns the new object.
14024 * @example
14025 *
14026 * _.zipObject([['fred', 30], ['barney', 40]]);
14027 * // => { 'fred': 30, 'barney': 40 }
14028 *
14029 * _.zipObject(['fred', 'barney'], [30, 40]);
14030 * // => { 'fred': 30, 'barney': 40 }
14031 */
14032 function zipObject(props, values) {
14033 var index = -1,
14034 length = props ? props.length : 0,
14035 result = {};
14036
14037 if (length && !values && !isArray(props[0])) {
14038 values = [];
14039 }
14040 while (++index < length) {
14041 var key = props[index];
14042 if (values) {
14043 result[key] = values[index];
14044 } else if (key) {
14045 result[key[0]] = key[1];
14046 }
14047 }
14048 return result;
14049 }
14050
14051 /**
14052 * This method is like `_.zip` except that it accepts an iteratee to specify
14053 * how grouped values should be combined. The `iteratee` is bound to `thisArg`
14054 * and invoked with four arguments: (accumulator, value, index, group).
14055 *
14056 * @static
14057 * @memberOf _
14058 * @category Array
14059 * @param {...Array} [arrays] The arrays to process.
14060 * @param {Function} [iteratee] The function to combine grouped values.
14061 * @param {*} [thisArg] The `this` binding of `iteratee`.
14062 * @returns {Array} Returns the new array of grouped elements.
14063 * @example
14064 *
14065 * _.zipWith([1, 2], [10, 20], [100, 200], _.add);
14066 * // => [111, 222]
14067 */
14068 var zipWith = restParam(function(arrays) {
14069 var length = arrays.length,
14070 iteratee = length > 2 ? arrays[length - 2] : undefined,
14071 thisArg = length > 1 ? arrays[length - 1] : undefined;
14072
14073 if (length > 2 && typeof iteratee == 'function') {
14074 length -= 2;
14075 } else {
14076 iteratee = (length > 1 && typeof thisArg == 'function') ? (--length, thisArg) : undefined;
14077 thisArg = undefined;
14078 }
14079 arrays.length = length;
14080 return unzipWith(arrays, iteratee, thisArg);
14081 });
14082
14083 /*------------------------------------------------------------------------*/
14084
14085 /**
14086 * Creates a `lodash` object that wraps `value` with explicit method
14087 * chaining enabled.
14088 *
14089 * @static
14090 * @memberOf _
14091 * @category Chain
14092 * @param {*} value The value to wrap.
14093 * @returns {Object} Returns the new `lodash` wrapper instance.
14094 * @example
14095 *
14096 * var users = [
14097 * { 'user': 'barney', 'age': 36 },
14098 * { 'user': 'fred', 'age': 40 },
14099 * { 'user': 'pebbles', 'age': 1 }
14100 * ];
14101 *
14102 * var youngest = _.chain(users)
14103 * .sortBy('age')
14104 * .map(function(chr) {
14105 * return chr.user + ' is ' + chr.age;
14106 * })
14107 * .first()
14108 * .value();
14109 * // => 'pebbles is 1'
14110 */
14111 function chain(value) {
14112 var result = lodash(value);
14113 result.__chain__ = true;
14114 return result;
14115 }
14116
14117 /**
14118 * This method invokes `interceptor` and returns `value`. The interceptor is
14119 * bound to `thisArg` and invoked with one argument; (value). The purpose of
14120 * this method is to "tap into" a method chain in order to perform operations
14121 * on intermediate results within the chain.
14122 *
14123 * @static
14124 * @memberOf _
14125 * @category Chain
14126 * @param {*} value The value to provide to `interceptor`.
14127 * @param {Function} interceptor The function to invoke.
14128 * @param {*} [thisArg] The `this` binding of `interceptor`.
14129 * @returns {*} Returns `value`.
14130 * @example
14131 *
14132 * _([1, 2, 3])
14133 * .tap(function(array) {
14134 * array.pop();
14135 * })
14136 * .reverse()
14137 * .value();
14138 * // => [2, 1]
14139 */
14140 function tap(value, interceptor, thisArg) {
14141 interceptor.call(thisArg, value);
14142 return value;
14143 }
14144
14145 /**
14146 * This method is like `_.tap` except that it returns the result of `interceptor`.
14147 *
14148 * @static
14149 * @memberOf _
14150 * @category Chain
14151 * @param {*} value The value to provide to `interceptor`.
14152 * @param {Function} interceptor The function to invoke.
14153 * @param {*} [thisArg] The `this` binding of `interceptor`.
14154 * @returns {*} Returns the result of `interceptor`.
14155 * @example
14156 *
14157 * _(' abc ')
14158 * .chain()
14159 * .trim()
14160 * .thru(function(value) {
14161 * return [value];
14162 * })
14163 * .value();
14164 * // => ['abc']
14165 */
14166 function thru(value, interceptor, thisArg) {
14167 return interceptor.call(thisArg, value);
14168 }
14169
14170 /**
14171 * Enables explicit method chaining on the wrapper object.
14172 *
14173 * @name chain
14174 * @memberOf _
14175 * @category Chain
14176 * @returns {Object} Returns the new `lodash` wrapper instance.
14177 * @example
14178 *
14179 * var users = [
14180 * { 'user': 'barney', 'age': 36 },
14181 * { 'user': 'fred', 'age': 40 }
14182 * ];
14183 *
14184 * // without explicit chaining
14185 * _(users).first();
14186 * // => { 'user': 'barney', 'age': 36 }
14187 *
14188 * // with explicit chaining
14189 * _(users).chain()
14190 * .first()
14191 * .pick('user')
14192 * .value();
14193 * // => { 'user': 'barney' }
14194 */
14195 function wrapperChain() {
14196 return chain(this);
14197 }
14198
14199 /**
14200 * Executes the chained sequence and returns the wrapped result.
14201 *
14202 * @name commit
14203 * @memberOf _
14204 * @category Chain
14205 * @returns {Object} Returns the new `lodash` wrapper instance.
14206 * @example
14207 *
14208 * var array = [1, 2];
14209 * var wrapped = _(array).push(3);
14210 *
14211 * console.log(array);
14212 * // => [1, 2]
14213 *
14214 * wrapped = wrapped.commit();
14215 * console.log(array);
14216 * // => [1, 2, 3]
14217 *
14218 * wrapped.last();
14219 * // => 3
14220 *
14221 * console.log(array);
14222 * // => [1, 2, 3]
14223 */
14224 function wrapperCommit() {
14225 return new LodashWrapper(this.value(), this.__chain__);
14226 }
14227
14228 /**
14229 * Creates a new array joining a wrapped array with any additional arrays
14230 * and/or values.
14231 *
14232 * @name concat
14233 * @memberOf _
14234 * @category Chain
14235 * @param {...*} [values] The values to concatenate.
14236 * @returns {Array} Returns the new concatenated array.
14237 * @example
14238 *
14239 * var array = [1];
14240 * var wrapped = _(array).concat(2, [3], [[4]]);
14241 *
14242 * console.log(wrapped.value());
14243 * // => [1, 2, 3, [4]]
14244 *
14245 * console.log(array);
14246 * // => [1]
14247 */
14248 var wrapperConcat = restParam(function(values) {
14249 values = baseFlatten(values);
14250 return this.thru(function(array) {
14251 return arrayConcat(isArray(array) ? array : [toObject(array)], values);
14252 });
14253 });
14254
14255 /**
14256 * Creates a clone of the chained sequence planting `value` as the wrapped value.
14257 *
14258 * @name plant
14259 * @memberOf _
14260 * @category Chain
14261 * @returns {Object} Returns the new `lodash` wrapper instance.
14262 * @example
14263 *
14264 * var array = [1, 2];
14265 * var wrapped = _(array).map(function(value) {
14266 * return Math.pow(value, 2);
14267 * });
14268 *
14269 * var other = [3, 4];
14270 * var otherWrapped = wrapped.plant(other);
14271 *
14272 * otherWrapped.value();
14273 * // => [9, 16]
14274 *
14275 * wrapped.value();
14276 * // => [1, 4]
14277 */
14278 function wrapperPlant(value) {
14279 var result,
14280 parent = this;
14281
14282 while (parent instanceof baseLodash) {
14283 var clone = wrapperClone(parent);
14284 if (result) {
14285 previous.__wrapped__ = clone;
14286 } else {
14287 result = clone;
14288 }
14289 var previous = clone;
14290 parent = parent.__wrapped__;
14291 }
14292 previous.__wrapped__ = value;
14293 return result;
14294 }
14295
14296 /**
14297 * Reverses the wrapped array so the first element becomes the last, the
14298 * second element becomes the second to last, and so on.
14299 *
14300 * **Note:** This method mutates the wrapped array.
14301 *
14302 * @name reverse
14303 * @memberOf _
14304 * @category Chain
14305 * @returns {Object} Returns the new reversed `lodash` wrapper instance.
14306 * @example
14307 *
14308 * var array = [1, 2, 3];
14309 *
14310 * _(array).reverse().value()
14311 * // => [3, 2, 1]
14312 *
14313 * console.log(array);
14314 * // => [3, 2, 1]
14315 */
14316 function wrapperReverse() {
14317 var value = this.__wrapped__;
14318
14319 var interceptor = function(value) {
14320 return (wrapped && wrapped.__dir__ < 0) ? value : value.reverse();
14321 };
14322 if (value instanceof LazyWrapper) {
14323 var wrapped = value;
14324 if (this.__actions__.length) {
14325 wrapped = new LazyWrapper(this);
14326 }
14327 wrapped = wrapped.reverse();
14328 wrapped.__actions__.push({ 'func': thru, 'args': [interceptor], 'thisArg': undefined });
14329 return new LodashWrapper(wrapped, this.__chain__);
14330 }
14331 return this.thru(interceptor);
14332 }
14333
14334 /**
14335 * Produces the result of coercing the unwrapped value to a string.
14336 *
14337 * @name toString
14338 * @memberOf _
14339 * @category Chain
14340 * @returns {string} Returns the coerced string value.
14341 * @example
14342 *
14343 * _([1, 2, 3]).toString();
14344 * // => '1,2,3'
14345 */
14346 function wrapperToString() {
14347 return (this.value() + '');
14348 }
14349
14350 /**
14351 * Executes the chained sequence to extract the unwrapped value.
14352 *
14353 * @name value
14354 * @memberOf _
14355 * @alias run, toJSON, valueOf
14356 * @category Chain
14357 * @returns {*} Returns the resolved unwrapped value.
14358 * @example
14359 *
14360 * _([1, 2, 3]).value();
14361 * // => [1, 2, 3]
14362 */
14363 function wrapperValue() {
14364 return baseWrapperValue(this.__wrapped__, this.__actions__);
14365 }
14366
14367 /*------------------------------------------------------------------------*/
14368
14369 /**
14370 * Creates an array of elements corresponding to the given keys, or indexes,
14371 * of `collection`. Keys may be specified as individual arguments or as arrays
14372 * of keys.
14373 *
14374 * @static
14375 * @memberOf _
14376 * @category Collection
14377 * @param {Array|Object|string} collection The collection to iterate over.
14378 * @param {...(number|number[]|string|string[])} [props] The property names
14379 * or indexes of elements to pick, specified individually or in arrays.
14380 * @returns {Array} Returns the new array of picked elements.
14381 * @example
14382 *
14383 * _.at(['a', 'b', 'c'], [0, 2]);
14384 * // => ['a', 'c']
14385 *
14386 * _.at(['barney', 'fred', 'pebbles'], 0, 2);
14387 * // => ['barney', 'pebbles']
14388 */
14389 var at = restParam(function(collection, props) {
14390 return baseAt(collection, baseFlatten(props));
14391 });
14392
14393 /**
14394 * Creates an object composed of keys generated from the results of running
14395 * each element of `collection` through `iteratee`. The corresponding value
14396 * of each key is the number of times the key was returned by `iteratee`.
14397 * The `iteratee` is bound to `thisArg` and invoked with three arguments:
14398 * (value, index|key, collection).
14399 *
14400 * If a property name is provided for `iteratee` the created `_.property`
14401 * style callback returns the property value of the given element.
14402 *
14403 * If a value is also provided for `thisArg` the created `_.matchesProperty`
14404 * style callback returns `true` for elements that have a matching property
14405 * value, else `false`.
14406 *
14407 * If an object is provided for `iteratee` the created `_.matches` style
14408 * callback returns `true` for elements that have the properties of the given
14409 * object, else `false`.
14410 *
14411 * @static
14412 * @memberOf _
14413 * @category Collection
14414 * @param {Array|Object|string} collection The collection to iterate over.
14415 * @param {Function|Object|string} [iteratee=_.identity] The function invoked
14416 * per iteration.
14417 * @param {*} [thisArg] The `this` binding of `iteratee`.
14418 * @returns {Object} Returns the composed aggregate object.
14419 * @example
14420 *
14421 * _.countBy([4.3, 6.1, 6.4], function(n) {
14422 * return Math.floor(n);
14423 * });
14424 * // => { '4': 1, '6': 2 }
14425 *
14426 * _.countBy([4.3, 6.1, 6.4], function(n) {
14427 * return this.floor(n);
14428 * }, Math);
14429 * // => { '4': 1, '6': 2 }
14430 *
14431 * _.countBy(['one', 'two', 'three'], 'length');
14432 * // => { '3': 2, '5': 1 }
14433 */
14434 var countBy = createAggregator(function(result, value, key) {
14435 hasOwnProperty.call(result, key) ? ++result[key] : (result[key] = 1);
14436 });
14437
14438 /**
14439 * Checks if `predicate` returns truthy for **all** elements of `collection`.
14440 * The predicate is bound to `thisArg` and invoked with three arguments:
14441 * (value, index|key, collection).
14442 *
14443 * If a property name is provided for `predicate` the created `_.property`
14444 * style callback returns the property value of the given element.
14445 *
14446 * If a value is also provided for `thisArg` the created `_.matchesProperty`
14447 * style callback returns `true` for elements that have a matching property
14448 * value, else `false`.
14449 *
14450 * If an object is provided for `predicate` the created `_.matches` style
14451 * callback returns `true` for elements that have the properties of the given
14452 * object, else `false`.
14453 *
14454 * @static
14455 * @memberOf _
14456 * @alias all
14457 * @category Collection
14458 * @param {Array|Object|string} collection The collection to iterate over.
14459 * @param {Function|Object|string} [predicate=_.identity] The function invoked
14460 * per iteration.
14461 * @param {*} [thisArg] The `this` binding of `predicate`.
14462 * @returns {boolean} Returns `true` if all elements pass the predicate check,
14463 * else `false`.
14464 * @example
14465 *
14466 * _.every([true, 1, null, 'yes'], Boolean);
14467 * // => false
14468 *
14469 * var users = [
14470 * { 'user': 'barney', 'active': false },
14471 * { 'user': 'fred', 'active': false }
14472 * ];
14473 *
14474 * // using the `_.matches` callback shorthand
14475 * _.every(users, { 'user': 'barney', 'active': false });
14476 * // => false
14477 *
14478 * // using the `_.matchesProperty` callback shorthand
14479 * _.every(users, 'active', false);
14480 * // => true
14481 *
14482 * // using the `_.property` callback shorthand
14483 * _.every(users, 'active');
14484 * // => false
14485 */
14486 function every(collection, predicate, thisArg) {
14487 var func = isArray(collection) ? arrayEvery : baseEvery;
14488 if (thisArg && isIterateeCall(collection, predicate, thisArg)) {
14489 predicate = undefined;
14490 }
14491 if (typeof predicate != 'function' || thisArg !== undefined) {
14492 predicate = getCallback(predicate, thisArg, 3);
14493 }
14494 return func(collection, predicate);
14495 }
14496
14497 /**
14498 * Iterates over elements of `collection`, returning an array of all elements
14499 * `predicate` returns truthy for. The predicate is bound to `thisArg` and
14500 * invoked with three arguments: (value, index|key, collection).
14501 *
14502 * If a property name is provided for `predicate` the created `_.property`
14503 * style callback returns the property value of the given element.
14504 *
14505 * If a value is also provided for `thisArg` the created `_.matchesProperty`
14506 * style callback returns `true` for elements that have a matching property
14507 * value, else `false`.
14508 *
14509 * If an object is provided for `predicate` the created `_.matches` style
14510 * callback returns `true` for elements that have the properties of the given
14511 * object, else `false`.
14512 *
14513 * @static
14514 * @memberOf _
14515 * @alias select
14516 * @category Collection
14517 * @param {Array|Object|string} collection The collection to iterate over.
14518 * @param {Function|Object|string} [predicate=_.identity] The function invoked
14519 * per iteration.
14520 * @param {*} [thisArg] The `this` binding of `predicate`.
14521 * @returns {Array} Returns the new filtered array.
14522 * @example
14523 *
14524 * _.filter([4, 5, 6], function(n) {
14525 * return n % 2 == 0;
14526 * });
14527 * // => [4, 6]
14528 *
14529 * var users = [
14530 * { 'user': 'barney', 'age': 36, 'active': true },
14531 * { 'user': 'fred', 'age': 40, 'active': false }
14532 * ];
14533 *
14534 * // using the `_.matches` callback shorthand
14535 * _.pluck(_.filter(users, { 'age': 36, 'active': true }), 'user');
14536 * // => ['barney']
14537 *
14538 * // using the `_.matchesProperty` callback shorthand
14539 * _.pluck(_.filter(users, 'active', false), 'user');
14540 * // => ['fred']
14541 *
14542 * // using the `_.property` callback shorthand
14543 * _.pluck(_.filter(users, 'active'), 'user');
14544 * // => ['barney']
14545 */
14546 function filter(collection, predicate, thisArg) {
14547 var func = isArray(collection) ? arrayFilter : baseFilter;
14548 predicate = getCallback(predicate, thisArg, 3);
14549 return func(collection, predicate);
14550 }
14551
14552 /**
14553 * Iterates over elements of `collection`, returning the first element
14554 * `predicate` returns truthy for. The predicate is bound to `thisArg` and
14555 * invoked with three arguments: (value, index|key, collection).
14556 *
14557 * If a property name is provided for `predicate` the created `_.property`
14558 * style callback returns the property value of the given element.
14559 *
14560 * If a value is also provided for `thisArg` the created `_.matchesProperty`
14561 * style callback returns `true` for elements that have a matching property
14562 * value, else `false`.
14563 *
14564 * If an object is provided for `predicate` the created `_.matches` style
14565 * callback returns `true` for elements that have the properties of the given
14566 * object, else `false`.
14567 *
14568 * @static
14569 * @memberOf _
14570 * @alias detect
14571 * @category Collection
14572 * @param {Array|Object|string} collection The collection to search.
14573 * @param {Function|Object|string} [predicate=_.identity] The function invoked
14574 * per iteration.
14575 * @param {*} [thisArg] The `this` binding of `predicate`.
14576 * @returns {*} Returns the matched element, else `undefined`.
14577 * @example
14578 *
14579 * var users = [
14580 * { 'user': 'barney', 'age': 36, 'active': true },
14581 * { 'user': 'fred', 'age': 40, 'active': false },
14582 * { 'user': 'pebbles', 'age': 1, 'active': true }
14583 * ];
14584 *
14585 * _.result(_.find(users, function(chr) {
14586 * return chr.age < 40;
14587 * }), 'user');
14588 * // => 'barney'
14589 *
14590 * // using the `_.matches` callback shorthand
14591 * _.result(_.find(users, { 'age': 1, 'active': true }), 'user');
14592 * // => 'pebbles'
14593 *
14594 * // using the `_.matchesProperty` callback shorthand
14595 * _.result(_.find(users, 'active', false), 'user');
14596 * // => 'fred'
14597 *
14598 * // using the `_.property` callback shorthand
14599 * _.result(_.find(users, 'active'), 'user');
14600 * // => 'barney'
14601 */
14602 var find = createFind(baseEach);
14603
14604 /**
14605 * This method is like `_.find` except that it iterates over elements of
14606 * `collection` from right to left.
14607 *
14608 * @static
14609 * @memberOf _
14610 * @category Collection
14611 * @param {Array|Object|string} collection The collection to search.
14612 * @param {Function|Object|string} [predicate=_.identity] The function invoked
14613 * per iteration.
14614 * @param {*} [thisArg] The `this` binding of `predicate`.
14615 * @returns {*} Returns the matched element, else `undefined`.
14616 * @example
14617 *
14618 * _.findLast([1, 2, 3, 4], function(n) {
14619 * return n % 2 == 1;
14620 * });
14621 * // => 3
14622 */
14623 var findLast = createFind(baseEachRight, true);
14624
14625 /**
14626 * Performs a deep comparison between each element in `collection` and the
14627 * source object, returning the first element that has equivalent property
14628 * values.
14629 *
14630 * **Note:** This method supports comparing arrays, booleans, `Date` objects,
14631 * numbers, `Object` objects, regexes, and strings. Objects are compared by
14632 * their own, not inherited, enumerable properties. For comparing a single
14633 * own or inherited property value see `_.matchesProperty`.
14634 *
14635 * @static
14636 * @memberOf _
14637 * @category Collection
14638 * @param {Array|Object|string} collection The collection to search.
14639 * @param {Object} source The object of property values to match.
14640 * @returns {*} Returns the matched element, else `undefined`.
14641 * @example
14642 *
14643 * var users = [
14644 * { 'user': 'barney', 'age': 36, 'active': true },
14645 * { 'user': 'fred', 'age': 40, 'active': false }
14646 * ];
14647 *
14648 * _.result(_.findWhere(users, { 'age': 36, 'active': true }), 'user');
14649 * // => 'barney'
14650 *
14651 * _.result(_.findWhere(users, { 'age': 40, 'active': false }), 'user');
14652 * // => 'fred'
14653 */
14654 function findWhere(collection, source) {
14655 return find(collection, baseMatches(source));
14656 }
14657
14658 /**
14659 * Iterates over elements of `collection` invoking `iteratee` for each element.
14660 * The `iteratee` is bound to `thisArg` and invoked with three arguments:
14661 * (value, index|key, collection). Iteratee functions may exit iteration early
14662 * by explicitly returning `false`.
14663 *
14664 * **Note:** As with other "Collections" methods, objects with a "length" property
14665 * are iterated like arrays. To avoid this behavior `_.forIn` or `_.forOwn`
14666 * may be used for object iteration.
14667 *
14668 * @static
14669 * @memberOf _
14670 * @alias each
14671 * @category Collection
14672 * @param {Array|Object|string} collection The collection to iterate over.
14673 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
14674 * @param {*} [thisArg] The `this` binding of `iteratee`.
14675 * @returns {Array|Object|string} Returns `collection`.
14676 * @example
14677 *
14678 * _([1, 2]).forEach(function(n) {
14679 * console.log(n);
14680 * }).value();
14681 * // => logs each value from left to right and returns the array
14682 *
14683 * _.forEach({ 'a': 1, 'b': 2 }, function(n, key) {
14684 * console.log(n, key);
14685 * });
14686 * // => logs each value-key pair and returns the object (iteration order is not guaranteed)
14687 */
14688 var forEach = createForEach(arrayEach, baseEach);
14689
14690 /**
14691 * This method is like `_.forEach` except that it iterates over elements of
14692 * `collection` from right to left.
14693 *
14694 * @static
14695 * @memberOf _
14696 * @alias eachRight
14697 * @category Collection
14698 * @param {Array|Object|string} collection The collection to iterate over.
14699 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
14700 * @param {*} [thisArg] The `this` binding of `iteratee`.
14701 * @returns {Array|Object|string} Returns `collection`.
14702 * @example
14703 *
14704 * _([1, 2]).forEachRight(function(n) {
14705 * console.log(n);
14706 * }).value();
14707 * // => logs each value from right to left and returns the array
14708 */
14709 var forEachRight = createForEach(arrayEachRight, baseEachRight);
14710
14711 /**
14712 * Creates an object composed of keys generated from the results of running
14713 * each element of `collection` through `iteratee`. The corresponding value
14714 * of each key is an array of the elements responsible for generating the key.
14715 * The `iteratee` is bound to `thisArg` and invoked with three arguments:
14716 * (value, index|key, collection).
14717 *
14718 * If a property name is provided for `iteratee` the created `_.property`
14719 * style callback returns the property value of the given element.
14720 *
14721 * If a value is also provided for `thisArg` the created `_.matchesProperty`
14722 * style callback returns `true` for elements that have a matching property
14723 * value, else `false`.
14724 *
14725 * If an object is provided for `iteratee` the created `_.matches` style
14726 * callback returns `true` for elements that have the properties of the given
14727 * object, else `false`.
14728 *
14729 * @static
14730 * @memberOf _
14731 * @category Collection
14732 * @param {Array|Object|string} collection The collection to iterate over.
14733 * @param {Function|Object|string} [iteratee=_.identity] The function invoked
14734 * per iteration.
14735 * @param {*} [thisArg] The `this` binding of `iteratee`.
14736 * @returns {Object} Returns the composed aggregate object.
14737 * @example
14738 *
14739 * _.groupBy([4.2, 6.1, 6.4], function(n) {
14740 * return Math.floor(n);
14741 * });
14742 * // => { '4': [4.2], '6': [6.1, 6.4] }
14743 *
14744 * _.groupBy([4.2, 6.1, 6.4], function(n) {
14745 * return this.floor(n);
14746 * }, Math);
14747 * // => { '4': [4.2], '6': [6.1, 6.4] }
14748 *
14749 * // using the `_.property` callback shorthand
14750 * _.groupBy(['one', 'two', 'three'], 'length');
14751 * // => { '3': ['one', 'two'], '5': ['three'] }
14752 */
14753 var groupBy = createAggregator(function(result, value, key) {
14754 if (hasOwnProperty.call(result, key)) {
14755 result[key].push(value);
14756 } else {
14757 result[key] = [value];
14758 }
14759 });
14760
14761 /**
14762 * Checks if `value` is in `collection` using
14763 * [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
14764 * for equality comparisons. If `fromIndex` is negative, it is used as the offset
14765 * from the end of `collection`.
14766 *
14767 * @static
14768 * @memberOf _
14769 * @alias contains, include
14770 * @category Collection
14771 * @param {Array|Object|string} collection The collection to search.
14772 * @param {*} target The value to search for.
14773 * @param {number} [fromIndex=0] The index to search from.
14774 * @param- {Object} [guard] Enables use as a callback for functions like `_.reduce`.
14775 * @returns {boolean} Returns `true` if a matching element is found, else `false`.
14776 * @example
14777 *
14778 * _.includes([1, 2, 3], 1);
14779 * // => true
14780 *
14781 * _.includes([1, 2, 3], 1, 2);
14782 * // => false
14783 *
14784 * _.includes({ 'user': 'fred', 'age': 40 }, 'fred');
14785 * // => true
14786 *
14787 * _.includes('pebbles', 'eb');
14788 * // => true
14789 */
14790 function includes(collection, target, fromIndex, guard) {
14791 var length = collection ? getLength(collection) : 0;
14792 if (!isLength(length)) {
14793 collection = values(collection);
14794 length = collection.length;
14795 }
14796 if (typeof fromIndex != 'number' || (guard && isIterateeCall(target, fromIndex, guard))) {
14797 fromIndex = 0;
14798 } else {
14799 fromIndex = fromIndex < 0 ? nativeMax(length + fromIndex, 0) : (fromIndex || 0);
14800 }
14801 return (typeof collection == 'string' || !isArray(collection) && isString(collection))
14802 ? (fromIndex <= length && collection.indexOf(target, fromIndex) > -1)
14803 : (!!length && getIndexOf(collection, target, fromIndex) > -1);
14804 }
14805
14806 /**
14807 * Creates an object composed of keys generated from the results of running
14808 * each element of `collection` through `iteratee`. The corresponding value
14809 * of each key is the last element responsible for generating the key. The
14810 * iteratee function is bound to `thisArg` and invoked with three arguments:
14811 * (value, index|key, collection).
14812 *
14813 * If a property name is provided for `iteratee` the created `_.property`
14814 * style callback returns the property value of the given element.
14815 *
14816 * If a value is also provided for `thisArg` the created `_.matchesProperty`
14817 * style callback returns `true` for elements that have a matching property
14818 * value, else `false`.
14819 *
14820 * If an object is provided for `iteratee` the created `_.matches` style
14821 * callback returns `true` for elements that have the properties of the given
14822 * object, else `false`.
14823 *
14824 * @static
14825 * @memberOf _
14826 * @category Collection
14827 * @param {Array|Object|string} collection The collection to iterate over.
14828 * @param {Function|Object|string} [iteratee=_.identity] The function invoked
14829 * per iteration.
14830 * @param {*} [thisArg] The `this` binding of `iteratee`.
14831 * @returns {Object} Returns the composed aggregate object.
14832 * @example
14833 *
14834 * var keyData = [
14835 * { 'dir': 'left', 'code': 97 },
14836 * { 'dir': 'right', 'code': 100 }
14837 * ];
14838 *
14839 * _.indexBy(keyData, 'dir');
14840 * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } }
14841 *
14842 * _.indexBy(keyData, function(object) {
14843 * return String.fromCharCode(object.code);
14844 * });
14845 * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } }
14846 *
14847 * _.indexBy(keyData, function(object) {
14848 * return this.fromCharCode(object.code);
14849 * }, String);
14850 * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } }
14851 */
14852 var indexBy = createAggregator(function(result, value, key) {
14853 result[key] = value;
14854 });
14855
14856 /**
14857 * Invokes the method at `path` of each element in `collection`, returning
14858 * an array of the results of each invoked method. Any additional arguments
14859 * are provided to each invoked method. If `methodName` is a function it is
14860 * invoked for, and `this` bound to, each element in `collection`.
14861 *
14862 * @static
14863 * @memberOf _
14864 * @category Collection
14865 * @param {Array|Object|string} collection The collection to iterate over.
14866 * @param {Array|Function|string} path The path of the method to invoke or
14867 * the function invoked per iteration.
14868 * @param {...*} [args] The arguments to invoke the method with.
14869 * @returns {Array} Returns the array of results.
14870 * @example
14871 *
14872 * _.invoke([[5, 1, 7], [3, 2, 1]], 'sort');
14873 * // => [[1, 5, 7], [1, 2, 3]]
14874 *
14875 * _.invoke([123, 456], String.prototype.split, '');
14876 * // => [['1', '2', '3'], ['4', '5', '6']]
14877 */
14878 var invoke = restParam(function(collection, path, args) {
14879 var index = -1,
14880 isFunc = typeof path == 'function',
14881 isProp = isKey(path),
14882 result = isArrayLike(collection) ? Array(collection.length) : [];
14883
14884 baseEach(collection, function(value) {
14885 var func = isFunc ? path : ((isProp && value != null) ? value[path] : undefined);
14886 result[++index] = func ? func.apply(value, args) : invokePath(value, path, args);
14887 });
14888 return result;
14889 });
14890
14891 /**
14892 * Creates an array of values by running each element in `collection` through
14893 * `iteratee`. The `iteratee` is bound to `thisArg` and invoked with three
14894 * arguments: (value, index|key, collection).
14895 *
14896 * If a property name is provided for `iteratee` the created `_.property`
14897 * style callback returns the property value of the given element.
14898 *
14899 * If a value is also provided for `thisArg` the created `_.matchesProperty`
14900 * style callback returns `true` for elements that have a matching property
14901 * value, else `false`.
14902 *
14903 * If an object is provided for `iteratee` the created `_.matches` style
14904 * callback returns `true` for elements that have the properties of the given
14905 * object, else `false`.
14906 *
14907 * Many lodash methods are guarded to work as iteratees for methods like
14908 * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`.
14909 *
14910 * The guarded methods are:
14911 * `ary`, `callback`, `chunk`, `clone`, `create`, `curry`, `curryRight`,
14912 * `drop`, `dropRight`, `every`, `fill`, `flatten`, `invert`, `max`, `min`,
14913 * `parseInt`, `slice`, `sortBy`, `take`, `takeRight`, `template`, `trim`,
14914 * `trimLeft`, `trimRight`, `trunc`, `random`, `range`, `sample`, `some`,
14915 * `sum`, `uniq`, and `words`
14916 *
14917 * @static
14918 * @memberOf _
14919 * @alias collect
14920 * @category Collection
14921 * @param {Array|Object|string} collection The collection to iterate over.
14922 * @param {Function|Object|string} [iteratee=_.identity] The function invoked
14923 * per iteration.
14924 * @param {*} [thisArg] The `this` binding of `iteratee`.
14925 * @returns {Array} Returns the new mapped array.
14926 * @example
14927 *
14928 * function timesThree(n) {
14929 * return n * 3;
14930 * }
14931 *
14932 * _.map([1, 2], timesThree);
14933 * // => [3, 6]
14934 *
14935 * _.map({ 'a': 1, 'b': 2 }, timesThree);
14936 * // => [3, 6] (iteration order is not guaranteed)
14937 *
14938 * var users = [
14939 * { 'user': 'barney' },
14940 * { 'user': 'fred' }
14941 * ];
14942 *
14943 * // using the `_.property` callback shorthand
14944 * _.map(users, 'user');
14945 * // => ['barney', 'fred']
14946 */
14947 function map(collection, iteratee, thisArg) {
14948 var func = isArray(collection) ? arrayMap : baseMap;
14949 iteratee = getCallback(iteratee, thisArg, 3);
14950 return func(collection, iteratee);
14951 }
14952
14953 /**
14954 * Creates an array of elements split into two groups, the first of which
14955 * contains elements `predicate` returns truthy for, while the second of which
14956 * contains elements `predicate` returns falsey for. The predicate is bound
14957 * to `thisArg` and invoked with three arguments: (value, index|key, collection).
14958 *
14959 * If a property name is provided for `predicate` the created `_.property`
14960 * style callback returns the property value of the given element.
14961 *
14962 * If a value is also provided for `thisArg` the created `_.matchesProperty`
14963 * style callback returns `true` for elements that have a matching property
14964 * value, else `false`.
14965 *
14966 * If an object is provided for `predicate` the created `_.matches` style
14967 * callback returns `true` for elements that have the properties of the given
14968 * object, else `false`.
14969 *
14970 * @static
14971 * @memberOf _
14972 * @category Collection
14973 * @param {Array|Object|string} collection The collection to iterate over.
14974 * @param {Function|Object|string} [predicate=_.identity] The function invoked
14975 * per iteration.
14976 * @param {*} [thisArg] The `this` binding of `predicate`.
14977 * @returns {Array} Returns the array of grouped elements.
14978 * @example
14979 *
14980 * _.partition([1, 2, 3], function(n) {
14981 * return n % 2;
14982 * });
14983 * // => [[1, 3], [2]]
14984 *
14985 * _.partition([1.2, 2.3, 3.4], function(n) {
14986 * return this.floor(n) % 2;
14987 * }, Math);
14988 * // => [[1.2, 3.4], [2.3]]
14989 *
14990 * var users = [
14991 * { 'user': 'barney', 'age': 36, 'active': false },
14992 * { 'user': 'fred', 'age': 40, 'active': true },
14993 * { 'user': 'pebbles', 'age': 1, 'active': false }
14994 * ];
14995 *
14996 * var mapper = function(array) {
14997 * return _.pluck(array, 'user');
14998 * };
14999 *
15000 * // using the `_.matches` callback shorthand
15001 * _.map(_.partition(users, { 'age': 1, 'active': false }), mapper);
15002 * // => [['pebbles'], ['barney', 'fred']]
15003 *
15004 * // using the `_.matchesProperty` callback shorthand
15005 * _.map(_.partition(users, 'active', false), mapper);
15006 * // => [['barney', 'pebbles'], ['fred']]
15007 *
15008 * // using the `_.property` callback shorthand
15009 * _.map(_.partition(users, 'active'), mapper);
15010 * // => [['fred'], ['barney', 'pebbles']]
15011 */
15012 var partition = createAggregator(function(result, value, key) {
15013 result[key ? 0 : 1].push(value);
15014 }, function() { return [[], []]; });
15015
15016 /**
15017 * Gets the property value of `path` from all elements in `collection`.
15018 *
15019 * @static
15020 * @memberOf _
15021 * @category Collection
15022 * @param {Array|Object|string} collection The collection to iterate over.
15023 * @param {Array|string} path The path of the property to pluck.
15024 * @returns {Array} Returns the property values.
15025 * @example
15026 *
15027 * var users = [
15028 * { 'user': 'barney', 'age': 36 },
15029 * { 'user': 'fred', 'age': 40 }
15030 * ];
15031 *
15032 * _.pluck(users, 'user');
15033 * // => ['barney', 'fred']
15034 *
15035 * var userIndex = _.indexBy(users, 'user');
15036 * _.pluck(userIndex, 'age');
15037 * // => [36, 40] (iteration order is not guaranteed)
15038 */
15039 function pluck(collection, path) {
15040 return map(collection, property(path));
15041 }
15042
15043 /**
15044 * Reduces `collection` to a value which is the accumulated result of running
15045 * each element in `collection` through `iteratee`, where each successive
15046 * invocation is supplied the return value of the previous. If `accumulator`
15047 * is not provided the first element of `collection` is used as the initial
15048 * value. The `iteratee` is bound to `thisArg` and invoked with four arguments:
15049 * (accumulator, value, index|key, collection).
15050 *
15051 * Many lodash methods are guarded to work as iteratees for methods like
15052 * `_.reduce`, `_.reduceRight`, and `_.transform`.
15053 *
15054 * The guarded methods are:
15055 * `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `sortByAll`,
15056 * and `sortByOrder`
15057 *
15058 * @static
15059 * @memberOf _
15060 * @alias foldl, inject
15061 * @category Collection
15062 * @param {Array|Object|string} collection The collection to iterate over.
15063 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
15064 * @param {*} [accumulator] The initial value.
15065 * @param {*} [thisArg] The `this` binding of `iteratee`.
15066 * @returns {*} Returns the accumulated value.
15067 * @example
15068 *
15069 * _.reduce([1, 2], function(total, n) {
15070 * return total + n;
15071 * });
15072 * // => 3
15073 *
15074 * _.reduce({ 'a': 1, 'b': 2 }, function(result, n, key) {
15075 * result[key] = n * 3;
15076 * return result;
15077 * }, {});
15078 * // => { 'a': 3, 'b': 6 } (iteration order is not guaranteed)
15079 */
15080 var reduce = createReduce(arrayReduce, baseEach);
15081
15082 /**
15083 * This method is like `_.reduce` except that it iterates over elements of
15084 * `collection` from right to left.
15085 *
15086 * @static
15087 * @memberOf _
15088 * @alias foldr
15089 * @category Collection
15090 * @param {Array|Object|string} collection The collection to iterate over.
15091 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
15092 * @param {*} [accumulator] The initial value.
15093 * @param {*} [thisArg] The `this` binding of `iteratee`.
15094 * @returns {*} Returns the accumulated value.
15095 * @example
15096 *
15097 * var array = [[0, 1], [2, 3], [4, 5]];
15098 *
15099 * _.reduceRight(array, function(flattened, other) {
15100 * return flattened.concat(other);
15101 * }, []);
15102 * // => [4, 5, 2, 3, 0, 1]
15103 */
15104 var reduceRight = createReduce(arrayReduceRight, baseEachRight);
15105
15106 /**
15107 * The opposite of `_.filter`; this method returns the elements of `collection`
15108 * that `predicate` does **not** return truthy for.
15109 *
15110 * @static
15111 * @memberOf _
15112 * @category Collection
15113 * @param {Array|Object|string} collection The collection to iterate over.
15114 * @param {Function|Object|string} [predicate=_.identity] The function invoked
15115 * per iteration.
15116 * @param {*} [thisArg] The `this` binding of `predicate`.
15117 * @returns {Array} Returns the new filtered array.
15118 * @example
15119 *
15120 * _.reject([1, 2, 3, 4], function(n) {
15121 * return n % 2 == 0;
15122 * });
15123 * // => [1, 3]
15124 *
15125 * var users = [
15126 * { 'user': 'barney', 'age': 36, 'active': false },
15127 * { 'user': 'fred', 'age': 40, 'active': true }
15128 * ];
15129 *
15130 * // using the `_.matches` callback shorthand
15131 * _.pluck(_.reject(users, { 'age': 40, 'active': true }), 'user');
15132 * // => ['barney']
15133 *
15134 * // using the `_.matchesProperty` callback shorthand
15135 * _.pluck(_.reject(users, 'active', false), 'user');
15136 * // => ['fred']
15137 *
15138 * // using the `_.property` callback shorthand
15139 * _.pluck(_.reject(users, 'active'), 'user');
15140 * // => ['barney']
15141 */
15142 function reject(collection, predicate, thisArg) {
15143 var func = isArray(collection) ? arrayFilter : baseFilter;
15144 predicate = getCallback(predicate, thisArg, 3);
15145 return func(collection, function(value, index, collection) {
15146 return !predicate(value, index, collection);
15147 });
15148 }
15149
15150 /**
15151 * Gets a random element or `n` random elements from a collection.
15152 *
15153 * @static
15154 * @memberOf _
15155 * @category Collection
15156 * @param {Array|Object|string} collection The collection to sample.
15157 * @param {number} [n] The number of elements to sample.
15158 * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
15159 * @returns {*} Returns the random sample(s).
15160 * @example
15161 *
15162 * _.sample([1, 2, 3, 4]);
15163 * // => 2
15164 *
15165 * _.sample([1, 2, 3, 4], 2);
15166 * // => [3, 1]
15167 */
15168 function sample(collection, n, guard) {
15169 if (guard ? isIterateeCall(collection, n, guard) : n == null) {
15170 collection = toIterable(collection);
15171 var length = collection.length;
15172 return length > 0 ? collection[baseRandom(0, length - 1)] : undefined;
15173 }
15174 var index = -1,
15175 result = toArray(collection),
15176 length = result.length,
15177 lastIndex = length - 1;
15178
15179 n = nativeMin(n < 0 ? 0 : (+n || 0), length);
15180 while (++index < n) {
15181 var rand = baseRandom(index, lastIndex),
15182 value = result[rand];
15183
15184 result[rand] = result[index];
15185 result[index] = value;
15186 }
15187 result.length = n;
15188 return result;
15189 }
15190
15191 /**
15192 * Creates an array of shuffled values, using a version of the
15193 * [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle).
15194 *
15195 * @static
15196 * @memberOf _
15197 * @category Collection
15198 * @param {Array|Object|string} collection The collection to shuffle.
15199 * @returns {Array} Returns the new shuffled array.
15200 * @example
15201 *
15202 * _.shuffle([1, 2, 3, 4]);
15203 * // => [4, 1, 3, 2]
15204 */
15205 function shuffle(collection) {
15206 return sample(collection, POSITIVE_INFINITY);
15207 }
15208
15209 /**
15210 * Gets the size of `collection` by returning its length for array-like
15211 * values or the number of own enumerable properties for objects.
15212 *
15213 * @static
15214 * @memberOf _
15215 * @category Collection
15216 * @param {Array|Object|string} collection The collection to inspect.
15217 * @returns {number} Returns the size of `collection`.
15218 * @example
15219 *
15220 * _.size([1, 2, 3]);
15221 * // => 3
15222 *
15223 * _.size({ 'a': 1, 'b': 2 });
15224 * // => 2
15225 *
15226 * _.size('pebbles');
15227 * // => 7
15228 */
15229 function size(collection) {
15230 var length = collection ? getLength(collection) : 0;
15231 return isLength(length) ? length : keys(collection).length;
15232 }
15233
15234 /**
15235 * Checks if `predicate` returns truthy for **any** element of `collection`.
15236 * The function returns as soon as it finds a passing value and does not iterate
15237 * over the entire collection. The predicate is bound to `thisArg` and invoked
15238 * with three arguments: (value, index|key, collection).
15239 *
15240 * If a property name is provided for `predicate` the created `_.property`
15241 * style callback returns the property value of the given element.
15242 *
15243 * If a value is also provided for `thisArg` the created `_.matchesProperty`
15244 * style callback returns `true` for elements that have a matching property
15245 * value, else `false`.
15246 *
15247 * If an object is provided for `predicate` the created `_.matches` style
15248 * callback returns `true` for elements that have the properties of the given
15249 * object, else `false`.
15250 *
15251 * @static
15252 * @memberOf _
15253 * @alias any
15254 * @category Collection
15255 * @param {Array|Object|string} collection The collection to iterate over.
15256 * @param {Function|Object|string} [predicate=_.identity] The function invoked
15257 * per iteration.
15258 * @param {*} [thisArg] The `this` binding of `predicate`.
15259 * @returns {boolean} Returns `true` if any element passes the predicate check,
15260 * else `false`.
15261 * @example
15262 *
15263 * _.some([null, 0, 'yes', false], Boolean);
15264 * // => true
15265 *
15266 * var users = [
15267 * { 'user': 'barney', 'active': true },
15268 * { 'user': 'fred', 'active': false }
15269 * ];
15270 *
15271 * // using the `_.matches` callback shorthand
15272 * _.some(users, { 'user': 'barney', 'active': false });
15273 * // => false
15274 *
15275 * // using the `_.matchesProperty` callback shorthand
15276 * _.some(users, 'active', false);
15277 * // => true
15278 *
15279 * // using the `_.property` callback shorthand
15280 * _.some(users, 'active');
15281 * // => true
15282 */
15283 function some(collection, predicate, thisArg) {
15284 var func = isArray(collection) ? arraySome : baseSome;
15285 if (thisArg && isIterateeCall(collection, predicate, thisArg)) {
15286 predicate = undefined;
15287 }
15288 if (typeof predicate != 'function' || thisArg !== undefined) {
15289 predicate = getCallback(predicate, thisArg, 3);
15290 }
15291 return func(collection, predicate);
15292 }
15293
15294 /**
15295 * Creates an array of elements, sorted in ascending order by the results of
15296 * running each element in a collection through `iteratee`. This method performs
15297 * a stable sort, that is, it preserves the original sort order of equal elements.
15298 * The `iteratee` is bound to `thisArg` and invoked with three arguments:
15299 * (value, index|key, collection).
15300 *
15301 * If a property name is provided for `iteratee` the created `_.property`
15302 * style callback returns the property value of the given element.
15303 *
15304 * If a value is also provided for `thisArg` the created `_.matchesProperty`
15305 * style callback returns `true` for elements that have a matching property
15306 * value, else `false`.
15307 *
15308 * If an object is provided for `iteratee` the created `_.matches` style
15309 * callback returns `true` for elements that have the properties of the given
15310 * object, else `false`.
15311 *
15312 * @static
15313 * @memberOf _
15314 * @category Collection
15315 * @param {Array|Object|string} collection The collection to iterate over.
15316 * @param {Function|Object|string} [iteratee=_.identity] The function invoked
15317 * per iteration.
15318 * @param {*} [thisArg] The `this` binding of `iteratee`.
15319 * @returns {Array} Returns the new sorted array.
15320 * @example
15321 *
15322 * _.sortBy([1, 2, 3], function(n) {
15323 * return Math.sin(n);
15324 * });
15325 * // => [3, 1, 2]
15326 *
15327 * _.sortBy([1, 2, 3], function(n) {
15328 * return this.sin(n);
15329 * }, Math);
15330 * // => [3, 1, 2]
15331 *
15332 * var users = [
15333 * { 'user': 'fred' },
15334 * { 'user': 'pebbles' },
15335 * { 'user': 'barney' }
15336 * ];
15337 *
15338 * // using the `_.property` callback shorthand
15339 * _.pluck(_.sortBy(users, 'user'), 'user');
15340 * // => ['barney', 'fred', 'pebbles']
15341 */
15342 function sortBy(collection, iteratee, thisArg) {
15343 if (collection == null) {
15344 return [];
15345 }
15346 if (thisArg && isIterateeCall(collection, iteratee, thisArg)) {
15347 iteratee = undefined;
15348 }
15349 var index = -1;
15350 iteratee = getCallback(iteratee, thisArg, 3);
15351
15352 var result = baseMap(collection, function(value, key, collection) {
15353 return { 'criteria': iteratee(value, key, collection), 'index': ++index, 'value': value };
15354 });
15355 return baseSortBy(result, compareAscending);
15356 }
15357
15358 /**
15359 * This method is like `_.sortBy` except that it can sort by multiple iteratees
15360 * or property names.
15361 *
15362 * If a property name is provided for an iteratee the created `_.property`
15363 * style callback returns the property value of the given element.
15364 *
15365 * If an object is provided for an iteratee the created `_.matches` style
15366 * callback returns `true` for elements that have the properties of the given
15367 * object, else `false`.
15368 *
15369 * @static
15370 * @memberOf _
15371 * @category Collection
15372 * @param {Array|Object|string} collection The collection to iterate over.
15373 * @param {...(Function|Function[]|Object|Object[]|string|string[])} iteratees
15374 * The iteratees to sort by, specified as individual values or arrays of values.
15375 * @returns {Array} Returns the new sorted array.
15376 * @example
15377 *
15378 * var users = [
15379 * { 'user': 'fred', 'age': 48 },
15380 * { 'user': 'barney', 'age': 36 },
15381 * { 'user': 'fred', 'age': 42 },
15382 * { 'user': 'barney', 'age': 34 }
15383 * ];
15384 *
15385 * _.map(_.sortByAll(users, ['user', 'age']), _.values);
15386 * // => [['barney', 34], ['barney', 36], ['fred', 42], ['fred', 48]]
15387 *
15388 * _.map(_.sortByAll(users, 'user', function(chr) {
15389 * return Math.floor(chr.age / 10);
15390 * }), _.values);
15391 * // => [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 42]]
15392 */
15393 var sortByAll = restParam(function(collection, iteratees) {
15394 if (collection == null) {
15395 return [];
15396 }
15397 var guard = iteratees[2];
15398 if (guard && isIterateeCall(iteratees[0], iteratees[1], guard)) {
15399 iteratees.length = 1;
15400 }
15401 return baseSortByOrder(collection, baseFlatten(iteratees), []);
15402 });
15403
15404 /**
15405 * This method is like `_.sortByAll` except that it allows specifying the
15406 * sort orders of the iteratees to sort by. If `orders` is unspecified, all
15407 * values are sorted in ascending order. Otherwise, a value is sorted in
15408 * ascending order if its corresponding order is "asc", and descending if "desc".
15409 *
15410 * If a property name is provided for an iteratee the created `_.property`
15411 * style callback returns the property value of the given element.
15412 *
15413 * If an object is provided for an iteratee the created `_.matches` style
15414 * callback returns `true` for elements that have the properties of the given
15415 * object, else `false`.
15416 *
15417 * @static
15418 * @memberOf _
15419 * @category Collection
15420 * @param {Array|Object|string} collection The collection to iterate over.
15421 * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by.
15422 * @param {boolean[]} [orders] The sort orders of `iteratees`.
15423 * @param- {Object} [guard] Enables use as a callback for functions like `_.reduce`.
15424 * @returns {Array} Returns the new sorted array.
15425 * @example
15426 *
15427 * var users = [
15428 * { 'user': 'fred', 'age': 48 },
15429 * { 'user': 'barney', 'age': 34 },
15430 * { 'user': 'fred', 'age': 42 },
15431 * { 'user': 'barney', 'age': 36 }
15432 * ];
15433 *
15434 * // sort by `user` in ascending order and by `age` in descending order
15435 * _.map(_.sortByOrder(users, ['user', 'age'], ['asc', 'desc']), _.values);
15436 * // => [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 42]]
15437 */
15438 function sortByOrder(collection, iteratees, orders, guard) {
15439 if (collection == null) {
15440 return [];
15441 }
15442 if (guard && isIterateeCall(iteratees, orders, guard)) {
15443 orders = undefined;
15444 }
15445 if (!isArray(iteratees)) {
15446 iteratees = iteratees == null ? [] : [iteratees];
15447 }
15448 if (!isArray(orders)) {
15449 orders = orders == null ? [] : [orders];
15450 }
15451 return baseSortByOrder(collection, iteratees, orders);
15452 }
15453
15454 /**
15455 * Performs a deep comparison between each element in `collection` and the
15456 * source object, returning an array of all elements that have equivalent
15457 * property values.
15458 *
15459 * **Note:** This method supports comparing arrays, booleans, `Date` objects,
15460 * numbers, `Object` objects, regexes, and strings. Objects are compared by
15461 * their own, not inherited, enumerable properties. For comparing a single
15462 * own or inherited property value see `_.matchesProperty`.
15463 *
15464 * @static
15465 * @memberOf _
15466 * @category Collection
15467 * @param {Array|Object|string} collection The collection to search.
15468 * @param {Object} source The object of property values to match.
15469 * @returns {Array} Returns the new filtered array.
15470 * @example
15471 *
15472 * var users = [
15473 * { 'user': 'barney', 'age': 36, 'active': false, 'pets': ['hoppy'] },
15474 * { 'user': 'fred', 'age': 40, 'active': true, 'pets': ['baby puss', 'dino'] }
15475 * ];
15476 *
15477 * _.pluck(_.where(users, { 'age': 36, 'active': false }), 'user');
15478 * // => ['barney']
15479 *
15480 * _.pluck(_.where(users, { 'pets': ['dino'] }), 'user');
15481 * // => ['fred']
15482 */
15483 function where(collection, source) {
15484 return filter(collection, baseMatches(source));
15485 }
15486
15487 /*------------------------------------------------------------------------*/
15488
15489 /**
15490 * Gets the number of milliseconds that have elapsed since the Unix epoch
15491 * (1 January 1970 00:00:00 UTC).
15492 *
15493 * @static
15494 * @memberOf _
15495 * @category Date
15496 * @example
15497 *
15498 * _.defer(function(stamp) {
15499 * console.log(_.now() - stamp);
15500 * }, _.now());
15501 * // => logs the number of milliseconds it took for the deferred function to be invoked
15502 */
15503 var now = nativeNow || function() {
15504 return new Date().getTime();
15505 };
15506
15507 /*------------------------------------------------------------------------*/
15508
15509 /**
15510 * The opposite of `_.before`; this method creates a function that invokes
15511 * `func` once it is called `n` or more times.
15512 *
15513 * @static
15514 * @memberOf _
15515 * @category Function
15516 * @param {number} n The number of calls before `func` is invoked.
15517 * @param {Function} func The function to restrict.
15518 * @returns {Function} Returns the new restricted function.
15519 * @example
15520 *
15521 * var saves = ['profile', 'settings'];
15522 *
15523 * var done = _.after(saves.length, function() {
15524 * console.log('done saving!');
15525 * });
15526 *
15527 * _.forEach(saves, function(type) {
15528 * asyncSave({ 'type': type, 'complete': done });
15529 * });
15530 * // => logs 'done saving!' after the two async saves have completed
15531 */
15532 function after(n, func) {
15533 if (typeof func != 'function') {
15534 if (typeof n == 'function') {
15535 var temp = n;
15536 n = func;
15537 func = temp;
15538 } else {
15539 throw new TypeError(FUNC_ERROR_TEXT);
15540 }
15541 }
15542 n = nativeIsFinite(n = +n) ? n : 0;
15543 return function() {
15544 if (--n < 1) {
15545 return func.apply(this, arguments);
15546 }
15547 };
15548 }
15549
15550 /**
15551 * Creates a function that accepts up to `n` arguments ignoring any
15552 * additional arguments.
15553 *
15554 * @static
15555 * @memberOf _
15556 * @category Function
15557 * @param {Function} func The function to cap arguments for.
15558 * @param {number} [n=func.length] The arity cap.
15559 * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
15560 * @returns {Function} Returns the new function.
15561 * @example
15562 *
15563 * _.map(['6', '8', '10'], _.ary(parseInt, 1));
15564 * // => [6, 8, 10]
15565 */
15566 function ary(func, n, guard) {
15567 if (guard && isIterateeCall(func, n, guard)) {
15568 n = undefined;
15569 }
15570 n = (func && n == null) ? func.length : nativeMax(+n || 0, 0);
15571 return createWrapper(func, ARY_FLAG, undefined, undefined, undefined, undefined, n);
15572 }
15573
15574 /**
15575 * Creates a function that invokes `func`, with the `this` binding and arguments
15576 * of the created function, while it is called less than `n` times. Subsequent
15577 * calls to the created function return the result of the last `func` invocation.
15578 *
15579 * @static
15580 * @memberOf _
15581 * @category Function
15582 * @param {number} n The number of calls at which `func` is no longer invoked.
15583 * @param {Function} func The function to restrict.
15584 * @returns {Function} Returns the new restricted function.
15585 * @example
15586 *
15587 * jQuery('#add').on('click', _.before(5, addContactToList));
15588 * // => allows adding up to 4 contacts to the list
15589 */
15590 function before(n, func) {
15591 var result;
15592 if (typeof func != 'function') {
15593 if (typeof n == 'function') {
15594 var temp = n;
15595 n = func;
15596 func = temp;
15597 } else {
15598 throw new TypeError(FUNC_ERROR_TEXT);
15599 }
15600 }
15601 return function() {
15602 if (--n > 0) {
15603 result = func.apply(this, arguments);
15604 }
15605 if (n <= 1) {
15606 func = undefined;
15607 }
15608 return result;
15609 };
15610 }
15611
15612 /**
15613 * Creates a function that invokes `func` with the `this` binding of `thisArg`
15614 * and prepends any additional `_.bind` arguments to those provided to the
15615 * bound function.
15616 *
15617 * The `_.bind.placeholder` value, which defaults to `_` in monolithic builds,
15618 * may be used as a placeholder for partially applied arguments.
15619 *
15620 * **Note:** Unlike native `Function#bind` this method does not set the "length"
15621 * property of bound functions.
15622 *
15623 * @static
15624 * @memberOf _
15625 * @category Function
15626 * @param {Function} func The function to bind.
15627 * @param {*} thisArg The `this` binding of `func`.
15628 * @param {...*} [partials] The arguments to be partially applied.
15629 * @returns {Function} Returns the new bound function.
15630 * @example
15631 *
15632 * var greet = function(greeting, punctuation) {
15633 * return greeting + ' ' + this.user + punctuation;
15634 * };
15635 *
15636 * var object = { 'user': 'fred' };
15637 *
15638 * var bound = _.bind(greet, object, 'hi');
15639 * bound('!');
15640 * // => 'hi fred!'
15641 *
15642 * // using placeholders
15643 * var bound = _.bind(greet, object, _, '!');
15644 * bound('hi');
15645 * // => 'hi fred!'
15646 */
15647 var bind = restParam(function(func, thisArg, partials) {
15648 var bitmask = BIND_FLAG;
15649 if (partials.length) {
15650 var holders = replaceHolders(partials, bind.placeholder);
15651 bitmask |= PARTIAL_FLAG;
15652 }
15653 return createWrapper(func, bitmask, thisArg, partials, holders);
15654 });
15655
15656 /**
15657 * Binds methods of an object to the object itself, overwriting the existing
15658 * method. Method names may be specified as individual arguments or as arrays
15659 * of method names. If no method names are provided all enumerable function
15660 * properties, own and inherited, of `object` are bound.
15661 *
15662 * **Note:** This method does not set the "length" property of bound functions.
15663 *
15664 * @static
15665 * @memberOf _
15666 * @category Function
15667 * @param {Object} object The object to bind and assign the bound methods to.
15668 * @param {...(string|string[])} [methodNames] The object method names to bind,
15669 * specified as individual method names or arrays of method names.
15670 * @returns {Object} Returns `object`.
15671 * @example
15672 *
15673 * var view = {
15674 * 'label': 'docs',
15675 * 'onClick': function() {
15676 * console.log('clicked ' + this.label);
15677 * }
15678 * };
15679 *
15680 * _.bindAll(view);
15681 * jQuery('#docs').on('click', view.onClick);
15682 * // => logs 'clicked docs' when the element is clicked
15683 */
15684 var bindAll = restParam(function(object, methodNames) {
15685 methodNames = methodNames.length ? baseFlatten(methodNames) : functions(object);
15686
15687 var index = -1,
15688 length = methodNames.length;
15689
15690 while (++index < length) {
15691 var key = methodNames[index];
15692 object[key] = createWrapper(object[key], BIND_FLAG, object);
15693 }
15694 return object;
15695 });
15696
15697 /**
15698 * Creates a function that invokes the method at `object[key]` and prepends
15699 * any additional `_.bindKey` arguments to those provided to the bound function.
15700 *
15701 * This method differs from `_.bind` by allowing bound functions to reference
15702 * methods that may be redefined or don't yet exist.
15703 * See [Peter Michaux's article](http://peter.michaux.ca/articles/lazy-function-definition-pattern)
15704 * for more details.
15705 *
15706 * The `_.bindKey.placeholder` value, which defaults to `_` in monolithic
15707 * builds, may be used as a placeholder for partially applied arguments.
15708 *
15709 * @static
15710 * @memberOf _
15711 * @category Function
15712 * @param {Object} object The object the method belongs to.
15713 * @param {string} key The key of the method.
15714 * @param {...*} [partials] The arguments to be partially applied.
15715 * @returns {Function} Returns the new bound function.
15716 * @example
15717 *
15718 * var object = {
15719 * 'user': 'fred',
15720 * 'greet': function(greeting, punctuation) {
15721 * return greeting + ' ' + this.user + punctuation;
15722 * }
15723 * };
15724 *
15725 * var bound = _.bindKey(object, 'greet', 'hi');
15726 * bound('!');
15727 * // => 'hi fred!'
15728 *
15729 * object.greet = function(greeting, punctuation) {
15730 * return greeting + 'ya ' + this.user + punctuation;
15731 * };
15732 *
15733 * bound('!');
15734 * // => 'hiya fred!'
15735 *
15736 * // using placeholders
15737 * var bound = _.bindKey(object, 'greet', _, '!');
15738 * bound('hi');
15739 * // => 'hiya fred!'
15740 */
15741 var bindKey = restParam(function(object, key, partials) {
15742 var bitmask = BIND_FLAG | BIND_KEY_FLAG;
15743 if (partials.length) {
15744 var holders = replaceHolders(partials, bindKey.placeholder);
15745 bitmask |= PARTIAL_FLAG;
15746 }
15747 return createWrapper(key, bitmask, object, partials, holders);
15748 });
15749
15750 /**
15751 * Creates a function that accepts one or more arguments of `func` that when
15752 * called either invokes `func` returning its result, if all `func` arguments
15753 * have been provided, or returns a function that accepts one or more of the
15754 * remaining `func` arguments, and so on. The arity of `func` may be specified
15755 * if `func.length` is not sufficient.
15756 *
15757 * The `_.curry.placeholder` value, which defaults to `_` in monolithic builds,
15758 * may be used as a placeholder for provided arguments.
15759 *
15760 * **Note:** This method does not set the "length" property of curried functions.
15761 *
15762 * @static
15763 * @memberOf _
15764 * @category Function
15765 * @param {Function} func The function to curry.
15766 * @param {number} [arity=func.length] The arity of `func`.
15767 * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
15768 * @returns {Function} Returns the new curried function.
15769 * @example
15770 *
15771 * var abc = function(a, b, c) {
15772 * return [a, b, c];
15773 * };
15774 *
15775 * var curried = _.curry(abc);
15776 *
15777 * curried(1)(2)(3);
15778 * // => [1, 2, 3]
15779 *
15780 * curried(1, 2)(3);
15781 * // => [1, 2, 3]
15782 *
15783 * curried(1, 2, 3);
15784 * // => [1, 2, 3]
15785 *
15786 * // using placeholders
15787 * curried(1)(_, 3)(2);
15788 * // => [1, 2, 3]
15789 */
15790 var curry = createCurry(CURRY_FLAG);
15791
15792 /**
15793 * This method is like `_.curry` except that arguments are applied to `func`
15794 * in the manner of `_.partialRight` instead of `_.partial`.
15795 *
15796 * The `_.curryRight.placeholder` value, which defaults to `_` in monolithic
15797 * builds, may be used as a placeholder for provided arguments.
15798 *
15799 * **Note:** This method does not set the "length" property of curried functions.
15800 *
15801 * @static
15802 * @memberOf _
15803 * @category Function
15804 * @param {Function} func The function to curry.
15805 * @param {number} [arity=func.length] The arity of `func`.
15806 * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
15807 * @returns {Function} Returns the new curried function.
15808 * @example
15809 *
15810 * var abc = function(a, b, c) {
15811 * return [a, b, c];
15812 * };
15813 *
15814 * var curried = _.curryRight(abc);
15815 *
15816 * curried(3)(2)(1);
15817 * // => [1, 2, 3]
15818 *
15819 * curried(2, 3)(1);
15820 * // => [1, 2, 3]
15821 *
15822 * curried(1, 2, 3);
15823 * // => [1, 2, 3]
15824 *
15825 * // using placeholders
15826 * curried(3)(1, _)(2);
15827 * // => [1, 2, 3]
15828 */
15829 var curryRight = createCurry(CURRY_RIGHT_FLAG);
15830
15831 /**
15832 * Creates a debounced function that delays invoking `func` until after `wait`
15833 * milliseconds have elapsed since the last time the debounced function was
15834 * invoked. The debounced function comes with a `cancel` method to cancel
15835 * delayed invocations. Provide an options object to indicate that `func`
15836 * should be invoked on the leading and/or trailing edge of the `wait` timeout.
15837 * Subsequent calls to the debounced function return the result of the last
15838 * `func` invocation.
15839 *
15840 * **Note:** If `leading` and `trailing` options are `true`, `func` is invoked
15841 * on the trailing edge of the timeout only if the the debounced function is
15842 * invoked more than once during the `wait` timeout.
15843 *
15844 * See [David Corbacho's article](http://drupalmotion.com/article/debounce-and-throttle-visual-explanation)
15845 * for details over the differences between `_.debounce` and `_.throttle`.
15846 *
15847 * @static
15848 * @memberOf _
15849 * @category Function
15850 * @param {Function} func The function to debounce.
15851 * @param {number} [wait=0] The number of milliseconds to delay.
15852 * @param {Object} [options] The options object.
15853 * @param {boolean} [options.leading=false] Specify invoking on the leading
15854 * edge of the timeout.
15855 * @param {number} [options.maxWait] The maximum time `func` is allowed to be
15856 * delayed before it is invoked.
15857 * @param {boolean} [options.trailing=true] Specify invoking on the trailing
15858 * edge of the timeout.
15859 * @returns {Function} Returns the new debounced function.
15860 * @example
15861 *
15862 * // avoid costly calculations while the window size is in flux
15863 * jQuery(window).on('resize', _.debounce(calculateLayout, 150));
15864 *
15865 * // invoke `sendMail` when the click event is fired, debouncing subsequent calls
15866 * jQuery('#postbox').on('click', _.debounce(sendMail, 300, {
15867 * 'leading': true,
15868 * 'trailing': false
15869 * }));
15870 *
15871 * // ensure `batchLog` is invoked once after 1 second of debounced calls
15872 * var source = new EventSource('/stream');
15873 * jQuery(source).on('message', _.debounce(batchLog, 250, {
15874 * 'maxWait': 1000
15875 * }));
15876 *
15877 * // cancel a debounced call
15878 * var todoChanges = _.debounce(batchLog, 1000);
15879 * Object.observe(models.todo, todoChanges);
15880 *
15881 * Object.observe(models, function(changes) {
15882 * if (_.find(changes, { 'user': 'todo', 'type': 'delete'})) {
15883 * todoChanges.cancel();
15884 * }
15885 * }, ['delete']);
15886 *
15887 * // ...at some point `models.todo` is changed
15888 * models.todo.completed = true;
15889 *
15890 * // ...before 1 second has passed `models.todo` is deleted
15891 * // which cancels the debounced `todoChanges` call
15892 * delete models.todo;
15893 */
15894 function debounce(func, wait, options) {
15895 var args,
15896 maxTimeoutId,
15897 result,
15898 stamp,
15899 thisArg,
15900 timeoutId,
15901 trailingCall,
15902 lastCalled = 0,
15903 maxWait = false,
15904 trailing = true;
15905
15906 if (typeof func != 'function') {
15907 throw new TypeError(FUNC_ERROR_TEXT);
15908 }
15909 wait = wait < 0 ? 0 : (+wait || 0);
15910 if (options === true) {
15911 var leading = true;
15912 trailing = false;
15913 } else if (isObject(options)) {
15914 leading = !!options.leading;
15915 maxWait = 'maxWait' in options && nativeMax(+options.maxWait || 0, wait);
15916 trailing = 'trailing' in options ? !!options.trailing : trailing;
15917 }
15918
15919 function cancel() {
15920 if (timeoutId) {
15921 clearTimeout(timeoutId);
15922 }
15923 if (maxTimeoutId) {
15924 clearTimeout(maxTimeoutId);
15925 }
15926 lastCalled = 0;
15927 maxTimeoutId = timeoutId = trailingCall = undefined;
15928 }
15929
15930 function complete(isCalled, id) {
15931 if (id) {
15932 clearTimeout(id);
15933 }
15934 maxTimeoutId = timeoutId = trailingCall = undefined;
15935 if (isCalled) {
15936 lastCalled = now();
15937 result = func.apply(thisArg, args);
15938 if (!timeoutId && !maxTimeoutId) {
15939 args = thisArg = undefined;
15940 }
15941 }
15942 }
15943
15944 function delayed() {
15945 var remaining = wait - (now() - stamp);
15946 if (remaining <= 0 || remaining > wait) {
15947 complete(trailingCall, maxTimeoutId);
15948 } else {
15949 timeoutId = setTimeout(delayed, remaining);
15950 }
15951 }
15952
15953 function maxDelayed() {
15954 complete(trailing, timeoutId);
15955 }
15956
15957 function debounced() {
15958 args = arguments;
15959 stamp = now();
15960 thisArg = this;
15961 trailingCall = trailing && (timeoutId || !leading);
15962
15963 if (maxWait === false) {
15964 var leadingCall = leading && !timeoutId;
15965 } else {
15966 if (!maxTimeoutId && !leading) {
15967 lastCalled = stamp;
15968 }
15969 var remaining = maxWait - (stamp - lastCalled),
15970 isCalled = remaining <= 0 || remaining > maxWait;
15971
15972 if (isCalled) {
15973 if (maxTimeoutId) {
15974 maxTimeoutId = clearTimeout(maxTimeoutId);
15975 }
15976 lastCalled = stamp;
15977 result = func.apply(thisArg, args);
15978 }
15979 else if (!maxTimeoutId) {
15980 maxTimeoutId = setTimeout(maxDelayed, remaining);
15981 }
15982 }
15983 if (isCalled && timeoutId) {
15984 timeoutId = clearTimeout(timeoutId);
15985 }
15986 else if (!timeoutId && wait !== maxWait) {
15987 timeoutId = setTimeout(delayed, wait);
15988 }
15989 if (leadingCall) {
15990 isCalled = true;
15991 result = func.apply(thisArg, args);
15992 }
15993 if (isCalled && !timeoutId && !maxTimeoutId) {
15994 args = thisArg = undefined;
15995 }
15996 return result;
15997 }
15998 debounced.cancel = cancel;
15999 return debounced;
16000 }
16001
16002 /**
16003 * Defers invoking the `func` until the current call stack has cleared. Any
16004 * additional arguments are provided to `func` when it is invoked.
16005 *
16006 * @static
16007 * @memberOf _
16008 * @category Function
16009 * @param {Function} func The function to defer.
16010 * @param {...*} [args] The arguments to invoke the function with.
16011 * @returns {number} Returns the timer id.
16012 * @example
16013 *
16014 * _.defer(function(text) {
16015 * console.log(text);
16016 * }, 'deferred');
16017 * // logs 'deferred' after one or more milliseconds
16018 */
16019 var defer = restParam(function(func, args) {
16020 return baseDelay(func, 1, args);
16021 });
16022
16023 /**
16024 * Invokes `func` after `wait` milliseconds. Any additional arguments are
16025 * provided to `func` when it is invoked.
16026 *
16027 * @static
16028 * @memberOf _
16029 * @category Function
16030 * @param {Function} func The function to delay.
16031 * @param {number} wait The number of milliseconds to delay invocation.
16032 * @param {...*} [args] The arguments to invoke the function with.
16033 * @returns {number} Returns the timer id.
16034 * @example
16035 *
16036 * _.delay(function(text) {
16037 * console.log(text);
16038 * }, 1000, 'later');
16039 * // => logs 'later' after one second
16040 */
16041 var delay = restParam(function(func, wait, args) {
16042 return baseDelay(func, wait, args);
16043 });
16044
16045 /**
16046 * Creates a function that returns the result of invoking the provided
16047 * functions with the `this` binding of the created function, where each
16048 * successive invocation is supplied the return value of the previous.
16049 *
16050 * @static
16051 * @memberOf _
16052 * @category Function
16053 * @param {...Function} [funcs] Functions to invoke.
16054 * @returns {Function} Returns the new function.
16055 * @example
16056 *
16057 * function square(n) {
16058 * return n * n;
16059 * }
16060 *
16061 * var addSquare = _.flow(_.add, square);
16062 * addSquare(1, 2);
16063 * // => 9
16064 */
16065 var flow = createFlow();
16066
16067 /**
16068 * This method is like `_.flow` except that it creates a function that
16069 * invokes the provided functions from right to left.
16070 *
16071 * @static
16072 * @memberOf _
16073 * @alias backflow, compose
16074 * @category Function
16075 * @param {...Function} [funcs] Functions to invoke.
16076 * @returns {Function} Returns the new function.
16077 * @example
16078 *
16079 * function square(n) {
16080 * return n * n;
16081 * }
16082 *
16083 * var addSquare = _.flowRight(square, _.add);
16084 * addSquare(1, 2);
16085 * // => 9
16086 */
16087 var flowRight = createFlow(true);
16088
16089 /**
16090 * Creates a function that memoizes the result of `func`. If `resolver` is
16091 * provided it determines the cache key for storing the result based on the
16092 * arguments provided to the memoized function. By default, the first argument
16093 * provided to the memoized function is coerced to a string and used as the
16094 * cache key. The `func` is invoked with the `this` binding of the memoized
16095 * function.
16096 *
16097 * **Note:** The cache is exposed as the `cache` property on the memoized
16098 * function. Its creation may be customized by replacing the `_.memoize.Cache`
16099 * constructor with one whose instances implement the [`Map`](http://ecma-international.org/ecma-262/6.0/#sec-properties-of-the-map-prototype-object)
16100 * method interface of `get`, `has`, and `set`.
16101 *
16102 * @static
16103 * @memberOf _
16104 * @category Function
16105 * @param {Function} func The function to have its output memoized.
16106 * @param {Function} [resolver] The function to resolve the cache key.
16107 * @returns {Function} Returns the new memoizing function.
16108 * @example
16109 *
16110 * var upperCase = _.memoize(function(string) {
16111 * return string.toUpperCase();
16112 * });
16113 *
16114 * upperCase('fred');
16115 * // => 'FRED'
16116 *
16117 * // modifying the result cache
16118 * upperCase.cache.set('fred', 'BARNEY');
16119 * upperCase('fred');
16120 * // => 'BARNEY'
16121 *
16122 * // replacing `_.memoize.Cache`
16123 * var object = { 'user': 'fred' };
16124 * var other = { 'user': 'barney' };
16125 * var identity = _.memoize(_.identity);
16126 *
16127 * identity(object);
16128 * // => { 'user': 'fred' }
16129 * identity(other);
16130 * // => { 'user': 'fred' }
16131 *
16132 * _.memoize.Cache = WeakMap;
16133 * var identity = _.memoize(_.identity);
16134 *
16135 * identity(object);
16136 * // => { 'user': 'fred' }
16137 * identity(other);
16138 * // => { 'user': 'barney' }
16139 */
16140 function memoize(func, resolver) {
16141 if (typeof func != 'function' || (resolver && typeof resolver != 'function')) {
16142 throw new TypeError(FUNC_ERROR_TEXT);
16143 }
16144 var memoized = function() {
16145 var args = arguments,
16146 key = resolver ? resolver.apply(this, args) : args[0],
16147 cache = memoized.cache;
16148
16149 if (cache.has(key)) {
16150 return cache.get(key);
16151 }
16152 var result = func.apply(this, args);
16153 memoized.cache = cache.set(key, result);
16154 return result;
16155 };
16156 memoized.cache = new memoize.Cache;
16157 return memoized;
16158 }
16159
16160 /**
16161 * Creates a function that runs each argument through a corresponding
16162 * transform function.
16163 *
16164 * @static
16165 * @memberOf _
16166 * @category Function
16167 * @param {Function} func The function to wrap.
16168 * @param {...(Function|Function[])} [transforms] The functions to transform
16169 * arguments, specified as individual functions or arrays of functions.
16170 * @returns {Function} Returns the new function.
16171 * @example
16172 *
16173 * function doubled(n) {
16174 * return n * 2;
16175 * }
16176 *
16177 * function square(n) {
16178 * return n * n;
16179 * }
16180 *
16181 * var modded = _.modArgs(function(x, y) {
16182 * return [x, y];
16183 * }, square, doubled);
16184 *
16185 * modded(1, 2);
16186 * // => [1, 4]
16187 *
16188 * modded(5, 10);
16189 * // => [25, 20]
16190 */
16191 var modArgs = restParam(function(func, transforms) {
16192 transforms = baseFlatten(transforms);
16193 if (typeof func != 'function' || !arrayEvery(transforms, baseIsFunction)) {
16194 throw new TypeError(FUNC_ERROR_TEXT);
16195 }
16196 var length = transforms.length;
16197 return restParam(function(args) {
16198 var index = nativeMin(args.length, length);
16199 while (index--) {
16200 args[index] = transforms[index](args[index]);
16201 }
16202 return func.apply(this, args);
16203 });
16204 });
16205
16206 /**
16207 * Creates a function that negates the result of the predicate `func`. The
16208 * `func` predicate is invoked with the `this` binding and arguments of the
16209 * created function.
16210 *
16211 * @static
16212 * @memberOf _
16213 * @category Function
16214 * @param {Function} predicate The predicate to negate.
16215 * @returns {Function} Returns the new function.
16216 * @example
16217 *
16218 * function isEven(n) {
16219 * return n % 2 == 0;
16220 * }
16221 *
16222 * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven));
16223 * // => [1, 3, 5]
16224 */
16225 function negate(predicate) {
16226 if (typeof predicate != 'function') {
16227 throw new TypeError(FUNC_ERROR_TEXT);
16228 }
16229 return function() {
16230 return !predicate.apply(this, arguments);
16231 };
16232 }
16233
16234 /**
16235 * Creates a function that is restricted to invoking `func` once. Repeat calls
16236 * to the function return the value of the first call. The `func` is invoked
16237 * with the `this` binding and arguments of the created function.
16238 *
16239 * @static
16240 * @memberOf _
16241 * @category Function
16242 * @param {Function} func The function to restrict.
16243 * @returns {Function} Returns the new restricted function.
16244 * @example
16245 *
16246 * var initialize = _.once(createApplication);
16247 * initialize();
16248 * initialize();
16249 * // `initialize` invokes `createApplication` once
16250 */
16251 function once(func) {
16252 return before(2, func);
16253 }
16254
16255 /**
16256 * Creates a function that invokes `func` with `partial` arguments prepended
16257 * to those provided to the new function. This method is like `_.bind` except
16258 * it does **not** alter the `this` binding.
16259 *
16260 * The `_.partial.placeholder` value, which defaults to `_` in monolithic
16261 * builds, may be used as a placeholder for partially applied arguments.
16262 *
16263 * **Note:** This method does not set the "length" property of partially
16264 * applied functions.
16265 *
16266 * @static
16267 * @memberOf _
16268 * @category Function
16269 * @param {Function} func The function to partially apply arguments to.
16270 * @param {...*} [partials] The arguments to be partially applied.
16271 * @returns {Function} Returns the new partially applied function.
16272 * @example
16273 *
16274 * var greet = function(greeting, name) {
16275 * return greeting + ' ' + name;
16276 * };
16277 *
16278 * var sayHelloTo = _.partial(greet, 'hello');
16279 * sayHelloTo('fred');
16280 * // => 'hello fred'
16281 *
16282 * // using placeholders
16283 * var greetFred = _.partial(greet, _, 'fred');
16284 * greetFred('hi');
16285 * // => 'hi fred'
16286 */
16287 var partial = createPartial(PARTIAL_FLAG);
16288
16289 /**
16290 * This method is like `_.partial` except that partially applied arguments
16291 * are appended to those provided to the new function.
16292 *
16293 * The `_.partialRight.placeholder` value, which defaults to `_` in monolithic
16294 * builds, may be used as a placeholder for partially applied arguments.
16295 *
16296 * **Note:** This method does not set the "length" property of partially
16297 * applied functions.
16298 *
16299 * @static
16300 * @memberOf _
16301 * @category Function
16302 * @param {Function} func The function to partially apply arguments to.
16303 * @param {...*} [partials] The arguments to be partially applied.
16304 * @returns {Function} Returns the new partially applied function.
16305 * @example
16306 *
16307 * var greet = function(greeting, name) {
16308 * return greeting + ' ' + name;
16309 * };
16310 *
16311 * var greetFred = _.partialRight(greet, 'fred');
16312 * greetFred('hi');
16313 * // => 'hi fred'
16314 *
16315 * // using placeholders
16316 * var sayHelloTo = _.partialRight(greet, 'hello', _);
16317 * sayHelloTo('fred');
16318 * // => 'hello fred'
16319 */
16320 var partialRight = createPartial(PARTIAL_RIGHT_FLAG);
16321
16322 /**
16323 * Creates a function that invokes `func` with arguments arranged according
16324 * to the specified indexes where the argument value at the first index is
16325 * provided as the first argument, the argument value at the second index is
16326 * provided as the second argument, and so on.
16327 *
16328 * @static
16329 * @memberOf _
16330 * @category Function
16331 * @param {Function} func The function to rearrange arguments for.
16332 * @param {...(number|number[])} indexes The arranged argument indexes,
16333 * specified as individual indexes or arrays of indexes.
16334 * @returns {Function} Returns the new function.
16335 * @example
16336 *
16337 * var rearged = _.rearg(function(a, b, c) {
16338 * return [a, b, c];
16339 * }, 2, 0, 1);
16340 *
16341 * rearged('b', 'c', 'a')
16342 * // => ['a', 'b', 'c']
16343 *
16344 * var map = _.rearg(_.map, [1, 0]);
16345 * map(function(n) {
16346 * return n * 3;
16347 * }, [1, 2, 3]);
16348 * // => [3, 6, 9]
16349 */
16350 var rearg = restParam(function(func, indexes) {
16351 return createWrapper(func, REARG_FLAG, undefined, undefined, undefined, baseFlatten(indexes));
16352 });
16353
16354 /**
16355 * Creates a function that invokes `func` with the `this` binding of the
16356 * created function and arguments from `start` and beyond provided as an array.
16357 *
16358 * **Note:** This method is based on the [rest parameter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters).
16359 *
16360 * @static
16361 * @memberOf _
16362 * @category Function
16363 * @param {Function} func The function to apply a rest parameter to.
16364 * @param {number} [start=func.length-1] The start position of the rest parameter.
16365 * @returns {Function} Returns the new function.
16366 * @example
16367 *
16368 * var say = _.restParam(function(what, names) {
16369 * return what + ' ' + _.initial(names).join(', ') +
16370 * (_.size(names) > 1 ? ', & ' : '') + _.last(names);
16371 * });
16372 *
16373 * say('hello', 'fred', 'barney', 'pebbles');
16374 * // => 'hello fred, barney, & pebbles'
16375 */
16376 function restParam(func, start) {
16377 if (typeof func != 'function') {
16378 throw new TypeError(FUNC_ERROR_TEXT);
16379 }
16380 start = nativeMax(start === undefined ? (func.length - 1) : (+start || 0), 0);
16381 return function() {
16382 var args = arguments,
16383 index = -1,
16384 length = nativeMax(args.length - start, 0),
16385 rest = Array(length);
16386
16387 while (++index < length) {
16388 rest[index] = args[start + index];
16389 }
16390 switch (start) {
16391 case 0: return func.call(this, rest);
16392 case 1: return func.call(this, args[0], rest);
16393 case 2: return func.call(this, args[0], args[1], rest);
16394 }
16395 var otherArgs = Array(start + 1);
16396 index = -1;
16397 while (++index < start) {
16398 otherArgs[index] = args[index];
16399 }
16400 otherArgs[start] = rest;
16401 return func.apply(this, otherArgs);
16402 };
16403 }
16404
16405 /**
16406 * Creates a function that invokes `func` with the `this` binding of the created
16407 * function and an array of arguments much like [`Function#apply`](https://es5.github.io/#x15.3.4.3).
16408 *
16409 * **Note:** This method is based on the [spread operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator).
16410 *
16411 * @static
16412 * @memberOf _
16413 * @category Function
16414 * @param {Function} func The function to spread arguments over.
16415 * @returns {Function} Returns the new function.
16416 * @example
16417 *
16418 * var say = _.spread(function(who, what) {
16419 * return who + ' says ' + what;
16420 * });
16421 *
16422 * say(['fred', 'hello']);
16423 * // => 'fred says hello'
16424 *
16425 * // with a Promise
16426 * var numbers = Promise.all([
16427 * Promise.resolve(40),
16428 * Promise.resolve(36)
16429 * ]);
16430 *
16431 * numbers.then(_.spread(function(x, y) {
16432 * return x + y;
16433 * }));
16434 * // => a Promise of 76
16435 */
16436 function spread(func) {
16437 if (typeof func != 'function') {
16438 throw new TypeError(FUNC_ERROR_TEXT);
16439 }
16440 return function(array) {
16441 return func.apply(this, array);
16442 };
16443 }
16444
16445 /**
16446 * Creates a throttled function that only invokes `func` at most once per
16447 * every `wait` milliseconds. The throttled function comes with a `cancel`
16448 * method to cancel delayed invocations. Provide an options object to indicate
16449 * that `func` should be invoked on the leading and/or trailing edge of the
16450 * `wait` timeout. Subsequent calls to the throttled function return the
16451 * result of the last `func` call.
16452 *
16453 * **Note:** If `leading` and `trailing` options are `true`, `func` is invoked
16454 * on the trailing edge of the timeout only if the the throttled function is
16455 * invoked more than once during the `wait` timeout.
16456 *
16457 * See [David Corbacho's article](http://drupalmotion.com/article/debounce-and-throttle-visual-explanation)
16458 * for details over the differences between `_.throttle` and `_.debounce`.
16459 *
16460 * @static
16461 * @memberOf _
16462 * @category Function
16463 * @param {Function} func The function to throttle.
16464 * @param {number} [wait=0] The number of milliseconds to throttle invocations to.
16465 * @param {Object} [options] The options object.
16466 * @param {boolean} [options.leading=true] Specify invoking on the leading
16467 * edge of the timeout.
16468 * @param {boolean} [options.trailing=true] Specify invoking on the trailing
16469 * edge of the timeout.
16470 * @returns {Function} Returns the new throttled function.
16471 * @example
16472 *
16473 * // avoid excessively updating the position while scrolling
16474 * jQuery(window).on('scroll', _.throttle(updatePosition, 100));
16475 *
16476 * // invoke `renewToken` when the click event is fired, but not more than once every 5 minutes
16477 * jQuery('.interactive').on('click', _.throttle(renewToken, 300000, {
16478 * 'trailing': false
16479 * }));
16480 *
16481 * // cancel a trailing throttled call
16482 * jQuery(window).on('popstate', throttled.cancel);
16483 */
16484 function throttle(func, wait, options) {
16485 var leading = true,
16486 trailing = true;
16487
16488 if (typeof func != 'function') {
16489 throw new TypeError(FUNC_ERROR_TEXT);
16490 }
16491 if (options === false) {
16492 leading = false;
16493 } else if (isObject(options)) {
16494 leading = 'leading' in options ? !!options.leading : leading;
16495 trailing = 'trailing' in options ? !!options.trailing : trailing;
16496 }
16497 return debounce(func, wait, { 'leading': leading, 'maxWait': +wait, 'trailing': trailing });
16498 }
16499
16500 /**
16501 * Creates a function that provides `value` to the wrapper function as its
16502 * first argument. Any additional arguments provided to the function are
16503 * appended to those provided to the wrapper function. The wrapper is invoked
16504 * with the `this` binding of the created function.
16505 *
16506 * @static
16507 * @memberOf _
16508 * @category Function
16509 * @param {*} value The value to wrap.
16510 * @param {Function} wrapper The wrapper function.
16511 * @returns {Function} Returns the new function.
16512 * @example
16513 *
16514 * var p = _.wrap(_.escape, function(func, text) {
16515 * return '<p>' + func(text) + '</p>';
16516 * });
16517 *
16518 * p('fred, barney, & pebbles');
16519 * // => '<p>fred, barney, &amp; pebbles</p>'
16520 */
16521 function wrap(value, wrapper) {
16522 wrapper = wrapper == null ? identity : wrapper;
16523 return createWrapper(wrapper, PARTIAL_FLAG, undefined, [value], []);
16524 }
16525
16526 /*------------------------------------------------------------------------*/
16527
16528 /**
16529 * Creates a clone of `value`. If `isDeep` is `true` nested objects are cloned,
16530 * otherwise they are assigned by reference. If `customizer` is provided it is
16531 * invoked to produce the cloned values. If `customizer` returns `undefined`
16532 * cloning is handled by the method instead. The `customizer` is bound to
16533 * `thisArg` and invoked with two argument; (value [, index|key, object]).
16534 *
16535 * **Note:** This method is loosely based on the
16536 * [structured clone algorithm](http://www.w3.org/TR/html5/infrastructure.html#internal-structured-cloning-algorithm).
16537 * The enumerable properties of `arguments` objects and objects created by
16538 * constructors other than `Object` are cloned to plain `Object` objects. An
16539 * empty object is returned for uncloneable values such as functions, DOM nodes,
16540 * Maps, Sets, and WeakMaps.
16541 *
16542 * @static
16543 * @memberOf _
16544 * @category Lang
16545 * @param {*} value The value to clone.
16546 * @param {boolean} [isDeep] Specify a deep clone.
16547 * @param {Function} [customizer] The function to customize cloning values.
16548 * @param {*} [thisArg] The `this` binding of `customizer`.
16549 * @returns {*} Returns the cloned value.
16550 * @example
16551 *
16552 * var users = [
16553 * { 'user': 'barney' },
16554 * { 'user': 'fred' }
16555 * ];
16556 *
16557 * var shallow = _.clone(users);
16558 * shallow[0] === users[0];
16559 * // => true
16560 *
16561 * var deep = _.clone(users, true);
16562 * deep[0] === users[0];
16563 * // => false
16564 *
16565 * // using a customizer callback
16566 * var el = _.clone(document.body, function(value) {
16567 * if (_.isElement(value)) {
16568 * return value.cloneNode(false);
16569 * }
16570 * });
16571 *
16572 * el === document.body
16573 * // => false
16574 * el.nodeName
16575 * // => BODY
16576 * el.childNodes.length;
16577 * // => 0
16578 */
16579 function clone(value, isDeep, customizer, thisArg) {
16580 if (isDeep && typeof isDeep != 'boolean' && isIterateeCall(value, isDeep, customizer)) {
16581 isDeep = false;
16582 }
16583 else if (typeof isDeep == 'function') {
16584 thisArg = customizer;
16585 customizer = isDeep;
16586 isDeep = false;
16587 }
16588 return typeof customizer == 'function'
16589 ? baseClone(value, isDeep, bindCallback(customizer, thisArg, 1))
16590 : baseClone(value, isDeep);
16591 }
16592
16593 /**
16594 * Creates a deep clone of `value`. If `customizer` is provided it is invoked
16595 * to produce the cloned values. If `customizer` returns `undefined` cloning
16596 * is handled by the method instead. The `customizer` is bound to `thisArg`
16597 * and invoked with two argument; (value [, index|key, object]).
16598 *
16599 * **Note:** This method is loosely based on the
16600 * [structured clone algorithm](http://www.w3.org/TR/html5/infrastructure.html#internal-structured-cloning-algorithm).
16601 * The enumerable properties of `arguments` objects and objects created by
16602 * constructors other than `Object` are cloned to plain `Object` objects. An
16603 * empty object is returned for uncloneable values such as functions, DOM nodes,
16604 * Maps, Sets, and WeakMaps.
16605 *
16606 * @static
16607 * @memberOf _
16608 * @category Lang
16609 * @param {*} value The value to deep clone.
16610 * @param {Function} [customizer] The function to customize cloning values.
16611 * @param {*} [thisArg] The `this` binding of `customizer`.
16612 * @returns {*} Returns the deep cloned value.
16613 * @example
16614 *
16615 * var users = [
16616 * { 'user': 'barney' },
16617 * { 'user': 'fred' }
16618 * ];
16619 *
16620 * var deep = _.cloneDeep(users);
16621 * deep[0] === users[0];
16622 * // => false
16623 *
16624 * // using a customizer callback
16625 * var el = _.cloneDeep(document.body, function(value) {
16626 * if (_.isElement(value)) {
16627 * return value.cloneNode(true);
16628 * }
16629 * });
16630 *
16631 * el === document.body
16632 * // => false
16633 * el.nodeName
16634 * // => BODY
16635 * el.childNodes.length;
16636 * // => 20
16637 */
16638 function cloneDeep(value, customizer, thisArg) {
16639 return typeof customizer == 'function'
16640 ? baseClone(value, true, bindCallback(customizer, thisArg, 1))
16641 : baseClone(value, true);
16642 }
16643
16644 /**
16645 * Checks if `value` is greater than `other`.
16646 *
16647 * @static
16648 * @memberOf _
16649 * @category Lang
16650 * @param {*} value The value to compare.
16651 * @param {*} other The other value to compare.
16652 * @returns {boolean} Returns `true` if `value` is greater than `other`, else `false`.
16653 * @example
16654 *
16655 * _.gt(3, 1);
16656 * // => true
16657 *
16658 * _.gt(3, 3);
16659 * // => false
16660 *
16661 * _.gt(1, 3);
16662 * // => false
16663 */
16664 function gt(value, other) {
16665 return value > other;
16666 }
16667
16668 /**
16669 * Checks if `value` is greater than or equal to `other`.
16670 *
16671 * @static
16672 * @memberOf _
16673 * @category Lang
16674 * @param {*} value The value to compare.
16675 * @param {*} other The other value to compare.
16676 * @returns {boolean} Returns `true` if `value` is greater than or equal to `other`, else `false`.
16677 * @example
16678 *
16679 * _.gte(3, 1);
16680 * // => true
16681 *
16682 * _.gte(3, 3);
16683 * // => true
16684 *
16685 * _.gte(1, 3);
16686 * // => false
16687 */
16688 function gte(value, other) {
16689 return value >= other;
16690 }
16691
16692 /**
16693 * Checks if `value` is classified as an `arguments` object.
16694 *
16695 * @static
16696 * @memberOf _
16697 * @category Lang
16698 * @param {*} value The value to check.
16699 * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
16700 * @example
16701 *
16702 * _.isArguments(function() { return arguments; }());
16703 * // => true
16704 *
16705 * _.isArguments([1, 2, 3]);
16706 * // => false
16707 */
16708 function isArguments(value) {
16709 return isObjectLike(value) && isArrayLike(value) &&
16710 hasOwnProperty.call(value, 'callee') && !propertyIsEnumerable.call(value, 'callee');
16711 }
16712
16713 /**
16714 * Checks if `value` is classified as an `Array` object.
16715 *
16716 * @static
16717 * @memberOf _
16718 * @category Lang
16719 * @param {*} value The value to check.
16720 * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
16721 * @example
16722 *
16723 * _.isArray([1, 2, 3]);
16724 * // => true
16725 *
16726 * _.isArray(function() { return arguments; }());
16727 * // => false
16728 */
16729 var isArray = nativeIsArray || function(value) {
16730 return isObjectLike(value) && isLength(value.length) && objToString.call(value) == arrayTag;
16731 };
16732
16733 /**
16734 * Checks if `value` is classified as a boolean primitive or object.
16735 *
16736 * @static
16737 * @memberOf _
16738 * @category Lang
16739 * @param {*} value The value to check.
16740 * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
16741 * @example
16742 *
16743 * _.isBoolean(false);
16744 * // => true
16745 *
16746 * _.isBoolean(null);
16747 * // => false
16748 */
16749 function isBoolean(value) {
16750 return value === true || value === false || (isObjectLike(value) && objToString.call(value) == boolTag);
16751 }
16752
16753 /**
16754 * Checks if `value` is classified as a `Date` object.
16755 *
16756 * @static
16757 * @memberOf _
16758 * @category Lang
16759 * @param {*} value The value to check.
16760 * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
16761 * @example
16762 *
16763 * _.isDate(new Date);
16764 * // => true
16765 *
16766 * _.isDate('Mon April 23 2012');
16767 * // => false
16768 */
16769 function isDate(value) {
16770 return isObjectLike(value) && objToString.call(value) == dateTag;
16771 }
16772
16773 /**
16774 * Checks if `value` is a DOM element.
16775 *
16776 * @static
16777 * @memberOf _
16778 * @category Lang
16779 * @param {*} value The value to check.
16780 * @returns {boolean} Returns `true` if `value` is a DOM element, else `false`.
16781 * @example
16782 *
16783 * _.isElement(document.body);
16784 * // => true
16785 *
16786 * _.isElement('<body>');
16787 * // => false
16788 */
16789 function isElement(value) {
16790 return !!value && value.nodeType === 1 && isObjectLike(value) && !isPlainObject(value);
16791 }
16792
16793 /**
16794 * Checks if `value` is empty. A value is considered empty unless it is an
16795 * `arguments` object, array, string, or jQuery-like collection with a length
16796 * greater than `0` or an object with own enumerable properties.
16797 *
16798 * @static
16799 * @memberOf _
16800 * @category Lang
16801 * @param {Array|Object|string} value The value to inspect.
16802 * @returns {boolean} Returns `true` if `value` is empty, else `false`.
16803 * @example
16804 *
16805 * _.isEmpty(null);
16806 * // => true
16807 *
16808 * _.isEmpty(true);
16809 * // => true
16810 *
16811 * _.isEmpty(1);
16812 * // => true
16813 *
16814 * _.isEmpty([1, 2, 3]);
16815 * // => false
16816 *
16817 * _.isEmpty({ 'a': 1 });
16818 * // => false
16819 */
16820 function isEmpty(value) {
16821 if (value == null) {
16822 return true;
16823 }
16824 if (isArrayLike(value) && (isArray(value) || isString(value) || isArguments(value) ||
16825 (isObjectLike(value) && isFunction(value.splice)))) {
16826 return !value.length;
16827 }
16828 return !keys(value).length;
16829 }
16830
16831 /**
16832 * Performs a deep comparison between two values to determine if they are
16833 * equivalent. If `customizer` is provided it is invoked to compare values.
16834 * If `customizer` returns `undefined` comparisons are handled by the method
16835 * instead. The `customizer` is bound to `thisArg` and invoked with three
16836 * arguments: (value, other [, index|key]).
16837 *
16838 * **Note:** This method supports comparing arrays, booleans, `Date` objects,
16839 * numbers, `Object` objects, regexes, and strings. Objects are compared by
16840 * their own, not inherited, enumerable properties. Functions and DOM nodes
16841 * are **not** supported. Provide a customizer function to extend support
16842 * for comparing other values.
16843 *
16844 * @static
16845 * @memberOf _
16846 * @alias eq
16847 * @category Lang
16848 * @param {*} value The value to compare.
16849 * @param {*} other The other value to compare.
16850 * @param {Function} [customizer] The function to customize value comparisons.
16851 * @param {*} [thisArg] The `this` binding of `customizer`.
16852 * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
16853 * @example
16854 *
16855 * var object = { 'user': 'fred' };
16856 * var other = { 'user': 'fred' };
16857 *
16858 * object == other;
16859 * // => false
16860 *
16861 * _.isEqual(object, other);
16862 * // => true
16863 *
16864 * // using a customizer callback
16865 * var array = ['hello', 'goodbye'];
16866 * var other = ['hi', 'goodbye'];
16867 *
16868 * _.isEqual(array, other, function(value, other) {
16869 * if (_.every([value, other], RegExp.prototype.test, /^h(?:i|ello)$/)) {
16870 * return true;
16871 * }
16872 * });
16873 * // => true
16874 */
16875 function isEqual(value, other, customizer, thisArg) {
16876 customizer = typeof customizer == 'function' ? bindCallback(customizer, thisArg, 3) : undefined;
16877 var result = customizer ? customizer(value, other) : undefined;
16878 return result === undefined ? baseIsEqual(value, other, customizer) : !!result;
16879 }
16880
16881 /**
16882 * Checks if `value` is an `Error`, `EvalError`, `RangeError`, `ReferenceError`,
16883 * `SyntaxError`, `TypeError`, or `URIError` object.
16884 *
16885 * @static
16886 * @memberOf _
16887 * @category Lang
16888 * @param {*} value The value to check.
16889 * @returns {boolean} Returns `true` if `value` is an error object, else `false`.
16890 * @example
16891 *
16892 * _.isError(new Error);
16893 * // => true
16894 *
16895 * _.isError(Error);
16896 * // => false
16897 */
16898 function isError(value) {
16899 return isObjectLike(value) && typeof value.message == 'string' && objToString.call(value) == errorTag;
16900 }
16901
16902 /**
16903 * Checks if `value` is a finite primitive number.
16904 *
16905 * **Note:** This method is based on [`Number.isFinite`](http://ecma-international.org/ecma-262/6.0/#sec-number.isfinite).
16906 *
16907 * @static
16908 * @memberOf _
16909 * @category Lang
16910 * @param {*} value The value to check.
16911 * @returns {boolean} Returns `true` if `value` is a finite number, else `false`.
16912 * @example
16913 *
16914 * _.isFinite(10);
16915 * // => true
16916 *
16917 * _.isFinite('10');
16918 * // => false
16919 *
16920 * _.isFinite(true);
16921 * // => false
16922 *
16923 * _.isFinite(Object(10));
16924 * // => false
16925 *
16926 * _.isFinite(Infinity);
16927 * // => false
16928 */
16929 function isFinite(value) {
16930 return typeof value == 'number' && nativeIsFinite(value);
16931 }
16932
16933 /**
16934 * Checks if `value` is classified as a `Function` object.
16935 *
16936 * @static
16937 * @memberOf _
16938 * @category Lang
16939 * @param {*} value The value to check.
16940 * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
16941 * @example
16942 *
16943 * _.isFunction(_);
16944 * // => true
16945 *
16946 * _.isFunction(/abc/);
16947 * // => false
16948 */
16949 function isFunction(value) {
16950 // The use of `Object#toString` avoids issues with the `typeof` operator
16951 // in older versions of Chrome and Safari which return 'function' for regexes
16952 // and Safari 8 equivalents which return 'object' for typed array constructors.
16953 return isObject(value) && objToString.call(value) == funcTag;
16954 }
16955
16956 /**
16957 * Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`.
16958 * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
16959 *
16960 * @static
16961 * @memberOf _
16962 * @category Lang
16963 * @param {*} value The value to check.
16964 * @returns {boolean} Returns `true` if `value` is an object, else `false`.
16965 * @example
16966 *
16967 * _.isObject({});
16968 * // => true
16969 *
16970 * _.isObject([1, 2, 3]);
16971 * // => true
16972 *
16973 * _.isObject(1);
16974 * // => false
16975 */
16976 function isObject(value) {
16977 // Avoid a V8 JIT bug in Chrome 19-20.
16978 // See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
16979 var type = typeof value;
16980 return !!value && (type == 'object' || type == 'function');
16981 }
16982
16983 /**
16984 * Performs a deep comparison between `object` and `source` to determine if
16985 * `object` contains equivalent property values. If `customizer` is provided
16986 * it is invoked to compare values. If `customizer` returns `undefined`
16987 * comparisons are handled by the method instead. The `customizer` is bound
16988 * to `thisArg` and invoked with three arguments: (value, other, index|key).
16989 *
16990 * **Note:** This method supports comparing properties of arrays, booleans,
16991 * `Date` objects, numbers, `Object` objects, regexes, and strings. Functions
16992 * and DOM nodes are **not** supported. Provide a customizer function to extend
16993 * support for comparing other values.
16994 *
16995 * @static
16996 * @memberOf _
16997 * @category Lang
16998 * @param {Object} object The object to inspect.
16999 * @param {Object} source The object of property values to match.
17000 * @param {Function} [customizer] The function to customize value comparisons.
17001 * @param {*} [thisArg] The `this` binding of `customizer`.
17002 * @returns {boolean} Returns `true` if `object` is a match, else `false`.
17003 * @example
17004 *
17005 * var object = { 'user': 'fred', 'age': 40 };
17006 *
17007 * _.isMatch(object, { 'age': 40 });
17008 * // => true
17009 *
17010 * _.isMatch(object, { 'age': 36 });
17011 * // => false
17012 *
17013 * // using a customizer callback
17014 * var object = { 'greeting': 'hello' };
17015 * var source = { 'greeting': 'hi' };
17016 *
17017 * _.isMatch(object, source, function(value, other) {
17018 * return _.every([value, other], RegExp.prototype.test, /^h(?:i|ello)$/) || undefined;
17019 * });
17020 * // => true
17021 */
17022 function isMatch(object, source, customizer, thisArg) {
17023 customizer = typeof customizer == 'function' ? bindCallback(customizer, thisArg, 3) : undefined;
17024 return baseIsMatch(object, getMatchData(source), customizer);
17025 }
17026
17027 /**
17028 * Checks if `value` is `NaN`.
17029 *
17030 * **Note:** This method is not the same as [`isNaN`](https://es5.github.io/#x15.1.2.4)
17031 * which returns `true` for `undefined` and other non-numeric values.
17032 *
17033 * @static
17034 * @memberOf _
17035 * @category Lang
17036 * @param {*} value The value to check.
17037 * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.
17038 * @example
17039 *
17040 * _.isNaN(NaN);
17041 * // => true
17042 *
17043 * _.isNaN(new Number(NaN));
17044 * // => true
17045 *
17046 * isNaN(undefined);
17047 * // => true
17048 *
17049 * _.isNaN(undefined);
17050 * // => false
17051 */
17052 function isNaN(value) {
17053 // An `NaN` primitive is the only value that is not equal to itself.
17054 // Perform the `toStringTag` check first to avoid errors with some host objects in IE.
17055 return isNumber(value) && value != +value;
17056 }
17057
17058 /**
17059 * Checks if `value` is a native function.
17060 *
17061 * @static
17062 * @memberOf _
17063 * @category Lang
17064 * @param {*} value The value to check.
17065 * @returns {boolean} Returns `true` if `value` is a native function, else `false`.
17066 * @example
17067 *
17068 * _.isNative(Array.prototype.push);
17069 * // => true
17070 *
17071 * _.isNative(_);
17072 * // => false
17073 */
17074 function isNative(value) {
17075 if (value == null) {
17076 return false;
17077 }
17078 if (isFunction(value)) {
17079 return reIsNative.test(fnToString.call(value));
17080 }
17081 return isObjectLike(value) && reIsHostCtor.test(value);
17082 }
17083
17084 /**
17085 * Checks if `value` is `null`.
17086 *
17087 * @static
17088 * @memberOf _
17089 * @category Lang
17090 * @param {*} value The value to check.
17091 * @returns {boolean} Returns `true` if `value` is `null`, else `false`.
17092 * @example
17093 *
17094 * _.isNull(null);
17095 * // => true
17096 *
17097 * _.isNull(void 0);
17098 * // => false
17099 */
17100 function isNull(value) {
17101 return value === null;
17102 }
17103
17104 /**
17105 * Checks if `value` is classified as a `Number` primitive or object.
17106 *
17107 * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are classified
17108 * as numbers, use the `_.isFinite` method.
17109 *
17110 * @static
17111 * @memberOf _
17112 * @category Lang
17113 * @param {*} value The value to check.
17114 * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
17115 * @example
17116 *
17117 * _.isNumber(8.4);
17118 * // => true
17119 *
17120 * _.isNumber(NaN);
17121 * // => true
17122 *
17123 * _.isNumber('8.4');
17124 * // => false
17125 */
17126 function isNumber(value) {
17127 return typeof value == 'number' || (isObjectLike(value) && objToString.call(value) == numberTag);
17128 }
17129
17130 /**
17131 * Checks if `value` is a plain object, that is, an object created by the
17132 * `Object` constructor or one with a `[[Prototype]]` of `null`.
17133 *
17134 * **Note:** This method assumes objects created by the `Object` constructor
17135 * have no inherited enumerable properties.
17136 *
17137 * @static
17138 * @memberOf _
17139 * @category Lang
17140 * @param {*} value The value to check.
17141 * @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
17142 * @example
17143 *
17144 * function Foo() {
17145 * this.a = 1;
17146 * }
17147 *
17148 * _.isPlainObject(new Foo);
17149 * // => false
17150 *
17151 * _.isPlainObject([1, 2, 3]);
17152 * // => false
17153 *
17154 * _.isPlainObject({ 'x': 0, 'y': 0 });
17155 * // => true
17156 *
17157 * _.isPlainObject(Object.create(null));
17158 * // => true
17159 */
17160 function isPlainObject(value) {
17161 var Ctor;
17162
17163 // Exit early for non `Object` objects.
17164 if (!(isObjectLike(value) && objToString.call(value) == objectTag && !isArguments(value)) ||
17165 (!hasOwnProperty.call(value, 'constructor') && (Ctor = value.constructor, typeof Ctor == 'function' && !(Ctor instanceof Ctor)))) {
17166 return false;
17167 }
17168 // IE < 9 iterates inherited properties before own properties. If the first
17169 // iterated property is an object's own property then there are no inherited
17170 // enumerable properties.
17171 var result;
17172 // In most environments an object's own properties are iterated before
17173 // its inherited properties. If the last iterated property is an object's
17174 // own property then there are no inherited enumerable properties.
17175 baseForIn(value, function(subValue, key) {
17176 result = key;
17177 });
17178 return result === undefined || hasOwnProperty.call(value, result);
17179 }
17180
17181 /**
17182 * Checks if `value` is classified as a `RegExp` object.
17183 *
17184 * @static
17185 * @memberOf _
17186 * @category Lang
17187 * @param {*} value The value to check.
17188 * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
17189 * @example
17190 *
17191 * _.isRegExp(/abc/);
17192 * // => true
17193 *
17194 * _.isRegExp('/abc/');
17195 * // => false
17196 */
17197 function isRegExp(value) {
17198 return isObject(value) && objToString.call(value) == regexpTag;
17199 }
17200
17201 /**
17202 * Checks if `value` is classified as a `String` primitive or object.
17203 *
17204 * @static
17205 * @memberOf _
17206 * @category Lang
17207 * @param {*} value The value to check.
17208 * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
17209 * @example
17210 *
17211 * _.isString('abc');
17212 * // => true
17213 *
17214 * _.isString(1);
17215 * // => false
17216 */
17217 function isString(value) {
17218 return typeof value == 'string' || (isObjectLike(value) && objToString.call(value) == stringTag);
17219 }
17220
17221 /**
17222 * Checks if `value` is classified as a typed array.
17223 *
17224 * @static
17225 * @memberOf _
17226 * @category Lang
17227 * @param {*} value The value to check.
17228 * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
17229 * @example
17230 *
17231 * _.isTypedArray(new Uint8Array);
17232 * // => true
17233 *
17234 * _.isTypedArray([]);
17235 * // => false
17236 */
17237 function isTypedArray(value) {
17238 return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[objToString.call(value)];
17239 }
17240
17241 /**
17242 * Checks if `value` is `undefined`.
17243 *
17244 * @static
17245 * @memberOf _
17246 * @category Lang
17247 * @param {*} value The value to check.
17248 * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`.
17249 * @example
17250 *
17251 * _.isUndefined(void 0);
17252 * // => true
17253 *
17254 * _.isUndefined(null);
17255 * // => false
17256 */
17257 function isUndefined(value) {
17258 return value === undefined;
17259 }
17260
17261 /**
17262 * Checks if `value` is less than `other`.
17263 *
17264 * @static
17265 * @memberOf _
17266 * @category Lang
17267 * @param {*} value The value to compare.
17268 * @param {*} other The other value to compare.
17269 * @returns {boolean} Returns `true` if `value` is less than `other`, else `false`.
17270 * @example
17271 *
17272 * _.lt(1, 3);
17273 * // => true
17274 *
17275 * _.lt(3, 3);
17276 * // => false
17277 *
17278 * _.lt(3, 1);
17279 * // => false
17280 */
17281 function lt(value, other) {
17282 return value < other;
17283 }
17284
17285 /**
17286 * Checks if `value` is less than or equal to `other`.
17287 *
17288 * @static
17289 * @memberOf _
17290 * @category Lang
17291 * @param {*} value The value to compare.
17292 * @param {*} other The other value to compare.
17293 * @returns {boolean} Returns `true` if `value` is less than or equal to `other`, else `false`.
17294 * @example
17295 *
17296 * _.lte(1, 3);
17297 * // => true
17298 *
17299 * _.lte(3, 3);
17300 * // => true
17301 *
17302 * _.lte(3, 1);
17303 * // => false
17304 */
17305 function lte(value, other) {
17306 return value <= other;
17307 }
17308
17309 /**
17310 * Converts `value` to an array.
17311 *
17312 * @static
17313 * @memberOf _
17314 * @category Lang
17315 * @param {*} value The value to convert.
17316 * @returns {Array} Returns the converted array.
17317 * @example
17318 *
17319 * (function() {
17320 * return _.toArray(arguments).slice(1);
17321 * }(1, 2, 3));
17322 * // => [2, 3]
17323 */
17324 function toArray(value) {
17325 var length = value ? getLength(value) : 0;
17326 if (!isLength(length)) {
17327 return values(value);
17328 }
17329 if (!length) {
17330 return [];
17331 }
17332 return arrayCopy(value);
17333 }
17334
17335 /**
17336 * Converts `value` to a plain object flattening inherited enumerable
17337 * properties of `value` to own properties of the plain object.
17338 *
17339 * @static
17340 * @memberOf _
17341 * @category Lang
17342 * @param {*} value The value to convert.
17343 * @returns {Object} Returns the converted plain object.
17344 * @example
17345 *
17346 * function Foo() {
17347 * this.b = 2;
17348 * }
17349 *
17350 * Foo.prototype.c = 3;
17351 *
17352 * _.assign({ 'a': 1 }, new Foo);
17353 * // => { 'a': 1, 'b': 2 }
17354 *
17355 * _.assign({ 'a': 1 }, _.toPlainObject(new Foo));
17356 * // => { 'a': 1, 'b': 2, 'c': 3 }
17357 */
17358 function toPlainObject(value) {
17359 return baseCopy(value, keysIn(value));
17360 }
17361
17362 /*------------------------------------------------------------------------*/
17363
17364 /**
17365 * Recursively merges own enumerable properties of the source object(s), that
17366 * don't resolve to `undefined` into the destination object. Subsequent sources
17367 * overwrite property assignments of previous sources. If `customizer` is
17368 * provided it is invoked to produce the merged values of the destination and
17369 * source properties. If `customizer` returns `undefined` merging is handled
17370 * by the method instead. The `customizer` is bound to `thisArg` and invoked
17371 * with five arguments: (objectValue, sourceValue, key, object, source).
17372 *
17373 * @static
17374 * @memberOf _
17375 * @category Object
17376 * @param {Object} object The destination object.
17377 * @param {...Object} [sources] The source objects.
17378 * @param {Function} [customizer] The function to customize assigned values.
17379 * @param {*} [thisArg] The `this` binding of `customizer`.
17380 * @returns {Object} Returns `object`.
17381 * @example
17382 *
17383 * var users = {
17384 * 'data': [{ 'user': 'barney' }, { 'user': 'fred' }]
17385 * };
17386 *
17387 * var ages = {
17388 * 'data': [{ 'age': 36 }, { 'age': 40 }]
17389 * };
17390 *
17391 * _.merge(users, ages);
17392 * // => { 'data': [{ 'user': 'barney', 'age': 36 }, { 'user': 'fred', 'age': 40 }] }
17393 *
17394 * // using a customizer callback
17395 * var object = {
17396 * 'fruits': ['apple'],
17397 * 'vegetables': ['beet']
17398 * };
17399 *
17400 * var other = {
17401 * 'fruits': ['banana'],
17402 * 'vegetables': ['carrot']
17403 * };
17404 *
17405 * _.merge(object, other, function(a, b) {
17406 * if (_.isArray(a)) {
17407 * return a.concat(b);
17408 * }
17409 * });
17410 * // => { 'fruits': ['apple', 'banana'], 'vegetables': ['beet', 'carrot'] }
17411 */
17412 var merge = createAssigner(baseMerge);
17413
17414 /**
17415 * Assigns own enumerable properties of source object(s) to the destination
17416 * object. Subsequent sources overwrite property assignments of previous sources.
17417 * If `customizer` is provided it is invoked to produce the assigned values.
17418 * The `customizer` is bound to `thisArg` and invoked with five arguments:
17419 * (objectValue, sourceValue, key, object, source).
17420 *
17421 * **Note:** This method mutates `object` and is based on
17422 * [`Object.assign`](http://ecma-international.org/ecma-262/6.0/#sec-object.assign).
17423 *
17424 * @static
17425 * @memberOf _
17426 * @alias extend
17427 * @category Object
17428 * @param {Object} object The destination object.
17429 * @param {...Object} [sources] The source objects.
17430 * @param {Function} [customizer] The function to customize assigned values.
17431 * @param {*} [thisArg] The `this` binding of `customizer`.
17432 * @returns {Object} Returns `object`.
17433 * @example
17434 *
17435 * _.assign({ 'user': 'barney' }, { 'age': 40 }, { 'user': 'fred' });
17436 * // => { 'user': 'fred', 'age': 40 }
17437 *
17438 * // using a customizer callback
17439 * var defaults = _.partialRight(_.assign, function(value, other) {
17440 * return _.isUndefined(value) ? other : value;
17441 * });
17442 *
17443 * defaults({ 'user': 'barney' }, { 'age': 36 }, { 'user': 'fred' });
17444 * // => { 'user': 'barney', 'age': 36 }
17445 */
17446 var assign = createAssigner(function(object, source, customizer) {
17447 return customizer
17448 ? assignWith(object, source, customizer)
17449 : baseAssign(object, source);
17450 });
17451
17452 /**
17453 * Creates an object that inherits from the given `prototype` object. If a
17454 * `properties` object is provided its own enumerable properties are assigned
17455 * to the created object.
17456 *
17457 * @static
17458 * @memberOf _
17459 * @category Object
17460 * @param {Object} prototype The object to inherit from.
17461 * @param {Object} [properties] The properties to assign to the object.
17462 * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
17463 * @returns {Object} Returns the new object.
17464 * @example
17465 *
17466 * function Shape() {
17467 * this.x = 0;
17468 * this.y = 0;
17469 * }
17470 *
17471 * function Circle() {
17472 * Shape.call(this);
17473 * }
17474 *
17475 * Circle.prototype = _.create(Shape.prototype, {
17476 * 'constructor': Circle
17477 * });
17478 *
17479 * var circle = new Circle;
17480 * circle instanceof Circle;
17481 * // => true
17482 *
17483 * circle instanceof Shape;
17484 * // => true
17485 */
17486 function create(prototype, properties, guard) {
17487 var result = baseCreate(prototype);
17488 if (guard && isIterateeCall(prototype, properties, guard)) {
17489 properties = undefined;
17490 }
17491 return properties ? baseAssign(result, properties) : result;
17492 }
17493
17494 /**
17495 * Assigns own enumerable properties of source object(s) to the destination
17496 * object for all destination properties that resolve to `undefined`. Once a
17497 * property is set, additional values of the same property are ignored.
17498 *
17499 * **Note:** This method mutates `object`.
17500 *
17501 * @static
17502 * @memberOf _
17503 * @category Object
17504 * @param {Object} object The destination object.
17505 * @param {...Object} [sources] The source objects.
17506 * @returns {Object} Returns `object`.
17507 * @example
17508 *
17509 * _.defaults({ 'user': 'barney' }, { 'age': 36 }, { 'user': 'fred' });
17510 * // => { 'user': 'barney', 'age': 36 }
17511 */
17512 var defaults = createDefaults(assign, assignDefaults);
17513
17514 /**
17515 * This method is like `_.defaults` except that it recursively assigns
17516 * default properties.
17517 *
17518 * **Note:** This method mutates `object`.
17519 *
17520 * @static
17521 * @memberOf _
17522 * @category Object
17523 * @param {Object} object The destination object.
17524 * @param {...Object} [sources] The source objects.
17525 * @returns {Object} Returns `object`.
17526 * @example
17527 *
17528 * _.defaultsDeep({ 'user': { 'name': 'barney' } }, { 'user': { 'name': 'fred', 'age': 36 } });
17529 * // => { 'user': { 'name': 'barney', 'age': 36 } }
17530 *
17531 */
17532 var defaultsDeep = createDefaults(merge, mergeDefaults);
17533
17534 /**
17535 * This method is like `_.find` except that it returns the key of the first
17536 * element `predicate` returns truthy for instead of the element itself.
17537 *
17538 * If a property name is provided for `predicate` the created `_.property`
17539 * style callback returns the property value of the given element.
17540 *
17541 * If a value is also provided for `thisArg` the created `_.matchesProperty`
17542 * style callback returns `true` for elements that have a matching property
17543 * value, else `false`.
17544 *
17545 * If an object is provided for `predicate` the created `_.matches` style
17546 * callback returns `true` for elements that have the properties of the given
17547 * object, else `false`.
17548 *
17549 * @static
17550 * @memberOf _
17551 * @category Object
17552 * @param {Object} object The object to search.
17553 * @param {Function|Object|string} [predicate=_.identity] The function invoked
17554 * per iteration.
17555 * @param {*} [thisArg] The `this` binding of `predicate`.
17556 * @returns {string|undefined} Returns the key of the matched element, else `undefined`.
17557 * @example
17558 *
17559 * var users = {
17560 * 'barney': { 'age': 36, 'active': true },
17561 * 'fred': { 'age': 40, 'active': false },
17562 * 'pebbles': { 'age': 1, 'active': true }
17563 * };
17564 *
17565 * _.findKey(users, function(chr) {
17566 * return chr.age < 40;
17567 * });
17568 * // => 'barney' (iteration order is not guaranteed)
17569 *
17570 * // using the `_.matches` callback shorthand
17571 * _.findKey(users, { 'age': 1, 'active': true });
17572 * // => 'pebbles'
17573 *
17574 * // using the `_.matchesProperty` callback shorthand
17575 * _.findKey(users, 'active', false);
17576 * // => 'fred'
17577 *
17578 * // using the `_.property` callback shorthand
17579 * _.findKey(users, 'active');
17580 * // => 'barney'
17581 */
17582 var findKey = createFindKey(baseForOwn);
17583
17584 /**
17585 * This method is like `_.findKey` except that it iterates over elements of
17586 * a collection in the opposite order.
17587 *
17588 * If a property name is provided for `predicate` the created `_.property`
17589 * style callback returns the property value of the given element.
17590 *
17591 * If a value is also provided for `thisArg` the created `_.matchesProperty`
17592 * style callback returns `true` for elements that have a matching property
17593 * value, else `false`.
17594 *
17595 * If an object is provided for `predicate` the created `_.matches` style
17596 * callback returns `true` for elements that have the properties of the given
17597 * object, else `false`.
17598 *
17599 * @static
17600 * @memberOf _
17601 * @category Object
17602 * @param {Object} object The object to search.
17603 * @param {Function|Object|string} [predicate=_.identity] The function invoked
17604 * per iteration.
17605 * @param {*} [thisArg] The `this` binding of `predicate`.
17606 * @returns {string|undefined} Returns the key of the matched element, else `undefined`.
17607 * @example
17608 *
17609 * var users = {
17610 * 'barney': { 'age': 36, 'active': true },
17611 * 'fred': { 'age': 40, 'active': false },
17612 * 'pebbles': { 'age': 1, 'active': true }
17613 * };
17614 *
17615 * _.findLastKey(users, function(chr) {
17616 * return chr.age < 40;
17617 * });
17618 * // => returns `pebbles` assuming `_.findKey` returns `barney`
17619 *
17620 * // using the `_.matches` callback shorthand
17621 * _.findLastKey(users, { 'age': 36, 'active': true });
17622 * // => 'barney'
17623 *
17624 * // using the `_.matchesProperty` callback shorthand
17625 * _.findLastKey(users, 'active', false);
17626 * // => 'fred'
17627 *
17628 * // using the `_.property` callback shorthand
17629 * _.findLastKey(users, 'active');
17630 * // => 'pebbles'
17631 */
17632 var findLastKey = createFindKey(baseForOwnRight);
17633
17634 /**
17635 * Iterates over own and inherited enumerable properties of an object invoking
17636 * `iteratee` for each property. The `iteratee` is bound to `thisArg` and invoked
17637 * with three arguments: (value, key, object). Iteratee functions may exit
17638 * iteration early by explicitly returning `false`.
17639 *
17640 * @static
17641 * @memberOf _
17642 * @category Object
17643 * @param {Object} object The object to iterate over.
17644 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
17645 * @param {*} [thisArg] The `this` binding of `iteratee`.
17646 * @returns {Object} Returns `object`.
17647 * @example
17648 *
17649 * function Foo() {
17650 * this.a = 1;
17651 * this.b = 2;
17652 * }
17653 *
17654 * Foo.prototype.c = 3;
17655 *
17656 * _.forIn(new Foo, function(value, key) {
17657 * console.log(key);
17658 * });
17659 * // => logs 'a', 'b', and 'c' (iteration order is not guaranteed)
17660 */
17661 var forIn = createForIn(baseFor);
17662
17663 /**
17664 * This method is like `_.forIn` except that it iterates over properties of
17665 * `object` in the opposite order.
17666 *
17667 * @static
17668 * @memberOf _
17669 * @category Object
17670 * @param {Object} object The object to iterate over.
17671 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
17672 * @param {*} [thisArg] The `this` binding of `iteratee`.
17673 * @returns {Object} Returns `object`.
17674 * @example
17675 *
17676 * function Foo() {
17677 * this.a = 1;
17678 * this.b = 2;
17679 * }
17680 *
17681 * Foo.prototype.c = 3;
17682 *
17683 * _.forInRight(new Foo, function(value, key) {
17684 * console.log(key);
17685 * });
17686 * // => logs 'c', 'b', and 'a' assuming `_.forIn ` logs 'a', 'b', and 'c'
17687 */
17688 var forInRight = createForIn(baseForRight);
17689
17690 /**
17691 * Iterates over own enumerable properties of an object invoking `iteratee`
17692 * for each property. The `iteratee` is bound to `thisArg` and invoked with
17693 * three arguments: (value, key, object). Iteratee functions may exit iteration
17694 * early by explicitly returning `false`.
17695 *
17696 * @static
17697 * @memberOf _
17698 * @category Object
17699 * @param {Object} object The object to iterate over.
17700 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
17701 * @param {*} [thisArg] The `this` binding of `iteratee`.
17702 * @returns {Object} Returns `object`.
17703 * @example
17704 *
17705 * function Foo() {
17706 * this.a = 1;
17707 * this.b = 2;
17708 * }
17709 *
17710 * Foo.prototype.c = 3;
17711 *
17712 * _.forOwn(new Foo, function(value, key) {
17713 * console.log(key);
17714 * });
17715 * // => logs 'a' and 'b' (iteration order is not guaranteed)
17716 */
17717 var forOwn = createForOwn(baseForOwn);
17718
17719 /**
17720 * This method is like `_.forOwn` except that it iterates over properties of
17721 * `object` in the opposite order.
17722 *
17723 * @static
17724 * @memberOf _
17725 * @category Object
17726 * @param {Object} object The object to iterate over.
17727 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
17728 * @param {*} [thisArg] The `this` binding of `iteratee`.
17729 * @returns {Object} Returns `object`.
17730 * @example
17731 *
17732 * function Foo() {
17733 * this.a = 1;
17734 * this.b = 2;
17735 * }
17736 *
17737 * Foo.prototype.c = 3;
17738 *
17739 * _.forOwnRight(new Foo, function(value, key) {
17740 * console.log(key);
17741 * });
17742 * // => logs 'b' and 'a' assuming `_.forOwn` logs 'a' and 'b'
17743 */
17744 var forOwnRight = createForOwn(baseForOwnRight);
17745
17746 /**
17747 * Creates an array of function property names from all enumerable properties,
17748 * own and inherited, of `object`.
17749 *
17750 * @static
17751 * @memberOf _
17752 * @alias methods
17753 * @category Object
17754 * @param {Object} object The object to inspect.
17755 * @returns {Array} Returns the new array of property names.
17756 * @example
17757 *
17758 * _.functions(_);
17759 * // => ['after', 'ary', 'assign', ...]
17760 */
17761 function functions(object) {
17762 return baseFunctions(object, keysIn(object));
17763 }
17764
17765 /**
17766 * Gets the property value at `path` of `object`. If the resolved value is
17767 * `undefined` the `defaultValue` is used in its place.
17768 *
17769 * @static
17770 * @memberOf _
17771 * @category Object
17772 * @param {Object} object The object to query.
17773 * @param {Array|string} path The path of the property to get.
17774 * @param {*} [defaultValue] The value returned if the resolved value is `undefined`.
17775 * @returns {*} Returns the resolved value.
17776 * @example
17777 *
17778 * var object = { 'a': [{ 'b': { 'c': 3 } }] };
17779 *
17780 * _.get(object, 'a[0].b.c');
17781 * // => 3
17782 *
17783 * _.get(object, ['a', '0', 'b', 'c']);
17784 * // => 3
17785 *
17786 * _.get(object, 'a.b.c', 'default');
17787 * // => 'default'
17788 */
17789 function get(object, path, defaultValue) {
17790 var result = object == null ? undefined : baseGet(object, toPath(path), path + '');
17791 return result === undefined ? defaultValue : result;
17792 }
17793
17794 /**
17795 * Checks if `path` is a direct property.
17796 *
17797 * @static
17798 * @memberOf _
17799 * @category Object
17800 * @param {Object} object The object to query.
17801 * @param {Array|string} path The path to check.
17802 * @returns {boolean} Returns `true` if `path` is a direct property, else `false`.
17803 * @example
17804 *
17805 * var object = { 'a': { 'b': { 'c': 3 } } };
17806 *
17807 * _.has(object, 'a');
17808 * // => true
17809 *
17810 * _.has(object, 'a.b.c');
17811 * // => true
17812 *
17813 * _.has(object, ['a', 'b', 'c']);
17814 * // => true
17815 */
17816 function has(object, path) {
17817 if (object == null) {
17818 return false;
17819 }
17820 var result = hasOwnProperty.call(object, path);
17821 if (!result && !isKey(path)) {
17822 path = toPath(path);
17823 object = path.length == 1 ? object : baseGet(object, baseSlice(path, 0, -1));
17824 if (object == null) {
17825 return false;
17826 }
17827 path = last(path);
17828 result = hasOwnProperty.call(object, path);
17829 }
17830 return result || (isLength(object.length) && isIndex(path, object.length) &&
17831 (isArray(object) || isArguments(object)));
17832 }
17833
17834 /**
17835 * Creates an object composed of the inverted keys and values of `object`.
17836 * If `object` contains duplicate values, subsequent values overwrite property
17837 * assignments of previous values unless `multiValue` is `true`.
17838 *
17839 * @static
17840 * @memberOf _
17841 * @category Object
17842 * @param {Object} object The object to invert.
17843 * @param {boolean} [multiValue] Allow multiple values per key.
17844 * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
17845 * @returns {Object} Returns the new inverted object.
17846 * @example
17847 *
17848 * var object = { 'a': 1, 'b': 2, 'c': 1 };
17849 *
17850 * _.invert(object);
17851 * // => { '1': 'c', '2': 'b' }
17852 *
17853 * // with `multiValue`
17854 * _.invert(object, true);
17855 * // => { '1': ['a', 'c'], '2': ['b'] }
17856 */
17857 function invert(object, multiValue, guard) {
17858 if (guard && isIterateeCall(object, multiValue, guard)) {
17859 multiValue = undefined;
17860 }
17861 var index = -1,
17862 props = keys(object),
17863 length = props.length,
17864 result = {};
17865
17866 while (++index < length) {
17867 var key = props[index],
17868 value = object[key];
17869
17870 if (multiValue) {
17871 if (hasOwnProperty.call(result, value)) {
17872 result[value].push(key);
17873 } else {
17874 result[value] = [key];
17875 }
17876 }
17877 else {
17878 result[value] = key;
17879 }
17880 }
17881 return result;
17882 }
17883
17884 /**
17885 * Creates an array of the own enumerable property names of `object`.
17886 *
17887 * **Note:** Non-object values are coerced to objects. See the
17888 * [ES spec](http://ecma-international.org/ecma-262/6.0/#sec-object.keys)
17889 * for more details.
17890 *
17891 * @static
17892 * @memberOf _
17893 * @category Object
17894 * @param {Object} object The object to query.
17895 * @returns {Array} Returns the array of property names.
17896 * @example
17897 *
17898 * function Foo() {
17899 * this.a = 1;
17900 * this.b = 2;
17901 * }
17902 *
17903 * Foo.prototype.c = 3;
17904 *
17905 * _.keys(new Foo);
17906 * // => ['a', 'b'] (iteration order is not guaranteed)
17907 *
17908 * _.keys('hi');
17909 * // => ['0', '1']
17910 */
17911 var keys = !nativeKeys ? shimKeys : function(object) {
17912 var Ctor = object == null ? undefined : object.constructor;
17913 if ((typeof Ctor == 'function' && Ctor.prototype === object) ||
17914 (typeof object != 'function' && isArrayLike(object))) {
17915 return shimKeys(object);
17916 }
17917 return isObject(object) ? nativeKeys(object) : [];
17918 };
17919
17920 /**
17921 * Creates an array of the own and inherited enumerable property names of `object`.
17922 *
17923 * **Note:** Non-object values are coerced to objects.
17924 *
17925 * @static
17926 * @memberOf _
17927 * @category Object
17928 * @param {Object} object The object to query.
17929 * @returns {Array} Returns the array of property names.
17930 * @example
17931 *
17932 * function Foo() {
17933 * this.a = 1;
17934 * this.b = 2;
17935 * }
17936 *
17937 * Foo.prototype.c = 3;
17938 *
17939 * _.keysIn(new Foo);
17940 * // => ['a', 'b', 'c'] (iteration order is not guaranteed)
17941 */
17942 function keysIn(object) {
17943 if (object == null) {
17944 return [];
17945 }
17946 if (!isObject(object)) {
17947 object = Object(object);
17948 }
17949 var length = object.length;
17950 length = (length && isLength(length) &&
17951 (isArray(object) || isArguments(object)) && length) || 0;
17952
17953 var Ctor = object.constructor,
17954 index = -1,
17955 isProto = typeof Ctor == 'function' && Ctor.prototype === object,
17956 result = Array(length),
17957 skipIndexes = length > 0;
17958
17959 while (++index < length) {
17960 result[index] = (index + '');
17961 }
17962 for (var key in object) {
17963 if (!(skipIndexes && isIndex(key, length)) &&
17964 !(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) {
17965 result.push(key);
17966 }
17967 }
17968 return result;
17969 }
17970
17971 /**
17972 * The opposite of `_.mapValues`; this method creates an object with the
17973 * same values as `object` and keys generated by running each own enumerable
17974 * property of `object` through `iteratee`.
17975 *
17976 * @static
17977 * @memberOf _
17978 * @category Object
17979 * @param {Object} object The object to iterate over.
17980 * @param {Function|Object|string} [iteratee=_.identity] The function invoked
17981 * per iteration.
17982 * @param {*} [thisArg] The `this` binding of `iteratee`.
17983 * @returns {Object} Returns the new mapped object.
17984 * @example
17985 *
17986 * _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) {
17987 * return key + value;
17988 * });
17989 * // => { 'a1': 1, 'b2': 2 }
17990 */
17991 var mapKeys = createObjectMapper(true);
17992
17993 /**
17994 * Creates an object with the same keys as `object` and values generated by
17995 * running each own enumerable property of `object` through `iteratee`. The
17996 * iteratee function is bound to `thisArg` and invoked with three arguments:
17997 * (value, key, object).
17998 *
17999 * If a property name is provided for `iteratee` the created `_.property`
18000 * style callback returns the property value of the given element.
18001 *
18002 * If a value is also provided for `thisArg` the created `_.matchesProperty`
18003 * style callback returns `true` for elements that have a matching property
18004 * value, else `false`.
18005 *
18006 * If an object is provided for `iteratee` the created `_.matches` style
18007 * callback returns `true` for elements that have the properties of the given
18008 * object, else `false`.
18009 *
18010 * @static
18011 * @memberOf _
18012 * @category Object
18013 * @param {Object} object The object to iterate over.
18014 * @param {Function|Object|string} [iteratee=_.identity] The function invoked
18015 * per iteration.
18016 * @param {*} [thisArg] The `this` binding of `iteratee`.
18017 * @returns {Object} Returns the new mapped object.
18018 * @example
18019 *
18020 * _.mapValues({ 'a': 1, 'b': 2 }, function(n) {
18021 * return n * 3;
18022 * });
18023 * // => { 'a': 3, 'b': 6 }
18024 *
18025 * var users = {
18026 * 'fred': { 'user': 'fred', 'age': 40 },
18027 * 'pebbles': { 'user': 'pebbles', 'age': 1 }
18028 * };
18029 *
18030 * // using the `_.property` callback shorthand
18031 * _.mapValues(users, 'age');
18032 * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)
18033 */
18034 var mapValues = createObjectMapper();
18035
18036 /**
18037 * The opposite of `_.pick`; this method creates an object composed of the
18038 * own and inherited enumerable properties of `object` that are not omitted.
18039 *
18040 * @static
18041 * @memberOf _
18042 * @category Object
18043 * @param {Object} object The source object.
18044 * @param {Function|...(string|string[])} [predicate] The function invoked per
18045 * iteration or property names to omit, specified as individual property
18046 * names or arrays of property names.
18047 * @param {*} [thisArg] The `this` binding of `predicate`.
18048 * @returns {Object} Returns the new object.
18049 * @example
18050 *
18051 * var object = { 'user': 'fred', 'age': 40 };
18052 *
18053 * _.omit(object, 'age');
18054 * // => { 'user': 'fred' }
18055 *
18056 * _.omit(object, _.isNumber);
18057 * // => { 'user': 'fred' }
18058 */
18059 var omit = restParam(function(object, props) {
18060 if (object == null) {
18061 return {};
18062 }
18063 if (typeof props[0] != 'function') {
18064 var props = arrayMap(baseFlatten(props), String);
18065 return pickByArray(object, baseDifference(keysIn(object), props));
18066 }
18067 var predicate = bindCallback(props[0], props[1], 3);
18068 return pickByCallback(object, function(value, key, object) {
18069 return !predicate(value, key, object);
18070 });
18071 });
18072
18073 /**
18074 * Creates a two dimensional array of the key-value pairs for `object`,
18075 * e.g. `[[key1, value1], [key2, value2]]`.
18076 *
18077 * @static
18078 * @memberOf _
18079 * @category Object
18080 * @param {Object} object The object to query.
18081 * @returns {Array} Returns the new array of key-value pairs.
18082 * @example
18083 *
18084 * _.pairs({ 'barney': 36, 'fred': 40 });
18085 * // => [['barney', 36], ['fred', 40]] (iteration order is not guaranteed)
18086 */
18087 function pairs(object) {
18088 object = toObject(object);
18089
18090 var index = -1,
18091 props = keys(object),
18092 length = props.length,
18093 result = Array(length);
18094
18095 while (++index < length) {
18096 var key = props[index];
18097 result[index] = [key, object[key]];
18098 }
18099 return result;
18100 }
18101
18102 /**
18103 * Creates an object composed of the picked `object` properties. Property
18104 * names may be specified as individual arguments or as arrays of property
18105 * names. If `predicate` is provided it is invoked for each property of `object`
18106 * picking the properties `predicate` returns truthy for. The predicate is
18107 * bound to `thisArg` and invoked with three arguments: (value, key, object).
18108 *
18109 * @static
18110 * @memberOf _
18111 * @category Object
18112 * @param {Object} object The source object.
18113 * @param {Function|...(string|string[])} [predicate] The function invoked per
18114 * iteration or property names to pick, specified as individual property
18115 * names or arrays of property names.
18116 * @param {*} [thisArg] The `this` binding of `predicate`.
18117 * @returns {Object} Returns the new object.
18118 * @example
18119 *
18120 * var object = { 'user': 'fred', 'age': 40 };
18121 *
18122 * _.pick(object, 'user');
18123 * // => { 'user': 'fred' }
18124 *
18125 * _.pick(object, _.isString);
18126 * // => { 'user': 'fred' }
18127 */
18128 var pick = restParam(function(object, props) {
18129 if (object == null) {
18130 return {};
18131 }
18132 return typeof props[0] == 'function'
18133 ? pickByCallback(object, bindCallback(props[0], props[1], 3))
18134 : pickByArray(object, baseFlatten(props));
18135 });
18136
18137 /**
18138 * This method is like `_.get` except that if the resolved value is a function
18139 * it is invoked with the `this` binding of its parent object and its result
18140 * is returned.
18141 *
18142 * @static
18143 * @memberOf _
18144 * @category Object
18145 * @param {Object} object The object to query.
18146 * @param {Array|string} path The path of the property to resolve.
18147 * @param {*} [defaultValue] The value returned if the resolved value is `undefined`.
18148 * @returns {*} Returns the resolved value.
18149 * @example
18150 *
18151 * var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] };
18152 *
18153 * _.result(object, 'a[0].b.c1');
18154 * // => 3
18155 *
18156 * _.result(object, 'a[0].b.c2');
18157 * // => 4
18158 *
18159 * _.result(object, 'a.b.c', 'default');
18160 * // => 'default'
18161 *
18162 * _.result(object, 'a.b.c', _.constant('default'));
18163 * // => 'default'
18164 */
18165 function result(object, path, defaultValue) {
18166 var result = object == null ? undefined : object[path];
18167 if (result === undefined) {
18168 if (object != null && !isKey(path, object)) {
18169 path = toPath(path);
18170 object = path.length == 1 ? object : baseGet(object, baseSlice(path, 0, -1));
18171 result = object == null ? undefined : object[last(path)];
18172 }
18173 result = result === undefined ? defaultValue : result;
18174 }
18175 return isFunction(result) ? result.call(object) : result;
18176 }
18177
18178 /**
18179 * Sets the property value of `path` on `object`. If a portion of `path`
18180 * does not exist it is created.
18181 *
18182 * @static
18183 * @memberOf _
18184 * @category Object
18185 * @param {Object} object The object to augment.
18186 * @param {Array|string} path The path of the property to set.
18187 * @param {*} value The value to set.
18188 * @returns {Object} Returns `object`.
18189 * @example
18190 *
18191 * var object = { 'a': [{ 'b': { 'c': 3 } }] };
18192 *
18193 * _.set(object, 'a[0].b.c', 4);
18194 * console.log(object.a[0].b.c);
18195 * // => 4
18196 *
18197 * _.set(object, 'x[0].y.z', 5);
18198 * console.log(object.x[0].y.z);
18199 * // => 5
18200 */
18201 function set(object, path, value) {
18202 if (object == null) {
18203 return object;
18204 }
18205 var pathKey = (path + '');
18206 path = (object[pathKey] != null || isKey(path, object)) ? [pathKey] : toPath(path);
18207
18208 var index = -1,
18209 length = path.length,
18210 lastIndex = length - 1,
18211 nested = object;
18212
18213 while (nested != null && ++index < length) {
18214 var key = path[index];
18215 if (isObject(nested)) {
18216 if (index == lastIndex) {
18217 nested[key] = value;
18218 } else if (nested[key] == null) {
18219 nested[key] = isIndex(path[index + 1]) ? [] : {};
18220 }
18221 }
18222 nested = nested[key];
18223 }
18224 return object;
18225 }
18226
18227 /**
18228 * An alternative to `_.reduce`; this method transforms `object` to a new
18229 * `accumulator` object which is the result of running each of its own enumerable
18230 * properties through `iteratee`, with each invocation potentially mutating
18231 * the `accumulator` object. The `iteratee` is bound to `thisArg` and invoked
18232 * with four arguments: (accumulator, value, key, object). Iteratee functions
18233 * may exit iteration early by explicitly returning `false`.
18234 *
18235 * @static
18236 * @memberOf _
18237 * @category Object
18238 * @param {Array|Object} object The object to iterate over.
18239 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
18240 * @param {*} [accumulator] The custom accumulator value.
18241 * @param {*} [thisArg] The `this` binding of `iteratee`.
18242 * @returns {*} Returns the accumulated value.
18243 * @example
18244 *
18245 * _.transform([2, 3, 4], function(result, n) {
18246 * result.push(n *= n);
18247 * return n % 2 == 0;
18248 * });
18249 * // => [4, 9]
18250 *
18251 * _.transform({ 'a': 1, 'b': 2 }, function(result, n, key) {
18252 * result[key] = n * 3;
18253 * });
18254 * // => { 'a': 3, 'b': 6 }
18255 */
18256 function transform(object, iteratee, accumulator, thisArg) {
18257 var isArr = isArray(object) || isTypedArray(object);
18258 iteratee = getCallback(iteratee, thisArg, 4);
18259
18260 if (accumulator == null) {
18261 if (isArr || isObject(object)) {
18262 var Ctor = object.constructor;
18263 if (isArr) {
18264 accumulator = isArray(object) ? new Ctor : [];
18265 } else {
18266 accumulator = baseCreate(isFunction(Ctor) ? Ctor.prototype : undefined);
18267 }
18268 } else {
18269 accumulator = {};
18270 }
18271 }
18272 (isArr ? arrayEach : baseForOwn)(object, function(value, index, object) {
18273 return iteratee(accumulator, value, index, object);
18274 });
18275 return accumulator;
18276 }
18277
18278 /**
18279 * Creates an array of the own enumerable property values of `object`.
18280 *
18281 * **Note:** Non-object values are coerced to objects.
18282 *
18283 * @static
18284 * @memberOf _
18285 * @category Object
18286 * @param {Object} object The object to query.
18287 * @returns {Array} Returns the array of property values.
18288 * @example
18289 *
18290 * function Foo() {
18291 * this.a = 1;
18292 * this.b = 2;
18293 * }
18294 *
18295 * Foo.prototype.c = 3;
18296 *
18297 * _.values(new Foo);
18298 * // => [1, 2] (iteration order is not guaranteed)
18299 *
18300 * _.values('hi');
18301 * // => ['h', 'i']
18302 */
18303 function values(object) {
18304 return baseValues(object, keys(object));
18305 }
18306
18307 /**
18308 * Creates an array of the own and inherited enumerable property values
18309 * of `object`.
18310 *
18311 * **Note:** Non-object values are coerced to objects.
18312 *
18313 * @static
18314 * @memberOf _
18315 * @category Object
18316 * @param {Object} object The object to query.
18317 * @returns {Array} Returns the array of property values.
18318 * @example
18319 *
18320 * function Foo() {
18321 * this.a = 1;
18322 * this.b = 2;
18323 * }
18324 *
18325 * Foo.prototype.c = 3;
18326 *
18327 * _.valuesIn(new Foo);
18328 * // => [1, 2, 3] (iteration order is not guaranteed)
18329 */
18330 function valuesIn(object) {
18331 return baseValues(object, keysIn(object));
18332 }
18333
18334 /*------------------------------------------------------------------------*/
18335
18336 /**
18337 * Checks if `n` is between `start` and up to but not including, `end`. If
18338 * `end` is not specified it is set to `start` with `start` then set to `0`.
18339 *
18340 * @static
18341 * @memberOf _
18342 * @category Number
18343 * @param {number} n The number to check.
18344 * @param {number} [start=0] The start of the range.
18345 * @param {number} end The end of the range.
18346 * @returns {boolean} Returns `true` if `n` is in the range, else `false`.
18347 * @example
18348 *
18349 * _.inRange(3, 2, 4);
18350 * // => true
18351 *
18352 * _.inRange(4, 8);
18353 * // => true
18354 *
18355 * _.inRange(4, 2);
18356 * // => false
18357 *
18358 * _.inRange(2, 2);
18359 * // => false
18360 *
18361 * _.inRange(1.2, 2);
18362 * // => true
18363 *
18364 * _.inRange(5.2, 4);
18365 * // => false
18366 */
18367 function inRange(value, start, end) {
18368 start = +start || 0;
18369 if (end === undefined) {
18370 end = start;
18371 start = 0;
18372 } else {
18373 end = +end || 0;
18374 }
18375 return value >= nativeMin(start, end) && value < nativeMax(start, end);
18376 }
18377
18378 /**
18379 * Produces a random number between `min` and `max` (inclusive). If only one
18380 * argument is provided a number between `0` and the given number is returned.
18381 * If `floating` is `true`, or either `min` or `max` are floats, a floating-point
18382 * number is returned instead of an integer.
18383 *
18384 * @static
18385 * @memberOf _
18386 * @category Number
18387 * @param {number} [min=0] The minimum possible value.
18388 * @param {number} [max=1] The maximum possible value.
18389 * @param {boolean} [floating] Specify returning a floating-point number.
18390 * @returns {number} Returns the random number.
18391 * @example
18392 *
18393 * _.random(0, 5);
18394 * // => an integer between 0 and 5
18395 *
18396 * _.random(5);
18397 * // => also an integer between 0 and 5
18398 *
18399 * _.random(5, true);
18400 * // => a floating-point number between 0 and 5
18401 *
18402 * _.random(1.2, 5.2);
18403 * // => a floating-point number between 1.2 and 5.2
18404 */
18405 function random(min, max, floating) {
18406 if (floating && isIterateeCall(min, max, floating)) {
18407 max = floating = undefined;
18408 }
18409 var noMin = min == null,
18410 noMax = max == null;
18411
18412 if (floating == null) {
18413 if (noMax && typeof min == 'boolean') {
18414 floating = min;
18415 min = 1;
18416 }
18417 else if (typeof max == 'boolean') {
18418 floating = max;
18419 noMax = true;
18420 }
18421 }
18422 if (noMin && noMax) {
18423 max = 1;
18424 noMax = false;
18425 }
18426 min = +min || 0;
18427 if (noMax) {
18428 max = min;
18429 min = 0;
18430 } else {
18431 max = +max || 0;
18432 }
18433 if (floating || min % 1 || max % 1) {
18434 var rand = nativeRandom();
18435 return nativeMin(min + (rand * (max - min + parseFloat('1e-' + ((rand + '').length - 1)))), max);
18436 }
18437 return baseRandom(min, max);
18438 }
18439
18440 /*------------------------------------------------------------------------*/
18441
18442 /**
18443 * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase).
18444 *
18445 * @static
18446 * @memberOf _
18447 * @category String
18448 * @param {string} [string=''] The string to convert.
18449 * @returns {string} Returns the camel cased string.
18450 * @example
18451 *
18452 * _.camelCase('Foo Bar');
18453 * // => 'fooBar'
18454 *
18455 * _.camelCase('--foo-bar');
18456 * // => 'fooBar'
18457 *
18458 * _.camelCase('__foo_bar__');
18459 * // => 'fooBar'
18460 */
18461 var camelCase = createCompounder(function(result, word, index) {
18462 word = word.toLowerCase();
18463 return result + (index ? (word.charAt(0).toUpperCase() + word.slice(1)) : word);
18464 });
18465
18466 /**
18467 * Capitalizes the first character of `string`.
18468 *
18469 * @static
18470 * @memberOf _
18471 * @category String
18472 * @param {string} [string=''] The string to capitalize.
18473 * @returns {string} Returns the capitalized string.
18474 * @example
18475 *
18476 * _.capitalize('fred');
18477 * // => 'Fred'
18478 */
18479 function capitalize(string) {
18480 string = baseToString(string);
18481 return string && (string.charAt(0).toUpperCase() + string.slice(1));
18482 }
18483
18484 /**
18485 * Deburrs `string` by converting [latin-1 supplementary letters](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table)
18486 * to basic latin letters and removing [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks).
18487 *
18488 * @static
18489 * @memberOf _
18490 * @category String
18491 * @param {string} [string=''] The string to deburr.
18492 * @returns {string} Returns the deburred string.
18493 * @example
18494 *
18495 * _.deburr('déjà vu');
18496 * // => 'deja vu'
18497 */
18498 function deburr(string) {
18499 string = baseToString(string);
18500 return string && string.replace(reLatin1, deburrLetter).replace(reComboMark, '');
18501 }
18502
18503 /**
18504 * Checks if `string` ends with the given target string.
18505 *
18506 * @static
18507 * @memberOf _
18508 * @category String
18509 * @param {string} [string=''] The string to search.
18510 * @param {string} [target] The string to search for.
18511 * @param {number} [position=string.length] The position to search from.
18512 * @returns {boolean} Returns `true` if `string` ends with `target`, else `false`.
18513 * @example
18514 *
18515 * _.endsWith('abc', 'c');
18516 * // => true
18517 *
18518 * _.endsWith('abc', 'b');
18519 * // => false
18520 *
18521 * _.endsWith('abc', 'b', 2);
18522 * // => true
18523 */
18524 function endsWith(string, target, position) {
18525 string = baseToString(string);
18526 target = (target + '');
18527
18528 var length = string.length;
18529 position = position === undefined
18530 ? length
18531 : nativeMin(position < 0 ? 0 : (+position || 0), length);
18532
18533 position -= target.length;
18534 return position >= 0 && string.indexOf(target, position) == position;
18535 }
18536
18537 /**
18538 * Converts the characters "&", "<", ">", '"', "'", and "\`", in `string` to
18539 * their corresponding HTML entities.
18540 *
18541 * **Note:** No other characters are escaped. To escape additional characters
18542 * use a third-party library like [_he_](https://mths.be/he).
18543 *
18544 * Though the ">" character is escaped for symmetry, characters like
18545 * ">" and "/" don't need escaping in HTML and have no special meaning
18546 * unless they're part of a tag or unquoted attribute value.
18547 * See [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands)
18548 * (under "semi-related fun fact") for more details.
18549 *
18550 * Backticks are escaped because in Internet Explorer < 9, they can break out
18551 * of attribute values or HTML comments. See [#59](https://html5sec.org/#59),
18552 * [#102](https://html5sec.org/#102), [#108](https://html5sec.org/#108), and
18553 * [#133](https://html5sec.org/#133) of the [HTML5 Security Cheatsheet](https://html5sec.org/)
18554 * for more details.
18555 *
18556 * When working with HTML you should always [quote attribute values](http://wonko.com/post/html-escaping)
18557 * to reduce XSS vectors.
18558 *
18559 * @static
18560 * @memberOf _
18561 * @category String
18562 * @param {string} [string=''] The string to escape.
18563 * @returns {string} Returns the escaped string.
18564 * @example
18565 *
18566 * _.escape('fred, barney, & pebbles');
18567 * // => 'fred, barney, &amp; pebbles'
18568 */
18569 function escape(string) {
18570 // Reset `lastIndex` because in IE < 9 `String#replace` does not.
18571 string = baseToString(string);
18572 return (string && reHasUnescapedHtml.test(string))
18573 ? string.replace(reUnescapedHtml, escapeHtmlChar)
18574 : string;
18575 }
18576
18577 /**
18578 * Escapes the `RegExp` special characters "\", "/", "^", "$", ".", "|", "?",
18579 * "*", "+", "(", ")", "[", "]", "{" and "}" in `string`.
18580 *
18581 * @static
18582 * @memberOf _
18583 * @category String
18584 * @param {string} [string=''] The string to escape.
18585 * @returns {string} Returns the escaped string.
18586 * @example
18587 *
18588 * _.escapeRegExp('[lodash](https://lodash.com/)');
18589 * // => '\[lodash\]\(https:\/\/lodash\.com\/\)'
18590 */
18591 function escapeRegExp(string) {
18592 string = baseToString(string);
18593 return (string && reHasRegExpChars.test(string))
18594 ? string.replace(reRegExpChars, escapeRegExpChar)
18595 : (string || '(?:)');
18596 }
18597
18598 /**
18599 * Converts `string` to [kebab case](https://en.wikipedia.org/wiki/Letter_case#Special_case_styles).
18600 *
18601 * @static
18602 * @memberOf _
18603 * @category String
18604 * @param {string} [string=''] The string to convert.
18605 * @returns {string} Returns the kebab cased string.
18606 * @example
18607 *
18608 * _.kebabCase('Foo Bar');
18609 * // => 'foo-bar'
18610 *
18611 * _.kebabCase('fooBar');
18612 * // => 'foo-bar'
18613 *
18614 * _.kebabCase('__foo_bar__');
18615 * // => 'foo-bar'
18616 */
18617 var kebabCase = createCompounder(function(result, word, index) {
18618 return result + (index ? '-' : '') + word.toLowerCase();
18619 });
18620
18621 /**
18622 * Pads `string` on the left and right sides if it's shorter than `length`.
18623 * Padding characters are truncated if they can't be evenly divided by `length`.
18624 *
18625 * @static
18626 * @memberOf _
18627 * @category String
18628 * @param {string} [string=''] The string to pad.
18629 * @param {number} [length=0] The padding length.
18630 * @param {string} [chars=' '] The string used as padding.
18631 * @returns {string} Returns the padded string.
18632 * @example
18633 *
18634 * _.pad('abc', 8);
18635 * // => ' abc '
18636 *
18637 * _.pad('abc', 8, '_-');
18638 * // => '_-abc_-_'
18639 *
18640 * _.pad('abc', 3);
18641 * // => 'abc'
18642 */
18643 function pad(string, length, chars) {
18644 string = baseToString(string);
18645 length = +length;
18646
18647 var strLength = string.length;
18648 if (strLength >= length || !nativeIsFinite(length)) {
18649 return string;
18650 }
18651 var mid = (length - strLength) / 2,
18652 leftLength = nativeFloor(mid),
18653 rightLength = nativeCeil(mid);
18654
18655 chars = createPadding('', rightLength, chars);
18656 return chars.slice(0, leftLength) + string + chars;
18657 }
18658
18659 /**
18660 * Pads `string` on the left side if it's shorter than `length`. Padding
18661 * characters are truncated if they exceed `length`.
18662 *
18663 * @static
18664 * @memberOf _
18665 * @category String
18666 * @param {string} [string=''] The string to pad.
18667 * @param {number} [length=0] The padding length.
18668 * @param {string} [chars=' '] The string used as padding.
18669 * @returns {string} Returns the padded string.
18670 * @example
18671 *
18672 * _.padLeft('abc', 6);
18673 * // => ' abc'
18674 *
18675 * _.padLeft('abc', 6, '_-');
18676 * // => '_-_abc'
18677 *
18678 * _.padLeft('abc', 3);
18679 * // => 'abc'
18680 */
18681 var padLeft = createPadDir();
18682
18683 /**
18684 * Pads `string` on the right side if it's shorter than `length`. Padding
18685 * characters are truncated if they exceed `length`.
18686 *
18687 * @static
18688 * @memberOf _
18689 * @category String
18690 * @param {string} [string=''] The string to pad.
18691 * @param {number} [length=0] The padding length.
18692 * @param {string} [chars=' '] The string used as padding.
18693 * @returns {string} Returns the padded string.
18694 * @example
18695 *
18696 * _.padRight('abc', 6);
18697 * // => 'abc '
18698 *
18699 * _.padRight('abc', 6, '_-');
18700 * // => 'abc_-_'
18701 *
18702 * _.padRight('abc', 3);
18703 * // => 'abc'
18704 */
18705 var padRight = createPadDir(true);
18706
18707 /**
18708 * Converts `string` to an integer of the specified radix. If `radix` is
18709 * `undefined` or `0`, a `radix` of `10` is used unless `value` is a hexadecimal,
18710 * in which case a `radix` of `16` is used.
18711 *
18712 * **Note:** This method aligns with the [ES5 implementation](https://es5.github.io/#E)
18713 * of `parseInt`.
18714 *
18715 * @static
18716 * @memberOf _
18717 * @category String
18718 * @param {string} string The string to convert.
18719 * @param {number} [radix] The radix to interpret `value` by.
18720 * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
18721 * @returns {number} Returns the converted integer.
18722 * @example
18723 *
18724 * _.parseInt('08');
18725 * // => 8
18726 *
18727 * _.map(['6', '08', '10'], _.parseInt);
18728 * // => [6, 8, 10]
18729 */
18730 function parseInt(string, radix, guard) {
18731 // Firefox < 21 and Opera < 15 follow ES3 for `parseInt`.
18732 // Chrome fails to trim leading <BOM> whitespace characters.
18733 // See https://code.google.com/p/v8/issues/detail?id=3109 for more details.
18734 if (guard ? isIterateeCall(string, radix, guard) : radix == null) {
18735 radix = 0;
18736 } else if (radix) {
18737 radix = +radix;
18738 }
18739 string = trim(string);
18740 return nativeParseInt(string, radix || (reHasHexPrefix.test(string) ? 16 : 10));
18741 }
18742
18743 /**
18744 * Repeats the given string `n` times.
18745 *
18746 * @static
18747 * @memberOf _
18748 * @category String
18749 * @param {string} [string=''] The string to repeat.
18750 * @param {number} [n=0] The number of times to repeat the string.
18751 * @returns {string} Returns the repeated string.
18752 * @example
18753 *
18754 * _.repeat('*', 3);
18755 * // => '***'
18756 *
18757 * _.repeat('abc', 2);
18758 * // => 'abcabc'
18759 *
18760 * _.repeat('abc', 0);
18761 * // => ''
18762 */
18763 function repeat(string, n) {
18764 var result = '';
18765 string = baseToString(string);
18766 n = +n;
18767 if (n < 1 || !string || !nativeIsFinite(n)) {
18768 return result;
18769 }
18770 // Leverage the exponentiation by squaring algorithm for a faster repeat.
18771 // See https://en.wikipedia.org/wiki/Exponentiation_by_squaring for more details.
18772 do {
18773 if (n % 2) {
18774 result += string;
18775 }
18776 n = nativeFloor(n / 2);
18777 string += string;
18778 } while (n);
18779
18780 return result;
18781 }
18782
18783 /**
18784 * Converts `string` to [snake case](https://en.wikipedia.org/wiki/Snake_case).
18785 *
18786 * @static
18787 * @memberOf _
18788 * @category String
18789 * @param {string} [string=''] The string to convert.
18790 * @returns {string} Returns the snake cased string.
18791 * @example
18792 *
18793 * _.snakeCase('Foo Bar');
18794 * // => 'foo_bar'
18795 *
18796 * _.snakeCase('fooBar');
18797 * // => 'foo_bar'
18798 *
18799 * _.snakeCase('--foo-bar');
18800 * // => 'foo_bar'
18801 */
18802 var snakeCase = createCompounder(function(result, word, index) {
18803 return result + (index ? '_' : '') + word.toLowerCase();
18804 });
18805
18806 /**
18807 * Converts `string` to [start case](https://en.wikipedia.org/wiki/Letter_case#Stylistic_or_specialised_usage).
18808 *
18809 * @static
18810 * @memberOf _
18811 * @category String
18812 * @param {string} [string=''] The string to convert.
18813 * @returns {string} Returns the start cased string.
18814 * @example
18815 *
18816 * _.startCase('--foo-bar');
18817 * // => 'Foo Bar'
18818 *
18819 * _.startCase('fooBar');
18820 * // => 'Foo Bar'
18821 *
18822 * _.startCase('__foo_bar__');
18823 * // => 'Foo Bar'
18824 */
18825 var startCase = createCompounder(function(result, word, index) {
18826 return result + (index ? ' ' : '') + (word.charAt(0).toUpperCase() + word.slice(1));
18827 });
18828
18829 /**
18830 * Checks if `string` starts with the given target string.
18831 *
18832 * @static
18833 * @memberOf _
18834 * @category String
18835 * @param {string} [string=''] The string to search.
18836 * @param {string} [target] The string to search for.
18837 * @param {number} [position=0] The position to search from.
18838 * @returns {boolean} Returns `true` if `string` starts with `target`, else `false`.
18839 * @example
18840 *
18841 * _.startsWith('abc', 'a');
18842 * // => true
18843 *
18844 * _.startsWith('abc', 'b');
18845 * // => false
18846 *
18847 * _.startsWith('abc', 'b', 1);
18848 * // => true
18849 */
18850 function startsWith(string, target, position) {
18851 string = baseToString(string);
18852 position = position == null
18853 ? 0
18854 : nativeMin(position < 0 ? 0 : (+position || 0), string.length);
18855
18856 return string.lastIndexOf(target, position) == position;
18857 }
18858
18859 /**
18860 * Creates a compiled template function that can interpolate data properties
18861 * in "interpolate" delimiters, HTML-escape interpolated data properties in
18862 * "escape" delimiters, and execute JavaScript in "evaluate" delimiters. Data
18863 * properties may be accessed as free variables in the template. If a setting
18864 * object is provided it takes precedence over `_.templateSettings` values.
18865 *
18866 * **Note:** In the development build `_.template` utilizes
18867 * [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl)
18868 * for easier debugging.
18869 *
18870 * For more information on precompiling templates see
18871 * [lodash's custom builds documentation](https://lodash.com/custom-builds).
18872 *
18873 * For more information on Chrome extension sandboxes see
18874 * [Chrome's extensions documentation](https://developer.chrome.com/extensions/sandboxingEval).
18875 *
18876 * @static
18877 * @memberOf _
18878 * @category String
18879 * @param {string} [string=''] The template string.
18880 * @param {Object} [options] The options object.
18881 * @param {RegExp} [options.escape] The HTML "escape" delimiter.
18882 * @param {RegExp} [options.evaluate] The "evaluate" delimiter.
18883 * @param {Object} [options.imports] An object to import into the template as free variables.
18884 * @param {RegExp} [options.interpolate] The "interpolate" delimiter.
18885 * @param {string} [options.sourceURL] The sourceURL of the template's compiled source.
18886 * @param {string} [options.variable] The data object variable name.
18887 * @param- {Object} [otherOptions] Enables the legacy `options` param signature.
18888 * @returns {Function} Returns the compiled template function.
18889 * @example
18890 *
18891 * // using the "interpolate" delimiter to create a compiled template
18892 * var compiled = _.template('hello <%= user %>!');
18893 * compiled({ 'user': 'fred' });
18894 * // => 'hello fred!'
18895 *
18896 * // using the HTML "escape" delimiter to escape data property values
18897 * var compiled = _.template('<b><%- value %></b>');
18898 * compiled({ 'value': '<script>' });
18899 * // => '<b>&lt;script&gt;</b>'
18900 *
18901 * // using the "evaluate" delimiter to execute JavaScript and generate HTML
18902 * var compiled = _.template('<% _.forEach(users, function(user) { %><li><%- user %></li><% }); %>');
18903 * compiled({ 'users': ['fred', 'barney'] });
18904 * // => '<li>fred</li><li>barney</li>'
18905 *
18906 * // using the internal `print` function in "evaluate" delimiters
18907 * var compiled = _.template('<% print("hello " + user); %>!');
18908 * compiled({ 'user': 'barney' });
18909 * // => 'hello barney!'
18910 *
18911 * // using the ES delimiter as an alternative to the default "interpolate" delimiter
18912 * var compiled = _.template('hello ${ user }!');
18913 * compiled({ 'user': 'pebbles' });
18914 * // => 'hello pebbles!'
18915 *
18916 * // using custom template delimiters
18917 * _.templateSettings.interpolate = /{{([\s\S]+?)}}/g;
18918 * var compiled = _.template('hello {{ user }}!');
18919 * compiled({ 'user': 'mustache' });
18920 * // => 'hello mustache!'
18921 *
18922 * // using backslashes to treat delimiters as plain text
18923 * var compiled = _.template('<%= "\\<%- value %\\>" %>');
18924 * compiled({ 'value': 'ignored' });
18925 * // => '<%- value %>'
18926 *
18927 * // using the `imports` option to import `jQuery` as `jq`
18928 * var text = '<% jq.each(users, function(user) { %><li><%- user %></li><% }); %>';
18929 * var compiled = _.template(text, { 'imports': { 'jq': jQuery } });
18930 * compiled({ 'users': ['fred', 'barney'] });
18931 * // => '<li>fred</li><li>barney</li>'
18932 *
18933 * // using the `sourceURL` option to specify a custom sourceURL for the template
18934 * var compiled = _.template('hello <%= user %>!', { 'sourceURL': '/basic/greeting.jst' });
18935 * compiled(data);
18936 * // => find the source of "greeting.jst" under the Sources tab or Resources panel of the web inspector
18937 *
18938 * // using the `variable` option to ensure a with-statement isn't used in the compiled template
18939 * var compiled = _.template('hi <%= data.user %>!', { 'variable': 'data' });
18940 * compiled.source;
18941 * // => function(data) {
18942 * // var __t, __p = '';
18943 * // __p += 'hi ' + ((__t = ( data.user )) == null ? '' : __t) + '!';
18944 * // return __p;
18945 * // }
18946 *
18947 * // using the `source` property to inline compiled templates for meaningful
18948 * // line numbers in error messages and a stack trace
18949 * fs.writeFileSync(path.join(cwd, 'jst.js'), '\
18950 * var JST = {\
18951 * "main": ' + _.template(mainText).source + '\
18952 * };\
18953 * ');
18954 */
18955 function template(string, options, otherOptions) {
18956 // Based on John Resig's `tmpl` implementation (http://ejohn.org/blog/javascript-micro-templating/)
18957 // and Laura Doktorova's doT.js (https://github.com/olado/doT).
18958 var settings = lodash.templateSettings;
18959
18960 if (otherOptions && isIterateeCall(string, options, otherOptions)) {
18961 options = otherOptions = undefined;
18962 }
18963 string = baseToString(string);
18964 options = assignWith(baseAssign({}, otherOptions || options), settings, assignOwnDefaults);
18965
18966 var imports = assignWith(baseAssign({}, options.imports), settings.imports, assignOwnDefaults),
18967 importsKeys = keys(imports),
18968 importsValues = baseValues(imports, importsKeys);
18969
18970 var isEscaping,
18971 isEvaluating,
18972 index = 0,
18973 interpolate = options.interpolate || reNoMatch,
18974 source = "__p += '";
18975
18976 // Compile the regexp to match each delimiter.
18977 var reDelimiters = RegExp(
18978 (options.escape || reNoMatch).source + '|' +
18979 interpolate.source + '|' +
18980 (interpolate === reInterpolate ? reEsTemplate : reNoMatch).source + '|' +
18981 (options.evaluate || reNoMatch).source + '|$'
18982 , 'g');
18983
18984 // Use a sourceURL for easier debugging.
18985 var sourceURL = '//# sourceURL=' +
18986 ('sourceURL' in options
18987 ? options.sourceURL
18988 : ('lodash.templateSources[' + (++templateCounter) + ']')
18989 ) + '\n';
18990
18991 string.replace(reDelimiters, function(match, escapeValue, interpolateValue, esTemplateValue, evaluateValue, offset) {
18992 interpolateValue || (interpolateValue = esTemplateValue);
18993
18994 // Escape characters that can't be included in string literals.
18995 source += string.slice(index, offset).replace(reUnescapedString, escapeStringChar);
18996
18997 // Replace delimiters with snippets.
18998 if (escapeValue) {
18999 isEscaping = true;
19000 source += "' +\n__e(" + escapeValue + ") +\n'";
19001 }
19002 if (evaluateValue) {
19003 isEvaluating = true;
19004 source += "';\n" + evaluateValue + ";\n__p += '";
19005 }
19006 if (interpolateValue) {
19007 source += "' +\n((__t = (" + interpolateValue + ")) == null ? '' : __t) +\n'";
19008 }
19009 index = offset + match.length;
19010
19011 // The JS engine embedded in Adobe products requires returning the `match`
19012 // string in order to produce the correct `offset` value.
19013 return match;
19014 });
19015
19016 source += "';\n";
19017
19018 // If `variable` is not specified wrap a with-statement around the generated
19019 // code to add the data object to the top of the scope chain.
19020 var variable = options.variable;
19021 if (!variable) {
19022 source = 'with (obj) {\n' + source + '\n}\n';
19023 }
19024 // Cleanup code by stripping empty strings.
19025 source = (isEvaluating ? source.replace(reEmptyStringLeading, '') : source)
19026 .replace(reEmptyStringMiddle, '$1')
19027 .replace(reEmptyStringTrailing, '$1;');
19028
19029 // Frame code as the function body.
19030 source = 'function(' + (variable || 'obj') + ') {\n' +
19031 (variable
19032 ? ''
19033 : 'obj || (obj = {});\n'
19034 ) +
19035 "var __t, __p = ''" +
19036 (isEscaping
19037 ? ', __e = _.escape'
19038 : ''
19039 ) +
19040 (isEvaluating
19041 ? ', __j = Array.prototype.join;\n' +
19042 "function print() { __p += __j.call(arguments, '') }\n"
19043 : ';\n'
19044 ) +
19045 source +
19046 'return __p\n}';
19047
19048 var result = attempt(function() {
19049 return Function(importsKeys, sourceURL + 'return ' + source).apply(undefined, importsValues);
19050 });
19051
19052 // Provide the compiled function's source by its `toString` method or
19053 // the `source` property as a convenience for inlining compiled templates.
19054 result.source = source;
19055 if (isError(result)) {
19056 throw result;
19057 }
19058 return result;
19059 }
19060
19061 /**
19062 * Removes leading and trailing whitespace or specified characters from `string`.
19063 *
19064 * @static
19065 * @memberOf _
19066 * @category String
19067 * @param {string} [string=''] The string to trim.
19068 * @param {string} [chars=whitespace] The characters to trim.
19069 * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
19070 * @returns {string} Returns the trimmed string.
19071 * @example
19072 *
19073 * _.trim(' abc ');
19074 * // => 'abc'
19075 *
19076 * _.trim('-_-abc-_-', '_-');
19077 * // => 'abc'
19078 *
19079 * _.map([' foo ', ' bar '], _.trim);
19080 * // => ['foo', 'bar']
19081 */
19082 function trim(string, chars, guard) {
19083 var value = string;
19084 string = baseToString(string);
19085 if (!string) {
19086 return string;
19087 }
19088 if (guard ? isIterateeCall(value, chars, guard) : chars == null) {
19089 return string.slice(trimmedLeftIndex(string), trimmedRightIndex(string) + 1);
19090 }
19091 chars = (chars + '');
19092 return string.slice(charsLeftIndex(string, chars), charsRightIndex(string, chars) + 1);
19093 }
19094
19095 /**
19096 * Removes leading whitespace or specified characters from `string`.
19097 *
19098 * @static
19099 * @memberOf _
19100 * @category String
19101 * @param {string} [string=''] The string to trim.
19102 * @param {string} [chars=whitespace] The characters to trim.
19103 * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
19104 * @returns {string} Returns the trimmed string.
19105 * @example
19106 *
19107 * _.trimLeft(' abc ');
19108 * // => 'abc '
19109 *
19110 * _.trimLeft('-_-abc-_-', '_-');
19111 * // => 'abc-_-'
19112 */
19113 function trimLeft(string, chars, guard) {
19114 var value = string;
19115 string = baseToString(string);
19116 if (!string) {
19117 return string;
19118 }
19119 if (guard ? isIterateeCall(value, chars, guard) : chars == null) {
19120 return string.slice(trimmedLeftIndex(string));
19121 }
19122 return string.slice(charsLeftIndex(string, (chars + '')));
19123 }
19124
19125 /**
19126 * Removes trailing whitespace or specified characters from `string`.
19127 *
19128 * @static
19129 * @memberOf _
19130 * @category String
19131 * @param {string} [string=''] The string to trim.
19132 * @param {string} [chars=whitespace] The characters to trim.
19133 * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
19134 * @returns {string} Returns the trimmed string.
19135 * @example
19136 *
19137 * _.trimRight(' abc ');
19138 * // => ' abc'
19139 *
19140 * _.trimRight('-_-abc-_-', '_-');
19141 * // => '-_-abc'
19142 */
19143 function trimRight(string, chars, guard) {
19144 var value = string;
19145 string = baseToString(string);
19146 if (!string) {
19147 return string;
19148 }
19149 if (guard ? isIterateeCall(value, chars, guard) : chars == null) {
19150 return string.slice(0, trimmedRightIndex(string) + 1);
19151 }
19152 return string.slice(0, charsRightIndex(string, (chars + '')) + 1);
19153 }
19154
19155 /**
19156 * Truncates `string` if it's longer than the given maximum string length.
19157 * The last characters of the truncated string are replaced with the omission
19158 * string which defaults to "...".
19159 *
19160 * @static
19161 * @memberOf _
19162 * @category String
19163 * @param {string} [string=''] The string to truncate.
19164 * @param {Object|number} [options] The options object or maximum string length.
19165 * @param {number} [options.length=30] The maximum string length.
19166 * @param {string} [options.omission='...'] The string to indicate text is omitted.
19167 * @param {RegExp|string} [options.separator] The separator pattern to truncate to.
19168 * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
19169 * @returns {string} Returns the truncated string.
19170 * @example
19171 *
19172 * _.trunc('hi-diddly-ho there, neighborino');
19173 * // => 'hi-diddly-ho there, neighbo...'
19174 *
19175 * _.trunc('hi-diddly-ho there, neighborino', 24);
19176 * // => 'hi-diddly-ho there, n...'
19177 *
19178 * _.trunc('hi-diddly-ho there, neighborino', {
19179 * 'length': 24,
19180 * 'separator': ' '
19181 * });
19182 * // => 'hi-diddly-ho there,...'
19183 *
19184 * _.trunc('hi-diddly-ho there, neighborino', {
19185 * 'length': 24,
19186 * 'separator': /,? +/
19187 * });
19188 * // => 'hi-diddly-ho there...'
19189 *
19190 * _.trunc('hi-diddly-ho there, neighborino', {
19191 * 'omission': ' [...]'
19192 * });
19193 * // => 'hi-diddly-ho there, neig [...]'
19194 */
19195 function trunc(string, options, guard) {
19196 if (guard && isIterateeCall(string, options, guard)) {
19197 options = undefined;
19198 }
19199 var length = DEFAULT_TRUNC_LENGTH,
19200 omission = DEFAULT_TRUNC_OMISSION;
19201
19202 if (options != null) {
19203 if (isObject(options)) {
19204 var separator = 'separator' in options ? options.separator : separator;
19205 length = 'length' in options ? (+options.length || 0) : length;
19206 omission = 'omission' in options ? baseToString(options.omission) : omission;
19207 } else {
19208 length = +options || 0;
19209 }
19210 }
19211 string = baseToString(string);
19212 if (length >= string.length) {
19213 return string;
19214 }
19215 var end = length - omission.length;
19216 if (end < 1) {
19217 return omission;
19218 }
19219 var result = string.slice(0, end);
19220 if (separator == null) {
19221 return result + omission;
19222 }
19223 if (isRegExp(separator)) {
19224 if (string.slice(end).search(separator)) {
19225 var match,
19226 newEnd,
19227 substring = string.slice(0, end);
19228
19229 if (!separator.global) {
19230 separator = RegExp(separator.source, (reFlags.exec(separator) || '') + 'g');
19231 }
19232 separator.lastIndex = 0;
19233 while ((match = separator.exec(substring))) {
19234 newEnd = match.index;
19235 }
19236 result = result.slice(0, newEnd == null ? end : newEnd);
19237 }
19238 } else if (string.indexOf(separator, end) != end) {
19239 var index = result.lastIndexOf(separator);
19240 if (index > -1) {
19241 result = result.slice(0, index);
19242 }
19243 }
19244 return result + omission;
19245 }
19246
19247 /**
19248 * The inverse of `_.escape`; this method converts the HTML entities
19249 * `&amp;`, `&lt;`, `&gt;`, `&quot;`, `&#39;`, and `&#96;` in `string` to their
19250 * corresponding characters.
19251 *
19252 * **Note:** No other HTML entities are unescaped. To unescape additional HTML
19253 * entities use a third-party library like [_he_](https://mths.be/he).
19254 *
19255 * @static
19256 * @memberOf _
19257 * @category String
19258 * @param {string} [string=''] The string to unescape.
19259 * @returns {string} Returns the unescaped string.
19260 * @example
19261 *
19262 * _.unescape('fred, barney, &amp; pebbles');
19263 * // => 'fred, barney, & pebbles'
19264 */
19265 function unescape(string) {
19266 string = baseToString(string);
19267 return (string && reHasEscapedHtml.test(string))
19268 ? string.replace(reEscapedHtml, unescapeHtmlChar)
19269 : string;
19270 }
19271
19272 /**
19273 * Splits `string` into an array of its words.
19274 *
19275 * @static
19276 * @memberOf _
19277 * @category String
19278 * @param {string} [string=''] The string to inspect.
19279 * @param {RegExp|string} [pattern] The pattern to match words.
19280 * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
19281 * @returns {Array} Returns the words of `string`.
19282 * @example
19283 *
19284 * _.words('fred, barney, & pebbles');
19285 * // => ['fred', 'barney', 'pebbles']
19286 *
19287 * _.words('fred, barney, & pebbles', /[^, ]+/g);
19288 * // => ['fred', 'barney', '&', 'pebbles']
19289 */
19290 function words(string, pattern, guard) {
19291 if (guard && isIterateeCall(string, pattern, guard)) {
19292 pattern = undefined;
19293 }
19294 string = baseToString(string);
19295 return string.match(pattern || reWords) || [];
19296 }
19297
19298 /*------------------------------------------------------------------------*/
19299
19300 /**
19301 * Attempts to invoke `func`, returning either the result or the caught error
19302 * object. Any additional arguments are provided to `func` when it is invoked.
19303 *
19304 * @static
19305 * @memberOf _
19306 * @category Utility
19307 * @param {Function} func The function to attempt.
19308 * @returns {*} Returns the `func` result or error object.
19309 * @example
19310 *
19311 * // avoid throwing errors for invalid selectors
19312 * var elements = _.attempt(function(selector) {
19313 * return document.querySelectorAll(selector);
19314 * }, '>_>');
19315 *
19316 * if (_.isError(elements)) {
19317 * elements = [];
19318 * }
19319 */
19320 var attempt = restParam(function(func, args) {
19321 try {
19322 return func.apply(undefined, args);
19323 } catch(e) {
19324 return isError(e) ? e : new Error(e);
19325 }
19326 });
19327
19328 /**
19329 * Creates a function that invokes `func` with the `this` binding of `thisArg`
19330 * and arguments of the created function. If `func` is a property name the
19331 * created callback returns the property value for a given element. If `func`
19332 * is an object the created callback returns `true` for elements that contain
19333 * the equivalent object properties, otherwise it returns `false`.
19334 *
19335 * @static
19336 * @memberOf _
19337 * @alias iteratee
19338 * @category Utility
19339 * @param {*} [func=_.identity] The value to convert to a callback.
19340 * @param {*} [thisArg] The `this` binding of `func`.
19341 * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
19342 * @returns {Function} Returns the callback.
19343 * @example
19344 *
19345 * var users = [
19346 * { 'user': 'barney', 'age': 36 },
19347 * { 'user': 'fred', 'age': 40 }
19348 * ];
19349 *
19350 * // wrap to create custom callback shorthands
19351 * _.callback = _.wrap(_.callback, function(callback, func, thisArg) {
19352 * var match = /^(.+?)__([gl]t)(.+)$/.exec(func);
19353 * if (!match) {
19354 * return callback(func, thisArg);
19355 * }
19356 * return function(object) {
19357 * return match[2] == 'gt'
19358 * ? object[match[1]] > match[3]
19359 * : object[match[1]] < match[3];
19360 * };
19361 * });
19362 *
19363 * _.filter(users, 'age__gt36');
19364 * // => [{ 'user': 'fred', 'age': 40 }]
19365 */
19366 function callback(func, thisArg, guard) {
19367 if (guard && isIterateeCall(func, thisArg, guard)) {
19368 thisArg = undefined;
19369 }
19370 return isObjectLike(func)
19371 ? matches(func)
19372 : baseCallback(func, thisArg);
19373 }
19374
19375 /**
19376 * Creates a function that returns `value`.
19377 *
19378 * @static
19379 * @memberOf _
19380 * @category Utility
19381 * @param {*} value The value to return from the new function.
19382 * @returns {Function} Returns the new function.
19383 * @example
19384 *
19385 * var object = { 'user': 'fred' };
19386 * var getter = _.constant(object);
19387 *
19388 * getter() === object;
19389 * // => true
19390 */
19391 function constant(value) {
19392 return function() {
19393 return value;
19394 };
19395 }
19396
19397 /**
19398 * This method returns the first argument provided to it.
19399 *
19400 * @static
19401 * @memberOf _
19402 * @category Utility
19403 * @param {*} value Any value.
19404 * @returns {*} Returns `value`.
19405 * @example
19406 *
19407 * var object = { 'user': 'fred' };
19408 *
19409 * _.identity(object) === object;
19410 * // => true
19411 */
19412 function identity(value) {
19413 return value;
19414 }
19415
19416 /**
19417 * Creates a function that performs a deep comparison between a given object
19418 * and `source`, returning `true` if the given object has equivalent property
19419 * values, else `false`.
19420 *
19421 * **Note:** This method supports comparing arrays, booleans, `Date` objects,
19422 * numbers, `Object` objects, regexes, and strings. Objects are compared by
19423 * their own, not inherited, enumerable properties. For comparing a single
19424 * own or inherited property value see `_.matchesProperty`.
19425 *
19426 * @static
19427 * @memberOf _
19428 * @category Utility
19429 * @param {Object} source The object of property values to match.
19430 * @returns {Function} Returns the new function.
19431 * @example
19432 *
19433 * var users = [
19434 * { 'user': 'barney', 'age': 36, 'active': true },
19435 * { 'user': 'fred', 'age': 40, 'active': false }
19436 * ];
19437 *
19438 * _.filter(users, _.matches({ 'age': 40, 'active': false }));
19439 * // => [{ 'user': 'fred', 'age': 40, 'active': false }]
19440 */
19441 function matches(source) {
19442 return baseMatches(baseClone(source, true));
19443 }
19444
19445 /**
19446 * Creates a function that compares the property value of `path` on a given
19447 * object to `value`.
19448 *
19449 * **Note:** This method supports comparing arrays, booleans, `Date` objects,
19450 * numbers, `Object` objects, regexes, and strings. Objects are compared by
19451 * their own, not inherited, enumerable properties.
19452 *
19453 * @static
19454 * @memberOf _
19455 * @category Utility
19456 * @param {Array|string} path The path of the property to get.
19457 * @param {*} srcValue The value to match.
19458 * @returns {Function} Returns the new function.
19459 * @example
19460 *
19461 * var users = [
19462 * { 'user': 'barney' },
19463 * { 'user': 'fred' }
19464 * ];
19465 *
19466 * _.find(users, _.matchesProperty('user', 'fred'));
19467 * // => { 'user': 'fred' }
19468 */
19469 function matchesProperty(path, srcValue) {
19470 return baseMatchesProperty(path, baseClone(srcValue, true));
19471 }
19472
19473 /**
19474 * Creates a function that invokes the method at `path` on a given object.
19475 * Any additional arguments are provided to the invoked method.
19476 *
19477 * @static
19478 * @memberOf _
19479 * @category Utility
19480 * @param {Array|string} path The path of the method to invoke.
19481 * @param {...*} [args] The arguments to invoke the method with.
19482 * @returns {Function} Returns the new function.
19483 * @example
19484 *
19485 * var objects = [
19486 * { 'a': { 'b': { 'c': _.constant(2) } } },
19487 * { 'a': { 'b': { 'c': _.constant(1) } } }
19488 * ];
19489 *
19490 * _.map(objects, _.method('a.b.c'));
19491 * // => [2, 1]
19492 *
19493 * _.invoke(_.sortBy(objects, _.method(['a', 'b', 'c'])), 'a.b.c');
19494 * // => [1, 2]
19495 */
19496 var method = restParam(function(path, args) {
19497 return function(object) {
19498 return invokePath(object, path, args);
19499 };
19500 });
19501
19502 /**
19503 * The opposite of `_.method`; this method creates a function that invokes
19504 * the method at a given path on `object`. Any additional arguments are
19505 * provided to the invoked method.
19506 *
19507 * @static
19508 * @memberOf _
19509 * @category Utility
19510 * @param {Object} object The object to query.
19511 * @param {...*} [args] The arguments to invoke the method with.
19512 * @returns {Function} Returns the new function.
19513 * @example
19514 *
19515 * var array = _.times(3, _.constant),
19516 * object = { 'a': array, 'b': array, 'c': array };
19517 *
19518 * _.map(['a[2]', 'c[0]'], _.methodOf(object));
19519 * // => [2, 0]
19520 *
19521 * _.map([['a', '2'], ['c', '0']], _.methodOf(object));
19522 * // => [2, 0]
19523 */
19524 var methodOf = restParam(function(object, args) {
19525 return function(path) {
19526 return invokePath(object, path, args);
19527 };
19528 });
19529
19530 /**
19531 * Adds all own enumerable function properties of a source object to the
19532 * destination object. If `object` is a function then methods are added to
19533 * its prototype as well.
19534 *
19535 * **Note:** Use `_.runInContext` to create a pristine `lodash` function to
19536 * avoid conflicts caused by modifying the original.
19537 *
19538 * @static
19539 * @memberOf _
19540 * @category Utility
19541 * @param {Function|Object} [object=lodash] The destination object.
19542 * @param {Object} source The object of functions to add.
19543 * @param {Object} [options] The options object.
19544 * @param {boolean} [options.chain=true] Specify whether the functions added
19545 * are chainable.
19546 * @returns {Function|Object} Returns `object`.
19547 * @example
19548 *
19549 * function vowels(string) {
19550 * return _.filter(string, function(v) {
19551 * return /[aeiou]/i.test(v);
19552 * });
19553 * }
19554 *
19555 * _.mixin({ 'vowels': vowels });
19556 * _.vowels('fred');
19557 * // => ['e']
19558 *
19559 * _('fred').vowels().value();
19560 * // => ['e']
19561 *
19562 * _.mixin({ 'vowels': vowels }, { 'chain': false });
19563 * _('fred').vowels();
19564 * // => ['e']
19565 */
19566 function mixin(object, source, options) {
19567 if (options == null) {
19568 var isObj = isObject(source),
19569 props = isObj ? keys(source) : undefined,
19570 methodNames = (props && props.length) ? baseFunctions(source, props) : undefined;
19571
19572 if (!(methodNames ? methodNames.length : isObj)) {
19573 methodNames = false;
19574 options = source;
19575 source = object;
19576 object = this;
19577 }
19578 }
19579 if (!methodNames) {
19580 methodNames = baseFunctions(source, keys(source));
19581 }
19582 var chain = true,
19583 index = -1,
19584 isFunc = isFunction(object),
19585 length = methodNames.length;
19586
19587 if (options === false) {
19588 chain = false;
19589 } else if (isObject(options) && 'chain' in options) {
19590 chain = options.chain;
19591 }
19592 while (++index < length) {
19593 var methodName = methodNames[index],
19594 func = source[methodName];
19595
19596 object[methodName] = func;
19597 if (isFunc) {
19598 object.prototype[methodName] = (function(func) {
19599 return function() {
19600 var chainAll = this.__chain__;
19601 if (chain || chainAll) {
19602 var result = object(this.__wrapped__),
19603 actions = result.__actions__ = arrayCopy(this.__actions__);
19604
19605 actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
19606 result.__chain__ = chainAll;
19607 return result;
19608 }
19609 return func.apply(object, arrayPush([this.value()], arguments));
19610 };
19611 }(func));
19612 }
19613 }
19614 return object;
19615 }
19616
19617 /**
19618 * Reverts the `_` variable to its previous value and returns a reference to
19619 * the `lodash` function.
19620 *
19621 * @static
19622 * @memberOf _
19623 * @category Utility
19624 * @returns {Function} Returns the `lodash` function.
19625 * @example
19626 *
19627 * var lodash = _.noConflict();
19628 */
19629 function noConflict() {
19630 root._ = oldDash;
19631 return this;
19632 }
19633
19634 /**
19635 * A no-operation function that returns `undefined` regardless of the
19636 * arguments it receives.
19637 *
19638 * @static
19639 * @memberOf _
19640 * @category Utility
19641 * @example
19642 *
19643 * var object = { 'user': 'fred' };
19644 *
19645 * _.noop(object) === undefined;
19646 * // => true
19647 */
19648 function noop() {
19649 // No operation performed.
19650 }
19651
19652 /**
19653 * Creates a function that returns the property value at `path` on a
19654 * given object.
19655 *
19656 * @static
19657 * @memberOf _
19658 * @category Utility
19659 * @param {Array|string} path The path of the property to get.
19660 * @returns {Function} Returns the new function.
19661 * @example
19662 *
19663 * var objects = [
19664 * { 'a': { 'b': { 'c': 2 } } },
19665 * { 'a': { 'b': { 'c': 1 } } }
19666 * ];
19667 *
19668 * _.map(objects, _.property('a.b.c'));
19669 * // => [2, 1]
19670 *
19671 * _.pluck(_.sortBy(objects, _.property(['a', 'b', 'c'])), 'a.b.c');
19672 * // => [1, 2]
19673 */
19674 function property(path) {
19675 return isKey(path) ? baseProperty(path) : basePropertyDeep(path);
19676 }
19677
19678 /**
19679 * The opposite of `_.property`; this method creates a function that returns
19680 * the property value at a given path on `object`.
19681 *
19682 * @static
19683 * @memberOf _
19684 * @category Utility
19685 * @param {Object} object The object to query.
19686 * @returns {Function} Returns the new function.
19687 * @example
19688 *
19689 * var array = [0, 1, 2],
19690 * object = { 'a': array, 'b': array, 'c': array };
19691 *
19692 * _.map(['a[2]', 'c[0]'], _.propertyOf(object));
19693 * // => [2, 0]
19694 *
19695 * _.map([['a', '2'], ['c', '0']], _.propertyOf(object));
19696 * // => [2, 0]
19697 */
19698 function propertyOf(object) {
19699 return function(path) {
19700 return baseGet(object, toPath(path), path + '');
19701 };
19702 }
19703
19704 /**
19705 * Creates an array of numbers (positive and/or negative) progressing from
19706 * `start` up to, but not including, `end`. If `end` is not specified it is
19707 * set to `start` with `start` then set to `0`. If `end` is less than `start`
19708 * a zero-length range is created unless a negative `step` is specified.
19709 *
19710 * @static
19711 * @memberOf _
19712 * @category Utility
19713 * @param {number} [start=0] The start of the range.
19714 * @param {number} end The end of the range.
19715 * @param {number} [step=1] The value to increment or decrement by.
19716 * @returns {Array} Returns the new array of numbers.
19717 * @example
19718 *
19719 * _.range(4);
19720 * // => [0, 1, 2, 3]
19721 *
19722 * _.range(1, 5);
19723 * // => [1, 2, 3, 4]
19724 *
19725 * _.range(0, 20, 5);
19726 * // => [0, 5, 10, 15]
19727 *
19728 * _.range(0, -4, -1);
19729 * // => [0, -1, -2, -3]
19730 *
19731 * _.range(1, 4, 0);
19732 * // => [1, 1, 1]
19733 *
19734 * _.range(0);
19735 * // => []
19736 */
19737 function range(start, end, step) {
19738 if (step && isIterateeCall(start, end, step)) {
19739 end = step = undefined;
19740 }
19741 start = +start || 0;
19742 step = step == null ? 1 : (+step || 0);
19743
19744 if (end == null) {
19745 end = start;
19746 start = 0;
19747 } else {
19748 end = +end || 0;
19749 }
19750 // Use `Array(length)` so engines like Chakra and V8 avoid slower modes.
19751 // See https://youtu.be/XAqIpGU8ZZk#t=17m25s for more details.
19752 var index = -1,
19753 length = nativeMax(nativeCeil((end - start) / (step || 1)), 0),
19754 result = Array(length);
19755
19756 while (++index < length) {
19757 result[index] = start;
19758 start += step;
19759 }
19760 return result;
19761 }
19762
19763 /**
19764 * Invokes the iteratee function `n` times, returning an array of the results
19765 * of each invocation. The `iteratee` is bound to `thisArg` and invoked with
19766 * one argument; (index).
19767 *
19768 * @static
19769 * @memberOf _
19770 * @category Utility
19771 * @param {number} n The number of times to invoke `iteratee`.
19772 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
19773 * @param {*} [thisArg] The `this` binding of `iteratee`.
19774 * @returns {Array} Returns the array of results.
19775 * @example
19776 *
19777 * var diceRolls = _.times(3, _.partial(_.random, 1, 6, false));
19778 * // => [3, 6, 4]
19779 *
19780 * _.times(3, function(n) {
19781 * mage.castSpell(n);
19782 * });
19783 * // => invokes `mage.castSpell(n)` three times with `n` of `0`, `1`, and `2`
19784 *
19785 * _.times(3, function(n) {
19786 * this.cast(n);
19787 * }, mage);
19788 * // => also invokes `mage.castSpell(n)` three times
19789 */
19790 function times(n, iteratee, thisArg) {
19791 n = nativeFloor(n);
19792
19793 // Exit early to avoid a JSC JIT bug in Safari 8
19794 // where `Array(0)` is treated as `Array(1)`.
19795 if (n < 1 || !nativeIsFinite(n)) {
19796 return [];
19797 }
19798 var index = -1,
19799 result = Array(nativeMin(n, MAX_ARRAY_LENGTH));
19800
19801 iteratee = bindCallback(iteratee, thisArg, 1);
19802 while (++index < n) {
19803 if (index < MAX_ARRAY_LENGTH) {
19804 result[index] = iteratee(index);
19805 } else {
19806 iteratee(index);
19807 }
19808 }
19809 return result;
19810 }
19811
19812 /**
19813 * Generates a unique ID. If `prefix` is provided the ID is appended to it.
19814 *
19815 * @static
19816 * @memberOf _
19817 * @category Utility
19818 * @param {string} [prefix] The value to prefix the ID with.
19819 * @returns {string} Returns the unique ID.
19820 * @example
19821 *
19822 * _.uniqueId('contact_');
19823 * // => 'contact_104'
19824 *
19825 * _.uniqueId();
19826 * // => '105'
19827 */
19828 function uniqueId(prefix) {
19829 var id = ++idCounter;
19830 return baseToString(prefix) + id;
19831 }
19832
19833 /*------------------------------------------------------------------------*/
19834
19835 /**
19836 * Adds two numbers.
19837 *
19838 * @static
19839 * @memberOf _
19840 * @category Math
19841 * @param {number} augend The first number to add.
19842 * @param {number} addend The second number to add.
19843 * @returns {number} Returns the sum.
19844 * @example
19845 *
19846 * _.add(6, 4);
19847 * // => 10
19848 */
19849 function add(augend, addend) {
19850 return (+augend || 0) + (+addend || 0);
19851 }
19852
19853 /**
19854 * Calculates `n` rounded up to `precision`.
19855 *
19856 * @static
19857 * @memberOf _
19858 * @category Math
19859 * @param {number} n The number to round up.
19860 * @param {number} [precision=0] The precision to round up to.
19861 * @returns {number} Returns the rounded up number.
19862 * @example
19863 *
19864 * _.ceil(4.006);
19865 * // => 5
19866 *
19867 * _.ceil(6.004, 2);
19868 * // => 6.01
19869 *
19870 * _.ceil(6040, -2);
19871 * // => 6100
19872 */
19873 var ceil = createRound('ceil');
19874
19875 /**
19876 * Calculates `n` rounded down to `precision`.
19877 *
19878 * @static
19879 * @memberOf _
19880 * @category Math
19881 * @param {number} n The number to round down.
19882 * @param {number} [precision=0] The precision to round down to.
19883 * @returns {number} Returns the rounded down number.
19884 * @example
19885 *
19886 * _.floor(4.006);
19887 * // => 4
19888 *
19889 * _.floor(0.046, 2);
19890 * // => 0.04
19891 *
19892 * _.floor(4060, -2);
19893 * // => 4000
19894 */
19895 var floor = createRound('floor');
19896
19897 /**
19898 * Gets the maximum value of `collection`. If `collection` is empty or falsey
19899 * `-Infinity` is returned. If an iteratee function is provided it is invoked
19900 * for each value in `collection` to generate the criterion by which the value
19901 * is ranked. The `iteratee` is bound to `thisArg` and invoked with three
19902 * arguments: (value, index, collection).
19903 *
19904 * If a property name is provided for `iteratee` the created `_.property`
19905 * style callback returns the property value of the given element.
19906 *
19907 * If a value is also provided for `thisArg` the created `_.matchesProperty`
19908 * style callback returns `true` for elements that have a matching property
19909 * value, else `false`.
19910 *
19911 * If an object is provided for `iteratee` the created `_.matches` style
19912 * callback returns `true` for elements that have the properties of the given
19913 * object, else `false`.
19914 *
19915 * @static
19916 * @memberOf _
19917 * @category Math
19918 * @param {Array|Object|string} collection The collection to iterate over.
19919 * @param {Function|Object|string} [iteratee] The function invoked per iteration.
19920 * @param {*} [thisArg] The `this` binding of `iteratee`.
19921 * @returns {*} Returns the maximum value.
19922 * @example
19923 *
19924 * _.max([4, 2, 8, 6]);
19925 * // => 8
19926 *
19927 * _.max([]);
19928 * // => -Infinity
19929 *
19930 * var users = [
19931 * { 'user': 'barney', 'age': 36 },
19932 * { 'user': 'fred', 'age': 40 }
19933 * ];
19934 *
19935 * _.max(users, function(chr) {
19936 * return chr.age;
19937 * });
19938 * // => { 'user': 'fred', 'age': 40 }
19939 *
19940 * // using the `_.property` callback shorthand
19941 * _.max(users, 'age');
19942 * // => { 'user': 'fred', 'age': 40 }
19943 */
19944 var max = createExtremum(gt, NEGATIVE_INFINITY);
19945
19946 /**
19947 * Gets the minimum value of `collection`. If `collection` is empty or falsey
19948 * `Infinity` is returned. If an iteratee function is provided it is invoked
19949 * for each value in `collection` to generate the criterion by which the value
19950 * is ranked. The `iteratee` is bound to `thisArg` and invoked with three
19951 * arguments: (value, index, collection).
19952 *
19953 * If a property name is provided for `iteratee` the created `_.property`
19954 * style callback returns the property value of the given element.
19955 *
19956 * If a value is also provided for `thisArg` the created `_.matchesProperty`
19957 * style callback returns `true` for elements that have a matching property
19958 * value, else `false`.
19959 *
19960 * If an object is provided for `iteratee` the created `_.matches` style
19961 * callback returns `true` for elements that have the properties of the given
19962 * object, else `false`.
19963 *
19964 * @static
19965 * @memberOf _
19966 * @category Math
19967 * @param {Array|Object|string} collection The collection to iterate over.
19968 * @param {Function|Object|string} [iteratee] The function invoked per iteration.
19969 * @param {*} [thisArg] The `this` binding of `iteratee`.
19970 * @returns {*} Returns the minimum value.
19971 * @example
19972 *
19973 * _.min([4, 2, 8, 6]);
19974 * // => 2
19975 *
19976 * _.min([]);
19977 * // => Infinity
19978 *
19979 * var users = [
19980 * { 'user': 'barney', 'age': 36 },
19981 * { 'user': 'fred', 'age': 40 }
19982 * ];
19983 *
19984 * _.min(users, function(chr) {
19985 * return chr.age;
19986 * });
19987 * // => { 'user': 'barney', 'age': 36 }
19988 *
19989 * // using the `_.property` callback shorthand
19990 * _.min(users, 'age');
19991 * // => { 'user': 'barney', 'age': 36 }
19992 */
19993 var min = createExtremum(lt, POSITIVE_INFINITY);
19994
19995 /**
19996 * Calculates `n` rounded to `precision`.
19997 *
19998 * @static
19999 * @memberOf _
20000 * @category Math
20001 * @param {number} n The number to round.
20002 * @param {number} [precision=0] The precision to round to.
20003 * @returns {number} Returns the rounded number.
20004 * @example
20005 *
20006 * _.round(4.006);
20007 * // => 4
20008 *
20009 * _.round(4.006, 2);
20010 * // => 4.01
20011 *
20012 * _.round(4060, -2);
20013 * // => 4100
20014 */
20015 var round = createRound('round');
20016
20017 /**
20018 * Gets the sum of the values in `collection`.
20019 *
20020 * @static
20021 * @memberOf _
20022 * @category Math
20023 * @param {Array|Object|string} collection The collection to iterate over.
20024 * @param {Function|Object|string} [iteratee] The function invoked per iteration.
20025 * @param {*} [thisArg] The `this` binding of `iteratee`.
20026 * @returns {number} Returns the sum.
20027 * @example
20028 *
20029 * _.sum([4, 6]);
20030 * // => 10
20031 *
20032 * _.sum({ 'a': 4, 'b': 6 });
20033 * // => 10
20034 *
20035 * var objects = [
20036 * { 'n': 4 },
20037 * { 'n': 6 }
20038 * ];
20039 *
20040 * _.sum(objects, function(object) {
20041 * return object.n;
20042 * });
20043 * // => 10
20044 *
20045 * // using the `_.property` callback shorthand
20046 * _.sum(objects, 'n');
20047 * // => 10
20048 */
20049 function sum(collection, iteratee, thisArg) {
20050 if (thisArg && isIterateeCall(collection, iteratee, thisArg)) {
20051 iteratee = undefined;
20052 }
20053 iteratee = getCallback(iteratee, thisArg, 3);
20054 return iteratee.length == 1
20055 ? arraySum(isArray(collection) ? collection : toIterable(collection), iteratee)
20056 : baseSum(collection, iteratee);
20057 }
20058
20059 /*------------------------------------------------------------------------*/
20060
20061 // Ensure wrappers are instances of `baseLodash`.
20062 lodash.prototype = baseLodash.prototype;
20063
20064 LodashWrapper.prototype = baseCreate(baseLodash.prototype);
20065 LodashWrapper.prototype.constructor = LodashWrapper;
20066
20067 LazyWrapper.prototype = baseCreate(baseLodash.prototype);
20068 LazyWrapper.prototype.constructor = LazyWrapper;
20069
20070 // Add functions to the `Map` cache.
20071 MapCache.prototype['delete'] = mapDelete;
20072 MapCache.prototype.get = mapGet;
20073 MapCache.prototype.has = mapHas;
20074 MapCache.prototype.set = mapSet;
20075
20076 // Add functions to the `Set` cache.
20077 SetCache.prototype.push = cachePush;
20078
20079 // Assign cache to `_.memoize`.
20080 memoize.Cache = MapCache;
20081
20082 // Add functions that return wrapped values when chaining.
20083 lodash.after = after;
20084 lodash.ary = ary;
20085 lodash.assign = assign;
20086 lodash.at = at;
20087 lodash.before = before;
20088 lodash.bind = bind;
20089 lodash.bindAll = bindAll;
20090 lodash.bindKey = bindKey;
20091 lodash.callback = callback;
20092 lodash.chain = chain;
20093 lodash.chunk = chunk;
20094 lodash.compact = compact;
20095 lodash.constant = constant;
20096 lodash.countBy = countBy;
20097 lodash.create = create;
20098 lodash.curry = curry;
20099 lodash.curryRight = curryRight;
20100 lodash.debounce = debounce;
20101 lodash.defaults = defaults;
20102 lodash.defaultsDeep = defaultsDeep;
20103 lodash.defer = defer;
20104 lodash.delay = delay;
20105 lodash.difference = difference;
20106 lodash.drop = drop;
20107 lodash.dropRight = dropRight;
20108 lodash.dropRightWhile = dropRightWhile;
20109 lodash.dropWhile = dropWhile;
20110 lodash.fill = fill;
20111 lodash.filter = filter;
20112 lodash.flatten = flatten;
20113 lodash.flattenDeep = flattenDeep;
20114 lodash.flow = flow;
20115 lodash.flowRight = flowRight;
20116 lodash.forEach = forEach;
20117 lodash.forEachRight = forEachRight;
20118 lodash.forIn = forIn;
20119 lodash.forInRight = forInRight;
20120 lodash.forOwn = forOwn;
20121 lodash.forOwnRight = forOwnRight;
20122 lodash.functions = functions;
20123 lodash.groupBy = groupBy;
20124 lodash.indexBy = indexBy;
20125 lodash.initial = initial;
20126 lodash.intersection = intersection;
20127 lodash.invert = invert;
20128 lodash.invoke = invoke;
20129 lodash.keys = keys;
20130 lodash.keysIn = keysIn;
20131 lodash.map = map;
20132 lodash.mapKeys = mapKeys;
20133 lodash.mapValues = mapValues;
20134 lodash.matches = matches;
20135 lodash.matchesProperty = matchesProperty;
20136 lodash.memoize = memoize;
20137 lodash.merge = merge;
20138 lodash.method = method;
20139 lodash.methodOf = methodOf;
20140 lodash.mixin = mixin;
20141 lodash.modArgs = modArgs;
20142 lodash.negate = negate;
20143 lodash.omit = omit;
20144 lodash.once = once;
20145 lodash.pairs = pairs;
20146 lodash.partial = partial;
20147 lodash.partialRight = partialRight;
20148 lodash.partition = partition;
20149 lodash.pick = pick;
20150 lodash.pluck = pluck;
20151 lodash.property = property;
20152 lodash.propertyOf = propertyOf;
20153 lodash.pull = pull;
20154 lodash.pullAt = pullAt;
20155 lodash.range = range;
20156 lodash.rearg = rearg;
20157 lodash.reject = reject;
20158 lodash.remove = remove;
20159 lodash.rest = rest;
20160 lodash.restParam = restParam;
20161 lodash.set = set;
20162 lodash.shuffle = shuffle;
20163 lodash.slice = slice;
20164 lodash.sortBy = sortBy;
20165 lodash.sortByAll = sortByAll;
20166 lodash.sortByOrder = sortByOrder;
20167 lodash.spread = spread;
20168 lodash.take = take;
20169 lodash.takeRight = takeRight;
20170 lodash.takeRightWhile = takeRightWhile;
20171 lodash.takeWhile = takeWhile;
20172 lodash.tap = tap;
20173 lodash.throttle = throttle;
20174 lodash.thru = thru;
20175 lodash.times = times;
20176 lodash.toArray = toArray;
20177 lodash.toPlainObject = toPlainObject;
20178 lodash.transform = transform;
20179 lodash.union = union;
20180 lodash.uniq = uniq;
20181 lodash.unzip = unzip;
20182 lodash.unzipWith = unzipWith;
20183 lodash.values = values;
20184 lodash.valuesIn = valuesIn;
20185 lodash.where = where;
20186 lodash.without = without;
20187 lodash.wrap = wrap;
20188 lodash.xor = xor;
20189 lodash.zip = zip;
20190 lodash.zipObject = zipObject;
20191 lodash.zipWith = zipWith;
20192
20193 // Add aliases.
20194 lodash.backflow = flowRight;
20195 lodash.collect = map;
20196 lodash.compose = flowRight;
20197 lodash.each = forEach;
20198 lodash.eachRight = forEachRight;
20199 lodash.extend = assign;
20200 lodash.iteratee = callback;
20201 lodash.methods = functions;
20202 lodash.object = zipObject;
20203 lodash.select = filter;
20204 lodash.tail = rest;
20205 lodash.unique = uniq;
20206
20207 // Add functions to `lodash.prototype`.
20208 mixin(lodash, lodash);
20209
20210 /*------------------------------------------------------------------------*/
20211
20212 // Add functions that return unwrapped values when chaining.
20213 lodash.add = add;
20214 lodash.attempt = attempt;
20215 lodash.camelCase = camelCase;
20216 lodash.capitalize = capitalize;
20217 lodash.ceil = ceil;
20218 lodash.clone = clone;
20219 lodash.cloneDeep = cloneDeep;
20220 lodash.deburr = deburr;
20221 lodash.endsWith = endsWith;
20222 lodash.escape = escape;
20223 lodash.escapeRegExp = escapeRegExp;
20224 lodash.every = every;
20225 lodash.find = find;
20226 lodash.findIndex = findIndex;
20227 lodash.findKey = findKey;
20228 lodash.findLast = findLast;
20229 lodash.findLastIndex = findLastIndex;
20230 lodash.findLastKey = findLastKey;
20231 lodash.findWhere = findWhere;
20232 lodash.first = first;
20233 lodash.floor = floor;
20234 lodash.get = get;
20235 lodash.gt = gt;
20236 lodash.gte = gte;
20237 lodash.has = has;
20238 lodash.identity = identity;
20239 lodash.includes = includes;
20240 lodash.indexOf = indexOf;
20241 lodash.inRange = inRange;
20242 lodash.isArguments = isArguments;
20243 lodash.isArray = isArray;
20244 lodash.isBoolean = isBoolean;
20245 lodash.isDate = isDate;
20246 lodash.isElement = isElement;
20247 lodash.isEmpty = isEmpty;
20248 lodash.isEqual = isEqual;
20249 lodash.isError = isError;
20250 lodash.isFinite = isFinite;
20251 lodash.isFunction = isFunction;
20252 lodash.isMatch = isMatch;
20253 lodash.isNaN = isNaN;
20254 lodash.isNative = isNative;
20255 lodash.isNull = isNull;
20256 lodash.isNumber = isNumber;
20257 lodash.isObject = isObject;
20258 lodash.isPlainObject = isPlainObject;
20259 lodash.isRegExp = isRegExp;
20260 lodash.isString = isString;
20261 lodash.isTypedArray = isTypedArray;
20262 lodash.isUndefined = isUndefined;
20263 lodash.kebabCase = kebabCase;
20264 lodash.last = last;
20265 lodash.lastIndexOf = lastIndexOf;
20266 lodash.lt = lt;
20267 lodash.lte = lte;
20268 lodash.max = max;
20269 lodash.min = min;
20270 lodash.noConflict = noConflict;
20271 lodash.noop = noop;
20272 lodash.now = now;
20273 lodash.pad = pad;
20274 lodash.padLeft = padLeft;
20275 lodash.padRight = padRight;
20276 lodash.parseInt = parseInt;
20277 lodash.random = random;
20278 lodash.reduce = reduce;
20279 lodash.reduceRight = reduceRight;
20280 lodash.repeat = repeat;
20281 lodash.result = result;
20282 lodash.round = round;
20283 lodash.runInContext = runInContext;
20284 lodash.size = size;
20285 lodash.snakeCase = snakeCase;
20286 lodash.some = some;
20287 lodash.sortedIndex = sortedIndex;
20288 lodash.sortedLastIndex = sortedLastIndex;
20289 lodash.startCase = startCase;
20290 lodash.startsWith = startsWith;
20291 lodash.sum = sum;
20292 lodash.template = template;
20293 lodash.trim = trim;
20294 lodash.trimLeft = trimLeft;
20295 lodash.trimRight = trimRight;
20296 lodash.trunc = trunc;
20297 lodash.unescape = unescape;
20298 lodash.uniqueId = uniqueId;
20299 lodash.words = words;
20300
20301 // Add aliases.
20302 lodash.all = every;
20303 lodash.any = some;
20304 lodash.contains = includes;
20305 lodash.eq = isEqual;
20306 lodash.detect = find;
20307 lodash.foldl = reduce;
20308 lodash.foldr = reduceRight;
20309 lodash.head = first;
20310 lodash.include = includes;
20311 lodash.inject = reduce;
20312
20313 mixin(lodash, (function() {
20314 var source = {};
20315 baseForOwn(lodash, function(func, methodName) {
20316 if (!lodash.prototype[methodName]) {
20317 source[methodName] = func;
20318 }
20319 });
20320 return source;
20321 }()), false);
20322
20323 /*------------------------------------------------------------------------*/
20324
20325 // Add functions capable of returning wrapped and unwrapped values when chaining.
20326 lodash.sample = sample;
20327
20328 lodash.prototype.sample = function(n) {
20329 if (!this.__chain__ && n == null) {
20330 return sample(this.value());
20331 }
20332 return this.thru(function(value) {
20333 return sample(value, n);
20334 });
20335 };
20336
20337 /*------------------------------------------------------------------------*/
20338
20339 /**
20340 * The semantic version number.
20341 *
20342 * @static
20343 * @memberOf _
20344 * @type string
20345 */
20346 lodash.VERSION = VERSION;
20347
20348 // Assign default placeholders.
20349 arrayEach(['bind', 'bindKey', 'curry', 'curryRight', 'partial', 'partialRight'], function(methodName) {
20350 lodash[methodName].placeholder = lodash;
20351 });
20352
20353 // Add `LazyWrapper` methods for `_.drop` and `_.take` variants.
20354 arrayEach(['drop', 'take'], function(methodName, index) {
20355 LazyWrapper.prototype[methodName] = function(n) {
20356 var filtered = this.__filtered__;
20357 if (filtered && !index) {
20358 return new LazyWrapper(this);
20359 }
20360 n = n == null ? 1 : nativeMax(nativeFloor(n) || 0, 0);
20361
20362 var result = this.clone();
20363 if (filtered) {
20364 result.__takeCount__ = nativeMin(result.__takeCount__, n);
20365 } else {
20366 result.__views__.push({ 'size': n, 'type': methodName + (result.__dir__ < 0 ? 'Right' : '') });
20367 }
20368 return result;
20369 };
20370
20371 LazyWrapper.prototype[methodName + 'Right'] = function(n) {
20372 return this.reverse()[methodName](n).reverse();
20373 };
20374 });
20375
20376 // Add `LazyWrapper` methods that accept an `iteratee` value.
20377 arrayEach(['filter', 'map', 'takeWhile'], function(methodName, index) {
20378 var type = index + 1,
20379 isFilter = type != LAZY_MAP_FLAG;
20380
20381 LazyWrapper.prototype[methodName] = function(iteratee, thisArg) {
20382 var result = this.clone();
20383 result.__iteratees__.push({ 'iteratee': getCallback(iteratee, thisArg, 1), 'type': type });
20384 result.__filtered__ = result.__filtered__ || isFilter;
20385 return result;
20386 };
20387 });
20388
20389 // Add `LazyWrapper` methods for `_.first` and `_.last`.
20390 arrayEach(['first', 'last'], function(methodName, index) {
20391 var takeName = 'take' + (index ? 'Right' : '');
20392
20393 LazyWrapper.prototype[methodName] = function() {
20394 return this[takeName](1).value()[0];
20395 };
20396 });
20397
20398 // Add `LazyWrapper` methods for `_.initial` and `_.rest`.
20399 arrayEach(['initial', 'rest'], function(methodName, index) {
20400 var dropName = 'drop' + (index ? '' : 'Right');
20401
20402 LazyWrapper.prototype[methodName] = function() {
20403 return this.__filtered__ ? new LazyWrapper(this) : this[dropName](1);
20404 };
20405 });
20406
20407 // Add `LazyWrapper` methods for `_.pluck` and `_.where`.
20408 arrayEach(['pluck', 'where'], function(methodName, index) {
20409 var operationName = index ? 'filter' : 'map',
20410 createCallback = index ? baseMatches : property;
20411
20412 LazyWrapper.prototype[methodName] = function(value) {
20413 return this[operationName](createCallback(value));
20414 };
20415 });
20416
20417 LazyWrapper.prototype.compact = function() {
20418 return this.filter(identity);
20419 };
20420
20421 LazyWrapper.prototype.reject = function(predicate, thisArg) {
20422 predicate = getCallback(predicate, thisArg, 1);
20423 return this.filter(function(value) {
20424 return !predicate(value);
20425 });
20426 };
20427
20428 LazyWrapper.prototype.slice = function(start, end) {
20429 start = start == null ? 0 : (+start || 0);
20430
20431 var result = this;
20432 if (result.__filtered__ && (start > 0 || end < 0)) {
20433 return new LazyWrapper(result);
20434 }
20435 if (start < 0) {
20436 result = result.takeRight(-start);
20437 } else if (start) {
20438 result = result.drop(start);
20439 }
20440 if (end !== undefined) {
20441 end = (+end || 0);
20442 result = end < 0 ? result.dropRight(-end) : result.take(end - start);
20443 }
20444 return result;
20445 };
20446
20447 LazyWrapper.prototype.takeRightWhile = function(predicate, thisArg) {
20448 return this.reverse().takeWhile(predicate, thisArg).reverse();
20449 };
20450
20451 LazyWrapper.prototype.toArray = function() {
20452 return this.take(POSITIVE_INFINITY);
20453 };
20454
20455 // Add `LazyWrapper` methods to `lodash.prototype`.
20456 baseForOwn(LazyWrapper.prototype, function(func, methodName) {
20457 var checkIteratee = /^(?:filter|map|reject)|While$/.test(methodName),
20458 retUnwrapped = /^(?:first|last)$/.test(methodName),
20459 lodashFunc = lodash[retUnwrapped ? ('take' + (methodName == 'last' ? 'Right' : '')) : methodName];
20460
20461 if (!lodashFunc) {
20462 return;
20463 }
20464 lodash.prototype[methodName] = function() {
20465 var args = retUnwrapped ? [1] : arguments,
20466 chainAll = this.__chain__,
20467 value = this.__wrapped__,
20468 isHybrid = !!this.__actions__.length,
20469 isLazy = value instanceof LazyWrapper,
20470 iteratee = args[0],
20471 useLazy = isLazy || isArray(value);
20472
20473 if (useLazy && checkIteratee && typeof iteratee == 'function' && iteratee.length != 1) {
20474 // Avoid lazy use if the iteratee has a "length" value other than `1`.
20475 isLazy = useLazy = false;
20476 }
20477 var interceptor = function(value) {
20478 return (retUnwrapped && chainAll)
20479 ? lodashFunc(value, 1)[0]
20480 : lodashFunc.apply(undefined, arrayPush([value], args));
20481 };
20482
20483 var action = { 'func': thru, 'args': [interceptor], 'thisArg': undefined },
20484 onlyLazy = isLazy && !isHybrid;
20485
20486 if (retUnwrapped && !chainAll) {
20487 if (onlyLazy) {
20488 value = value.clone();
20489 value.__actions__.push(action);
20490 return func.call(value);
20491 }
20492 return lodashFunc.call(undefined, this.value())[0];
20493 }
20494 if (!retUnwrapped && useLazy) {
20495 value = onlyLazy ? value : new LazyWrapper(this);
20496 var result = func.apply(value, args);
20497 result.__actions__.push(action);
20498 return new LodashWrapper(result, chainAll);
20499 }
20500 return this.thru(interceptor);
20501 };
20502 });
20503
20504 // Add `Array` and `String` methods to `lodash.prototype`.
20505 arrayEach(['join', 'pop', 'push', 'replace', 'shift', 'sort', 'splice', 'split', 'unshift'], function(methodName) {
20506 var func = (/^(?:replace|split)$/.test(methodName) ? stringProto : arrayProto)[methodName],
20507 chainName = /^(?:push|sort|unshift)$/.test(methodName) ? 'tap' : 'thru',
20508 retUnwrapped = /^(?:join|pop|replace|shift)$/.test(methodName);
20509
20510 lodash.prototype[methodName] = function() {
20511 var args = arguments;
20512 if (retUnwrapped && !this.__chain__) {
20513 return func.apply(this.value(), args);
20514 }
20515 return this[chainName](function(value) {
20516 return func.apply(value, args);
20517 });
20518 };
20519 });
20520
20521 // Map minified function names to their real names.
20522 baseForOwn(LazyWrapper.prototype, function(func, methodName) {
20523 var lodashFunc = lodash[methodName];
20524 if (lodashFunc) {
20525 var key = lodashFunc.name,
20526 names = realNames[key] || (realNames[key] = []);
20527
20528 names.push({ 'name': methodName, 'func': lodashFunc });
20529 }
20530 });
20531
20532 realNames[createHybridWrapper(undefined, BIND_KEY_FLAG).name] = [{ 'name': 'wrapper', 'func': undefined }];
20533
20534 // Add functions to the lazy wrapper.
20535 LazyWrapper.prototype.clone = lazyClone;
20536 LazyWrapper.prototype.reverse = lazyReverse;
20537 LazyWrapper.prototype.value = lazyValue;
20538
20539 // Add chaining functions to the `lodash` wrapper.
20540 lodash.prototype.chain = wrapperChain;
20541 lodash.prototype.commit = wrapperCommit;
20542 lodash.prototype.concat = wrapperConcat;
20543 lodash.prototype.plant = wrapperPlant;
20544 lodash.prototype.reverse = wrapperReverse;
20545 lodash.prototype.toString = wrapperToString;
20546 lodash.prototype.run = lodash.prototype.toJSON = lodash.prototype.valueOf = lodash.prototype.value = wrapperValue;
20547
20548 // Add function aliases to the `lodash` wrapper.
20549 lodash.prototype.collect = lodash.prototype.map;
20550 lodash.prototype.head = lodash.prototype.first;
20551 lodash.prototype.select = lodash.prototype.filter;
20552 lodash.prototype.tail = lodash.prototype.rest;
20553
20554 return lodash;
20555 }
20556
20557 /*--------------------------------------------------------------------------*/
20558
20559 // Export lodash.
20560 var _ = runInContext();
20561
20562 // Some AMD build optimizers like r.js check for condition patterns like the following:
20563 if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) {
20564 // Expose lodash to the global object when an AMD loader is present to avoid
20565 // errors in cases where lodash is loaded by a script tag and not intended
20566 // as an AMD module. See http://requirejs.org/docs/errors.html#mismatch for
20567 // more details.
20568 root._ = _;
20569
20570 // Define as an anonymous module so, through path mapping, it can be
20571 // referenced as the "underscore" module.
20572 define(function() {
20573 return _;
20574 });
20575 }
20576 // Check for `exports` after `define` in case a build optimizer adds an `exports` object.
20577 else if (freeExports && freeModule) {
20578 // Export for Node.js or RingoJS.
20579 if (moduleExports) {
20580 (freeModule.exports = _)._ = _;
20581 }
20582 // Export for Rhino with CommonJS support.
20583 else {
20584 freeExports._ = _;
20585 }
20586 }
20587 else {
20588 // Export for a browser or Rhino.
20589 root._ = _;
20590 }
20591}.call(this));
20592
20593}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
20594},{}],"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/lib/index.js":[function(require,module,exports){
20595
20596/**
20597 * Module dependencies.
20598 */
20599
20600var url = require('./url');
20601var parser = require('socket.io-parser');
20602var Manager = require('./manager');
20603var debug = require('debug')('socket.io-client');
20604
20605/**
20606 * Module exports.
20607 */
20608
20609module.exports = exports = lookup;
20610
20611/**
20612 * Managers cache.
20613 */
20614
20615var cache = exports.managers = {};
20616
20617/**
20618 * Looks up an existing `Manager` for multiplexing.
20619 * If the user summons:
20620 *
20621 * `io('http://localhost/a');`
20622 * `io('http://localhost/b');`
20623 *
20624 * We reuse the existing instance based on same scheme/port/host,
20625 * and we initialize sockets for each namespace.
20626 *
20627 * @api public
20628 */
20629
20630function lookup(uri, opts) {
20631 if (typeof uri == 'object') {
20632 opts = uri;
20633 uri = undefined;
20634 }
20635
20636 opts = opts || {};
20637
20638 var parsed = url(uri);
20639 var source = parsed.source;
20640 var id = parsed.id;
20641 var path = parsed.path;
20642 var sameNamespace = cache[id] && path in cache[id].nsps;
20643 var newConnection = opts.forceNew || opts['force new connection'] ||
20644 false === opts.multiplex || sameNamespace;
20645
20646 var io;
20647
20648 if (newConnection) {
20649 debug('ignoring socket cache for %s', source);
20650 io = Manager(source, opts);
20651 } else {
20652 if (!cache[id]) {
20653 debug('new io instance for %s', source);
20654 cache[id] = Manager(source, opts);
20655 }
20656 io = cache[id];
20657 }
20658
20659 return io.socket(parsed.path);
20660}
20661
20662/**
20663 * Protocol version.
20664 *
20665 * @api public
20666 */
20667
20668exports.protocol = parser.protocol;
20669
20670/**
20671 * `connect`.
20672 *
20673 * @param {String} uri
20674 * @api public
20675 */
20676
20677exports.connect = lookup;
20678
20679/**
20680 * Expose constructors for standalone build.
20681 *
20682 * @api public
20683 */
20684
20685exports.Manager = require('./manager');
20686exports.Socket = require('./socket');
20687
20688},{"./manager":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/lib/manager.js","./socket":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/lib/socket.js","./url":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/lib/url.js","debug":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/debug/browser.js","socket.io-parser":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/socket.io-parser/index.js"}],"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/lib/manager.js":[function(require,module,exports){
20689
20690/**
20691 * Module dependencies.
20692 */
20693
20694var eio = require('engine.io-client');
20695var Socket = require('./socket');
20696var Emitter = require('component-emitter');
20697var parser = require('socket.io-parser');
20698var on = require('./on');
20699var bind = require('component-bind');
20700var debug = require('debug')('socket.io-client:manager');
20701var indexOf = require('indexof');
20702var Backoff = require('backo2');
20703
20704/**
20705 * IE6+ hasOwnProperty
20706 */
20707
20708var has = Object.prototype.hasOwnProperty;
20709
20710/**
20711 * Module exports
20712 */
20713
20714module.exports = Manager;
20715
20716/**
20717 * `Manager` constructor.
20718 *
20719 * @param {String} engine instance or engine uri/opts
20720 * @param {Object} options
20721 * @api public
20722 */
20723
20724function Manager(uri, opts){
20725 if (!(this instanceof Manager)) return new Manager(uri, opts);
20726 if (uri && ('object' == typeof uri)) {
20727 opts = uri;
20728 uri = undefined;
20729 }
20730 opts = opts || {};
20731
20732 opts.path = opts.path || '/socket.io';
20733 this.nsps = {};
20734 this.subs = [];
20735 this.opts = opts;
20736 this.reconnection(opts.reconnection !== false);
20737 this.reconnectionAttempts(opts.reconnectionAttempts || Infinity);
20738 this.reconnectionDelay(opts.reconnectionDelay || 1000);
20739 this.reconnectionDelayMax(opts.reconnectionDelayMax || 5000);
20740 this.randomizationFactor(opts.randomizationFactor || 0.5);
20741 this.backoff = new Backoff({
20742 min: this.reconnectionDelay(),
20743 max: this.reconnectionDelayMax(),
20744 jitter: this.randomizationFactor()
20745 });
20746 this.timeout(null == opts.timeout ? 20000 : opts.timeout);
20747 this.readyState = 'closed';
20748 this.uri = uri;
20749 this.connecting = [];
20750 this.lastPing = null;
20751 this.encoding = false;
20752 this.packetBuffer = [];
20753 this.encoder = new parser.Encoder();
20754 this.decoder = new parser.Decoder();
20755 this.autoConnect = opts.autoConnect !== false;
20756 if (this.autoConnect) this.open();
20757}
20758
20759/**
20760 * Propagate given event to sockets and emit on `this`
20761 *
20762 * @api private
20763 */
20764
20765Manager.prototype.emitAll = function() {
20766 this.emit.apply(this, arguments);
20767 for (var nsp in this.nsps) {
20768 if (has.call(this.nsps, nsp)) {
20769 this.nsps[nsp].emit.apply(this.nsps[nsp], arguments);
20770 }
20771 }
20772};
20773
20774/**
20775 * Update `socket.id` of all sockets
20776 *
20777 * @api private
20778 */
20779
20780Manager.prototype.updateSocketIds = function(){
20781 for (var nsp in this.nsps) {
20782 if (has.call(this.nsps, nsp)) {
20783 this.nsps[nsp].id = this.engine.id;
20784 }
20785 }
20786};
20787
20788/**
20789 * Mix in `Emitter`.
20790 */
20791
20792Emitter(Manager.prototype);
20793
20794/**
20795 * Sets the `reconnection` config.
20796 *
20797 * @param {Boolean} true/false if it should automatically reconnect
20798 * @return {Manager} self or value
20799 * @api public
20800 */
20801
20802Manager.prototype.reconnection = function(v){
20803 if (!arguments.length) return this._reconnection;
20804 this._reconnection = !!v;
20805 return this;
20806};
20807
20808/**
20809 * Sets the reconnection attempts config.
20810 *
20811 * @param {Number} max reconnection attempts before giving up
20812 * @return {Manager} self or value
20813 * @api public
20814 */
20815
20816Manager.prototype.reconnectionAttempts = function(v){
20817 if (!arguments.length) return this._reconnectionAttempts;
20818 this._reconnectionAttempts = v;
20819 return this;
20820};
20821
20822/**
20823 * Sets the delay between reconnections.
20824 *
20825 * @param {Number} delay
20826 * @return {Manager} self or value
20827 * @api public
20828 */
20829
20830Manager.prototype.reconnectionDelay = function(v){
20831 if (!arguments.length) return this._reconnectionDelay;
20832 this._reconnectionDelay = v;
20833 this.backoff && this.backoff.setMin(v);
20834 return this;
20835};
20836
20837Manager.prototype.randomizationFactor = function(v){
20838 if (!arguments.length) return this._randomizationFactor;
20839 this._randomizationFactor = v;
20840 this.backoff && this.backoff.setJitter(v);
20841 return this;
20842};
20843
20844/**
20845 * Sets the maximum delay between reconnections.
20846 *
20847 * @param {Number} delay
20848 * @return {Manager} self or value
20849 * @api public
20850 */
20851
20852Manager.prototype.reconnectionDelayMax = function(v){
20853 if (!arguments.length) return this._reconnectionDelayMax;
20854 this._reconnectionDelayMax = v;
20855 this.backoff && this.backoff.setMax(v);
20856 return this;
20857};
20858
20859/**
20860 * Sets the connection timeout. `false` to disable
20861 *
20862 * @return {Manager} self or value
20863 * @api public
20864 */
20865
20866Manager.prototype.timeout = function(v){
20867 if (!arguments.length) return this._timeout;
20868 this._timeout = v;
20869 return this;
20870};
20871
20872/**
20873 * Starts trying to reconnect if reconnection is enabled and we have not
20874 * started reconnecting yet
20875 *
20876 * @api private
20877 */
20878
20879Manager.prototype.maybeReconnectOnOpen = function() {
20880 // Only try to reconnect if it's the first time we're connecting
20881 if (!this.reconnecting && this._reconnection && this.backoff.attempts === 0) {
20882 // keeps reconnection from firing twice for the same reconnection loop
20883 this.reconnect();
20884 }
20885};
20886
20887
20888/**
20889 * Sets the current transport `socket`.
20890 *
20891 * @param {Function} optional, callback
20892 * @return {Manager} self
20893 * @api public
20894 */
20895
20896Manager.prototype.open =
20897Manager.prototype.connect = function(fn){
20898 debug('readyState %s', this.readyState);
20899 if (~this.readyState.indexOf('open')) return this;
20900
20901 debug('opening %s', this.uri);
20902 this.engine = eio(this.uri, this.opts);
20903 var socket = this.engine;
20904 var self = this;
20905 this.readyState = 'opening';
20906 this.skipReconnect = false;
20907
20908 // emit `open`
20909 var openSub = on(socket, 'open', function() {
20910 self.onopen();
20911 fn && fn();
20912 });
20913
20914 // emit `connect_error`
20915 var errorSub = on(socket, 'error', function(data){
20916 debug('connect_error');
20917 self.cleanup();
20918 self.readyState = 'closed';
20919 self.emitAll('connect_error', data);
20920 if (fn) {
20921 var err = new Error('Connection error');
20922 err.data = data;
20923 fn(err);
20924 } else {
20925 // Only do this if there is no fn to handle the error
20926 self.maybeReconnectOnOpen();
20927 }
20928 });
20929
20930 // emit `connect_timeout`
20931 if (false !== this._timeout) {
20932 var timeout = this._timeout;
20933 debug('connect attempt will timeout after %d', timeout);
20934
20935 // set timer
20936 var timer = setTimeout(function(){
20937 debug('connect attempt timed out after %d', timeout);
20938 openSub.destroy();
20939 socket.close();
20940 socket.emit('error', 'timeout');
20941 self.emitAll('connect_timeout', timeout);
20942 }, timeout);
20943
20944 this.subs.push({
20945 destroy: function(){
20946 clearTimeout(timer);
20947 }
20948 });
20949 }
20950
20951 this.subs.push(openSub);
20952 this.subs.push(errorSub);
20953
20954 return this;
20955};
20956
20957/**
20958 * Called upon transport open.
20959 *
20960 * @api private
20961 */
20962
20963Manager.prototype.onopen = function(){
20964 debug('open');
20965
20966 // clear old subs
20967 this.cleanup();
20968
20969 // mark as open
20970 this.readyState = 'open';
20971 this.emit('open');
20972
20973 // add new subs
20974 var socket = this.engine;
20975 this.subs.push(on(socket, 'data', bind(this, 'ondata')));
20976 this.subs.push(on(socket, 'ping', bind(this, 'onping')));
20977 this.subs.push(on(socket, 'pong', bind(this, 'onpong')));
20978 this.subs.push(on(socket, 'error', bind(this, 'onerror')));
20979 this.subs.push(on(socket, 'close', bind(this, 'onclose')));
20980 this.subs.push(on(this.decoder, 'decoded', bind(this, 'ondecoded')));
20981};
20982
20983/**
20984 * Called upon a ping.
20985 *
20986 * @api private
20987 */
20988
20989Manager.prototype.onping = function(){
20990 this.lastPing = new Date;
20991 this.emitAll('ping');
20992};
20993
20994/**
20995 * Called upon a packet.
20996 *
20997 * @api private
20998 */
20999
21000Manager.prototype.onpong = function(){
21001 this.emitAll('pong', new Date - this.lastPing);
21002};
21003
21004/**
21005 * Called with data.
21006 *
21007 * @api private
21008 */
21009
21010Manager.prototype.ondata = function(data){
21011 this.decoder.add(data);
21012};
21013
21014/**
21015 * Called when parser fully decodes a packet.
21016 *
21017 * @api private
21018 */
21019
21020Manager.prototype.ondecoded = function(packet) {
21021 this.emit('packet', packet);
21022};
21023
21024/**
21025 * Called upon socket error.
21026 *
21027 * @api private
21028 */
21029
21030Manager.prototype.onerror = function(err){
21031 debug('error', err);
21032 this.emitAll('error', err);
21033};
21034
21035/**
21036 * Creates a new socket for the given `nsp`.
21037 *
21038 * @return {Socket}
21039 * @api public
21040 */
21041
21042Manager.prototype.socket = function(nsp){
21043 var socket = this.nsps[nsp];
21044 if (!socket) {
21045 socket = new Socket(this, nsp);
21046 this.nsps[nsp] = socket;
21047 var self = this;
21048 socket.on('connecting', onConnecting);
21049 socket.on('connect', function(){
21050 socket.id = self.engine.id;
21051 });
21052
21053 if (this.autoConnect) {
21054 // manually call here since connecting evnet is fired before listening
21055 onConnecting();
21056 }
21057 }
21058
21059 function onConnecting() {
21060 if (!~indexOf(self.connecting, socket)) {
21061 self.connecting.push(socket);
21062 }
21063 }
21064
21065 return socket;
21066};
21067
21068/**
21069 * Called upon a socket close.
21070 *
21071 * @param {Socket} socket
21072 */
21073
21074Manager.prototype.destroy = function(socket){
21075 var index = indexOf(this.connecting, socket);
21076 if (~index) this.connecting.splice(index, 1);
21077 if (this.connecting.length) return;
21078
21079 this.close();
21080};
21081
21082/**
21083 * Writes a packet.
21084 *
21085 * @param {Object} packet
21086 * @api private
21087 */
21088
21089Manager.prototype.packet = function(packet){
21090 debug('writing packet %j', packet);
21091 var self = this;
21092
21093 if (!self.encoding) {
21094 // encode, then write to engine with result
21095 self.encoding = true;
21096 this.encoder.encode(packet, function(encodedPackets) {
21097 for (var i = 0; i < encodedPackets.length; i++) {
21098 self.engine.write(encodedPackets[i], packet.options);
21099 }
21100 self.encoding = false;
21101 self.processPacketQueue();
21102 });
21103 } else { // add packet to the queue
21104 self.packetBuffer.push(packet);
21105 }
21106};
21107
21108/**
21109 * If packet buffer is non-empty, begins encoding the
21110 * next packet in line.
21111 *
21112 * @api private
21113 */
21114
21115Manager.prototype.processPacketQueue = function() {
21116 if (this.packetBuffer.length > 0 && !this.encoding) {
21117 var pack = this.packetBuffer.shift();
21118 this.packet(pack);
21119 }
21120};
21121
21122/**
21123 * Clean up transport subscriptions and packet buffer.
21124 *
21125 * @api private
21126 */
21127
21128Manager.prototype.cleanup = function(){
21129 debug('cleanup');
21130
21131 var sub;
21132 while (sub = this.subs.shift()) sub.destroy();
21133
21134 this.packetBuffer = [];
21135 this.encoding = false;
21136 this.lastPing = null;
21137
21138 this.decoder.destroy();
21139};
21140
21141/**
21142 * Close the current socket.
21143 *
21144 * @api private
21145 */
21146
21147Manager.prototype.close =
21148Manager.prototype.disconnect = function(){
21149 debug('disconnect');
21150 this.skipReconnect = true;
21151 this.reconnecting = false;
21152 if ('opening' == this.readyState) {
21153 // `onclose` will not fire because
21154 // an open event never happened
21155 this.cleanup();
21156 }
21157 this.backoff.reset();
21158 this.readyState = 'closed';
21159 if (this.engine) this.engine.close();
21160};
21161
21162/**
21163 * Called upon engine close.
21164 *
21165 * @api private
21166 */
21167
21168Manager.prototype.onclose = function(reason){
21169 debug('onclose');
21170
21171 this.cleanup();
21172 this.backoff.reset();
21173 this.readyState = 'closed';
21174 this.emit('close', reason);
21175
21176 if (this._reconnection && !this.skipReconnect) {
21177 this.reconnect();
21178 }
21179};
21180
21181/**
21182 * Attempt a reconnection.
21183 *
21184 * @api private
21185 */
21186
21187Manager.prototype.reconnect = function(){
21188 if (this.reconnecting || this.skipReconnect) return this;
21189
21190 var self = this;
21191
21192 if (this.backoff.attempts >= this._reconnectionAttempts) {
21193 debug('reconnect failed');
21194 this.backoff.reset();
21195 this.emitAll('reconnect_failed');
21196 this.reconnecting = false;
21197 } else {
21198 var delay = this.backoff.duration();
21199 debug('will wait %dms before reconnect attempt', delay);
21200
21201 this.reconnecting = true;
21202 var timer = setTimeout(function(){
21203 if (self.skipReconnect) return;
21204
21205 debug('attempting reconnect');
21206 self.emitAll('reconnect_attempt', self.backoff.attempts);
21207 self.emitAll('reconnecting', self.backoff.attempts);
21208
21209 // check again for the case socket closed in above events
21210 if (self.skipReconnect) return;
21211
21212 self.open(function(err){
21213 if (err) {
21214 debug('reconnect attempt error');
21215 self.reconnecting = false;
21216 self.reconnect();
21217 self.emitAll('reconnect_error', err.data);
21218 } else {
21219 debug('reconnect success');
21220 self.onreconnect();
21221 }
21222 });
21223 }, delay);
21224
21225 this.subs.push({
21226 destroy: function(){
21227 clearTimeout(timer);
21228 }
21229 });
21230 }
21231};
21232
21233/**
21234 * Called upon successful reconnect.
21235 *
21236 * @api private
21237 */
21238
21239Manager.prototype.onreconnect = function(){
21240 var attempt = this.backoff.attempts;
21241 this.reconnecting = false;
21242 this.backoff.reset();
21243 this.updateSocketIds();
21244 this.emitAll('reconnect', attempt);
21245};
21246
21247},{"./on":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/lib/on.js","./socket":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/lib/socket.js","backo2":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/backo2/index.js","component-bind":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/component-bind/index.js","component-emitter":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/component-emitter/index.js","debug":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/debug/browser.js","engine.io-client":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/index.js","indexof":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/indexof/index.js","socket.io-parser":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/socket.io-parser/index.js"}],"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/lib/on.js":[function(require,module,exports){
21248
21249/**
21250 * Module exports.
21251 */
21252
21253module.exports = on;
21254
21255/**
21256 * Helper for subscriptions.
21257 *
21258 * @param {Object|EventEmitter} obj with `Emitter` mixin or `EventEmitter`
21259 * @param {String} event name
21260 * @param {Function} callback
21261 * @api public
21262 */
21263
21264function on(obj, ev, fn) {
21265 obj.on(ev, fn);
21266 return {
21267 destroy: function(){
21268 obj.removeListener(ev, fn);
21269 }
21270 };
21271}
21272
21273},{}],"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/lib/socket.js":[function(require,module,exports){
21274
21275/**
21276 * Module dependencies.
21277 */
21278
21279var parser = require('socket.io-parser');
21280var Emitter = require('component-emitter');
21281var toArray = require('to-array');
21282var on = require('./on');
21283var bind = require('component-bind');
21284var debug = require('debug')('socket.io-client:socket');
21285var hasBin = require('has-binary');
21286
21287/**
21288 * Module exports.
21289 */
21290
21291module.exports = exports = Socket;
21292
21293/**
21294 * Internal events (blacklisted).
21295 * These events can't be emitted by the user.
21296 *
21297 * @api private
21298 */
21299
21300var events = {
21301 connect: 1,
21302 connect_error: 1,
21303 connect_timeout: 1,
21304 connecting: 1,
21305 disconnect: 1,
21306 error: 1,
21307 reconnect: 1,
21308 reconnect_attempt: 1,
21309 reconnect_failed: 1,
21310 reconnect_error: 1,
21311 reconnecting: 1,
21312 ping: 1,
21313 pong: 1
21314};
21315
21316/**
21317 * Shortcut to `Emitter#emit`.
21318 */
21319
21320var emit = Emitter.prototype.emit;
21321
21322/**
21323 * `Socket` constructor.
21324 *
21325 * @api public
21326 */
21327
21328function Socket(io, nsp){
21329 this.io = io;
21330 this.nsp = nsp;
21331 this.json = this; // compat
21332 this.ids = 0;
21333 this.acks = {};
21334 this.receiveBuffer = [];
21335 this.sendBuffer = [];
21336 this.connected = false;
21337 this.disconnected = true;
21338 if (this.io.autoConnect) this.open();
21339}
21340
21341/**
21342 * Mix in `Emitter`.
21343 */
21344
21345Emitter(Socket.prototype);
21346
21347/**
21348 * Subscribe to open, close and packet events
21349 *
21350 * @api private
21351 */
21352
21353Socket.prototype.subEvents = function() {
21354 if (this.subs) return;
21355
21356 var io = this.io;
21357 this.subs = [
21358 on(io, 'open', bind(this, 'onopen')),
21359 on(io, 'packet', bind(this, 'onpacket')),
21360 on(io, 'close', bind(this, 'onclose'))
21361 ];
21362};
21363
21364/**
21365 * "Opens" the socket.
21366 *
21367 * @api public
21368 */
21369
21370Socket.prototype.open =
21371Socket.prototype.connect = function(){
21372 if (this.connected) return this;
21373
21374 this.subEvents();
21375 this.io.open(); // ensure open
21376 if ('open' == this.io.readyState) this.onopen();
21377 this.emit('connecting');
21378 return this;
21379};
21380
21381/**
21382 * Sends a `message` event.
21383 *
21384 * @return {Socket} self
21385 * @api public
21386 */
21387
21388Socket.prototype.send = function(){
21389 var args = toArray(arguments);
21390 args.unshift('message');
21391 this.emit.apply(this, args);
21392 return this;
21393};
21394
21395/**
21396 * Override `emit`.
21397 * If the event is in `events`, it's emitted normally.
21398 *
21399 * @param {String} event name
21400 * @return {Socket} self
21401 * @api public
21402 */
21403
21404Socket.prototype.emit = function(ev){
21405 if (events.hasOwnProperty(ev)) {
21406 emit.apply(this, arguments);
21407 return this;
21408 }
21409
21410 var args = toArray(arguments);
21411 var parserType = parser.EVENT; // default
21412 if (hasBin(args)) { parserType = parser.BINARY_EVENT; } // binary
21413 var packet = { type: parserType, data: args };
21414
21415 packet.options = {};
21416 packet.options.compress = !this.flags || false !== this.flags.compress;
21417
21418 // event ack callback
21419 if ('function' == typeof args[args.length - 1]) {
21420 debug('emitting packet with ack id %d', this.ids);
21421 this.acks[this.ids] = args.pop();
21422 packet.id = this.ids++;
21423 }
21424
21425 if (this.connected) {
21426 this.packet(packet);
21427 } else {
21428 this.sendBuffer.push(packet);
21429 }
21430
21431 delete this.flags;
21432
21433 return this;
21434};
21435
21436/**
21437 * Sends a packet.
21438 *
21439 * @param {Object} packet
21440 * @api private
21441 */
21442
21443Socket.prototype.packet = function(packet){
21444 packet.nsp = this.nsp;
21445 this.io.packet(packet);
21446};
21447
21448/**
21449 * Called upon engine `open`.
21450 *
21451 * @api private
21452 */
21453
21454Socket.prototype.onopen = function(){
21455 debug('transport is open - connecting');
21456
21457 // write connect packet if necessary
21458 if ('/' != this.nsp) {
21459 this.packet({ type: parser.CONNECT });
21460 }
21461};
21462
21463/**
21464 * Called upon engine `close`.
21465 *
21466 * @param {String} reason
21467 * @api private
21468 */
21469
21470Socket.prototype.onclose = function(reason){
21471 debug('close (%s)', reason);
21472 this.connected = false;
21473 this.disconnected = true;
21474 delete this.id;
21475 this.emit('disconnect', reason);
21476};
21477
21478/**
21479 * Called with socket packet.
21480 *
21481 * @param {Object} packet
21482 * @api private
21483 */
21484
21485Socket.prototype.onpacket = function(packet){
21486 if (packet.nsp != this.nsp) return;
21487
21488 switch (packet.type) {
21489 case parser.CONNECT:
21490 this.onconnect();
21491 break;
21492
21493 case parser.EVENT:
21494 this.onevent(packet);
21495 break;
21496
21497 case parser.BINARY_EVENT:
21498 this.onevent(packet);
21499 break;
21500
21501 case parser.ACK:
21502 this.onack(packet);
21503 break;
21504
21505 case parser.BINARY_ACK:
21506 this.onack(packet);
21507 break;
21508
21509 case parser.DISCONNECT:
21510 this.ondisconnect();
21511 break;
21512
21513 case parser.ERROR:
21514 this.emit('error', packet.data);
21515 break;
21516 }
21517};
21518
21519/**
21520 * Called upon a server event.
21521 *
21522 * @param {Object} packet
21523 * @api private
21524 */
21525
21526Socket.prototype.onevent = function(packet){
21527 var args = packet.data || [];
21528 debug('emitting event %j', args);
21529
21530 if (null != packet.id) {
21531 debug('attaching ack callback to event');
21532 args.push(this.ack(packet.id));
21533 }
21534
21535 if (this.connected) {
21536 emit.apply(this, args);
21537 } else {
21538 this.receiveBuffer.push(args);
21539 }
21540};
21541
21542/**
21543 * Produces an ack callback to emit with an event.
21544 *
21545 * @api private
21546 */
21547
21548Socket.prototype.ack = function(id){
21549 var self = this;
21550 var sent = false;
21551 return function(){
21552 // prevent double callbacks
21553 if (sent) return;
21554 sent = true;
21555 var args = toArray(arguments);
21556 debug('sending ack %j', args);
21557
21558 var type = hasBin(args) ? parser.BINARY_ACK : parser.ACK;
21559 self.packet({
21560 type: type,
21561 id: id,
21562 data: args
21563 });
21564 };
21565};
21566
21567/**
21568 * Called upon a server acknowlegement.
21569 *
21570 * @param {Object} packet
21571 * @api private
21572 */
21573
21574Socket.prototype.onack = function(packet){
21575 var ack = this.acks[packet.id];
21576 if ('function' == typeof ack) {
21577 debug('calling ack %s with %j', packet.id, packet.data);
21578 ack.apply(this, packet.data);
21579 delete this.acks[packet.id];
21580 } else {
21581 debug('bad ack %s', packet.id);
21582 }
21583};
21584
21585/**
21586 * Called upon server connect.
21587 *
21588 * @api private
21589 */
21590
21591Socket.prototype.onconnect = function(){
21592 this.connected = true;
21593 this.disconnected = false;
21594 this.emit('connect');
21595 this.emitBuffered();
21596};
21597
21598/**
21599 * Emit buffered events (received and emitted).
21600 *
21601 * @api private
21602 */
21603
21604Socket.prototype.emitBuffered = function(){
21605 var i;
21606 for (i = 0; i < this.receiveBuffer.length; i++) {
21607 emit.apply(this, this.receiveBuffer[i]);
21608 }
21609 this.receiveBuffer = [];
21610
21611 for (i = 0; i < this.sendBuffer.length; i++) {
21612 this.packet(this.sendBuffer[i]);
21613 }
21614 this.sendBuffer = [];
21615};
21616
21617/**
21618 * Called upon server disconnect.
21619 *
21620 * @api private
21621 */
21622
21623Socket.prototype.ondisconnect = function(){
21624 debug('server disconnect (%s)', this.nsp);
21625 this.destroy();
21626 this.onclose('io server disconnect');
21627};
21628
21629/**
21630 * Called upon forced client/server side disconnections,
21631 * this method ensures the manager stops tracking us and
21632 * that reconnections don't get triggered for this.
21633 *
21634 * @api private.
21635 */
21636
21637Socket.prototype.destroy = function(){
21638 if (this.subs) {
21639 // clean subscriptions to avoid reconnections
21640 for (var i = 0; i < this.subs.length; i++) {
21641 this.subs[i].destroy();
21642 }
21643 this.subs = null;
21644 }
21645
21646 this.io.destroy(this);
21647};
21648
21649/**
21650 * Disconnects the socket manually.
21651 *
21652 * @return {Socket} self
21653 * @api public
21654 */
21655
21656Socket.prototype.close =
21657Socket.prototype.disconnect = function(){
21658 if (this.connected) {
21659 debug('performing disconnect (%s)', this.nsp);
21660 this.packet({ type: parser.DISCONNECT });
21661 }
21662
21663 // remove socket from pool
21664 this.destroy();
21665
21666 if (this.connected) {
21667 // fire events
21668 this.onclose('io client disconnect');
21669 }
21670 return this;
21671};
21672
21673/**
21674 * Sets the compress flag.
21675 *
21676 * @param {Boolean} if `true`, compresses the sending data
21677 * @return {Socket} self
21678 * @api public
21679 */
21680
21681Socket.prototype.compress = function(compress){
21682 this.flags = this.flags || {};
21683 this.flags.compress = compress;
21684 return this;
21685};
21686
21687},{"./on":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/lib/on.js","component-bind":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/component-bind/index.js","component-emitter":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/component-emitter/index.js","debug":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/debug/browser.js","has-binary":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/has-binary/index.js","socket.io-parser":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/socket.io-parser/index.js","to-array":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/to-array/index.js"}],"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/lib/url.js":[function(require,module,exports){
21688(function (global){
21689
21690/**
21691 * Module dependencies.
21692 */
21693
21694var parseuri = require('parseuri');
21695var debug = require('debug')('socket.io-client:url');
21696
21697/**
21698 * Module exports.
21699 */
21700
21701module.exports = url;
21702
21703/**
21704 * URL parser.
21705 *
21706 * @param {String} url
21707 * @param {Object} An object meant to mimic window.location.
21708 * Defaults to window.location.
21709 * @api public
21710 */
21711
21712function url(uri, loc){
21713 var obj = uri;
21714
21715 // default to window.location
21716 var loc = loc || global.location;
21717 if (null == uri) uri = loc.protocol + '//' + loc.host;
21718
21719 // relative path support
21720 if ('string' == typeof uri) {
21721 if ('/' == uri.charAt(0)) {
21722 if ('/' == uri.charAt(1)) {
21723 uri = loc.protocol + uri;
21724 } else {
21725 uri = loc.host + uri;
21726 }
21727 }
21728
21729 if (!/^(https?|wss?):\/\//.test(uri)) {
21730 debug('protocol-less url %s', uri);
21731 if ('undefined' != typeof loc) {
21732 uri = loc.protocol + '//' + uri;
21733 } else {
21734 uri = 'https://' + uri;
21735 }
21736 }
21737
21738 // parse
21739 debug('parse %s', uri);
21740 obj = parseuri(uri);
21741 }
21742
21743 // make sure we treat `localhost:80` and `localhost` equally
21744 if (!obj.port) {
21745 if (/^(http|ws)$/.test(obj.protocol)) {
21746 obj.port = '80';
21747 }
21748 else if (/^(http|ws)s$/.test(obj.protocol)) {
21749 obj.port = '443';
21750 }
21751 }
21752
21753 obj.path = obj.path || '/';
21754
21755 var ipv6 = obj.host.indexOf(':') !== -1;
21756 var host = ipv6 ? '[' + obj.host + ']' : obj.host;
21757
21758 // define unique id
21759 obj.id = obj.protocol + '://' + host + ':' + obj.port;
21760 // define href
21761 obj.href = obj.protocol + '://' + host + (loc && loc.port == obj.port ? '' : (':' + obj.port));
21762
21763 return obj;
21764}
21765
21766}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
21767},{"debug":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/debug/browser.js","parseuri":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/parseuri/index.js"}],"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/backo2/index.js":[function(require,module,exports){
21768
21769/**
21770 * Expose `Backoff`.
21771 */
21772
21773module.exports = Backoff;
21774
21775/**
21776 * Initialize backoff timer with `opts`.
21777 *
21778 * - `min` initial timeout in milliseconds [100]
21779 * - `max` max timeout [10000]
21780 * - `jitter` [0]
21781 * - `factor` [2]
21782 *
21783 * @param {Object} opts
21784 * @api public
21785 */
21786
21787function Backoff(opts) {
21788 opts = opts || {};
21789 this.ms = opts.min || 100;
21790 this.max = opts.max || 10000;
21791 this.factor = opts.factor || 2;
21792 this.jitter = opts.jitter > 0 && opts.jitter <= 1 ? opts.jitter : 0;
21793 this.attempts = 0;
21794}
21795
21796/**
21797 * Return the backoff duration.
21798 *
21799 * @return {Number}
21800 * @api public
21801 */
21802
21803Backoff.prototype.duration = function(){
21804 var ms = this.ms * Math.pow(this.factor, this.attempts++);
21805 if (this.jitter) {
21806 var rand = Math.random();
21807 var deviation = Math.floor(rand * this.jitter * ms);
21808 ms = (Math.floor(rand * 10) & 1) == 0 ? ms - deviation : ms + deviation;
21809 }
21810 return Math.min(ms, this.max) | 0;
21811};
21812
21813/**
21814 * Reset the number of attempts.
21815 *
21816 * @api public
21817 */
21818
21819Backoff.prototype.reset = function(){
21820 this.attempts = 0;
21821};
21822
21823/**
21824 * Set the minimum duration
21825 *
21826 * @api public
21827 */
21828
21829Backoff.prototype.setMin = function(min){
21830 this.ms = min;
21831};
21832
21833/**
21834 * Set the maximum duration
21835 *
21836 * @api public
21837 */
21838
21839Backoff.prototype.setMax = function(max){
21840 this.max = max;
21841};
21842
21843/**
21844 * Set the jitter
21845 *
21846 * @api public
21847 */
21848
21849Backoff.prototype.setJitter = function(jitter){
21850 this.jitter = jitter;
21851};
21852
21853
21854},{}],"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/component-bind/index.js":[function(require,module,exports){
21855/**
21856 * Slice reference.
21857 */
21858
21859var slice = [].slice;
21860
21861/**
21862 * Bind `obj` to `fn`.
21863 *
21864 * @param {Object} obj
21865 * @param {Function|String} fn or string
21866 * @return {Function}
21867 * @api public
21868 */
21869
21870module.exports = function(obj, fn){
21871 if ('string' == typeof fn) fn = obj[fn];
21872 if ('function' != typeof fn) throw new Error('bind() requires a function');
21873 var args = slice.call(arguments, 2);
21874 return function(){
21875 return fn.apply(obj, args.concat(slice.call(arguments)));
21876 }
21877};
21878
21879},{}],"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/component-emitter/index.js":[function(require,module,exports){
21880
21881/**
21882 * Expose `Emitter`.
21883 */
21884
21885module.exports = Emitter;
21886
21887/**
21888 * Initialize a new `Emitter`.
21889 *
21890 * @api public
21891 */
21892
21893function Emitter(obj) {
21894 if (obj) return mixin(obj);
21895};
21896
21897/**
21898 * Mixin the emitter properties.
21899 *
21900 * @param {Object} obj
21901 * @return {Object}
21902 * @api private
21903 */
21904
21905function mixin(obj) {
21906 for (var key in Emitter.prototype) {
21907 obj[key] = Emitter.prototype[key];
21908 }
21909 return obj;
21910}
21911
21912/**
21913 * Listen on the given `event` with `fn`.
21914 *
21915 * @param {String} event
21916 * @param {Function} fn
21917 * @return {Emitter}
21918 * @api public
21919 */
21920
21921Emitter.prototype.on =
21922Emitter.prototype.addEventListener = function(event, fn){
21923 this._callbacks = this._callbacks || {};
21924 (this._callbacks['$' + event] = this._callbacks['$' + event] || [])
21925 .push(fn);
21926 return this;
21927};
21928
21929/**
21930 * Adds an `event` listener that will be invoked a single
21931 * time then automatically removed.
21932 *
21933 * @param {String} event
21934 * @param {Function} fn
21935 * @return {Emitter}
21936 * @api public
21937 */
21938
21939Emitter.prototype.once = function(event, fn){
21940 function on() {
21941 this.off(event, on);
21942 fn.apply(this, arguments);
21943 }
21944
21945 on.fn = fn;
21946 this.on(event, on);
21947 return this;
21948};
21949
21950/**
21951 * Remove the given callback for `event` or all
21952 * registered callbacks.
21953 *
21954 * @param {String} event
21955 * @param {Function} fn
21956 * @return {Emitter}
21957 * @api public
21958 */
21959
21960Emitter.prototype.off =
21961Emitter.prototype.removeListener =
21962Emitter.prototype.removeAllListeners =
21963Emitter.prototype.removeEventListener = function(event, fn){
21964 this._callbacks = this._callbacks || {};
21965
21966 // all
21967 if (0 == arguments.length) {
21968 this._callbacks = {};
21969 return this;
21970 }
21971
21972 // specific event
21973 var callbacks = this._callbacks['$' + event];
21974 if (!callbacks) return this;
21975
21976 // remove all handlers
21977 if (1 == arguments.length) {
21978 delete this._callbacks['$' + event];
21979 return this;
21980 }
21981
21982 // remove specific handler
21983 var cb;
21984 for (var i = 0; i < callbacks.length; i++) {
21985 cb = callbacks[i];
21986 if (cb === fn || cb.fn === fn) {
21987 callbacks.splice(i, 1);
21988 break;
21989 }
21990 }
21991 return this;
21992};
21993
21994/**
21995 * Emit `event` with the given args.
21996 *
21997 * @param {String} event
21998 * @param {Mixed} ...
21999 * @return {Emitter}
22000 */
22001
22002Emitter.prototype.emit = function(event){
22003 this._callbacks = this._callbacks || {};
22004 var args = [].slice.call(arguments, 1)
22005 , callbacks = this._callbacks['$' + event];
22006
22007 if (callbacks) {
22008 callbacks = callbacks.slice(0);
22009 for (var i = 0, len = callbacks.length; i < len; ++i) {
22010 callbacks[i].apply(this, args);
22011 }
22012 }
22013
22014 return this;
22015};
22016
22017/**
22018 * Return array of callbacks for `event`.
22019 *
22020 * @param {String} event
22021 * @return {Array}
22022 * @api public
22023 */
22024
22025Emitter.prototype.listeners = function(event){
22026 this._callbacks = this._callbacks || {};
22027 return this._callbacks['$' + event] || [];
22028};
22029
22030/**
22031 * Check if this emitter has `event` handlers.
22032 *
22033 * @param {String} event
22034 * @return {Boolean}
22035 * @api public
22036 */
22037
22038Emitter.prototype.hasListeners = function(event){
22039 return !! this.listeners(event).length;
22040};
22041
22042},{}],"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/debug/browser.js":[function(require,module,exports){
22043
22044/**
22045 * This is the web browser implementation of `debug()`.
22046 *
22047 * Expose `debug()` as the module.
22048 */
22049
22050exports = module.exports = require('./debug');
22051exports.log = log;
22052exports.formatArgs = formatArgs;
22053exports.save = save;
22054exports.load = load;
22055exports.useColors = useColors;
22056exports.storage = 'undefined' != typeof chrome
22057 && 'undefined' != typeof chrome.storage
22058 ? chrome.storage.local
22059 : localstorage();
22060
22061/**
22062 * Colors.
22063 */
22064
22065exports.colors = [
22066 'lightseagreen',
22067 'forestgreen',
22068 'goldenrod',
22069 'dodgerblue',
22070 'darkorchid',
22071 'crimson'
22072];
22073
22074/**
22075 * Currently only WebKit-based Web Inspectors, Firefox >= v31,
22076 * and the Firebug extension (any Firefox version) are known
22077 * to support "%c" CSS customizations.
22078 *
22079 * TODO: add a `localStorage` variable to explicitly enable/disable colors
22080 */
22081
22082function useColors() {
22083 // is webkit? http://stackoverflow.com/a/16459606/376773
22084 return ('WebkitAppearance' in document.documentElement.style) ||
22085 // is firebug? http://stackoverflow.com/a/398120/376773
22086 (window.console && (console.firebug || (console.exception && console.table))) ||
22087 // is firefox >= v31?
22088 // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
22089 (navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31);
22090}
22091
22092/**
22093 * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
22094 */
22095
22096exports.formatters.j = function(v) {
22097 return JSON.stringify(v);
22098};
22099
22100
22101/**
22102 * Colorize log arguments if enabled.
22103 *
22104 * @api public
22105 */
22106
22107function formatArgs() {
22108 var args = arguments;
22109 var useColors = this.useColors;
22110
22111 args[0] = (useColors ? '%c' : '')
22112 + this.namespace
22113 + (useColors ? ' %c' : ' ')
22114 + args[0]
22115 + (useColors ? '%c ' : ' ')
22116 + '+' + exports.humanize(this.diff);
22117
22118 if (!useColors) return args;
22119
22120 var c = 'color: ' + this.color;
22121 args = [args[0], c, 'color: inherit'].concat(Array.prototype.slice.call(args, 1));
22122
22123 // the final "%c" is somewhat tricky, because there could be other
22124 // arguments passed either before or after the %c, so we need to
22125 // figure out the correct index to insert the CSS into
22126 var index = 0;
22127 var lastC = 0;
22128 args[0].replace(/%[a-z%]/g, function(match) {
22129 if ('%%' === match) return;
22130 index++;
22131 if ('%c' === match) {
22132 // we only are interested in the *last* %c
22133 // (the user may have provided their own)
22134 lastC = index;
22135 }
22136 });
22137
22138 args.splice(lastC, 0, c);
22139 return args;
22140}
22141
22142/**
22143 * Invokes `console.log()` when available.
22144 * No-op when `console.log` is not a "function".
22145 *
22146 * @api public
22147 */
22148
22149function log() {
22150 // this hackery is required for IE8/9, where
22151 // the `console.log` function doesn't have 'apply'
22152 return 'object' === typeof console
22153 && console.log
22154 && Function.prototype.apply.call(console.log, console, arguments);
22155}
22156
22157/**
22158 * Save `namespaces`.
22159 *
22160 * @param {String} namespaces
22161 * @api private
22162 */
22163
22164function save(namespaces) {
22165 try {
22166 if (null == namespaces) {
22167 exports.storage.removeItem('debug');
22168 } else {
22169 exports.storage.debug = namespaces;
22170 }
22171 } catch(e) {}
22172}
22173
22174/**
22175 * Load `namespaces`.
22176 *
22177 * @return {String} returns the previously persisted debug modes
22178 * @api private
22179 */
22180
22181function load() {
22182 var r;
22183 try {
22184 r = exports.storage.debug;
22185 } catch(e) {}
22186 return r;
22187}
22188
22189/**
22190 * Enable namespaces listed in `localStorage.debug` initially.
22191 */
22192
22193exports.enable(load());
22194
22195/**
22196 * Localstorage attempts to return the localstorage.
22197 *
22198 * This is necessary because safari throws
22199 * when a user disables cookies/localstorage
22200 * and you attempt to access it.
22201 *
22202 * @return {LocalStorage}
22203 * @api private
22204 */
22205
22206function localstorage(){
22207 try {
22208 return window.localStorage;
22209 } catch (e) {}
22210}
22211
22212},{"./debug":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/debug/debug.js"}],"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/debug/debug.js":[function(require,module,exports){
22213
22214/**
22215 * This is the common logic for both the Node.js and web browser
22216 * implementations of `debug()`.
22217 *
22218 * Expose `debug()` as the module.
22219 */
22220
22221exports = module.exports = debug;
22222exports.coerce = coerce;
22223exports.disable = disable;
22224exports.enable = enable;
22225exports.enabled = enabled;
22226exports.humanize = require('ms');
22227
22228/**
22229 * The currently active debug mode names, and names to skip.
22230 */
22231
22232exports.names = [];
22233exports.skips = [];
22234
22235/**
22236 * Map of special "%n" handling functions, for the debug "format" argument.
22237 *
22238 * Valid key names are a single, lowercased letter, i.e. "n".
22239 */
22240
22241exports.formatters = {};
22242
22243/**
22244 * Previously assigned color.
22245 */
22246
22247var prevColor = 0;
22248
22249/**
22250 * Previous log timestamp.
22251 */
22252
22253var prevTime;
22254
22255/**
22256 * Select a color.
22257 *
22258 * @return {Number}
22259 * @api private
22260 */
22261
22262function selectColor() {
22263 return exports.colors[prevColor++ % exports.colors.length];
22264}
22265
22266/**
22267 * Create a debugger with the given `namespace`.
22268 *
22269 * @param {String} namespace
22270 * @return {Function}
22271 * @api public
22272 */
22273
22274function debug(namespace) {
22275
22276 // define the `disabled` version
22277 function disabled() {
22278 }
22279 disabled.enabled = false;
22280
22281 // define the `enabled` version
22282 function enabled() {
22283
22284 var self = enabled;
22285
22286 // set `diff` timestamp
22287 var curr = +new Date();
22288 var ms = curr - (prevTime || curr);
22289 self.diff = ms;
22290 self.prev = prevTime;
22291 self.curr = curr;
22292 prevTime = curr;
22293
22294 // add the `color` if not set
22295 if (null == self.useColors) self.useColors = exports.useColors();
22296 if (null == self.color && self.useColors) self.color = selectColor();
22297
22298 var args = Array.prototype.slice.call(arguments);
22299
22300 args[0] = exports.coerce(args[0]);
22301
22302 if ('string' !== typeof args[0]) {
22303 // anything else let's inspect with %o
22304 args = ['%o'].concat(args);
22305 }
22306
22307 // apply any `formatters` transformations
22308 var index = 0;
22309 args[0] = args[0].replace(/%([a-z%])/g, function(match, format) {
22310 // if we encounter an escaped % then don't increase the array index
22311 if (match === '%%') return match;
22312 index++;
22313 var formatter = exports.formatters[format];
22314 if ('function' === typeof formatter) {
22315 var val = args[index];
22316 match = formatter.call(self, val);
22317
22318 // now we need to remove `args[index]` since it's inlined in the `format`
22319 args.splice(index, 1);
22320 index--;
22321 }
22322 return match;
22323 });
22324
22325 if ('function' === typeof exports.formatArgs) {
22326 args = exports.formatArgs.apply(self, args);
22327 }
22328 var logFn = enabled.log || exports.log || console.log.bind(console);
22329 logFn.apply(self, args);
22330 }
22331 enabled.enabled = true;
22332
22333 var fn = exports.enabled(namespace) ? enabled : disabled;
22334
22335 fn.namespace = namespace;
22336
22337 return fn;
22338}
22339
22340/**
22341 * Enables a debug mode by namespaces. This can include modes
22342 * separated by a colon and wildcards.
22343 *
22344 * @param {String} namespaces
22345 * @api public
22346 */
22347
22348function enable(namespaces) {
22349 exports.save(namespaces);
22350
22351 var split = (namespaces || '').split(/[\s,]+/);
22352 var len = split.length;
22353
22354 for (var i = 0; i < len; i++) {
22355 if (!split[i]) continue; // ignore empty strings
22356 namespaces = split[i].replace(/\*/g, '.*?');
22357 if (namespaces[0] === '-') {
22358 exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
22359 } else {
22360 exports.names.push(new RegExp('^' + namespaces + '$'));
22361 }
22362 }
22363}
22364
22365/**
22366 * Disable debug output.
22367 *
22368 * @api public
22369 */
22370
22371function disable() {
22372 exports.enable('');
22373}
22374
22375/**
22376 * Returns true if the given mode name is enabled, false otherwise.
22377 *
22378 * @param {String} name
22379 * @return {Boolean}
22380 * @api public
22381 */
22382
22383function enabled(name) {
22384 var i, len;
22385 for (i = 0, len = exports.skips.length; i < len; i++) {
22386 if (exports.skips[i].test(name)) {
22387 return false;
22388 }
22389 }
22390 for (i = 0, len = exports.names.length; i < len; i++) {
22391 if (exports.names[i].test(name)) {
22392 return true;
22393 }
22394 }
22395 return false;
22396}
22397
22398/**
22399 * Coerce `val`.
22400 *
22401 * @param {Mixed} val
22402 * @return {Mixed}
22403 * @api private
22404 */
22405
22406function coerce(val) {
22407 if (val instanceof Error) return val.stack || val.message;
22408 return val;
22409}
22410
22411},{"ms":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/debug/node_modules/ms/index.js"}],"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/debug/node_modules/ms/index.js":[function(require,module,exports){
22412/**
22413 * Helpers.
22414 */
22415
22416var s = 1000;
22417var m = s * 60;
22418var h = m * 60;
22419var d = h * 24;
22420var y = d * 365.25;
22421
22422/**
22423 * Parse or format the given `val`.
22424 *
22425 * Options:
22426 *
22427 * - `long` verbose formatting [false]
22428 *
22429 * @param {String|Number} val
22430 * @param {Object} options
22431 * @return {String|Number}
22432 * @api public
22433 */
22434
22435module.exports = function(val, options){
22436 options = options || {};
22437 if ('string' == typeof val) return parse(val);
22438 return options.long
22439 ? long(val)
22440 : short(val);
22441};
22442
22443/**
22444 * Parse the given `str` and return milliseconds.
22445 *
22446 * @param {String} str
22447 * @return {Number}
22448 * @api private
22449 */
22450
22451function parse(str) {
22452 str = '' + str;
22453 if (str.length > 10000) return;
22454 var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(str);
22455 if (!match) return;
22456 var n = parseFloat(match[1]);
22457 var type = (match[2] || 'ms').toLowerCase();
22458 switch (type) {
22459 case 'years':
22460 case 'year':
22461 case 'yrs':
22462 case 'yr':
22463 case 'y':
22464 return n * y;
22465 case 'days':
22466 case 'day':
22467 case 'd':
22468 return n * d;
22469 case 'hours':
22470 case 'hour':
22471 case 'hrs':
22472 case 'hr':
22473 case 'h':
22474 return n * h;
22475 case 'minutes':
22476 case 'minute':
22477 case 'mins':
22478 case 'min':
22479 case 'm':
22480 return n * m;
22481 case 'seconds':
22482 case 'second':
22483 case 'secs':
22484 case 'sec':
22485 case 's':
22486 return n * s;
22487 case 'milliseconds':
22488 case 'millisecond':
22489 case 'msecs':
22490 case 'msec':
22491 case 'ms':
22492 return n;
22493 }
22494}
22495
22496/**
22497 * Short format for `ms`.
22498 *
22499 * @param {Number} ms
22500 * @return {String}
22501 * @api private
22502 */
22503
22504function short(ms) {
22505 if (ms >= d) return Math.round(ms / d) + 'd';
22506 if (ms >= h) return Math.round(ms / h) + 'h';
22507 if (ms >= m) return Math.round(ms / m) + 'm';
22508 if (ms >= s) return Math.round(ms / s) + 's';
22509 return ms + 'ms';
22510}
22511
22512/**
22513 * Long format for `ms`.
22514 *
22515 * @param {Number} ms
22516 * @return {String}
22517 * @api private
22518 */
22519
22520function long(ms) {
22521 return plural(ms, d, 'day')
22522 || plural(ms, h, 'hour')
22523 || plural(ms, m, 'minute')
22524 || plural(ms, s, 'second')
22525 || ms + ' ms';
22526}
22527
22528/**
22529 * Pluralization helper.
22530 */
22531
22532function plural(ms, n, name) {
22533 if (ms < n) return;
22534 if (ms < n * 1.5) return Math.floor(ms / n) + ' ' + name;
22535 return Math.ceil(ms / n) + ' ' + name + 's';
22536}
22537
22538},{}],"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/index.js":[function(require,module,exports){
22539
22540module.exports = require('./lib/');
22541
22542},{"./lib/":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/lib/index.js"}],"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/lib/index.js":[function(require,module,exports){
22543
22544module.exports = require('./socket');
22545
22546/**
22547 * Exports parser
22548 *
22549 * @api public
22550 *
22551 */
22552module.exports.parser = require('engine.io-parser');
22553
22554},{"./socket":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/lib/socket.js","engine.io-parser":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/node_modules/engine.io-parser/lib/browser.js"}],"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/lib/socket.js":[function(require,module,exports){
22555(function (global){
22556/**
22557 * Module dependencies.
22558 */
22559
22560var transports = require('./transports');
22561var Emitter = require('component-emitter');
22562var debug = require('debug')('engine.io-client:socket');
22563var index = require('indexof');
22564var parser = require('engine.io-parser');
22565var parseuri = require('parseuri');
22566var parsejson = require('parsejson');
22567var parseqs = require('parseqs');
22568
22569/**
22570 * Module exports.
22571 */
22572
22573module.exports = Socket;
22574
22575/**
22576 * Noop function.
22577 *
22578 * @api private
22579 */
22580
22581function noop(){}
22582
22583/**
22584 * Socket constructor.
22585 *
22586 * @param {String|Object} uri or options
22587 * @param {Object} options
22588 * @api public
22589 */
22590
22591function Socket(uri, opts){
22592 if (!(this instanceof Socket)) return new Socket(uri, opts);
22593
22594 opts = opts || {};
22595
22596 if (uri && 'object' == typeof uri) {
22597 opts = uri;
22598 uri = null;
22599 }
22600
22601 if (uri) {
22602 uri = parseuri(uri);
22603 opts.hostname = uri.host;
22604 opts.secure = uri.protocol == 'https' || uri.protocol == 'wss';
22605 opts.port = uri.port;
22606 if (uri.query) opts.query = uri.query;
22607 } else if (opts.host) {
22608 opts.hostname = parseuri(opts.host).host;
22609 }
22610
22611 this.secure = null != opts.secure ? opts.secure :
22612 (global.location && 'https:' == location.protocol);
22613
22614 if (opts.hostname && !opts.port) {
22615 // if no port is specified manually, use the protocol default
22616 opts.port = this.secure ? '443' : '80';
22617 }
22618
22619 this.agent = opts.agent || false;
22620 this.hostname = opts.hostname ||
22621 (global.location ? location.hostname : 'localhost');
22622 this.port = opts.port || (global.location && location.port ?
22623 location.port :
22624 (this.secure ? 443 : 80));
22625 this.query = opts.query || {};
22626 if ('string' == typeof this.query) this.query = parseqs.decode(this.query);
22627 this.upgrade = false !== opts.upgrade;
22628 this.path = (opts.path || '/engine.io').replace(/\/$/, '') + '/';
22629 this.forceJSONP = !!opts.forceJSONP;
22630 this.jsonp = false !== opts.jsonp;
22631 this.forceBase64 = !!opts.forceBase64;
22632 this.enablesXDR = !!opts.enablesXDR;
22633 this.timestampParam = opts.timestampParam || 't';
22634 this.timestampRequests = opts.timestampRequests;
22635 this.transports = opts.transports || ['polling', 'websocket'];
22636 this.readyState = '';
22637 this.writeBuffer = [];
22638 this.policyPort = opts.policyPort || 843;
22639 this.rememberUpgrade = opts.rememberUpgrade || false;
22640 this.binaryType = null;
22641 this.onlyBinaryUpgrades = opts.onlyBinaryUpgrades;
22642 this.perMessageDeflate = false !== opts.perMessageDeflate ? (opts.perMessageDeflate || {}) : false;
22643
22644 if (true === this.perMessageDeflate) this.perMessageDeflate = {};
22645 if (this.perMessageDeflate && null == this.perMessageDeflate.threshold) {
22646 this.perMessageDeflate.threshold = 1024;
22647 }
22648
22649 // SSL options for Node.js client
22650 this.pfx = opts.pfx || null;
22651 this.key = opts.key || null;
22652 this.passphrase = opts.passphrase || null;
22653 this.cert = opts.cert || null;
22654 this.ca = opts.ca || null;
22655 this.ciphers = opts.ciphers || null;
22656 this.rejectUnauthorized = opts.rejectUnauthorized === undefined ? true : opts.rejectUnauthorized;
22657
22658 // other options for Node.js client
22659 var freeGlobal = typeof global == 'object' && global;
22660 if (freeGlobal.global === freeGlobal) {
22661 if (opts.extraHeaders && Object.keys(opts.extraHeaders).length > 0) {
22662 this.extraHeaders = opts.extraHeaders;
22663 }
22664 }
22665
22666 this.open();
22667}
22668
22669Socket.priorWebsocketSuccess = false;
22670
22671/**
22672 * Mix in `Emitter`.
22673 */
22674
22675Emitter(Socket.prototype);
22676
22677/**
22678 * Protocol version.
22679 *
22680 * @api public
22681 */
22682
22683Socket.protocol = parser.protocol; // this is an int
22684
22685/**
22686 * Expose deps for legacy compatibility
22687 * and standalone browser access.
22688 */
22689
22690Socket.Socket = Socket;
22691Socket.Transport = require('./transport');
22692Socket.transports = require('./transports');
22693Socket.parser = require('engine.io-parser');
22694
22695/**
22696 * Creates transport of the given type.
22697 *
22698 * @param {String} transport name
22699 * @return {Transport}
22700 * @api private
22701 */
22702
22703Socket.prototype.createTransport = function (name) {
22704 debug('creating transport "%s"', name);
22705 var query = clone(this.query);
22706
22707 // append engine.io protocol identifier
22708 query.EIO = parser.protocol;
22709
22710 // transport name
22711 query.transport = name;
22712
22713 // session id if we already have one
22714 if (this.id) query.sid = this.id;
22715
22716 var transport = new transports[name]({
22717 agent: this.agent,
22718 hostname: this.hostname,
22719 port: this.port,
22720 secure: this.secure,
22721 path: this.path,
22722 query: query,
22723 forceJSONP: this.forceJSONP,
22724 jsonp: this.jsonp,
22725 forceBase64: this.forceBase64,
22726 enablesXDR: this.enablesXDR,
22727 timestampRequests: this.timestampRequests,
22728 timestampParam: this.timestampParam,
22729 policyPort: this.policyPort,
22730 socket: this,
22731 pfx: this.pfx,
22732 key: this.key,
22733 passphrase: this.passphrase,
22734 cert: this.cert,
22735 ca: this.ca,
22736 ciphers: this.ciphers,
22737 rejectUnauthorized: this.rejectUnauthorized,
22738 perMessageDeflate: this.perMessageDeflate,
22739 extraHeaders: this.extraHeaders
22740 });
22741
22742 return transport;
22743};
22744
22745function clone (obj) {
22746 var o = {};
22747 for (var i in obj) {
22748 if (obj.hasOwnProperty(i)) {
22749 o[i] = obj[i];
22750 }
22751 }
22752 return o;
22753}
22754
22755/**
22756 * Initializes transport to use and starts probe.
22757 *
22758 * @api private
22759 */
22760Socket.prototype.open = function () {
22761 var transport;
22762 if (this.rememberUpgrade && Socket.priorWebsocketSuccess && this.transports.indexOf('websocket') != -1) {
22763 transport = 'websocket';
22764 } else if (0 === this.transports.length) {
22765 // Emit error on next tick so it can be listened to
22766 var self = this;
22767 setTimeout(function() {
22768 self.emit('error', 'No transports available');
22769 }, 0);
22770 return;
22771 } else {
22772 transport = this.transports[0];
22773 }
22774 this.readyState = 'opening';
22775
22776 // Retry with the next transport if the transport is disabled (jsonp: false)
22777 try {
22778 transport = this.createTransport(transport);
22779 } catch (e) {
22780 this.transports.shift();
22781 this.open();
22782 return;
22783 }
22784
22785 transport.open();
22786 this.setTransport(transport);
22787};
22788
22789/**
22790 * Sets the current transport. Disables the existing one (if any).
22791 *
22792 * @api private
22793 */
22794
22795Socket.prototype.setTransport = function(transport){
22796 debug('setting transport %s', transport.name);
22797 var self = this;
22798
22799 if (this.transport) {
22800 debug('clearing existing transport %s', this.transport.name);
22801 this.transport.removeAllListeners();
22802 }
22803
22804 // set up transport
22805 this.transport = transport;
22806
22807 // set up transport listeners
22808 transport
22809 .on('drain', function(){
22810 self.onDrain();
22811 })
22812 .on('packet', function(packet){
22813 self.onPacket(packet);
22814 })
22815 .on('error', function(e){
22816 self.onError(e);
22817 })
22818 .on('close', function(){
22819 self.onClose('transport close');
22820 });
22821};
22822
22823/**
22824 * Probes a transport.
22825 *
22826 * @param {String} transport name
22827 * @api private
22828 */
22829
22830Socket.prototype.probe = function (name) {
22831 debug('probing transport "%s"', name);
22832 var transport = this.createTransport(name, { probe: 1 })
22833 , failed = false
22834 , self = this;
22835
22836 Socket.priorWebsocketSuccess = false;
22837
22838 function onTransportOpen(){
22839 if (self.onlyBinaryUpgrades) {
22840 var upgradeLosesBinary = !this.supportsBinary && self.transport.supportsBinary;
22841 failed = failed || upgradeLosesBinary;
22842 }
22843 if (failed) return;
22844
22845 debug('probe transport "%s" opened', name);
22846 transport.send([{ type: 'ping', data: 'probe' }]);
22847 transport.once('packet', function (msg) {
22848 if (failed) return;
22849 if ('pong' == msg.type && 'probe' == msg.data) {
22850 debug('probe transport "%s" pong', name);
22851 self.upgrading = true;
22852 self.emit('upgrading', transport);
22853 if (!transport) return;
22854 Socket.priorWebsocketSuccess = 'websocket' == transport.name;
22855
22856 debug('pausing current transport "%s"', self.transport.name);
22857 self.transport.pause(function () {
22858 if (failed) return;
22859 if ('closed' == self.readyState) return;
22860 debug('changing transport and sending upgrade packet');
22861
22862 cleanup();
22863
22864 self.setTransport(transport);
22865 transport.send([{ type: 'upgrade' }]);
22866 self.emit('upgrade', transport);
22867 transport = null;
22868 self.upgrading = false;
22869 self.flush();
22870 });
22871 } else {
22872 debug('probe transport "%s" failed', name);
22873 var err = new Error('probe error');
22874 err.transport = transport.name;
22875 self.emit('upgradeError', err);
22876 }
22877 });
22878 }
22879
22880 function freezeTransport() {
22881 if (failed) return;
22882
22883 // Any callback called by transport should be ignored since now
22884 failed = true;
22885
22886 cleanup();
22887
22888 transport.close();
22889 transport = null;
22890 }
22891
22892 //Handle any error that happens while probing
22893 function onerror(err) {
22894 var error = new Error('probe error: ' + err);
22895 error.transport = transport.name;
22896
22897 freezeTransport();
22898
22899 debug('probe transport "%s" failed because of error: %s', name, err);
22900
22901 self.emit('upgradeError', error);
22902 }
22903
22904 function onTransportClose(){
22905 onerror("transport closed");
22906 }
22907
22908 //When the socket is closed while we're probing
22909 function onclose(){
22910 onerror("socket closed");
22911 }
22912
22913 //When the socket is upgraded while we're probing
22914 function onupgrade(to){
22915 if (transport && to.name != transport.name) {
22916 debug('"%s" works - aborting "%s"', to.name, transport.name);
22917 freezeTransport();
22918 }
22919 }
22920
22921 //Remove all listeners on the transport and on self
22922 function cleanup(){
22923 transport.removeListener('open', onTransportOpen);
22924 transport.removeListener('error', onerror);
22925 transport.removeListener('close', onTransportClose);
22926 self.removeListener('close', onclose);
22927 self.removeListener('upgrading', onupgrade);
22928 }
22929
22930 transport.once('open', onTransportOpen);
22931 transport.once('error', onerror);
22932 transport.once('close', onTransportClose);
22933
22934 this.once('close', onclose);
22935 this.once('upgrading', onupgrade);
22936
22937 transport.open();
22938
22939};
22940
22941/**
22942 * Called when connection is deemed open.
22943 *
22944 * @api public
22945 */
22946
22947Socket.prototype.onOpen = function () {
22948 debug('socket open');
22949 this.readyState = 'open';
22950 Socket.priorWebsocketSuccess = 'websocket' == this.transport.name;
22951 this.emit('open');
22952 this.flush();
22953
22954 // we check for `readyState` in case an `open`
22955 // listener already closed the socket
22956 if ('open' == this.readyState && this.upgrade && this.transport.pause) {
22957 debug('starting upgrade probes');
22958 for (var i = 0, l = this.upgrades.length; i < l; i++) {
22959 this.probe(this.upgrades[i]);
22960 }
22961 }
22962};
22963
22964/**
22965 * Handles a packet.
22966 *
22967 * @api private
22968 */
22969
22970Socket.prototype.onPacket = function (packet) {
22971 if ('opening' == this.readyState || 'open' == this.readyState) {
22972 debug('socket receive: type "%s", data "%s"', packet.type, packet.data);
22973
22974 this.emit('packet', packet);
22975
22976 // Socket is live - any packet counts
22977 this.emit('heartbeat');
22978
22979 switch (packet.type) {
22980 case 'open':
22981 this.onHandshake(parsejson(packet.data));
22982 break;
22983
22984 case 'pong':
22985 this.setPing();
22986 this.emit('pong');
22987 break;
22988
22989 case 'error':
22990 var err = new Error('server error');
22991 err.code = packet.data;
22992 this.onError(err);
22993 break;
22994
22995 case 'message':
22996 this.emit('data', packet.data);
22997 this.emit('message', packet.data);
22998 break;
22999 }
23000 } else {
23001 debug('packet received with socket readyState "%s"', this.readyState);
23002 }
23003};
23004
23005/**
23006 * Called upon handshake completion.
23007 *
23008 * @param {Object} handshake obj
23009 * @api private
23010 */
23011
23012Socket.prototype.onHandshake = function (data) {
23013 this.emit('handshake', data);
23014 this.id = data.sid;
23015 this.transport.query.sid = data.sid;
23016 this.upgrades = this.filterUpgrades(data.upgrades);
23017 this.pingInterval = data.pingInterval;
23018 this.pingTimeout = data.pingTimeout;
23019 this.onOpen();
23020 // In case open handler closes socket
23021 if ('closed' == this.readyState) return;
23022 this.setPing();
23023
23024 // Prolong liveness of socket on heartbeat
23025 this.removeListener('heartbeat', this.onHeartbeat);
23026 this.on('heartbeat', this.onHeartbeat);
23027};
23028
23029/**
23030 * Resets ping timeout.
23031 *
23032 * @api private
23033 */
23034
23035Socket.prototype.onHeartbeat = function (timeout) {
23036 clearTimeout(this.pingTimeoutTimer);
23037 var self = this;
23038 self.pingTimeoutTimer = setTimeout(function () {
23039 if ('closed' == self.readyState) return;
23040 self.onClose('ping timeout');
23041 }, timeout || (self.pingInterval + self.pingTimeout));
23042};
23043
23044/**
23045 * Pings server every `this.pingInterval` and expects response
23046 * within `this.pingTimeout` or closes connection.
23047 *
23048 * @api private
23049 */
23050
23051Socket.prototype.setPing = function () {
23052 var self = this;
23053 clearTimeout(self.pingIntervalTimer);
23054 self.pingIntervalTimer = setTimeout(function () {
23055 debug('writing ping packet - expecting pong within %sms', self.pingTimeout);
23056 self.ping();
23057 self.onHeartbeat(self.pingTimeout);
23058 }, self.pingInterval);
23059};
23060
23061/**
23062* Sends a ping packet.
23063*
23064* @api private
23065*/
23066
23067Socket.prototype.ping = function () {
23068 var self = this;
23069 this.sendPacket('ping', function(){
23070 self.emit('ping');
23071 });
23072};
23073
23074/**
23075 * Called on `drain` event
23076 *
23077 * @api private
23078 */
23079
23080Socket.prototype.onDrain = function() {
23081 this.writeBuffer.splice(0, this.prevBufferLen);
23082
23083 // setting prevBufferLen = 0 is very important
23084 // for example, when upgrading, upgrade packet is sent over,
23085 // and a nonzero prevBufferLen could cause problems on `drain`
23086 this.prevBufferLen = 0;
23087
23088 if (0 === this.writeBuffer.length) {
23089 this.emit('drain');
23090 } else {
23091 this.flush();
23092 }
23093};
23094
23095/**
23096 * Flush write buffers.
23097 *
23098 * @api private
23099 */
23100
23101Socket.prototype.flush = function () {
23102 if ('closed' != this.readyState && this.transport.writable &&
23103 !this.upgrading && this.writeBuffer.length) {
23104 debug('flushing %d packets in socket', this.writeBuffer.length);
23105 this.transport.send(this.writeBuffer);
23106 // keep track of current length of writeBuffer
23107 // splice writeBuffer and callbackBuffer on `drain`
23108 this.prevBufferLen = this.writeBuffer.length;
23109 this.emit('flush');
23110 }
23111};
23112
23113/**
23114 * Sends a message.
23115 *
23116 * @param {String} message.
23117 * @param {Function} callback function.
23118 * @param {Object} options.
23119 * @return {Socket} for chaining.
23120 * @api public
23121 */
23122
23123Socket.prototype.write =
23124Socket.prototype.send = function (msg, options, fn) {
23125 this.sendPacket('message', msg, options, fn);
23126 return this;
23127};
23128
23129/**
23130 * Sends a packet.
23131 *
23132 * @param {String} packet type.
23133 * @param {String} data.
23134 * @param {Object} options.
23135 * @param {Function} callback function.
23136 * @api private
23137 */
23138
23139Socket.prototype.sendPacket = function (type, data, options, fn) {
23140 if('function' == typeof data) {
23141 fn = data;
23142 data = undefined;
23143 }
23144
23145 if ('function' == typeof options) {
23146 fn = options;
23147 options = null;
23148 }
23149
23150 if ('closing' == this.readyState || 'closed' == this.readyState) {
23151 return;
23152 }
23153
23154 options = options || {};
23155 options.compress = false !== options.compress;
23156
23157 var packet = {
23158 type: type,
23159 data: data,
23160 options: options
23161 };
23162 this.emit('packetCreate', packet);
23163 this.writeBuffer.push(packet);
23164 if (fn) this.once('flush', fn);
23165 this.flush();
23166};
23167
23168/**
23169 * Closes the connection.
23170 *
23171 * @api private
23172 */
23173
23174Socket.prototype.close = function () {
23175 if ('opening' == this.readyState || 'open' == this.readyState) {
23176 this.readyState = 'closing';
23177
23178 var self = this;
23179
23180 if (this.writeBuffer.length) {
23181 this.once('drain', function() {
23182 if (this.upgrading) {
23183 waitForUpgrade();
23184 } else {
23185 close();
23186 }
23187 });
23188 } else if (this.upgrading) {
23189 waitForUpgrade();
23190 } else {
23191 close();
23192 }
23193 }
23194
23195 function close() {
23196 self.onClose('forced close');
23197 debug('socket closing - telling transport to close');
23198 self.transport.close();
23199 }
23200
23201 function cleanupAndClose() {
23202 self.removeListener('upgrade', cleanupAndClose);
23203 self.removeListener('upgradeError', cleanupAndClose);
23204 close();
23205 }
23206
23207 function waitForUpgrade() {
23208 // wait for upgrade to finish since we can't send packets while pausing a transport
23209 self.once('upgrade', cleanupAndClose);
23210 self.once('upgradeError', cleanupAndClose);
23211 }
23212
23213 return this;
23214};
23215
23216/**
23217 * Called upon transport error
23218 *
23219 * @api private
23220 */
23221
23222Socket.prototype.onError = function (err) {
23223 debug('socket error %j', err);
23224 Socket.priorWebsocketSuccess = false;
23225 this.emit('error', err);
23226 this.onClose('transport error', err);
23227};
23228
23229/**
23230 * Called upon transport close.
23231 *
23232 * @api private
23233 */
23234
23235Socket.prototype.onClose = function (reason, desc) {
23236 if ('opening' == this.readyState || 'open' == this.readyState || 'closing' == this.readyState) {
23237 debug('socket close with reason: "%s"', reason);
23238 var self = this;
23239
23240 // clear timers
23241 clearTimeout(this.pingIntervalTimer);
23242 clearTimeout(this.pingTimeoutTimer);
23243
23244 // stop event from firing again for transport
23245 this.transport.removeAllListeners('close');
23246
23247 // ensure transport won't stay open
23248 this.transport.close();
23249
23250 // ignore further transport communication
23251 this.transport.removeAllListeners();
23252
23253 // set ready state
23254 this.readyState = 'closed';
23255
23256 // clear session id
23257 this.id = null;
23258
23259 // emit close event
23260 this.emit('close', reason, desc);
23261
23262 // clean buffers after, so users can still
23263 // grab the buffers on `close` event
23264 self.writeBuffer = [];
23265 self.prevBufferLen = 0;
23266 }
23267};
23268
23269/**
23270 * Filters upgrades, returning only those matching client transports.
23271 *
23272 * @param {Array} server upgrades
23273 * @api private
23274 *
23275 */
23276
23277Socket.prototype.filterUpgrades = function (upgrades) {
23278 var filteredUpgrades = [];
23279 for (var i = 0, j = upgrades.length; i<j; i++) {
23280 if (~index(this.transports, upgrades[i])) filteredUpgrades.push(upgrades[i]);
23281 }
23282 return filteredUpgrades;
23283};
23284
23285}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
23286},{"./transport":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/lib/transport.js","./transports":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/lib/transports/index.js","component-emitter":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/node_modules/component-emitter/index.js","debug":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/debug/browser.js","engine.io-parser":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/node_modules/engine.io-parser/lib/browser.js","indexof":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/indexof/index.js","parsejson":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/node_modules/parsejson/index.js","parseqs":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/node_modules/parseqs/index.js","parseuri":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/parseuri/index.js"}],"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/lib/transport.js":[function(require,module,exports){
23287/**
23288 * Module dependencies.
23289 */
23290
23291var parser = require('engine.io-parser');
23292var Emitter = require('component-emitter');
23293
23294/**
23295 * Module exports.
23296 */
23297
23298module.exports = Transport;
23299
23300/**
23301 * Transport abstract constructor.
23302 *
23303 * @param {Object} options.
23304 * @api private
23305 */
23306
23307function Transport (opts) {
23308 this.path = opts.path;
23309 this.hostname = opts.hostname;
23310 this.port = opts.port;
23311 this.secure = opts.secure;
23312 this.query = opts.query;
23313 this.timestampParam = opts.timestampParam;
23314 this.timestampRequests = opts.timestampRequests;
23315 this.readyState = '';
23316 this.agent = opts.agent || false;
23317 this.socket = opts.socket;
23318 this.enablesXDR = opts.enablesXDR;
23319
23320 // SSL options for Node.js client
23321 this.pfx = opts.pfx;
23322 this.key = opts.key;
23323 this.passphrase = opts.passphrase;
23324 this.cert = opts.cert;
23325 this.ca = opts.ca;
23326 this.ciphers = opts.ciphers;
23327 this.rejectUnauthorized = opts.rejectUnauthorized;
23328
23329 // other options for Node.js client
23330 this.extraHeaders = opts.extraHeaders;
23331}
23332
23333/**
23334 * Mix in `Emitter`.
23335 */
23336
23337Emitter(Transport.prototype);
23338
23339/**
23340 * Emits an error.
23341 *
23342 * @param {String} str
23343 * @return {Transport} for chaining
23344 * @api public
23345 */
23346
23347Transport.prototype.onError = function (msg, desc) {
23348 var err = new Error(msg);
23349 err.type = 'TransportError';
23350 err.description = desc;
23351 this.emit('error', err);
23352 return this;
23353};
23354
23355/**
23356 * Opens the transport.
23357 *
23358 * @api public
23359 */
23360
23361Transport.prototype.open = function () {
23362 if ('closed' == this.readyState || '' == this.readyState) {
23363 this.readyState = 'opening';
23364 this.doOpen();
23365 }
23366
23367 return this;
23368};
23369
23370/**
23371 * Closes the transport.
23372 *
23373 * @api private
23374 */
23375
23376Transport.prototype.close = function () {
23377 if ('opening' == this.readyState || 'open' == this.readyState) {
23378 this.doClose();
23379 this.onClose();
23380 }
23381
23382 return this;
23383};
23384
23385/**
23386 * Sends multiple packets.
23387 *
23388 * @param {Array} packets
23389 * @api private
23390 */
23391
23392Transport.prototype.send = function(packets){
23393 if ('open' == this.readyState) {
23394 this.write(packets);
23395 } else {
23396 throw new Error('Transport not open');
23397 }
23398};
23399
23400/**
23401 * Called upon open
23402 *
23403 * @api private
23404 */
23405
23406Transport.prototype.onOpen = function () {
23407 this.readyState = 'open';
23408 this.writable = true;
23409 this.emit('open');
23410};
23411
23412/**
23413 * Called with data.
23414 *
23415 * @param {String} data
23416 * @api private
23417 */
23418
23419Transport.prototype.onData = function(data){
23420 var packet = parser.decodePacket(data, this.socket.binaryType);
23421 this.onPacket(packet);
23422};
23423
23424/**
23425 * Called with a decoded packet.
23426 */
23427
23428Transport.prototype.onPacket = function (packet) {
23429 this.emit('packet', packet);
23430};
23431
23432/**
23433 * Called upon close.
23434 *
23435 * @api private
23436 */
23437
23438Transport.prototype.onClose = function () {
23439 this.readyState = 'closed';
23440 this.emit('close');
23441};
23442
23443},{"component-emitter":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/node_modules/component-emitter/index.js","engine.io-parser":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/node_modules/engine.io-parser/lib/browser.js"}],"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/lib/transports/index.js":[function(require,module,exports){
23444(function (global){
23445/**
23446 * Module dependencies
23447 */
23448
23449var XMLHttpRequest = require('xmlhttprequest-ssl');
23450var XHR = require('./polling-xhr');
23451var JSONP = require('./polling-jsonp');
23452var websocket = require('./websocket');
23453
23454/**
23455 * Export transports.
23456 */
23457
23458exports.polling = polling;
23459exports.websocket = websocket;
23460
23461/**
23462 * Polling transport polymorphic constructor.
23463 * Decides on xhr vs jsonp based on feature detection.
23464 *
23465 * @api private
23466 */
23467
23468function polling(opts){
23469 var xhr;
23470 var xd = false;
23471 var xs = false;
23472 var jsonp = false !== opts.jsonp;
23473
23474 if (global.location) {
23475 var isSSL = 'https:' == location.protocol;
23476 var port = location.port;
23477
23478 // some user agents have empty `location.port`
23479 if (!port) {
23480 port = isSSL ? 443 : 80;
23481 }
23482
23483 xd = opts.hostname != location.hostname || port != opts.port;
23484 xs = opts.secure != isSSL;
23485 }
23486
23487 opts.xdomain = xd;
23488 opts.xscheme = xs;
23489 xhr = new XMLHttpRequest(opts);
23490
23491 if ('open' in xhr && !opts.forceJSONP) {
23492 return new XHR(opts);
23493 } else {
23494 if (!jsonp) throw new Error('JSONP disabled');
23495 return new JSONP(opts);
23496 }
23497}
23498
23499}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
23500},{"./polling-jsonp":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/lib/transports/polling-jsonp.js","./polling-xhr":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/lib/transports/polling-xhr.js","./websocket":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/lib/transports/websocket.js","xmlhttprequest-ssl":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/lib/xmlhttprequest.js"}],"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/lib/transports/polling-jsonp.js":[function(require,module,exports){
23501(function (global){
23502
23503/**
23504 * Module requirements.
23505 */
23506
23507var Polling = require('./polling');
23508var inherit = require('component-inherit');
23509
23510/**
23511 * Module exports.
23512 */
23513
23514module.exports = JSONPPolling;
23515
23516/**
23517 * Cached regular expressions.
23518 */
23519
23520var rNewline = /\n/g;
23521var rEscapedNewline = /\\n/g;
23522
23523/**
23524 * Global JSONP callbacks.
23525 */
23526
23527var callbacks;
23528
23529/**
23530 * Callbacks count.
23531 */
23532
23533var index = 0;
23534
23535/**
23536 * Noop.
23537 */
23538
23539function empty () { }
23540
23541/**
23542 * JSONP Polling constructor.
23543 *
23544 * @param {Object} opts.
23545 * @api public
23546 */
23547
23548function JSONPPolling (opts) {
23549 Polling.call(this, opts);
23550
23551 this.query = this.query || {};
23552
23553 // define global callbacks array if not present
23554 // we do this here (lazily) to avoid unneeded global pollution
23555 if (!callbacks) {
23556 // we need to consider multiple engines in the same page
23557 if (!global.___eio) global.___eio = [];
23558 callbacks = global.___eio;
23559 }
23560
23561 // callback identifier
23562 this.index = callbacks.length;
23563
23564 // add callback to jsonp global
23565 var self = this;
23566 callbacks.push(function (msg) {
23567 self.onData(msg);
23568 });
23569
23570 // append to query string
23571 this.query.j = this.index;
23572
23573 // prevent spurious errors from being emitted when the window is unloaded
23574 if (global.document && global.addEventListener) {
23575 global.addEventListener('beforeunload', function () {
23576 if (self.script) self.script.onerror = empty;
23577 }, false);
23578 }
23579}
23580
23581/**
23582 * Inherits from Polling.
23583 */
23584
23585inherit(JSONPPolling, Polling);
23586
23587/*
23588 * JSONP only supports binary as base64 encoded strings
23589 */
23590
23591JSONPPolling.prototype.supportsBinary = false;
23592
23593/**
23594 * Closes the socket.
23595 *
23596 * @api private
23597 */
23598
23599JSONPPolling.prototype.doClose = function () {
23600 if (this.script) {
23601 this.script.parentNode.removeChild(this.script);
23602 this.script = null;
23603 }
23604
23605 if (this.form) {
23606 this.form.parentNode.removeChild(this.form);
23607 this.form = null;
23608 this.iframe = null;
23609 }
23610
23611 Polling.prototype.doClose.call(this);
23612};
23613
23614/**
23615 * Starts a poll cycle.
23616 *
23617 * @api private
23618 */
23619
23620JSONPPolling.prototype.doPoll = function () {
23621 var self = this;
23622 var script = document.createElement('script');
23623
23624 if (this.script) {
23625 this.script.parentNode.removeChild(this.script);
23626 this.script = null;
23627 }
23628
23629 script.async = true;
23630 script.src = this.uri();
23631 script.onerror = function(e){
23632 self.onError('jsonp poll error',e);
23633 };
23634
23635 var insertAt = document.getElementsByTagName('script')[0];
23636 if (insertAt) {
23637 insertAt.parentNode.insertBefore(script, insertAt);
23638 }
23639 else {
23640 (document.head || document.body).appendChild(script);
23641 }
23642 this.script = script;
23643
23644 var isUAgecko = 'undefined' != typeof navigator && /gecko/i.test(navigator.userAgent);
23645
23646 if (isUAgecko) {
23647 setTimeout(function () {
23648 var iframe = document.createElement('iframe');
23649 document.body.appendChild(iframe);
23650 document.body.removeChild(iframe);
23651 }, 100);
23652 }
23653};
23654
23655/**
23656 * Writes with a hidden iframe.
23657 *
23658 * @param {String} data to send
23659 * @param {Function} called upon flush.
23660 * @api private
23661 */
23662
23663JSONPPolling.prototype.doWrite = function (data, fn) {
23664 var self = this;
23665
23666 if (!this.form) {
23667 var form = document.createElement('form');
23668 var area = document.createElement('textarea');
23669 var id = this.iframeId = 'eio_iframe_' + this.index;
23670 var iframe;
23671
23672 form.className = 'socketio';
23673 form.style.position = 'absolute';
23674 form.style.top = '-1000px';
23675 form.style.left = '-1000px';
23676 form.target = id;
23677 form.method = 'POST';
23678 form.setAttribute('accept-charset', 'utf-8');
23679 area.name = 'd';
23680 form.appendChild(area);
23681 document.body.appendChild(form);
23682
23683 this.form = form;
23684 this.area = area;
23685 }
23686
23687 this.form.action = this.uri();
23688
23689 function complete () {
23690 initIframe();
23691 fn();
23692 }
23693
23694 function initIframe () {
23695 if (self.iframe) {
23696 try {
23697 self.form.removeChild(self.iframe);
23698 } catch (e) {
23699 self.onError('jsonp polling iframe removal error', e);
23700 }
23701 }
23702
23703 try {
23704 // ie6 dynamic iframes with target="" support (thanks Chris Lambacher)
23705 var html = '<iframe src="javascript:0" name="'+ self.iframeId +'">';
23706 iframe = document.createElement(html);
23707 } catch (e) {
23708 iframe = document.createElement('iframe');
23709 iframe.name = self.iframeId;
23710 iframe.src = 'javascript:0';
23711 }
23712
23713 iframe.id = self.iframeId;
23714
23715 self.form.appendChild(iframe);
23716 self.iframe = iframe;
23717 }
23718
23719 initIframe();
23720
23721 // escape \n to prevent it from being converted into \r\n by some UAs
23722 // double escaping is required for escaped new lines because unescaping of new lines can be done safely on server-side
23723 data = data.replace(rEscapedNewline, '\\\n');
23724 this.area.value = data.replace(rNewline, '\\n');
23725
23726 try {
23727 this.form.submit();
23728 } catch(e) {}
23729
23730 if (this.iframe.attachEvent) {
23731 this.iframe.onreadystatechange = function(){
23732 if (self.iframe.readyState == 'complete') {
23733 complete();
23734 }
23735 };
23736 } else {
23737 this.iframe.onload = complete;
23738 }
23739};
23740
23741}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
23742},{"./polling":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/lib/transports/polling.js","component-inherit":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/node_modules/component-inherit/index.js"}],"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/lib/transports/polling-xhr.js":[function(require,module,exports){
23743(function (global){
23744/**
23745 * Module requirements.
23746 */
23747
23748var XMLHttpRequest = require('xmlhttprequest-ssl');
23749var Polling = require('./polling');
23750var Emitter = require('component-emitter');
23751var inherit = require('component-inherit');
23752var debug = require('debug')('engine.io-client:polling-xhr');
23753
23754/**
23755 * Module exports.
23756 */
23757
23758module.exports = XHR;
23759module.exports.Request = Request;
23760
23761/**
23762 * Empty function
23763 */
23764
23765function empty(){}
23766
23767/**
23768 * XHR Polling constructor.
23769 *
23770 * @param {Object} opts
23771 * @api public
23772 */
23773
23774function XHR(opts){
23775 Polling.call(this, opts);
23776
23777 if (global.location) {
23778 var isSSL = 'https:' == location.protocol;
23779 var port = location.port;
23780
23781 // some user agents have empty `location.port`
23782 if (!port) {
23783 port = isSSL ? 443 : 80;
23784 }
23785
23786 this.xd = opts.hostname != global.location.hostname ||
23787 port != opts.port;
23788 this.xs = opts.secure != isSSL;
23789 } else {
23790 this.extraHeaders = opts.extraHeaders;
23791 }
23792}
23793
23794/**
23795 * Inherits from Polling.
23796 */
23797
23798inherit(XHR, Polling);
23799
23800/**
23801 * XHR supports binary
23802 */
23803
23804XHR.prototype.supportsBinary = true;
23805
23806/**
23807 * Creates a request.
23808 *
23809 * @param {String} method
23810 * @api private
23811 */
23812
23813XHR.prototype.request = function(opts){
23814 opts = opts || {};
23815 opts.uri = this.uri();
23816 opts.xd = this.xd;
23817 opts.xs = this.xs;
23818 opts.agent = this.agent || false;
23819 opts.supportsBinary = this.supportsBinary;
23820 opts.enablesXDR = this.enablesXDR;
23821
23822 // SSL options for Node.js client
23823 opts.pfx = this.pfx;
23824 opts.key = this.key;
23825 opts.passphrase = this.passphrase;
23826 opts.cert = this.cert;
23827 opts.ca = this.ca;
23828 opts.ciphers = this.ciphers;
23829 opts.rejectUnauthorized = this.rejectUnauthorized;
23830
23831 // other options for Node.js client
23832 opts.extraHeaders = this.extraHeaders;
23833
23834 return new Request(opts);
23835};
23836
23837/**
23838 * Sends data.
23839 *
23840 * @param {String} data to send.
23841 * @param {Function} called upon flush.
23842 * @api private
23843 */
23844
23845XHR.prototype.doWrite = function(data, fn){
23846 var isBinary = typeof data !== 'string' && data !== undefined;
23847 var req = this.request({ method: 'POST', data: data, isBinary: isBinary });
23848 var self = this;
23849 req.on('success', fn);
23850 req.on('error', function(err){
23851 self.onError('xhr post error', err);
23852 });
23853 this.sendXhr = req;
23854};
23855
23856/**
23857 * Starts a poll cycle.
23858 *
23859 * @api private
23860 */
23861
23862XHR.prototype.doPoll = function(){
23863 debug('xhr poll');
23864 var req = this.request();
23865 var self = this;
23866 req.on('data', function(data){
23867 self.onData(data);
23868 });
23869 req.on('error', function(err){
23870 self.onError('xhr poll error', err);
23871 });
23872 this.pollXhr = req;
23873};
23874
23875/**
23876 * Request constructor
23877 *
23878 * @param {Object} options
23879 * @api public
23880 */
23881
23882function Request(opts){
23883 this.method = opts.method || 'GET';
23884 this.uri = opts.uri;
23885 this.xd = !!opts.xd;
23886 this.xs = !!opts.xs;
23887 this.async = false !== opts.async;
23888 this.data = undefined != opts.data ? opts.data : null;
23889 this.agent = opts.agent;
23890 this.isBinary = opts.isBinary;
23891 this.supportsBinary = opts.supportsBinary;
23892 this.enablesXDR = opts.enablesXDR;
23893
23894 // SSL options for Node.js client
23895 this.pfx = opts.pfx;
23896 this.key = opts.key;
23897 this.passphrase = opts.passphrase;
23898 this.cert = opts.cert;
23899 this.ca = opts.ca;
23900 this.ciphers = opts.ciphers;
23901 this.rejectUnauthorized = opts.rejectUnauthorized;
23902
23903 // other options for Node.js client
23904 this.extraHeaders = opts.extraHeaders;
23905
23906 this.create();
23907}
23908
23909/**
23910 * Mix in `Emitter`.
23911 */
23912
23913Emitter(Request.prototype);
23914
23915/**
23916 * Creates the XHR object and sends the request.
23917 *
23918 * @api private
23919 */
23920
23921Request.prototype.create = function(){
23922 var opts = { agent: this.agent, xdomain: this.xd, xscheme: this.xs, enablesXDR: this.enablesXDR };
23923
23924 // SSL options for Node.js client
23925 opts.pfx = this.pfx;
23926 opts.key = this.key;
23927 opts.passphrase = this.passphrase;
23928 opts.cert = this.cert;
23929 opts.ca = this.ca;
23930 opts.ciphers = this.ciphers;
23931 opts.rejectUnauthorized = this.rejectUnauthorized;
23932
23933 var xhr = this.xhr = new XMLHttpRequest(opts);
23934 var self = this;
23935
23936 try {
23937 debug('xhr open %s: %s', this.method, this.uri);
23938 xhr.open(this.method, this.uri, this.async);
23939 try {
23940 if (this.extraHeaders) {
23941 xhr.setDisableHeaderCheck(true);
23942 for (var i in this.extraHeaders) {
23943 if (this.extraHeaders.hasOwnProperty(i)) {
23944 xhr.setRequestHeader(i, this.extraHeaders[i]);
23945 }
23946 }
23947 }
23948 } catch (e) {}
23949 if (this.supportsBinary) {
23950 // This has to be done after open because Firefox is stupid
23951 // http://stackoverflow.com/questions/13216903/get-binary-data-with-xmlhttprequest-in-a-firefox-extension
23952 xhr.responseType = 'arraybuffer';
23953 }
23954
23955 if ('POST' == this.method) {
23956 try {
23957 if (this.isBinary) {
23958 xhr.setRequestHeader('Content-type', 'application/octet-stream');
23959 } else {
23960 xhr.setRequestHeader('Content-type', 'text/plain;charset=UTF-8');
23961 }
23962 } catch (e) {}
23963 }
23964
23965 // ie6 check
23966 if ('withCredentials' in xhr) {
23967 xhr.withCredentials = true;
23968 }
23969
23970 if (this.hasXDR()) {
23971 xhr.onload = function(){
23972 self.onLoad();
23973 };
23974 xhr.onerror = function(){
23975 self.onError(xhr.responseText);
23976 };
23977 } else {
23978 xhr.onreadystatechange = function(){
23979 if (4 != xhr.readyState) return;
23980 if (200 == xhr.status || 1223 == xhr.status) {
23981 self.onLoad();
23982 } else {
23983 // make sure the `error` event handler that's user-set
23984 // does not throw in the same tick and gets caught here
23985 setTimeout(function(){
23986 self.onError(xhr.status);
23987 }, 0);
23988 }
23989 };
23990 }
23991
23992 debug('xhr data %s', this.data);
23993 xhr.send(this.data);
23994 } catch (e) {
23995 // Need to defer since .create() is called directly fhrom the constructor
23996 // and thus the 'error' event can only be only bound *after* this exception
23997 // occurs. Therefore, also, we cannot throw here at all.
23998 setTimeout(function() {
23999 self.onError(e);
24000 }, 0);
24001 return;
24002 }
24003
24004 if (global.document) {
24005 this.index = Request.requestsCount++;
24006 Request.requests[this.index] = this;
24007 }
24008};
24009
24010/**
24011 * Called upon successful response.
24012 *
24013 * @api private
24014 */
24015
24016Request.prototype.onSuccess = function(){
24017 this.emit('success');
24018 this.cleanup();
24019};
24020
24021/**
24022 * Called if we have data.
24023 *
24024 * @api private
24025 */
24026
24027Request.prototype.onData = function(data){
24028 this.emit('data', data);
24029 this.onSuccess();
24030};
24031
24032/**
24033 * Called upon error.
24034 *
24035 * @api private
24036 */
24037
24038Request.prototype.onError = function(err){
24039 this.emit('error', err);
24040 this.cleanup(true);
24041};
24042
24043/**
24044 * Cleans up house.
24045 *
24046 * @api private
24047 */
24048
24049Request.prototype.cleanup = function(fromError){
24050 if ('undefined' == typeof this.xhr || null === this.xhr) {
24051 return;
24052 }
24053 // xmlhttprequest
24054 if (this.hasXDR()) {
24055 this.xhr.onload = this.xhr.onerror = empty;
24056 } else {
24057 this.xhr.onreadystatechange = empty;
24058 }
24059
24060 if (fromError) {
24061 try {
24062 this.xhr.abort();
24063 } catch(e) {}
24064 }
24065
24066 if (global.document) {
24067 delete Request.requests[this.index];
24068 }
24069
24070 this.xhr = null;
24071};
24072
24073/**
24074 * Called upon load.
24075 *
24076 * @api private
24077 */
24078
24079Request.prototype.onLoad = function(){
24080 var data;
24081 try {
24082 var contentType;
24083 try {
24084 contentType = this.xhr.getResponseHeader('Content-Type').split(';')[0];
24085 } catch (e) {}
24086 if (contentType === 'application/octet-stream') {
24087 data = this.xhr.response;
24088 } else {
24089 if (!this.supportsBinary) {
24090 data = this.xhr.responseText;
24091 } else {
24092 try {
24093 data = String.fromCharCode.apply(null, new Uint8Array(this.xhr.response));
24094 } catch (e) {
24095 var ui8Arr = new Uint8Array(this.xhr.response);
24096 var dataArray = [];
24097 for (var idx = 0, length = ui8Arr.length; idx < length; idx++) {
24098 dataArray.push(ui8Arr[idx]);
24099 }
24100
24101 data = String.fromCharCode.apply(null, dataArray);
24102 }
24103 }
24104 }
24105 } catch (e) {
24106 this.onError(e);
24107 }
24108 if (null != data) {
24109 this.onData(data);
24110 }
24111};
24112
24113/**
24114 * Check if it has XDomainRequest.
24115 *
24116 * @api private
24117 */
24118
24119Request.prototype.hasXDR = function(){
24120 return 'undefined' !== typeof global.XDomainRequest && !this.xs && this.enablesXDR;
24121};
24122
24123/**
24124 * Aborts the request.
24125 *
24126 * @api public
24127 */
24128
24129Request.prototype.abort = function(){
24130 this.cleanup();
24131};
24132
24133/**
24134 * Aborts pending requests when unloading the window. This is needed to prevent
24135 * memory leaks (e.g. when using IE) and to ensure that no spurious error is
24136 * emitted.
24137 */
24138
24139if (global.document) {
24140 Request.requestsCount = 0;
24141 Request.requests = {};
24142 if (global.attachEvent) {
24143 global.attachEvent('onunload', unloadHandler);
24144 } else if (global.addEventListener) {
24145 global.addEventListener('beforeunload', unloadHandler, false);
24146 }
24147}
24148
24149function unloadHandler() {
24150 for (var i in Request.requests) {
24151 if (Request.requests.hasOwnProperty(i)) {
24152 Request.requests[i].abort();
24153 }
24154 }
24155}
24156
24157}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
24158},{"./polling":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/lib/transports/polling.js","component-emitter":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/node_modules/component-emitter/index.js","component-inherit":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/node_modules/component-inherit/index.js","debug":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/debug/browser.js","xmlhttprequest-ssl":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/lib/xmlhttprequest.js"}],"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/lib/transports/polling.js":[function(require,module,exports){
24159/**
24160 * Module dependencies.
24161 */
24162
24163var Transport = require('../transport');
24164var parseqs = require('parseqs');
24165var parser = require('engine.io-parser');
24166var inherit = require('component-inherit');
24167var yeast = require('yeast');
24168var debug = require('debug')('engine.io-client:polling');
24169
24170/**
24171 * Module exports.
24172 */
24173
24174module.exports = Polling;
24175
24176/**
24177 * Is XHR2 supported?
24178 */
24179
24180var hasXHR2 = (function() {
24181 var XMLHttpRequest = require('xmlhttprequest-ssl');
24182 var xhr = new XMLHttpRequest({ xdomain: false });
24183 return null != xhr.responseType;
24184})();
24185
24186/**
24187 * Polling interface.
24188 *
24189 * @param {Object} opts
24190 * @api private
24191 */
24192
24193function Polling(opts){
24194 var forceBase64 = (opts && opts.forceBase64);
24195 if (!hasXHR2 || forceBase64) {
24196 this.supportsBinary = false;
24197 }
24198 Transport.call(this, opts);
24199}
24200
24201/**
24202 * Inherits from Transport.
24203 */
24204
24205inherit(Polling, Transport);
24206
24207/**
24208 * Transport name.
24209 */
24210
24211Polling.prototype.name = 'polling';
24212
24213/**
24214 * Opens the socket (triggers polling). We write a PING message to determine
24215 * when the transport is open.
24216 *
24217 * @api private
24218 */
24219
24220Polling.prototype.doOpen = function(){
24221 this.poll();
24222};
24223
24224/**
24225 * Pauses polling.
24226 *
24227 * @param {Function} callback upon buffers are flushed and transport is paused
24228 * @api private
24229 */
24230
24231Polling.prototype.pause = function(onPause){
24232 var pending = 0;
24233 var self = this;
24234
24235 this.readyState = 'pausing';
24236
24237 function pause(){
24238 debug('paused');
24239 self.readyState = 'paused';
24240 onPause();
24241 }
24242
24243 if (this.polling || !this.writable) {
24244 var total = 0;
24245
24246 if (this.polling) {
24247 debug('we are currently polling - waiting to pause');
24248 total++;
24249 this.once('pollComplete', function(){
24250 debug('pre-pause polling complete');
24251 --total || pause();
24252 });
24253 }
24254
24255 if (!this.writable) {
24256 debug('we are currently writing - waiting to pause');
24257 total++;
24258 this.once('drain', function(){
24259 debug('pre-pause writing complete');
24260 --total || pause();
24261 });
24262 }
24263 } else {
24264 pause();
24265 }
24266};
24267
24268/**
24269 * Starts polling cycle.
24270 *
24271 * @api public
24272 */
24273
24274Polling.prototype.poll = function(){
24275 debug('polling');
24276 this.polling = true;
24277 this.doPoll();
24278 this.emit('poll');
24279};
24280
24281/**
24282 * Overloads onData to detect payloads.
24283 *
24284 * @api private
24285 */
24286
24287Polling.prototype.onData = function(data){
24288 var self = this;
24289 debug('polling got data %s', data);
24290 var callback = function(packet, index, total) {
24291 // if its the first message we consider the transport open
24292 if ('opening' == self.readyState) {
24293 self.onOpen();
24294 }
24295
24296 // if its a close packet, we close the ongoing requests
24297 if ('close' == packet.type) {
24298 self.onClose();
24299 return false;
24300 }
24301
24302 // otherwise bypass onData and handle the message
24303 self.onPacket(packet);
24304 };
24305
24306 // decode payload
24307 parser.decodePayload(data, this.socket.binaryType, callback);
24308
24309 // if an event did not trigger closing
24310 if ('closed' != this.readyState) {
24311 // if we got data we're not polling
24312 this.polling = false;
24313 this.emit('pollComplete');
24314
24315 if ('open' == this.readyState) {
24316 this.poll();
24317 } else {
24318 debug('ignoring poll - transport state "%s"', this.readyState);
24319 }
24320 }
24321};
24322
24323/**
24324 * For polling, send a close packet.
24325 *
24326 * @api private
24327 */
24328
24329Polling.prototype.doClose = function(){
24330 var self = this;
24331
24332 function close(){
24333 debug('writing close packet');
24334 self.write([{ type: 'close' }]);
24335 }
24336
24337 if ('open' == this.readyState) {
24338 debug('transport open - closing');
24339 close();
24340 } else {
24341 // in case we're trying to close while
24342 // handshaking is in progress (GH-164)
24343 debug('transport not open - deferring close');
24344 this.once('open', close);
24345 }
24346};
24347
24348/**
24349 * Writes a packets payload.
24350 *
24351 * @param {Array} data packets
24352 * @param {Function} drain callback
24353 * @api private
24354 */
24355
24356Polling.prototype.write = function(packets){
24357 var self = this;
24358 this.writable = false;
24359 var callbackfn = function() {
24360 self.writable = true;
24361 self.emit('drain');
24362 };
24363
24364 var self = this;
24365 parser.encodePayload(packets, this.supportsBinary, function(data) {
24366 self.doWrite(data, callbackfn);
24367 });
24368};
24369
24370/**
24371 * Generates uri for connection.
24372 *
24373 * @api private
24374 */
24375
24376Polling.prototype.uri = function(){
24377 var query = this.query || {};
24378 var schema = this.secure ? 'https' : 'http';
24379 var port = '';
24380
24381 // cache busting is forced
24382 if (false !== this.timestampRequests) {
24383 query[this.timestampParam] = yeast();
24384 }
24385
24386 if (!this.supportsBinary && !query.sid) {
24387 query.b64 = 1;
24388 }
24389
24390 query = parseqs.encode(query);
24391
24392 // avoid port if default for schema
24393 if (this.port && (('https' == schema && this.port != 443) ||
24394 ('http' == schema && this.port != 80))) {
24395 port = ':' + this.port;
24396 }
24397
24398 // prepend ? to query
24399 if (query.length) {
24400 query = '?' + query;
24401 }
24402
24403 var ipv6 = this.hostname.indexOf(':') !== -1;
24404 return schema + '://' + (ipv6 ? '[' + this.hostname + ']' : this.hostname) + port + this.path + query;
24405};
24406
24407},{"../transport":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/lib/transport.js","component-inherit":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/node_modules/component-inherit/index.js","debug":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/debug/browser.js","engine.io-parser":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/node_modules/engine.io-parser/lib/browser.js","parseqs":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/node_modules/parseqs/index.js","xmlhttprequest-ssl":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/lib/xmlhttprequest.js","yeast":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/node_modules/yeast/index.js"}],"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/lib/transports/websocket.js":[function(require,module,exports){
24408(function (global){
24409/**
24410 * Module dependencies.
24411 */
24412
24413var Transport = require('../transport');
24414var parser = require('engine.io-parser');
24415var parseqs = require('parseqs');
24416var inherit = require('component-inherit');
24417var yeast = require('yeast');
24418var debug = require('debug')('engine.io-client:websocket');
24419var BrowserWebSocket = global.WebSocket || global.MozWebSocket;
24420
24421/**
24422 * Get either the `WebSocket` or `MozWebSocket` globals
24423 * in the browser or try to resolve WebSocket-compatible
24424 * interface exposed by `ws` for Node-like environment.
24425 */
24426
24427var WebSocket = BrowserWebSocket;
24428if (!WebSocket && typeof window === 'undefined') {
24429 try {
24430 WebSocket = require('ws');
24431 } catch (e) { }
24432}
24433
24434/**
24435 * Module exports.
24436 */
24437
24438module.exports = WS;
24439
24440/**
24441 * WebSocket transport constructor.
24442 *
24443 * @api {Object} connection options
24444 * @api public
24445 */
24446
24447function WS(opts){
24448 var forceBase64 = (opts && opts.forceBase64);
24449 if (forceBase64) {
24450 this.supportsBinary = false;
24451 }
24452 this.perMessageDeflate = opts.perMessageDeflate;
24453 Transport.call(this, opts);
24454}
24455
24456/**
24457 * Inherits from Transport.
24458 */
24459
24460inherit(WS, Transport);
24461
24462/**
24463 * Transport name.
24464 *
24465 * @api public
24466 */
24467
24468WS.prototype.name = 'websocket';
24469
24470/*
24471 * WebSockets support binary
24472 */
24473
24474WS.prototype.supportsBinary = true;
24475
24476/**
24477 * Opens socket.
24478 *
24479 * @api private
24480 */
24481
24482WS.prototype.doOpen = function(){
24483 if (!this.check()) {
24484 // let probe timeout
24485 return;
24486 }
24487
24488 var self = this;
24489 var uri = this.uri();
24490 var protocols = void(0);
24491 var opts = {
24492 agent: this.agent,
24493 perMessageDeflate: this.perMessageDeflate
24494 };
24495
24496 // SSL options for Node.js client
24497 opts.pfx = this.pfx;
24498 opts.key = this.key;
24499 opts.passphrase = this.passphrase;
24500 opts.cert = this.cert;
24501 opts.ca = this.ca;
24502 opts.ciphers = this.ciphers;
24503 opts.rejectUnauthorized = this.rejectUnauthorized;
24504 if (this.extraHeaders) {
24505 opts.headers = this.extraHeaders;
24506 }
24507
24508 this.ws = BrowserWebSocket ? new WebSocket(uri) : new WebSocket(uri, protocols, opts);
24509
24510 if (this.ws.binaryType === undefined) {
24511 this.supportsBinary = false;
24512 }
24513
24514 if (this.ws.supports && this.ws.supports.binary) {
24515 this.supportsBinary = true;
24516 this.ws.binaryType = 'buffer';
24517 } else {
24518 this.ws.binaryType = 'arraybuffer';
24519 }
24520
24521 this.addEventListeners();
24522};
24523
24524/**
24525 * Adds event listeners to the socket
24526 *
24527 * @api private
24528 */
24529
24530WS.prototype.addEventListeners = function(){
24531 var self = this;
24532
24533 this.ws.onopen = function(){
24534 self.onOpen();
24535 };
24536 this.ws.onclose = function(){
24537 self.onClose();
24538 };
24539 this.ws.onmessage = function(ev){
24540 self.onData(ev.data);
24541 };
24542 this.ws.onerror = function(e){
24543 self.onError('websocket error', e);
24544 };
24545};
24546
24547/**
24548 * Override `onData` to use a timer on iOS.
24549 * See: https://gist.github.com/mloughran/2052006
24550 *
24551 * @api private
24552 */
24553
24554if ('undefined' != typeof navigator
24555 && /iPad|iPhone|iPod/i.test(navigator.userAgent)) {
24556 WS.prototype.onData = function(data){
24557 var self = this;
24558 setTimeout(function(){
24559 Transport.prototype.onData.call(self, data);
24560 }, 0);
24561 };
24562}
24563
24564/**
24565 * Writes data to socket.
24566 *
24567 * @param {Array} array of packets.
24568 * @api private
24569 */
24570
24571WS.prototype.write = function(packets){
24572 var self = this;
24573 this.writable = false;
24574
24575 // encodePacket efficient as it uses WS framing
24576 // no need for encodePayload
24577 var total = packets.length;
24578 for (var i = 0, l = total; i < l; i++) {
24579 (function(packet) {
24580 parser.encodePacket(packet, self.supportsBinary, function(data) {
24581 if (!BrowserWebSocket) {
24582 // always create a new object (GH-437)
24583 var opts = {};
24584 if (packet.options) {
24585 opts.compress = packet.options.compress;
24586 }
24587
24588 if (self.perMessageDeflate) {
24589 var len = 'string' == typeof data ? global.Buffer.byteLength(data) : data.length;
24590 if (len < self.perMessageDeflate.threshold) {
24591 opts.compress = false;
24592 }
24593 }
24594 }
24595
24596 //Sometimes the websocket has already been closed but the browser didn't
24597 //have a chance of informing us about it yet, in that case send will
24598 //throw an error
24599 try {
24600 if (BrowserWebSocket) {
24601 // TypeError is thrown when passing the second argument on Safari
24602 self.ws.send(data);
24603 } else {
24604 self.ws.send(data, opts);
24605 }
24606 } catch (e){
24607 debug('websocket closed before onclose event');
24608 }
24609
24610 --total || done();
24611 });
24612 })(packets[i]);
24613 }
24614
24615 function done(){
24616 self.emit('flush');
24617
24618 // fake drain
24619 // defer to next tick to allow Socket to clear writeBuffer
24620 setTimeout(function(){
24621 self.writable = true;
24622 self.emit('drain');
24623 }, 0);
24624 }
24625};
24626
24627/**
24628 * Called upon close
24629 *
24630 * @api private
24631 */
24632
24633WS.prototype.onClose = function(){
24634 Transport.prototype.onClose.call(this);
24635};
24636
24637/**
24638 * Closes socket.
24639 *
24640 * @api private
24641 */
24642
24643WS.prototype.doClose = function(){
24644 if (typeof this.ws !== 'undefined') {
24645 this.ws.close();
24646 }
24647};
24648
24649/**
24650 * Generates uri for connection.
24651 *
24652 * @api private
24653 */
24654
24655WS.prototype.uri = function(){
24656 var query = this.query || {};
24657 var schema = this.secure ? 'wss' : 'ws';
24658 var port = '';
24659
24660 // avoid port if default for schema
24661 if (this.port && (('wss' == schema && this.port != 443)
24662 || ('ws' == schema && this.port != 80))) {
24663 port = ':' + this.port;
24664 }
24665
24666 // append timestamp to URI
24667 if (this.timestampRequests) {
24668 query[this.timestampParam] = yeast();
24669 }
24670
24671 // communicate binary support capabilities
24672 if (!this.supportsBinary) {
24673 query.b64 = 1;
24674 }
24675
24676 query = parseqs.encode(query);
24677
24678 // prepend ? to query
24679 if (query.length) {
24680 query = '?' + query;
24681 }
24682
24683 var ipv6 = this.hostname.indexOf(':') !== -1;
24684 return schema + '://' + (ipv6 ? '[' + this.hostname + ']' : this.hostname) + port + this.path + query;
24685};
24686
24687/**
24688 * Feature detection for WebSocket.
24689 *
24690 * @return {Boolean} whether this transport is available.
24691 * @api public
24692 */
24693
24694WS.prototype.check = function(){
24695 return !!WebSocket && !('__initialize' in WebSocket && this.name === WS.prototype.name);
24696};
24697
24698}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
24699},{"../transport":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/lib/transport.js","component-inherit":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/node_modules/component-inherit/index.js","debug":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/debug/browser.js","engine.io-parser":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/node_modules/engine.io-parser/lib/browser.js","parseqs":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/node_modules/parseqs/index.js","ws":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/browserify/node_modules/browser-resolve/empty.js","yeast":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/node_modules/yeast/index.js"}],"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/lib/xmlhttprequest.js":[function(require,module,exports){
24700// browser shim for xmlhttprequest module
24701var hasCORS = require('has-cors');
24702
24703module.exports = function(opts) {
24704 var xdomain = opts.xdomain;
24705
24706 // scheme must be same when usign XDomainRequest
24707 // http://blogs.msdn.com/b/ieinternals/archive/2010/05/13/xdomainrequest-restrictions-limitations-and-workarounds.aspx
24708 var xscheme = opts.xscheme;
24709
24710 // XDomainRequest has a flow of not sending cookie, therefore it should be disabled as a default.
24711 // https://github.com/Automattic/engine.io-client/pull/217
24712 var enablesXDR = opts.enablesXDR;
24713
24714 // XMLHttpRequest can be disabled on IE
24715 try {
24716 if ('undefined' != typeof XMLHttpRequest && (!xdomain || hasCORS)) {
24717 return new XMLHttpRequest();
24718 }
24719 } catch (e) { }
24720
24721 // Use XDomainRequest for IE8 if enablesXDR is true
24722 // because loading bar keeps flashing when using jsonp-polling
24723 // https://github.com/yujiosaka/socke.io-ie8-loading-example
24724 try {
24725 if ('undefined' != typeof XDomainRequest && !xscheme && enablesXDR) {
24726 return new XDomainRequest();
24727 }
24728 } catch (e) { }
24729
24730 if (!xdomain) {
24731 try {
24732 return new ActiveXObject('Microsoft.XMLHTTP');
24733 } catch(e) { }
24734 }
24735}
24736
24737},{"has-cors":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/node_modules/has-cors/index.js"}],"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/node_modules/component-emitter/index.js":[function(require,module,exports){
24738
24739/**
24740 * Expose `Emitter`.
24741 */
24742
24743module.exports = Emitter;
24744
24745/**
24746 * Initialize a new `Emitter`.
24747 *
24748 * @api public
24749 */
24750
24751function Emitter(obj) {
24752 if (obj) return mixin(obj);
24753};
24754
24755/**
24756 * Mixin the emitter properties.
24757 *
24758 * @param {Object} obj
24759 * @return {Object}
24760 * @api private
24761 */
24762
24763function mixin(obj) {
24764 for (var key in Emitter.prototype) {
24765 obj[key] = Emitter.prototype[key];
24766 }
24767 return obj;
24768}
24769
24770/**
24771 * Listen on the given `event` with `fn`.
24772 *
24773 * @param {String} event
24774 * @param {Function} fn
24775 * @return {Emitter}
24776 * @api public
24777 */
24778
24779Emitter.prototype.on =
24780Emitter.prototype.addEventListener = function(event, fn){
24781 this._callbacks = this._callbacks || {};
24782 (this._callbacks[event] = this._callbacks[event] || [])
24783 .push(fn);
24784 return this;
24785};
24786
24787/**
24788 * Adds an `event` listener that will be invoked a single
24789 * time then automatically removed.
24790 *
24791 * @param {String} event
24792 * @param {Function} fn
24793 * @return {Emitter}
24794 * @api public
24795 */
24796
24797Emitter.prototype.once = function(event, fn){
24798 var self = this;
24799 this._callbacks = this._callbacks || {};
24800
24801 function on() {
24802 self.off(event, on);
24803 fn.apply(this, arguments);
24804 }
24805
24806 on.fn = fn;
24807 this.on(event, on);
24808 return this;
24809};
24810
24811/**
24812 * Remove the given callback for `event` or all
24813 * registered callbacks.
24814 *
24815 * @param {String} event
24816 * @param {Function} fn
24817 * @return {Emitter}
24818 * @api public
24819 */
24820
24821Emitter.prototype.off =
24822Emitter.prototype.removeListener =
24823Emitter.prototype.removeAllListeners =
24824Emitter.prototype.removeEventListener = function(event, fn){
24825 this._callbacks = this._callbacks || {};
24826
24827 // all
24828 if (0 == arguments.length) {
24829 this._callbacks = {};
24830 return this;
24831 }
24832
24833 // specific event
24834 var callbacks = this._callbacks[event];
24835 if (!callbacks) return this;
24836
24837 // remove all handlers
24838 if (1 == arguments.length) {
24839 delete this._callbacks[event];
24840 return this;
24841 }
24842
24843 // remove specific handler
24844 var cb;
24845 for (var i = 0; i < callbacks.length; i++) {
24846 cb = callbacks[i];
24847 if (cb === fn || cb.fn === fn) {
24848 callbacks.splice(i, 1);
24849 break;
24850 }
24851 }
24852 return this;
24853};
24854
24855/**
24856 * Emit `event` with the given args.
24857 *
24858 * @param {String} event
24859 * @param {Mixed} ...
24860 * @return {Emitter}
24861 */
24862
24863Emitter.prototype.emit = function(event){
24864 this._callbacks = this._callbacks || {};
24865 var args = [].slice.call(arguments, 1)
24866 , callbacks = this._callbacks[event];
24867
24868 if (callbacks) {
24869 callbacks = callbacks.slice(0);
24870 for (var i = 0, len = callbacks.length; i < len; ++i) {
24871 callbacks[i].apply(this, args);
24872 }
24873 }
24874
24875 return this;
24876};
24877
24878/**
24879 * Return array of callbacks for `event`.
24880 *
24881 * @param {String} event
24882 * @return {Array}
24883 * @api public
24884 */
24885
24886Emitter.prototype.listeners = function(event){
24887 this._callbacks = this._callbacks || {};
24888 return this._callbacks[event] || [];
24889};
24890
24891/**
24892 * Check if this emitter has `event` handlers.
24893 *
24894 * @param {String} event
24895 * @return {Boolean}
24896 * @api public
24897 */
24898
24899Emitter.prototype.hasListeners = function(event){
24900 return !! this.listeners(event).length;
24901};
24902
24903},{}],"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/node_modules/component-inherit/index.js":[function(require,module,exports){
24904
24905module.exports = function(a, b){
24906 var fn = function(){};
24907 fn.prototype = b.prototype;
24908 a.prototype = new fn;
24909 a.prototype.constructor = a;
24910};
24911},{}],"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/node_modules/engine.io-parser/lib/browser.js":[function(require,module,exports){
24912(function (global){
24913/**
24914 * Module dependencies.
24915 */
24916
24917var keys = require('./keys');
24918var hasBinary = require('has-binary');
24919var sliceBuffer = require('arraybuffer.slice');
24920var base64encoder = require('base64-arraybuffer');
24921var after = require('after');
24922var utf8 = require('utf8');
24923
24924/**
24925 * Check if we are running an android browser. That requires us to use
24926 * ArrayBuffer with polling transports...
24927 *
24928 * http://ghinda.net/jpeg-blob-ajax-android/
24929 */
24930
24931var isAndroid = navigator.userAgent.match(/Android/i);
24932
24933/**
24934 * Check if we are running in PhantomJS.
24935 * Uploading a Blob with PhantomJS does not work correctly, as reported here:
24936 * https://github.com/ariya/phantomjs/issues/11395
24937 * @type boolean
24938 */
24939var isPhantomJS = /PhantomJS/i.test(navigator.userAgent);
24940
24941/**
24942 * When true, avoids using Blobs to encode payloads.
24943 * @type boolean
24944 */
24945var dontSendBlobs = isAndroid || isPhantomJS;
24946
24947/**
24948 * Current protocol version.
24949 */
24950
24951exports.protocol = 3;
24952
24953/**
24954 * Packet types.
24955 */
24956
24957var packets = exports.packets = {
24958 open: 0 // non-ws
24959 , close: 1 // non-ws
24960 , ping: 2
24961 , pong: 3
24962 , message: 4
24963 , upgrade: 5
24964 , noop: 6
24965};
24966
24967var packetslist = keys(packets);
24968
24969/**
24970 * Premade error packet.
24971 */
24972
24973var err = { type: 'error', data: 'parser error' };
24974
24975/**
24976 * Create a blob api even for blob builder when vendor prefixes exist
24977 */
24978
24979var Blob = require('blob');
24980
24981/**
24982 * Encodes a packet.
24983 *
24984 * <packet type id> [ <data> ]
24985 *
24986 * Example:
24987 *
24988 * 5hello world
24989 * 3
24990 * 4
24991 *
24992 * Binary is encoded in an identical principle
24993 *
24994 * @api private
24995 */
24996
24997exports.encodePacket = function (packet, supportsBinary, utf8encode, callback) {
24998 if ('function' == typeof supportsBinary) {
24999 callback = supportsBinary;
25000 supportsBinary = false;
25001 }
25002
25003 if ('function' == typeof utf8encode) {
25004 callback = utf8encode;
25005 utf8encode = null;
25006 }
25007
25008 var data = (packet.data === undefined)
25009 ? undefined
25010 : packet.data.buffer || packet.data;
25011
25012 if (global.ArrayBuffer && data instanceof ArrayBuffer) {
25013 return encodeArrayBuffer(packet, supportsBinary, callback);
25014 } else if (Blob && data instanceof global.Blob) {
25015 return encodeBlob(packet, supportsBinary, callback);
25016 }
25017
25018 // might be an object with { base64: true, data: dataAsBase64String }
25019 if (data && data.base64) {
25020 return encodeBase64Object(packet, callback);
25021 }
25022
25023 // Sending data as a utf-8 string
25024 var encoded = packets[packet.type];
25025
25026 // data fragment is optional
25027 if (undefined !== packet.data) {
25028 encoded += utf8encode ? utf8.encode(String(packet.data)) : String(packet.data);
25029 }
25030
25031 return callback('' + encoded);
25032
25033};
25034
25035function encodeBase64Object(packet, callback) {
25036 // packet data is an object { base64: true, data: dataAsBase64String }
25037 var message = 'b' + exports.packets[packet.type] + packet.data.data;
25038 return callback(message);
25039}
25040
25041/**
25042 * Encode packet helpers for binary types
25043 */
25044
25045function encodeArrayBuffer(packet, supportsBinary, callback) {
25046 if (!supportsBinary) {
25047 return exports.encodeBase64Packet(packet, callback);
25048 }
25049
25050 var data = packet.data;
25051 var contentArray = new Uint8Array(data);
25052 var resultBuffer = new Uint8Array(1 + data.byteLength);
25053
25054 resultBuffer[0] = packets[packet.type];
25055 for (var i = 0; i < contentArray.length; i++) {
25056 resultBuffer[i+1] = contentArray[i];
25057 }
25058
25059 return callback(resultBuffer.buffer);
25060}
25061
25062function encodeBlobAsArrayBuffer(packet, supportsBinary, callback) {
25063 if (!supportsBinary) {
25064 return exports.encodeBase64Packet(packet, callback);
25065 }
25066
25067 var fr = new FileReader();
25068 fr.onload = function() {
25069 packet.data = fr.result;
25070 exports.encodePacket(packet, supportsBinary, true, callback);
25071 };
25072 return fr.readAsArrayBuffer(packet.data);
25073}
25074
25075function encodeBlob(packet, supportsBinary, callback) {
25076 if (!supportsBinary) {
25077 return exports.encodeBase64Packet(packet, callback);
25078 }
25079
25080 if (dontSendBlobs) {
25081 return encodeBlobAsArrayBuffer(packet, supportsBinary, callback);
25082 }
25083
25084 var length = new Uint8Array(1);
25085 length[0] = packets[packet.type];
25086 var blob = new Blob([length.buffer, packet.data]);
25087
25088 return callback(blob);
25089}
25090
25091/**
25092 * Encodes a packet with binary data in a base64 string
25093 *
25094 * @param {Object} packet, has `type` and `data`
25095 * @return {String} base64 encoded message
25096 */
25097
25098exports.encodeBase64Packet = function(packet, callback) {
25099 var message = 'b' + exports.packets[packet.type];
25100 if (Blob && packet.data instanceof global.Blob) {
25101 var fr = new FileReader();
25102 fr.onload = function() {
25103 var b64 = fr.result.split(',')[1];
25104 callback(message + b64);
25105 };
25106 return fr.readAsDataURL(packet.data);
25107 }
25108
25109 var b64data;
25110 try {
25111 b64data = String.fromCharCode.apply(null, new Uint8Array(packet.data));
25112 } catch (e) {
25113 // iPhone Safari doesn't let you apply with typed arrays
25114 var typed = new Uint8Array(packet.data);
25115 var basic = new Array(typed.length);
25116 for (var i = 0; i < typed.length; i++) {
25117 basic[i] = typed[i];
25118 }
25119 b64data = String.fromCharCode.apply(null, basic);
25120 }
25121 message += global.btoa(b64data);
25122 return callback(message);
25123};
25124
25125/**
25126 * Decodes a packet. Changes format to Blob if requested.
25127 *
25128 * @return {Object} with `type` and `data` (if any)
25129 * @api private
25130 */
25131
25132exports.decodePacket = function (data, binaryType, utf8decode) {
25133 // String data
25134 if (typeof data == 'string' || data === undefined) {
25135 if (data.charAt(0) == 'b') {
25136 return exports.decodeBase64Packet(data.substr(1), binaryType);
25137 }
25138
25139 if (utf8decode) {
25140 try {
25141 data = utf8.decode(data);
25142 } catch (e) {
25143 return err;
25144 }
25145 }
25146 var type = data.charAt(0);
25147
25148 if (Number(type) != type || !packetslist[type]) {
25149 return err;
25150 }
25151
25152 if (data.length > 1) {
25153 return { type: packetslist[type], data: data.substring(1) };
25154 } else {
25155 return { type: packetslist[type] };
25156 }
25157 }
25158
25159 var asArray = new Uint8Array(data);
25160 var type = asArray[0];
25161 var rest = sliceBuffer(data, 1);
25162 if (Blob && binaryType === 'blob') {
25163 rest = new Blob([rest]);
25164 }
25165 return { type: packetslist[type], data: rest };
25166};
25167
25168/**
25169 * Decodes a packet encoded in a base64 string
25170 *
25171 * @param {String} base64 encoded message
25172 * @return {Object} with `type` and `data` (if any)
25173 */
25174
25175exports.decodeBase64Packet = function(msg, binaryType) {
25176 var type = packetslist[msg.charAt(0)];
25177 if (!global.ArrayBuffer) {
25178 return { type: type, data: { base64: true, data: msg.substr(1) } };
25179 }
25180
25181 var data = base64encoder.decode(msg.substr(1));
25182
25183 if (binaryType === 'blob' && Blob) {
25184 data = new Blob([data]);
25185 }
25186
25187 return { type: type, data: data };
25188};
25189
25190/**
25191 * Encodes multiple messages (payload).
25192 *
25193 * <length>:data
25194 *
25195 * Example:
25196 *
25197 * 11:hello world2:hi
25198 *
25199 * If any contents are binary, they will be encoded as base64 strings. Base64
25200 * encoded strings are marked with a b before the length specifier
25201 *
25202 * @param {Array} packets
25203 * @api private
25204 */
25205
25206exports.encodePayload = function (packets, supportsBinary, callback) {
25207 if (typeof supportsBinary == 'function') {
25208 callback = supportsBinary;
25209 supportsBinary = null;
25210 }
25211
25212 var isBinary = hasBinary(packets);
25213
25214 if (supportsBinary && isBinary) {
25215 if (Blob && !dontSendBlobs) {
25216 return exports.encodePayloadAsBlob(packets, callback);
25217 }
25218
25219 return exports.encodePayloadAsArrayBuffer(packets, callback);
25220 }
25221
25222 if (!packets.length) {
25223 return callback('0:');
25224 }
25225
25226 function setLengthHeader(message) {
25227 return message.length + ':' + message;
25228 }
25229
25230 function encodeOne(packet, doneCallback) {
25231 exports.encodePacket(packet, !isBinary ? false : supportsBinary, true, function(message) {
25232 doneCallback(null, setLengthHeader(message));
25233 });
25234 }
25235
25236 map(packets, encodeOne, function(err, results) {
25237 return callback(results.join(''));
25238 });
25239};
25240
25241/**
25242 * Async array map using after
25243 */
25244
25245function map(ary, each, done) {
25246 var result = new Array(ary.length);
25247 var next = after(ary.length, done);
25248
25249 var eachWithIndex = function(i, el, cb) {
25250 each(el, function(error, msg) {
25251 result[i] = msg;
25252 cb(error, result);
25253 });
25254 };
25255
25256 for (var i = 0; i < ary.length; i++) {
25257 eachWithIndex(i, ary[i], next);
25258 }
25259}
25260
25261/*
25262 * Decodes data when a payload is maybe expected. Possible binary contents are
25263 * decoded from their base64 representation
25264 *
25265 * @param {String} data, callback method
25266 * @api public
25267 */
25268
25269exports.decodePayload = function (data, binaryType, callback) {
25270 if (typeof data != 'string') {
25271 return exports.decodePayloadAsBinary(data, binaryType, callback);
25272 }
25273
25274 if (typeof binaryType === 'function') {
25275 callback = binaryType;
25276 binaryType = null;
25277 }
25278
25279 var packet;
25280 if (data == '') {
25281 // parser error - ignoring payload
25282 return callback(err, 0, 1);
25283 }
25284
25285 var length = ''
25286 , n, msg;
25287
25288 for (var i = 0, l = data.length; i < l; i++) {
25289 var chr = data.charAt(i);
25290
25291 if (':' != chr) {
25292 length += chr;
25293 } else {
25294 if ('' == length || (length != (n = Number(length)))) {
25295 // parser error - ignoring payload
25296 return callback(err, 0, 1);
25297 }
25298
25299 msg = data.substr(i + 1, n);
25300
25301 if (length != msg.length) {
25302 // parser error - ignoring payload
25303 return callback(err, 0, 1);
25304 }
25305
25306 if (msg.length) {
25307 packet = exports.decodePacket(msg, binaryType, true);
25308
25309 if (err.type == packet.type && err.data == packet.data) {
25310 // parser error in individual packet - ignoring payload
25311 return callback(err, 0, 1);
25312 }
25313
25314 var ret = callback(packet, i + n, l);
25315 if (false === ret) return;
25316 }
25317
25318 // advance cursor
25319 i += n;
25320 length = '';
25321 }
25322 }
25323
25324 if (length != '') {
25325 // parser error - ignoring payload
25326 return callback(err, 0, 1);
25327 }
25328
25329};
25330
25331/**
25332 * Encodes multiple messages (payload) as binary.
25333 *
25334 * <1 = binary, 0 = string><number from 0-9><number from 0-9>[...]<number
25335 * 255><data>
25336 *
25337 * Example:
25338 * 1 3 255 1 2 3, if the binary contents are interpreted as 8 bit integers
25339 *
25340 * @param {Array} packets
25341 * @return {ArrayBuffer} encoded payload
25342 * @api private
25343 */
25344
25345exports.encodePayloadAsArrayBuffer = function(packets, callback) {
25346 if (!packets.length) {
25347 return callback(new ArrayBuffer(0));
25348 }
25349
25350 function encodeOne(packet, doneCallback) {
25351 exports.encodePacket(packet, true, true, function(data) {
25352 return doneCallback(null, data);
25353 });
25354 }
25355
25356 map(packets, encodeOne, function(err, encodedPackets) {
25357 var totalLength = encodedPackets.reduce(function(acc, p) {
25358 var len;
25359 if (typeof p === 'string'){
25360 len = p.length;
25361 } else {
25362 len = p.byteLength;
25363 }
25364 return acc + len.toString().length + len + 2; // string/binary identifier + separator = 2
25365 }, 0);
25366
25367 var resultArray = new Uint8Array(totalLength);
25368
25369 var bufferIndex = 0;
25370 encodedPackets.forEach(function(p) {
25371 var isString = typeof p === 'string';
25372 var ab = p;
25373 if (isString) {
25374 var view = new Uint8Array(p.length);
25375 for (var i = 0; i < p.length; i++) {
25376 view[i] = p.charCodeAt(i);
25377 }
25378 ab = view.buffer;
25379 }
25380
25381 if (isString) { // not true binary
25382 resultArray[bufferIndex++] = 0;
25383 } else { // true binary
25384 resultArray[bufferIndex++] = 1;
25385 }
25386
25387 var lenStr = ab.byteLength.toString();
25388 for (var i = 0; i < lenStr.length; i++) {
25389 resultArray[bufferIndex++] = parseInt(lenStr[i]);
25390 }
25391 resultArray[bufferIndex++] = 255;
25392
25393 var view = new Uint8Array(ab);
25394 for (var i = 0; i < view.length; i++) {
25395 resultArray[bufferIndex++] = view[i];
25396 }
25397 });
25398
25399 return callback(resultArray.buffer);
25400 });
25401};
25402
25403/**
25404 * Encode as Blob
25405 */
25406
25407exports.encodePayloadAsBlob = function(packets, callback) {
25408 function encodeOne(packet, doneCallback) {
25409 exports.encodePacket(packet, true, true, function(encoded) {
25410 var binaryIdentifier = new Uint8Array(1);
25411 binaryIdentifier[0] = 1;
25412 if (typeof encoded === 'string') {
25413 var view = new Uint8Array(encoded.length);
25414 for (var i = 0; i < encoded.length; i++) {
25415 view[i] = encoded.charCodeAt(i);
25416 }
25417 encoded = view.buffer;
25418 binaryIdentifier[0] = 0;
25419 }
25420
25421 var len = (encoded instanceof ArrayBuffer)
25422 ? encoded.byteLength
25423 : encoded.size;
25424
25425 var lenStr = len.toString();
25426 var lengthAry = new Uint8Array(lenStr.length + 1);
25427 for (var i = 0; i < lenStr.length; i++) {
25428 lengthAry[i] = parseInt(lenStr[i]);
25429 }
25430 lengthAry[lenStr.length] = 255;
25431
25432 if (Blob) {
25433 var blob = new Blob([binaryIdentifier.buffer, lengthAry.buffer, encoded]);
25434 doneCallback(null, blob);
25435 }
25436 });
25437 }
25438
25439 map(packets, encodeOne, function(err, results) {
25440 return callback(new Blob(results));
25441 });
25442};
25443
25444/*
25445 * Decodes data when a payload is maybe expected. Strings are decoded by
25446 * interpreting each byte as a key code for entries marked to start with 0. See
25447 * description of encodePayloadAsBinary
25448 *
25449 * @param {ArrayBuffer} data, callback method
25450 * @api public
25451 */
25452
25453exports.decodePayloadAsBinary = function (data, binaryType, callback) {
25454 if (typeof binaryType === 'function') {
25455 callback = binaryType;
25456 binaryType = null;
25457 }
25458
25459 var bufferTail = data;
25460 var buffers = [];
25461
25462 var numberTooLong = false;
25463 while (bufferTail.byteLength > 0) {
25464 var tailArray = new Uint8Array(bufferTail);
25465 var isString = tailArray[0] === 0;
25466 var msgLength = '';
25467
25468 for (var i = 1; ; i++) {
25469 if (tailArray[i] == 255) break;
25470
25471 if (msgLength.length > 310) {
25472 numberTooLong = true;
25473 break;
25474 }
25475
25476 msgLength += tailArray[i];
25477 }
25478
25479 if(numberTooLong) return callback(err, 0, 1);
25480
25481 bufferTail = sliceBuffer(bufferTail, 2 + msgLength.length);
25482 msgLength = parseInt(msgLength);
25483
25484 var msg = sliceBuffer(bufferTail, 0, msgLength);
25485 if (isString) {
25486 try {
25487 msg = String.fromCharCode.apply(null, new Uint8Array(msg));
25488 } catch (e) {
25489 // iPhone Safari doesn't let you apply to typed arrays
25490 var typed = new Uint8Array(msg);
25491 msg = '';
25492 for (var i = 0; i < typed.length; i++) {
25493 msg += String.fromCharCode(typed[i]);
25494 }
25495 }
25496 }
25497
25498 buffers.push(msg);
25499 bufferTail = sliceBuffer(bufferTail, msgLength);
25500 }
25501
25502 var total = buffers.length;
25503 buffers.forEach(function(buffer, i) {
25504 callback(exports.decodePacket(buffer, binaryType, true), i, total);
25505 });
25506};
25507
25508}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
25509},{"./keys":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/node_modules/engine.io-parser/lib/keys.js","after":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/node_modules/engine.io-parser/node_modules/after/index.js","arraybuffer.slice":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/node_modules/engine.io-parser/node_modules/arraybuffer.slice/index.js","base64-arraybuffer":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/node_modules/engine.io-parser/node_modules/base64-arraybuffer/lib/base64-arraybuffer.js","blob":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/node_modules/engine.io-parser/node_modules/blob/index.js","has-binary":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/node_modules/engine.io-parser/node_modules/has-binary/index.js","utf8":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/node_modules/engine.io-parser/node_modules/utf8/utf8.js"}],"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/node_modules/engine.io-parser/lib/keys.js":[function(require,module,exports){
25510
25511/**
25512 * Gets the keys for an object.
25513 *
25514 * @return {Array} keys
25515 * @api private
25516 */
25517
25518module.exports = Object.keys || function keys (obj){
25519 var arr = [];
25520 var has = Object.prototype.hasOwnProperty;
25521
25522 for (var i in obj) {
25523 if (has.call(obj, i)) {
25524 arr.push(i);
25525 }
25526 }
25527 return arr;
25528};
25529
25530},{}],"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/node_modules/engine.io-parser/node_modules/after/index.js":[function(require,module,exports){
25531module.exports = after
25532
25533function after(count, callback, err_cb) {
25534 var bail = false
25535 err_cb = err_cb || noop
25536 proxy.count = count
25537
25538 return (count === 0) ? callback() : proxy
25539
25540 function proxy(err, result) {
25541 if (proxy.count <= 0) {
25542 throw new Error('after called too many times')
25543 }
25544 --proxy.count
25545
25546 // after first error, rest are passed to err_cb
25547 if (err) {
25548 bail = true
25549 callback(err)
25550 // future error callbacks will go to error handler
25551 callback = err_cb
25552 } else if (proxy.count === 0 && !bail) {
25553 callback(null, result)
25554 }
25555 }
25556}
25557
25558function noop() {}
25559
25560},{}],"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/node_modules/engine.io-parser/node_modules/arraybuffer.slice/index.js":[function(require,module,exports){
25561/**
25562 * An abstraction for slicing an arraybuffer even when
25563 * ArrayBuffer.prototype.slice is not supported
25564 *
25565 * @api public
25566 */
25567
25568module.exports = function(arraybuffer, start, end) {
25569 var bytes = arraybuffer.byteLength;
25570 start = start || 0;
25571 end = end || bytes;
25572
25573 if (arraybuffer.slice) { return arraybuffer.slice(start, end); }
25574
25575 if (start < 0) { start += bytes; }
25576 if (end < 0) { end += bytes; }
25577 if (end > bytes) { end = bytes; }
25578
25579 if (start >= bytes || start >= end || bytes === 0) {
25580 return new ArrayBuffer(0);
25581 }
25582
25583 var abv = new Uint8Array(arraybuffer);
25584 var result = new Uint8Array(end - start);
25585 for (var i = start, ii = 0; i < end; i++, ii++) {
25586 result[ii] = abv[i];
25587 }
25588 return result.buffer;
25589};
25590
25591},{}],"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/node_modules/engine.io-parser/node_modules/base64-arraybuffer/lib/base64-arraybuffer.js":[function(require,module,exports){
25592/*
25593 * base64-arraybuffer
25594 * https://github.com/niklasvh/base64-arraybuffer
25595 *
25596 * Copyright (c) 2012 Niklas von Hertzen
25597 * Licensed under the MIT license.
25598 */
25599(function(chars){
25600 "use strict";
25601
25602 exports.encode = function(arraybuffer) {
25603 var bytes = new Uint8Array(arraybuffer),
25604 i, len = bytes.length, base64 = "";
25605
25606 for (i = 0; i < len; i+=3) {
25607 base64 += chars[bytes[i] >> 2];
25608 base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];
25609 base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];
25610 base64 += chars[bytes[i + 2] & 63];
25611 }
25612
25613 if ((len % 3) === 2) {
25614 base64 = base64.substring(0, base64.length - 1) + "=";
25615 } else if (len % 3 === 1) {
25616 base64 = base64.substring(0, base64.length - 2) + "==";
25617 }
25618
25619 return base64;
25620 };
25621
25622 exports.decode = function(base64) {
25623 var bufferLength = base64.length * 0.75,
25624 len = base64.length, i, p = 0,
25625 encoded1, encoded2, encoded3, encoded4;
25626
25627 if (base64[base64.length - 1] === "=") {
25628 bufferLength--;
25629 if (base64[base64.length - 2] === "=") {
25630 bufferLength--;
25631 }
25632 }
25633
25634 var arraybuffer = new ArrayBuffer(bufferLength),
25635 bytes = new Uint8Array(arraybuffer);
25636
25637 for (i = 0; i < len; i+=4) {
25638 encoded1 = chars.indexOf(base64[i]);
25639 encoded2 = chars.indexOf(base64[i+1]);
25640 encoded3 = chars.indexOf(base64[i+2]);
25641 encoded4 = chars.indexOf(base64[i+3]);
25642
25643 bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);
25644 bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);
25645 bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);
25646 }
25647
25648 return arraybuffer;
25649 };
25650})("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/");
25651
25652},{}],"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/node_modules/engine.io-parser/node_modules/blob/index.js":[function(require,module,exports){
25653(function (global){
25654/**
25655 * Create a blob builder even when vendor prefixes exist
25656 */
25657
25658var BlobBuilder = global.BlobBuilder
25659 || global.WebKitBlobBuilder
25660 || global.MSBlobBuilder
25661 || global.MozBlobBuilder;
25662
25663/**
25664 * Check if Blob constructor is supported
25665 */
25666
25667var blobSupported = (function() {
25668 try {
25669 var a = new Blob(['hi']);
25670 return a.size === 2;
25671 } catch(e) {
25672 return false;
25673 }
25674})();
25675
25676/**
25677 * Check if Blob constructor supports ArrayBufferViews
25678 * Fails in Safari 6, so we need to map to ArrayBuffers there.
25679 */
25680
25681var blobSupportsArrayBufferView = blobSupported && (function() {
25682 try {
25683 var b = new Blob([new Uint8Array([1,2])]);
25684 return b.size === 2;
25685 } catch(e) {
25686 return false;
25687 }
25688})();
25689
25690/**
25691 * Check if BlobBuilder is supported
25692 */
25693
25694var blobBuilderSupported = BlobBuilder
25695 && BlobBuilder.prototype.append
25696 && BlobBuilder.prototype.getBlob;
25697
25698/**
25699 * Helper function that maps ArrayBufferViews to ArrayBuffers
25700 * Used by BlobBuilder constructor and old browsers that didn't
25701 * support it in the Blob constructor.
25702 */
25703
25704function mapArrayBufferViews(ary) {
25705 for (var i = 0; i < ary.length; i++) {
25706 var chunk = ary[i];
25707 if (chunk.buffer instanceof ArrayBuffer) {
25708 var buf = chunk.buffer;
25709
25710 // if this is a subarray, make a copy so we only
25711 // include the subarray region from the underlying buffer
25712 if (chunk.byteLength !== buf.byteLength) {
25713 var copy = new Uint8Array(chunk.byteLength);
25714 copy.set(new Uint8Array(buf, chunk.byteOffset, chunk.byteLength));
25715 buf = copy.buffer;
25716 }
25717
25718 ary[i] = buf;
25719 }
25720 }
25721}
25722
25723function BlobBuilderConstructor(ary, options) {
25724 options = options || {};
25725
25726 var bb = new BlobBuilder();
25727 mapArrayBufferViews(ary);
25728
25729 for (var i = 0; i < ary.length; i++) {
25730 bb.append(ary[i]);
25731 }
25732
25733 return (options.type) ? bb.getBlob(options.type) : bb.getBlob();
25734};
25735
25736function BlobConstructor(ary, options) {
25737 mapArrayBufferViews(ary);
25738 return new Blob(ary, options || {});
25739};
25740
25741module.exports = (function() {
25742 if (blobSupported) {
25743 return blobSupportsArrayBufferView ? global.Blob : BlobConstructor;
25744 } else if (blobBuilderSupported) {
25745 return BlobBuilderConstructor;
25746 } else {
25747 return undefined;
25748 }
25749})();
25750
25751}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
25752},{}],"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/node_modules/engine.io-parser/node_modules/has-binary/index.js":[function(require,module,exports){
25753(function (global){
25754
25755/*
25756 * Module requirements.
25757 */
25758
25759var isArray = require('isarray');
25760
25761/**
25762 * Module exports.
25763 */
25764
25765module.exports = hasBinary;
25766
25767/**
25768 * Checks for binary data.
25769 *
25770 * Right now only Buffer and ArrayBuffer are supported..
25771 *
25772 * @param {Object} anything
25773 * @api public
25774 */
25775
25776function hasBinary(data) {
25777
25778 function _hasBinary(obj) {
25779 if (!obj) return false;
25780
25781 if ( (global.Buffer && global.Buffer.isBuffer(obj)) ||
25782 (global.ArrayBuffer && obj instanceof ArrayBuffer) ||
25783 (global.Blob && obj instanceof Blob) ||
25784 (global.File && obj instanceof File)
25785 ) {
25786 return true;
25787 }
25788
25789 if (isArray(obj)) {
25790 for (var i = 0; i < obj.length; i++) {
25791 if (_hasBinary(obj[i])) {
25792 return true;
25793 }
25794 }
25795 } else if (obj && 'object' == typeof obj) {
25796 if (obj.toJSON) {
25797 obj = obj.toJSON();
25798 }
25799
25800 for (var key in obj) {
25801 if (Object.prototype.hasOwnProperty.call(obj, key) && _hasBinary(obj[key])) {
25802 return true;
25803 }
25804 }
25805 }
25806
25807 return false;
25808 }
25809
25810 return _hasBinary(data);
25811}
25812
25813}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
25814},{"isarray":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/node_modules/engine.io-parser/node_modules/has-binary/node_modules/isarray/index.js"}],"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/node_modules/engine.io-parser/node_modules/has-binary/node_modules/isarray/index.js":[function(require,module,exports){
25815module.exports = Array.isArray || function (arr) {
25816 return Object.prototype.toString.call(arr) == '[object Array]';
25817};
25818
25819},{}],"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/node_modules/engine.io-parser/node_modules/utf8/utf8.js":[function(require,module,exports){
25820(function (global){
25821/*! https://mths.be/utf8js v2.0.0 by @mathias */
25822;(function(root) {
25823
25824 // Detect free variables `exports`
25825 var freeExports = typeof exports == 'object' && exports;
25826
25827 // Detect free variable `module`
25828 var freeModule = typeof module == 'object' && module &&
25829 module.exports == freeExports && module;
25830
25831 // Detect free variable `global`, from Node.js or Browserified code,
25832 // and use it as `root`
25833 var freeGlobal = typeof global == 'object' && global;
25834 if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) {
25835 root = freeGlobal;
25836 }
25837
25838 /*--------------------------------------------------------------------------*/
25839
25840 var stringFromCharCode = String.fromCharCode;
25841
25842 // Taken from https://mths.be/punycode
25843 function ucs2decode(string) {
25844 var output = [];
25845 var counter = 0;
25846 var length = string.length;
25847 var value;
25848 var extra;
25849 while (counter < length) {
25850 value = string.charCodeAt(counter++);
25851 if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
25852 // high surrogate, and there is a next character
25853 extra = string.charCodeAt(counter++);
25854 if ((extra & 0xFC00) == 0xDC00) { // low surrogate
25855 output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
25856 } else {
25857 // unmatched surrogate; only append this code unit, in case the next
25858 // code unit is the high surrogate of a surrogate pair
25859 output.push(value);
25860 counter--;
25861 }
25862 } else {
25863 output.push(value);
25864 }
25865 }
25866 return output;
25867 }
25868
25869 // Taken from https://mths.be/punycode
25870 function ucs2encode(array) {
25871 var length = array.length;
25872 var index = -1;
25873 var value;
25874 var output = '';
25875 while (++index < length) {
25876 value = array[index];
25877 if (value > 0xFFFF) {
25878 value -= 0x10000;
25879 output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
25880 value = 0xDC00 | value & 0x3FF;
25881 }
25882 output += stringFromCharCode(value);
25883 }
25884 return output;
25885 }
25886
25887 function checkScalarValue(codePoint) {
25888 if (codePoint >= 0xD800 && codePoint <= 0xDFFF) {
25889 throw Error(
25890 'Lone surrogate U+' + codePoint.toString(16).toUpperCase() +
25891 ' is not a scalar value'
25892 );
25893 }
25894 }
25895 /*--------------------------------------------------------------------------*/
25896
25897 function createByte(codePoint, shift) {
25898 return stringFromCharCode(((codePoint >> shift) & 0x3F) | 0x80);
25899 }
25900
25901 function encodeCodePoint(codePoint) {
25902 if ((codePoint & 0xFFFFFF80) == 0) { // 1-byte sequence
25903 return stringFromCharCode(codePoint);
25904 }
25905 var symbol = '';
25906 if ((codePoint & 0xFFFFF800) == 0) { // 2-byte sequence
25907 symbol = stringFromCharCode(((codePoint >> 6) & 0x1F) | 0xC0);
25908 }
25909 else if ((codePoint & 0xFFFF0000) == 0) { // 3-byte sequence
25910 checkScalarValue(codePoint);
25911 symbol = stringFromCharCode(((codePoint >> 12) & 0x0F) | 0xE0);
25912 symbol += createByte(codePoint, 6);
25913 }
25914 else if ((codePoint & 0xFFE00000) == 0) { // 4-byte sequence
25915 symbol = stringFromCharCode(((codePoint >> 18) & 0x07) | 0xF0);
25916 symbol += createByte(codePoint, 12);
25917 symbol += createByte(codePoint, 6);
25918 }
25919 symbol += stringFromCharCode((codePoint & 0x3F) | 0x80);
25920 return symbol;
25921 }
25922
25923 function utf8encode(string) {
25924 var codePoints = ucs2decode(string);
25925 var length = codePoints.length;
25926 var index = -1;
25927 var codePoint;
25928 var byteString = '';
25929 while (++index < length) {
25930 codePoint = codePoints[index];
25931 byteString += encodeCodePoint(codePoint);
25932 }
25933 return byteString;
25934 }
25935
25936 /*--------------------------------------------------------------------------*/
25937
25938 function readContinuationByte() {
25939 if (byteIndex >= byteCount) {
25940 throw Error('Invalid byte index');
25941 }
25942
25943 var continuationByte = byteArray[byteIndex] & 0xFF;
25944 byteIndex++;
25945
25946 if ((continuationByte & 0xC0) == 0x80) {
25947 return continuationByte & 0x3F;
25948 }
25949
25950 // If we end up here, it’s not a continuation byte
25951 throw Error('Invalid continuation byte');
25952 }
25953
25954 function decodeSymbol() {
25955 var byte1;
25956 var byte2;
25957 var byte3;
25958 var byte4;
25959 var codePoint;
25960
25961 if (byteIndex > byteCount) {
25962 throw Error('Invalid byte index');
25963 }
25964
25965 if (byteIndex == byteCount) {
25966 return false;
25967 }
25968
25969 // Read first byte
25970 byte1 = byteArray[byteIndex] & 0xFF;
25971 byteIndex++;
25972
25973 // 1-byte sequence (no continuation bytes)
25974 if ((byte1 & 0x80) == 0) {
25975 return byte1;
25976 }
25977
25978 // 2-byte sequence
25979 if ((byte1 & 0xE0) == 0xC0) {
25980 var byte2 = readContinuationByte();
25981 codePoint = ((byte1 & 0x1F) << 6) | byte2;
25982 if (codePoint >= 0x80) {
25983 return codePoint;
25984 } else {
25985 throw Error('Invalid continuation byte');
25986 }
25987 }
25988
25989 // 3-byte sequence (may include unpaired surrogates)
25990 if ((byte1 & 0xF0) == 0xE0) {
25991 byte2 = readContinuationByte();
25992 byte3 = readContinuationByte();
25993 codePoint = ((byte1 & 0x0F) << 12) | (byte2 << 6) | byte3;
25994 if (codePoint >= 0x0800) {
25995 checkScalarValue(codePoint);
25996 return codePoint;
25997 } else {
25998 throw Error('Invalid continuation byte');
25999 }
26000 }
26001
26002 // 4-byte sequence
26003 if ((byte1 & 0xF8) == 0xF0) {
26004 byte2 = readContinuationByte();
26005 byte3 = readContinuationByte();
26006 byte4 = readContinuationByte();
26007 codePoint = ((byte1 & 0x0F) << 0x12) | (byte2 << 0x0C) |
26008 (byte3 << 0x06) | byte4;
26009 if (codePoint >= 0x010000 && codePoint <= 0x10FFFF) {
26010 return codePoint;
26011 }
26012 }
26013
26014 throw Error('Invalid UTF-8 detected');
26015 }
26016
26017 var byteArray;
26018 var byteCount;
26019 var byteIndex;
26020 function utf8decode(byteString) {
26021 byteArray = ucs2decode(byteString);
26022 byteCount = byteArray.length;
26023 byteIndex = 0;
26024 var codePoints = [];
26025 var tmp;
26026 while ((tmp = decodeSymbol()) !== false) {
26027 codePoints.push(tmp);
26028 }
26029 return ucs2encode(codePoints);
26030 }
26031
26032 /*--------------------------------------------------------------------------*/
26033
26034 var utf8 = {
26035 'version': '2.0.0',
26036 'encode': utf8encode,
26037 'decode': utf8decode
26038 };
26039
26040 // Some AMD build optimizers, like r.js, check for specific condition patterns
26041 // like the following:
26042 if (
26043 typeof define == 'function' &&
26044 typeof define.amd == 'object' &&
26045 define.amd
26046 ) {
26047 define(function() {
26048 return utf8;
26049 });
26050 } else if (freeExports && !freeExports.nodeType) {
26051 if (freeModule) { // in Node.js or RingoJS v0.8.0+
26052 freeModule.exports = utf8;
26053 } else { // in Narwhal or RingoJS v0.7.0-
26054 var object = {};
26055 var hasOwnProperty = object.hasOwnProperty;
26056 for (var key in utf8) {
26057 hasOwnProperty.call(utf8, key) && (freeExports[key] = utf8[key]);
26058 }
26059 }
26060 } else { // in Rhino or a web browser
26061 root.utf8 = utf8;
26062 }
26063
26064}(this));
26065
26066}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
26067},{}],"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/node_modules/has-cors/index.js":[function(require,module,exports){
26068
26069/**
26070 * Module exports.
26071 *
26072 * Logic borrowed from Modernizr:
26073 *
26074 * - https://github.com/Modernizr/Modernizr/blob/master/feature-detects/cors.js
26075 */
26076
26077try {
26078 module.exports = typeof XMLHttpRequest !== 'undefined' &&
26079 'withCredentials' in new XMLHttpRequest();
26080} catch (err) {
26081 // if XMLHttp support is disabled in IE then it will throw
26082 // when trying to create
26083 module.exports = false;
26084}
26085
26086},{}],"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/node_modules/parsejson/index.js":[function(require,module,exports){
26087(function (global){
26088/**
26089 * JSON parse.
26090 *
26091 * @see Based on jQuery#parseJSON (MIT) and JSON2
26092 * @api private
26093 */
26094
26095var rvalidchars = /^[\],:{}\s]*$/;
26096var rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g;
26097var rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g;
26098var rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g;
26099var rtrimLeft = /^\s+/;
26100var rtrimRight = /\s+$/;
26101
26102module.exports = function parsejson(data) {
26103 if ('string' != typeof data || !data) {
26104 return null;
26105 }
26106
26107 data = data.replace(rtrimLeft, '').replace(rtrimRight, '');
26108
26109 // Attempt to parse using the native JSON parser first
26110 if (global.JSON && JSON.parse) {
26111 return JSON.parse(data);
26112 }
26113
26114 if (rvalidchars.test(data.replace(rvalidescape, '@')
26115 .replace(rvalidtokens, ']')
26116 .replace(rvalidbraces, ''))) {
26117 return (new Function('return ' + data))();
26118 }
26119};
26120}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
26121},{}],"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/node_modules/parseqs/index.js":[function(require,module,exports){
26122/**
26123 * Compiles a querystring
26124 * Returns string representation of the object
26125 *
26126 * @param {Object}
26127 * @api private
26128 */
26129
26130exports.encode = function (obj) {
26131 var str = '';
26132
26133 for (var i in obj) {
26134 if (obj.hasOwnProperty(i)) {
26135 if (str.length) str += '&';
26136 str += encodeURIComponent(i) + '=' + encodeURIComponent(obj[i]);
26137 }
26138 }
26139
26140 return str;
26141};
26142
26143/**
26144 * Parses a simple querystring into an object
26145 *
26146 * @param {String} qs
26147 * @api private
26148 */
26149
26150exports.decode = function(qs){
26151 var qry = {};
26152 var pairs = qs.split('&');
26153 for (var i = 0, l = pairs.length; i < l; i++) {
26154 var pair = pairs[i].split('=');
26155 qry[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
26156 }
26157 return qry;
26158};
26159
26160},{}],"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/node_modules/yeast/index.js":[function(require,module,exports){
26161'use strict';
26162
26163var alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_'.split('')
26164 , length = 64
26165 , map = {}
26166 , seed = 0
26167 , i = 0
26168 , prev;
26169
26170/**
26171 * Return a string representing the specified number.
26172 *
26173 * @param {Number} num The number to convert.
26174 * @returns {String} The string representation of the number.
26175 * @api public
26176 */
26177function encode(num) {
26178 var encoded = '';
26179
26180 do {
26181 encoded = alphabet[num % length] + encoded;
26182 num = Math.floor(num / length);
26183 } while (num > 0);
26184
26185 return encoded;
26186}
26187
26188/**
26189 * Return the integer value specified by the given string.
26190 *
26191 * @param {String} str The string to convert.
26192 * @returns {Number} The integer value represented by the string.
26193 * @api public
26194 */
26195function decode(str) {
26196 var decoded = 0;
26197
26198 for (i = 0; i < str.length; i++) {
26199 decoded = decoded * length + map[str.charAt(i)];
26200 }
26201
26202 return decoded;
26203}
26204
26205/**
26206 * Yeast: A tiny growing id generator.
26207 *
26208 * @returns {String} A unique id.
26209 * @api public
26210 */
26211function yeast() {
26212 var now = encode(+new Date());
26213
26214 if (now !== prev) return seed = 0, prev = now;
26215 return now +'.'+ encode(seed++);
26216}
26217
26218//
26219// Map each character to its index.
26220//
26221for (; i < length; i++) map[alphabet[i]] = i;
26222
26223//
26224// Expose the `yeast`, `encode` and `decode` functions.
26225//
26226yeast.encode = encode;
26227yeast.decode = decode;
26228module.exports = yeast;
26229
26230},{}],"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/has-binary/index.js":[function(require,module,exports){
26231(function (global){
26232
26233/*
26234 * Module requirements.
26235 */
26236
26237var isArray = require('isarray');
26238
26239/**
26240 * Module exports.
26241 */
26242
26243module.exports = hasBinary;
26244
26245/**
26246 * Checks for binary data.
26247 *
26248 * Right now only Buffer and ArrayBuffer are supported..
26249 *
26250 * @param {Object} anything
26251 * @api public
26252 */
26253
26254function hasBinary(data) {
26255
26256 function _hasBinary(obj) {
26257 if (!obj) return false;
26258
26259 if ( (global.Buffer && global.Buffer.isBuffer && global.Buffer.isBuffer(obj)) ||
26260 (global.ArrayBuffer && obj instanceof ArrayBuffer) ||
26261 (global.Blob && obj instanceof Blob) ||
26262 (global.File && obj instanceof File)
26263 ) {
26264 return true;
26265 }
26266
26267 if (isArray(obj)) {
26268 for (var i = 0; i < obj.length; i++) {
26269 if (_hasBinary(obj[i])) {
26270 return true;
26271 }
26272 }
26273 } else if (obj && 'object' == typeof obj) {
26274 // see: https://github.com/Automattic/has-binary/pull/4
26275 if (obj.toJSON && 'function' == typeof obj.toJSON) {
26276 obj = obj.toJSON();
26277 }
26278
26279 for (var key in obj) {
26280 if (Object.prototype.hasOwnProperty.call(obj, key) && _hasBinary(obj[key])) {
26281 return true;
26282 }
26283 }
26284 }
26285
26286 return false;
26287 }
26288
26289 return _hasBinary(data);
26290}
26291
26292}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
26293},{"isarray":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/has-binary/node_modules/isarray/index.js"}],"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/has-binary/node_modules/isarray/index.js":[function(require,module,exports){
26294arguments[4]["/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/node_modules/engine.io-parser/node_modules/has-binary/node_modules/isarray/index.js"][0].apply(exports,arguments)
26295},{}],"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/indexof/index.js":[function(require,module,exports){
26296
26297var indexOf = [].indexOf;
26298
26299module.exports = function(arr, obj){
26300 if (indexOf) return arr.indexOf(obj);
26301 for (var i = 0; i < arr.length; ++i) {
26302 if (arr[i] === obj) return i;
26303 }
26304 return -1;
26305};
26306},{}],"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/parseuri/index.js":[function(require,module,exports){
26307/**
26308 * Parses an URI
26309 *
26310 * @author Steven Levithan <stevenlevithan.com> (MIT license)
26311 * @api private
26312 */
26313
26314var re = /^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
26315
26316var parts = [
26317 'source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'
26318];
26319
26320module.exports = function parseuri(str) {
26321 var src = str,
26322 b = str.indexOf('['),
26323 e = str.indexOf(']');
26324
26325 if (b != -1 && e != -1) {
26326 str = str.substring(0, b) + str.substring(b, e).replace(/:/g, ';') + str.substring(e, str.length);
26327 }
26328
26329 var m = re.exec(str || ''),
26330 uri = {},
26331 i = 14;
26332
26333 while (i--) {
26334 uri[parts[i]] = m[i] || '';
26335 }
26336
26337 if (b != -1 && e != -1) {
26338 uri.source = src;
26339 uri.host = uri.host.substring(1, uri.host.length - 1).replace(/;/g, ':');
26340 uri.authority = uri.authority.replace('[', '').replace(']', '').replace(/;/g, ':');
26341 uri.ipv6uri = true;
26342 }
26343
26344 return uri;
26345};
26346
26347},{}],"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/socket.io-parser/binary.js":[function(require,module,exports){
26348(function (global){
26349/*global Blob,File*/
26350
26351/**
26352 * Module requirements
26353 */
26354
26355var isArray = require('isarray');
26356var isBuf = require('./is-buffer');
26357
26358/**
26359 * Replaces every Buffer | ArrayBuffer in packet with a numbered placeholder.
26360 * Anything with blobs or files should be fed through removeBlobs before coming
26361 * here.
26362 *
26363 * @param {Object} packet - socket.io event packet
26364 * @return {Object} with deconstructed packet and list of buffers
26365 * @api public
26366 */
26367
26368exports.deconstructPacket = function(packet){
26369 var buffers = [];
26370 var packetData = packet.data;
26371
26372 function _deconstructPacket(data) {
26373 if (!data) return data;
26374
26375 if (isBuf(data)) {
26376 var placeholder = { _placeholder: true, num: buffers.length };
26377 buffers.push(data);
26378 return placeholder;
26379 } else if (isArray(data)) {
26380 var newData = new Array(data.length);
26381 for (var i = 0; i < data.length; i++) {
26382 newData[i] = _deconstructPacket(data[i]);
26383 }
26384 return newData;
26385 } else if ('object' == typeof data && !(data instanceof Date)) {
26386 var newData = {};
26387 for (var key in data) {
26388 newData[key] = _deconstructPacket(data[key]);
26389 }
26390 return newData;
26391 }
26392 return data;
26393 }
26394
26395 var pack = packet;
26396 pack.data = _deconstructPacket(packetData);
26397 pack.attachments = buffers.length; // number of binary 'attachments'
26398 return {packet: pack, buffers: buffers};
26399};
26400
26401/**
26402 * Reconstructs a binary packet from its placeholder packet and buffers
26403 *
26404 * @param {Object} packet - event packet with placeholders
26405 * @param {Array} buffers - binary buffers to put in placeholder positions
26406 * @return {Object} reconstructed packet
26407 * @api public
26408 */
26409
26410exports.reconstructPacket = function(packet, buffers) {
26411 var curPlaceHolder = 0;
26412
26413 function _reconstructPacket(data) {
26414 if (data && data._placeholder) {
26415 var buf = buffers[data.num]; // appropriate buffer (should be natural order anyway)
26416 return buf;
26417 } else if (isArray(data)) {
26418 for (var i = 0; i < data.length; i++) {
26419 data[i] = _reconstructPacket(data[i]);
26420 }
26421 return data;
26422 } else if (data && 'object' == typeof data) {
26423 for (var key in data) {
26424 data[key] = _reconstructPacket(data[key]);
26425 }
26426 return data;
26427 }
26428 return data;
26429 }
26430
26431 packet.data = _reconstructPacket(packet.data);
26432 packet.attachments = undefined; // no longer useful
26433 return packet;
26434};
26435
26436/**
26437 * Asynchronously removes Blobs or Files from data via
26438 * FileReader's readAsArrayBuffer method. Used before encoding
26439 * data as msgpack. Calls callback with the blobless data.
26440 *
26441 * @param {Object} data
26442 * @param {Function} callback
26443 * @api private
26444 */
26445
26446exports.removeBlobs = function(data, callback) {
26447 function _removeBlobs(obj, curKey, containingObject) {
26448 if (!obj) return obj;
26449
26450 // convert any blob
26451 if ((global.Blob && obj instanceof Blob) ||
26452 (global.File && obj instanceof File)) {
26453 pendingBlobs++;
26454
26455 // async filereader
26456 var fileReader = new FileReader();
26457 fileReader.onload = function() { // this.result == arraybuffer
26458 if (containingObject) {
26459 containingObject[curKey] = this.result;
26460 }
26461 else {
26462 bloblessData = this.result;
26463 }
26464
26465 // if nothing pending its callback time
26466 if(! --pendingBlobs) {
26467 callback(bloblessData);
26468 }
26469 };
26470
26471 fileReader.readAsArrayBuffer(obj); // blob -> arraybuffer
26472 } else if (isArray(obj)) { // handle array
26473 for (var i = 0; i < obj.length; i++) {
26474 _removeBlobs(obj[i], i, obj);
26475 }
26476 } else if (obj && 'object' == typeof obj && !isBuf(obj)) { // and object
26477 for (var key in obj) {
26478 _removeBlobs(obj[key], key, obj);
26479 }
26480 }
26481 }
26482
26483 var pendingBlobs = 0;
26484 var bloblessData = data;
26485 _removeBlobs(bloblessData);
26486 if (!pendingBlobs) {
26487 callback(bloblessData);
26488 }
26489};
26490
26491}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
26492},{"./is-buffer":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/socket.io-parser/is-buffer.js","isarray":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/socket.io-parser/node_modules/isarray/index.js"}],"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/socket.io-parser/index.js":[function(require,module,exports){
26493
26494/**
26495 * Module dependencies.
26496 */
26497
26498var debug = require('debug')('socket.io-parser');
26499var json = require('json3');
26500var isArray = require('isarray');
26501var Emitter = require('component-emitter');
26502var binary = require('./binary');
26503var isBuf = require('./is-buffer');
26504
26505/**
26506 * Protocol version.
26507 *
26508 * @api public
26509 */
26510
26511exports.protocol = 4;
26512
26513/**
26514 * Packet types.
26515 *
26516 * @api public
26517 */
26518
26519exports.types = [
26520 'CONNECT',
26521 'DISCONNECT',
26522 'EVENT',
26523 'ACK',
26524 'ERROR',
26525 'BINARY_EVENT',
26526 'BINARY_ACK'
26527];
26528
26529/**
26530 * Packet type `connect`.
26531 *
26532 * @api public
26533 */
26534
26535exports.CONNECT = 0;
26536
26537/**
26538 * Packet type `disconnect`.
26539 *
26540 * @api public
26541 */
26542
26543exports.DISCONNECT = 1;
26544
26545/**
26546 * Packet type `event`.
26547 *
26548 * @api public
26549 */
26550
26551exports.EVENT = 2;
26552
26553/**
26554 * Packet type `ack`.
26555 *
26556 * @api public
26557 */
26558
26559exports.ACK = 3;
26560
26561/**
26562 * Packet type `error`.
26563 *
26564 * @api public
26565 */
26566
26567exports.ERROR = 4;
26568
26569/**
26570 * Packet type 'binary event'
26571 *
26572 * @api public
26573 */
26574
26575exports.BINARY_EVENT = 5;
26576
26577/**
26578 * Packet type `binary ack`. For acks with binary arguments.
26579 *
26580 * @api public
26581 */
26582
26583exports.BINARY_ACK = 6;
26584
26585/**
26586 * Encoder constructor.
26587 *
26588 * @api public
26589 */
26590
26591exports.Encoder = Encoder;
26592
26593/**
26594 * Decoder constructor.
26595 *
26596 * @api public
26597 */
26598
26599exports.Decoder = Decoder;
26600
26601/**
26602 * A socket.io Encoder instance
26603 *
26604 * @api public
26605 */
26606
26607function Encoder() {}
26608
26609/**
26610 * Encode a packet as a single string if non-binary, or as a
26611 * buffer sequence, depending on packet type.
26612 *
26613 * @param {Object} obj - packet object
26614 * @param {Function} callback - function to handle encodings (likely engine.write)
26615 * @return Calls callback with Array of encodings
26616 * @api public
26617 */
26618
26619Encoder.prototype.encode = function(obj, callback){
26620 debug('encoding packet %j', obj);
26621
26622 if (exports.BINARY_EVENT == obj.type || exports.BINARY_ACK == obj.type) {
26623 encodeAsBinary(obj, callback);
26624 }
26625 else {
26626 var encoding = encodeAsString(obj);
26627 callback([encoding]);
26628 }
26629};
26630
26631/**
26632 * Encode packet as string.
26633 *
26634 * @param {Object} packet
26635 * @return {String} encoded
26636 * @api private
26637 */
26638
26639function encodeAsString(obj) {
26640 var str = '';
26641 var nsp = false;
26642
26643 // first is type
26644 str += obj.type;
26645
26646 // attachments if we have them
26647 if (exports.BINARY_EVENT == obj.type || exports.BINARY_ACK == obj.type) {
26648 str += obj.attachments;
26649 str += '-';
26650 }
26651
26652 // if we have a namespace other than `/`
26653 // we append it followed by a comma `,`
26654 if (obj.nsp && '/' != obj.nsp) {
26655 nsp = true;
26656 str += obj.nsp;
26657 }
26658
26659 // immediately followed by the id
26660 if (null != obj.id) {
26661 if (nsp) {
26662 str += ',';
26663 nsp = false;
26664 }
26665 str += obj.id;
26666 }
26667
26668 // json data
26669 if (null != obj.data) {
26670 if (nsp) str += ',';
26671 str += json.stringify(obj.data);
26672 }
26673
26674 debug('encoded %j as %s', obj, str);
26675 return str;
26676}
26677
26678/**
26679 * Encode packet as 'buffer sequence' by removing blobs, and
26680 * deconstructing packet into object with placeholders and
26681 * a list of buffers.
26682 *
26683 * @param {Object} packet
26684 * @return {Buffer} encoded
26685 * @api private
26686 */
26687
26688function encodeAsBinary(obj, callback) {
26689
26690 function writeEncoding(bloblessData) {
26691 var deconstruction = binary.deconstructPacket(bloblessData);
26692 var pack = encodeAsString(deconstruction.packet);
26693 var buffers = deconstruction.buffers;
26694
26695 buffers.unshift(pack); // add packet info to beginning of data list
26696 callback(buffers); // write all the buffers
26697 }
26698
26699 binary.removeBlobs(obj, writeEncoding);
26700}
26701
26702/**
26703 * A socket.io Decoder instance
26704 *
26705 * @return {Object} decoder
26706 * @api public
26707 */
26708
26709function Decoder() {
26710 this.reconstructor = null;
26711}
26712
26713/**
26714 * Mix in `Emitter` with Decoder.
26715 */
26716
26717Emitter(Decoder.prototype);
26718
26719/**
26720 * Decodes an ecoded packet string into packet JSON.
26721 *
26722 * @param {String} obj - encoded packet
26723 * @return {Object} packet
26724 * @api public
26725 */
26726
26727Decoder.prototype.add = function(obj) {
26728 var packet;
26729 if ('string' == typeof obj) {
26730 packet = decodeString(obj);
26731 if (exports.BINARY_EVENT == packet.type || exports.BINARY_ACK == packet.type) { // binary packet's json
26732 this.reconstructor = new BinaryReconstructor(packet);
26733
26734 // no attachments, labeled binary but no binary data to follow
26735 if (this.reconstructor.reconPack.attachments === 0) {
26736 this.emit('decoded', packet);
26737 }
26738 } else { // non-binary full packet
26739 this.emit('decoded', packet);
26740 }
26741 }
26742 else if (isBuf(obj) || obj.base64) { // raw binary data
26743 if (!this.reconstructor) {
26744 throw new Error('got binary data when not reconstructing a packet');
26745 } else {
26746 packet = this.reconstructor.takeBinaryData(obj);
26747 if (packet) { // received final buffer
26748 this.reconstructor = null;
26749 this.emit('decoded', packet);
26750 }
26751 }
26752 }
26753 else {
26754 throw new Error('Unknown type: ' + obj);
26755 }
26756};
26757
26758/**
26759 * Decode a packet String (JSON data)
26760 *
26761 * @param {String} str
26762 * @return {Object} packet
26763 * @api private
26764 */
26765
26766function decodeString(str) {
26767 var p = {};
26768 var i = 0;
26769
26770 // look up type
26771 p.type = Number(str.charAt(0));
26772 if (null == exports.types[p.type]) return error();
26773
26774 // look up attachments if type binary
26775 if (exports.BINARY_EVENT == p.type || exports.BINARY_ACK == p.type) {
26776 var buf = '';
26777 while (str.charAt(++i) != '-') {
26778 buf += str.charAt(i);
26779 if (i == str.length) break;
26780 }
26781 if (buf != Number(buf) || str.charAt(i) != '-') {
26782 throw new Error('Illegal attachments');
26783 }
26784 p.attachments = Number(buf);
26785 }
26786
26787 // look up namespace (if any)
26788 if ('/' == str.charAt(i + 1)) {
26789 p.nsp = '';
26790 while (++i) {
26791 var c = str.charAt(i);
26792 if (',' == c) break;
26793 p.nsp += c;
26794 if (i == str.length) break;
26795 }
26796 } else {
26797 p.nsp = '/';
26798 }
26799
26800 // look up id
26801 var next = str.charAt(i + 1);
26802 if ('' !== next && Number(next) == next) {
26803 p.id = '';
26804 while (++i) {
26805 var c = str.charAt(i);
26806 if (null == c || Number(c) != c) {
26807 --i;
26808 break;
26809 }
26810 p.id += str.charAt(i);
26811 if (i == str.length) break;
26812 }
26813 p.id = Number(p.id);
26814 }
26815
26816 // look up json data
26817 if (str.charAt(++i)) {
26818 try {
26819 p.data = json.parse(str.substr(i));
26820 } catch(e){
26821 return error();
26822 }
26823 }
26824
26825 debug('decoded %s as %j', str, p);
26826 return p;
26827}
26828
26829/**
26830 * Deallocates a parser's resources
26831 *
26832 * @api public
26833 */
26834
26835Decoder.prototype.destroy = function() {
26836 if (this.reconstructor) {
26837 this.reconstructor.finishedReconstruction();
26838 }
26839};
26840
26841/**
26842 * A manager of a binary event's 'buffer sequence'. Should
26843 * be constructed whenever a packet of type BINARY_EVENT is
26844 * decoded.
26845 *
26846 * @param {Object} packet
26847 * @return {BinaryReconstructor} initialized reconstructor
26848 * @api private
26849 */
26850
26851function BinaryReconstructor(packet) {
26852 this.reconPack = packet;
26853 this.buffers = [];
26854}
26855
26856/**
26857 * Method to be called when binary data received from connection
26858 * after a BINARY_EVENT packet.
26859 *
26860 * @param {Buffer | ArrayBuffer} binData - the raw binary data received
26861 * @return {null | Object} returns null if more binary data is expected or
26862 * a reconstructed packet object if all buffers have been received.
26863 * @api private
26864 */
26865
26866BinaryReconstructor.prototype.takeBinaryData = function(binData) {
26867 this.buffers.push(binData);
26868 if (this.buffers.length == this.reconPack.attachments) { // done with buffer list
26869 var packet = binary.reconstructPacket(this.reconPack, this.buffers);
26870 this.finishedReconstruction();
26871 return packet;
26872 }
26873 return null;
26874};
26875
26876/**
26877 * Cleans up binary packet reconstruction variables.
26878 *
26879 * @api private
26880 */
26881
26882BinaryReconstructor.prototype.finishedReconstruction = function() {
26883 this.reconPack = null;
26884 this.buffers = [];
26885};
26886
26887function error(data){
26888 return {
26889 type: exports.ERROR,
26890 data: 'parser error'
26891 };
26892}
26893
26894},{"./binary":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/socket.io-parser/binary.js","./is-buffer":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/socket.io-parser/is-buffer.js","component-emitter":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/socket.io-parser/node_modules/component-emitter/index.js","debug":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/debug/browser.js","isarray":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/socket.io-parser/node_modules/isarray/index.js","json3":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/socket.io-parser/node_modules/json3/lib/json3.js"}],"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/socket.io-parser/is-buffer.js":[function(require,module,exports){
26895(function (global){
26896
26897module.exports = isBuf;
26898
26899/**
26900 * Returns true if obj is a buffer or an arraybuffer.
26901 *
26902 * @api private
26903 */
26904
26905function isBuf(obj) {
26906 return (global.Buffer && global.Buffer.isBuffer(obj)) ||
26907 (global.ArrayBuffer && obj instanceof ArrayBuffer);
26908}
26909
26910}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
26911},{}],"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/socket.io-parser/node_modules/component-emitter/index.js":[function(require,module,exports){
26912arguments[4]["/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/node_modules/component-emitter/index.js"][0].apply(exports,arguments)
26913},{}],"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/socket.io-parser/node_modules/isarray/index.js":[function(require,module,exports){
26914arguments[4]["/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/node_modules/engine.io-parser/node_modules/has-binary/node_modules/isarray/index.js"][0].apply(exports,arguments)
26915},{}],"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/socket.io-parser/node_modules/json3/lib/json3.js":[function(require,module,exports){
26916(function (global){
26917/*! JSON v3.3.2 | http://bestiejs.github.io/json3 | Copyright 2012-2014, Kit Cambridge | http://kit.mit-license.org */
26918;(function () {
26919 // Detect the `define` function exposed by asynchronous module loaders. The
26920 // strict `define` check is necessary for compatibility with `r.js`.
26921 var isLoader = typeof define === "function" && define.amd;
26922
26923 // A set of types used to distinguish objects from primitives.
26924 var objectTypes = {
26925 "function": true,
26926 "object": true
26927 };
26928
26929 // Detect the `exports` object exposed by CommonJS implementations.
26930 var freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports;
26931
26932 // Use the `global` object exposed by Node (including Browserify via
26933 // `insert-module-globals`), Narwhal, and Ringo as the default context,
26934 // and the `window` object in browsers. Rhino exports a `global` function
26935 // instead.
26936 var root = objectTypes[typeof window] && window || this,
26937 freeGlobal = freeExports && objectTypes[typeof module] && module && !module.nodeType && typeof global == "object" && global;
26938
26939 if (freeGlobal && (freeGlobal["global"] === freeGlobal || freeGlobal["window"] === freeGlobal || freeGlobal["self"] === freeGlobal)) {
26940 root = freeGlobal;
26941 }
26942
26943 // Public: Initializes JSON 3 using the given `context` object, attaching the
26944 // `stringify` and `parse` functions to the specified `exports` object.
26945 function runInContext(context, exports) {
26946 context || (context = root["Object"]());
26947 exports || (exports = root["Object"]());
26948
26949 // Native constructor aliases.
26950 var Number = context["Number"] || root["Number"],
26951 String = context["String"] || root["String"],
26952 Object = context["Object"] || root["Object"],
26953 Date = context["Date"] || root["Date"],
26954 SyntaxError = context["SyntaxError"] || root["SyntaxError"],
26955 TypeError = context["TypeError"] || root["TypeError"],
26956 Math = context["Math"] || root["Math"],
26957 nativeJSON = context["JSON"] || root["JSON"];
26958
26959 // Delegate to the native `stringify` and `parse` implementations.
26960 if (typeof nativeJSON == "object" && nativeJSON) {
26961 exports.stringify = nativeJSON.stringify;
26962 exports.parse = nativeJSON.parse;
26963 }
26964
26965 // Convenience aliases.
26966 var objectProto = Object.prototype,
26967 getClass = objectProto.toString,
26968 isProperty, forEach, undef;
26969
26970 // Test the `Date#getUTC*` methods. Based on work by @Yaffle.
26971 var isExtended = new Date(-3509827334573292);
26972 try {
26973 // The `getUTCFullYear`, `Month`, and `Date` methods return nonsensical
26974 // results for certain dates in Opera >= 10.53.
26975 isExtended = isExtended.getUTCFullYear() == -109252 && isExtended.getUTCMonth() === 0 && isExtended.getUTCDate() === 1 &&
26976 // Safari < 2.0.2 stores the internal millisecond time value correctly,
26977 // but clips the values returned by the date methods to the range of
26978 // signed 32-bit integers ([-2 ** 31, 2 ** 31 - 1]).
26979 isExtended.getUTCHours() == 10 && isExtended.getUTCMinutes() == 37 && isExtended.getUTCSeconds() == 6 && isExtended.getUTCMilliseconds() == 708;
26980 } catch (exception) {}
26981
26982 // Internal: Determines whether the native `JSON.stringify` and `parse`
26983 // implementations are spec-compliant. Based on work by Ken Snyder.
26984 function has(name) {
26985 if (has[name] !== undef) {
26986 // Return cached feature test result.
26987 return has[name];
26988 }
26989 var isSupported;
26990 if (name == "bug-string-char-index") {
26991 // IE <= 7 doesn't support accessing string characters using square
26992 // bracket notation. IE 8 only supports this for primitives.
26993 isSupported = "a"[0] != "a";
26994 } else if (name == "json") {
26995 // Indicates whether both `JSON.stringify` and `JSON.parse` are
26996 // supported.
26997 isSupported = has("json-stringify") && has("json-parse");
26998 } else {
26999 var value, serialized = '{"a":[1,true,false,null,"\\u0000\\b\\n\\f\\r\\t"]}';
27000 // Test `JSON.stringify`.
27001 if (name == "json-stringify") {
27002 var stringify = exports.stringify, stringifySupported = typeof stringify == "function" && isExtended;
27003 if (stringifySupported) {
27004 // A test function object with a custom `toJSON` method.
27005 (value = function () {
27006 return 1;
27007 }).toJSON = value;
27008 try {
27009 stringifySupported =
27010 // Firefox 3.1b1 and b2 serialize string, number, and boolean
27011 // primitives as object literals.
27012 stringify(0) === "0" &&
27013 // FF 3.1b1, b2, and JSON 2 serialize wrapped primitives as object
27014 // literals.
27015 stringify(new Number()) === "0" &&
27016 stringify(new String()) == '""' &&
27017 // FF 3.1b1, 2 throw an error if the value is `null`, `undefined`, or
27018 // does not define a canonical JSON representation (this applies to
27019 // objects with `toJSON` properties as well, *unless* they are nested
27020 // within an object or array).
27021 stringify(getClass) === undef &&
27022 // IE 8 serializes `undefined` as `"undefined"`. Safari <= 5.1.7 and
27023 // FF 3.1b3 pass this test.
27024 stringify(undef) === undef &&
27025 // Safari <= 5.1.7 and FF 3.1b3 throw `Error`s and `TypeError`s,
27026 // respectively, if the value is omitted entirely.
27027 stringify() === undef &&
27028 // FF 3.1b1, 2 throw an error if the given value is not a number,
27029 // string, array, object, Boolean, or `null` literal. This applies to
27030 // objects with custom `toJSON` methods as well, unless they are nested
27031 // inside object or array literals. YUI 3.0.0b1 ignores custom `toJSON`
27032 // methods entirely.
27033 stringify(value) === "1" &&
27034 stringify([value]) == "[1]" &&
27035 // Prototype <= 1.6.1 serializes `[undefined]` as `"[]"` instead of
27036 // `"[null]"`.
27037 stringify([undef]) == "[null]" &&
27038 // YUI 3.0.0b1 fails to serialize `null` literals.
27039 stringify(null) == "null" &&
27040 // FF 3.1b1, 2 halts serialization if an array contains a function:
27041 // `[1, true, getClass, 1]` serializes as "[1,true,],". FF 3.1b3
27042 // elides non-JSON values from objects and arrays, unless they
27043 // define custom `toJSON` methods.
27044 stringify([undef, getClass, null]) == "[null,null,null]" &&
27045 // Simple serialization test. FF 3.1b1 uses Unicode escape sequences
27046 // where character escape codes are expected (e.g., `\b` => `\u0008`).
27047 stringify({ "a": [value, true, false, null, "\x00\b\n\f\r\t"] }) == serialized &&
27048 // FF 3.1b1 and b2 ignore the `filter` and `width` arguments.
27049 stringify(null, value) === "1" &&
27050 stringify([1, 2], null, 1) == "[\n 1,\n 2\n]" &&
27051 // JSON 2, Prototype <= 1.7, and older WebKit builds incorrectly
27052 // serialize extended years.
27053 stringify(new Date(-8.64e15)) == '"-271821-04-20T00:00:00.000Z"' &&
27054 // The milliseconds are optional in ES 5, but required in 5.1.
27055 stringify(new Date(8.64e15)) == '"+275760-09-13T00:00:00.000Z"' &&
27056 // Firefox <= 11.0 incorrectly serializes years prior to 0 as negative
27057 // four-digit years instead of six-digit years. Credits: @Yaffle.
27058 stringify(new Date(-621987552e5)) == '"-000001-01-01T00:00:00.000Z"' &&
27059 // Safari <= 5.1.5 and Opera >= 10.53 incorrectly serialize millisecond
27060 // values less than 1000. Credits: @Yaffle.
27061 stringify(new Date(-1)) == '"1969-12-31T23:59:59.999Z"';
27062 } catch (exception) {
27063 stringifySupported = false;
27064 }
27065 }
27066 isSupported = stringifySupported;
27067 }
27068 // Test `JSON.parse`.
27069 if (name == "json-parse") {
27070 var parse = exports.parse;
27071 if (typeof parse == "function") {
27072 try {
27073 // FF 3.1b1, b2 will throw an exception if a bare literal is provided.
27074 // Conforming implementations should also coerce the initial argument to
27075 // a string prior to parsing.
27076 if (parse("0") === 0 && !parse(false)) {
27077 // Simple parsing test.
27078 value = parse(serialized);
27079 var parseSupported = value["a"].length == 5 && value["a"][0] === 1;
27080 if (parseSupported) {
27081 try {
27082 // Safari <= 5.1.2 and FF 3.1b1 allow unescaped tabs in strings.
27083 parseSupported = !parse('"\t"');
27084 } catch (exception) {}
27085 if (parseSupported) {
27086 try {
27087 // FF 4.0 and 4.0.1 allow leading `+` signs and leading
27088 // decimal points. FF 4.0, 4.0.1, and IE 9-10 also allow
27089 // certain octal literals.
27090 parseSupported = parse("01") !== 1;
27091 } catch (exception) {}
27092 }
27093 if (parseSupported) {
27094 try {
27095 // FF 4.0, 4.0.1, and Rhino 1.7R3-R4 allow trailing decimal
27096 // points. These environments, along with FF 3.1b1 and 2,
27097 // also allow trailing commas in JSON objects and arrays.
27098 parseSupported = parse("1.") !== 1;
27099 } catch (exception) {}
27100 }
27101 }
27102 }
27103 } catch (exception) {
27104 parseSupported = false;
27105 }
27106 }
27107 isSupported = parseSupported;
27108 }
27109 }
27110 return has[name] = !!isSupported;
27111 }
27112
27113 if (!has("json")) {
27114 // Common `[[Class]]` name aliases.
27115 var functionClass = "[object Function]",
27116 dateClass = "[object Date]",
27117 numberClass = "[object Number]",
27118 stringClass = "[object String]",
27119 arrayClass = "[object Array]",
27120 booleanClass = "[object Boolean]";
27121
27122 // Detect incomplete support for accessing string characters by index.
27123 var charIndexBuggy = has("bug-string-char-index");
27124
27125 // Define additional utility methods if the `Date` methods are buggy.
27126 if (!isExtended) {
27127 var floor = Math.floor;
27128 // A mapping between the months of the year and the number of days between
27129 // January 1st and the first of the respective month.
27130 var Months = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
27131 // Internal: Calculates the number of days between the Unix epoch and the
27132 // first day of the given month.
27133 var getDay = function (year, month) {
27134 return Months[month] + 365 * (year - 1970) + floor((year - 1969 + (month = +(month > 1))) / 4) - floor((year - 1901 + month) / 100) + floor((year - 1601 + month) / 400);
27135 };
27136 }
27137
27138 // Internal: Determines if a property is a direct property of the given
27139 // object. Delegates to the native `Object#hasOwnProperty` method.
27140 if (!(isProperty = objectProto.hasOwnProperty)) {
27141 isProperty = function (property) {
27142 var members = {}, constructor;
27143 if ((members.__proto__ = null, members.__proto__ = {
27144 // The *proto* property cannot be set multiple times in recent
27145 // versions of Firefox and SeaMonkey.
27146 "toString": 1
27147 }, members).toString != getClass) {
27148 // Safari <= 2.0.3 doesn't implement `Object#hasOwnProperty`, but
27149 // supports the mutable *proto* property.
27150 isProperty = function (property) {
27151 // Capture and break the object's prototype chain (see section 8.6.2
27152 // of the ES 5.1 spec). The parenthesized expression prevents an
27153 // unsafe transformation by the Closure Compiler.
27154 var original = this.__proto__, result = property in (this.__proto__ = null, this);
27155 // Restore the original prototype chain.
27156 this.__proto__ = original;
27157 return result;
27158 };
27159 } else {
27160 // Capture a reference to the top-level `Object` constructor.
27161 constructor = members.constructor;
27162 // Use the `constructor` property to simulate `Object#hasOwnProperty` in
27163 // other environments.
27164 isProperty = function (property) {
27165 var parent = (this.constructor || constructor).prototype;
27166 return property in this && !(property in parent && this[property] === parent[property]);
27167 };
27168 }
27169 members = null;
27170 return isProperty.call(this, property);
27171 };
27172 }
27173
27174 // Internal: Normalizes the `for...in` iteration algorithm across
27175 // environments. Each enumerated key is yielded to a `callback` function.
27176 forEach = function (object, callback) {
27177 var size = 0, Properties, members, property;
27178
27179 // Tests for bugs in the current environment's `for...in` algorithm. The
27180 // `valueOf` property inherits the non-enumerable flag from
27181 // `Object.prototype` in older versions of IE, Netscape, and Mozilla.
27182 (Properties = function () {
27183 this.valueOf = 0;
27184 }).prototype.valueOf = 0;
27185
27186 // Iterate over a new instance of the `Properties` class.
27187 members = new Properties();
27188 for (property in members) {
27189 // Ignore all properties inherited from `Object.prototype`.
27190 if (isProperty.call(members, property)) {
27191 size++;
27192 }
27193 }
27194 Properties = members = null;
27195
27196 // Normalize the iteration algorithm.
27197 if (!size) {
27198 // A list of non-enumerable properties inherited from `Object.prototype`.
27199 members = ["valueOf", "toString", "toLocaleString", "propertyIsEnumerable", "isPrototypeOf", "hasOwnProperty", "constructor"];
27200 // IE <= 8, Mozilla 1.0, and Netscape 6.2 ignore shadowed non-enumerable
27201 // properties.
27202 forEach = function (object, callback) {
27203 var isFunction = getClass.call(object) == functionClass, property, length;
27204 var hasProperty = !isFunction && typeof object.constructor != "function" && objectTypes[typeof object.hasOwnProperty] && object.hasOwnProperty || isProperty;
27205 for (property in object) {
27206 // Gecko <= 1.0 enumerates the `prototype` property of functions under
27207 // certain conditions; IE does not.
27208 if (!(isFunction && property == "prototype") && hasProperty.call(object, property)) {
27209 callback(property);
27210 }
27211 }
27212 // Manually invoke the callback for each non-enumerable property.
27213 for (length = members.length; property = members[--length]; hasProperty.call(object, property) && callback(property));
27214 };
27215 } else if (size == 2) {
27216 // Safari <= 2.0.4 enumerates shadowed properties twice.
27217 forEach = function (object, callback) {
27218 // Create a set of iterated properties.
27219 var members = {}, isFunction = getClass.call(object) == functionClass, property;
27220 for (property in object) {
27221 // Store each property name to prevent double enumeration. The
27222 // `prototype` property of functions is not enumerated due to cross-
27223 // environment inconsistencies.
27224 if (!(isFunction && property == "prototype") && !isProperty.call(members, property) && (members[property] = 1) && isProperty.call(object, property)) {
27225 callback(property);
27226 }
27227 }
27228 };
27229 } else {
27230 // No bugs detected; use the standard `for...in` algorithm.
27231 forEach = function (object, callback) {
27232 var isFunction = getClass.call(object) == functionClass, property, isConstructor;
27233 for (property in object) {
27234 if (!(isFunction && property == "prototype") && isProperty.call(object, property) && !(isConstructor = property === "constructor")) {
27235 callback(property);
27236 }
27237 }
27238 // Manually invoke the callback for the `constructor` property due to
27239 // cross-environment inconsistencies.
27240 if (isConstructor || isProperty.call(object, (property = "constructor"))) {
27241 callback(property);
27242 }
27243 };
27244 }
27245 return forEach(object, callback);
27246 };
27247
27248 // Public: Serializes a JavaScript `value` as a JSON string. The optional
27249 // `filter` argument may specify either a function that alters how object and
27250 // array members are serialized, or an array of strings and numbers that
27251 // indicates which properties should be serialized. The optional `width`
27252 // argument may be either a string or number that specifies the indentation
27253 // level of the output.
27254 if (!has("json-stringify")) {
27255 // Internal: A map of control characters and their escaped equivalents.
27256 var Escapes = {
27257 92: "\\\\",
27258 34: '\\"',
27259 8: "\\b",
27260 12: "\\f",
27261 10: "\\n",
27262 13: "\\r",
27263 9: "\\t"
27264 };
27265
27266 // Internal: Converts `value` into a zero-padded string such that its
27267 // length is at least equal to `width`. The `width` must be <= 6.
27268 var leadingZeroes = "000000";
27269 var toPaddedString = function (width, value) {
27270 // The `|| 0` expression is necessary to work around a bug in
27271 // Opera <= 7.54u2 where `0 == -0`, but `String(-0) !== "0"`.
27272 return (leadingZeroes + (value || 0)).slice(-width);
27273 };
27274
27275 // Internal: Double-quotes a string `value`, replacing all ASCII control
27276 // characters (characters with code unit values between 0 and 31) with
27277 // their escaped equivalents. This is an implementation of the
27278 // `Quote(value)` operation defined in ES 5.1 section 15.12.3.
27279 var unicodePrefix = "\\u00";
27280 var quote = function (value) {
27281 var result = '"', index = 0, length = value.length, useCharIndex = !charIndexBuggy || length > 10;
27282 var symbols = useCharIndex && (charIndexBuggy ? value.split("") : value);
27283 for (; index < length; index++) {
27284 var charCode = value.charCodeAt(index);
27285 // If the character is a control character, append its Unicode or
27286 // shorthand escape sequence; otherwise, append the character as-is.
27287 switch (charCode) {
27288 case 8: case 9: case 10: case 12: case 13: case 34: case 92:
27289 result += Escapes[charCode];
27290 break;
27291 default:
27292 if (charCode < 32) {
27293 result += unicodePrefix + toPaddedString(2, charCode.toString(16));
27294 break;
27295 }
27296 result += useCharIndex ? symbols[index] : value.charAt(index);
27297 }
27298 }
27299 return result + '"';
27300 };
27301
27302 // Internal: Recursively serializes an object. Implements the
27303 // `Str(key, holder)`, `JO(value)`, and `JA(value)` operations.
27304 var serialize = function (property, object, callback, properties, whitespace, indentation, stack) {
27305 var value, className, year, month, date, time, hours, minutes, seconds, milliseconds, results, element, index, length, prefix, result;
27306 try {
27307 // Necessary for host object support.
27308 value = object[property];
27309 } catch (exception) {}
27310 if (typeof value == "object" && value) {
27311 className = getClass.call(value);
27312 if (className == dateClass && !isProperty.call(value, "toJSON")) {
27313 if (value > -1 / 0 && value < 1 / 0) {
27314 // Dates are serialized according to the `Date#toJSON` method
27315 // specified in ES 5.1 section 15.9.5.44. See section 15.9.1.15
27316 // for the ISO 8601 date time string format.
27317 if (getDay) {
27318 // Manually compute the year, month, date, hours, minutes,
27319 // seconds, and milliseconds if the `getUTC*` methods are
27320 // buggy. Adapted from @Yaffle's `date-shim` project.
27321 date = floor(value / 864e5);
27322 for (year = floor(date / 365.2425) + 1970 - 1; getDay(year + 1, 0) <= date; year++);
27323 for (month = floor((date - getDay(year, 0)) / 30.42); getDay(year, month + 1) <= date; month++);
27324 date = 1 + date - getDay(year, month);
27325 // The `time` value specifies the time within the day (see ES
27326 // 5.1 section 15.9.1.2). The formula `(A % B + B) % B` is used
27327 // to compute `A modulo B`, as the `%` operator does not
27328 // correspond to the `modulo` operation for negative numbers.
27329 time = (value % 864e5 + 864e5) % 864e5;
27330 // The hours, minutes, seconds, and milliseconds are obtained by
27331 // decomposing the time within the day. See section 15.9.1.10.
27332 hours = floor(time / 36e5) % 24;
27333 minutes = floor(time / 6e4) % 60;
27334 seconds = floor(time / 1e3) % 60;
27335 milliseconds = time % 1e3;
27336 } else {
27337 year = value.getUTCFullYear();
27338 month = value.getUTCMonth();
27339 date = value.getUTCDate();
27340 hours = value.getUTCHours();
27341 minutes = value.getUTCMinutes();
27342 seconds = value.getUTCSeconds();
27343 milliseconds = value.getUTCMilliseconds();
27344 }
27345 // Serialize extended years correctly.
27346 value = (year <= 0 || year >= 1e4 ? (year < 0 ? "-" : "+") + toPaddedString(6, year < 0 ? -year : year) : toPaddedString(4, year)) +
27347 "-" + toPaddedString(2, month + 1) + "-" + toPaddedString(2, date) +
27348 // Months, dates, hours, minutes, and seconds should have two
27349 // digits; milliseconds should have three.
27350 "T" + toPaddedString(2, hours) + ":" + toPaddedString(2, minutes) + ":" + toPaddedString(2, seconds) +
27351 // Milliseconds are optional in ES 5.0, but required in 5.1.
27352 "." + toPaddedString(3, milliseconds) + "Z";
27353 } else {
27354 value = null;
27355 }
27356 } else if (typeof value.toJSON == "function" && ((className != numberClass && className != stringClass && className != arrayClass) || isProperty.call(value, "toJSON"))) {
27357 // Prototype <= 1.6.1 adds non-standard `toJSON` methods to the
27358 // `Number`, `String`, `Date`, and `Array` prototypes. JSON 3
27359 // ignores all `toJSON` methods on these objects unless they are
27360 // defined directly on an instance.
27361 value = value.toJSON(property);
27362 }
27363 }
27364 if (callback) {
27365 // If a replacement function was provided, call it to obtain the value
27366 // for serialization.
27367 value = callback.call(object, property, value);
27368 }
27369 if (value === null) {
27370 return "null";
27371 }
27372 className = getClass.call(value);
27373 if (className == booleanClass) {
27374 // Booleans are represented literally.
27375 return "" + value;
27376 } else if (className == numberClass) {
27377 // JSON numbers must be finite. `Infinity` and `NaN` are serialized as
27378 // `"null"`.
27379 return value > -1 / 0 && value < 1 / 0 ? "" + value : "null";
27380 } else if (className == stringClass) {
27381 // Strings are double-quoted and escaped.
27382 return quote("" + value);
27383 }
27384 // Recursively serialize objects and arrays.
27385 if (typeof value == "object") {
27386 // Check for cyclic structures. This is a linear search; performance
27387 // is inversely proportional to the number of unique nested objects.
27388 for (length = stack.length; length--;) {
27389 if (stack[length] === value) {
27390 // Cyclic structures cannot be serialized by `JSON.stringify`.
27391 throw TypeError();
27392 }
27393 }
27394 // Add the object to the stack of traversed objects.
27395 stack.push(value);
27396 results = [];
27397 // Save the current indentation level and indent one additional level.
27398 prefix = indentation;
27399 indentation += whitespace;
27400 if (className == arrayClass) {
27401 // Recursively serialize array elements.
27402 for (index = 0, length = value.length; index < length; index++) {
27403 element = serialize(index, value, callback, properties, whitespace, indentation, stack);
27404 results.push(element === undef ? "null" : element);
27405 }
27406 result = results.length ? (whitespace ? "[\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "]" : ("[" + results.join(",") + "]")) : "[]";
27407 } else {
27408 // Recursively serialize object members. Members are selected from
27409 // either a user-specified list of property names, or the object
27410 // itself.
27411 forEach(properties || value, function (property) {
27412 var element = serialize(property, value, callback, properties, whitespace, indentation, stack);
27413 if (element !== undef) {
27414 // According to ES 5.1 section 15.12.3: "If `gap` {whitespace}
27415 // is not the empty string, let `member` {quote(property) + ":"}
27416 // be the concatenation of `member` and the `space` character."
27417 // The "`space` character" refers to the literal space
27418 // character, not the `space` {width} argument provided to
27419 // `JSON.stringify`.
27420 results.push(quote(property) + ":" + (whitespace ? " " : "") + element);
27421 }
27422 });
27423 result = results.length ? (whitespace ? "{\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "}" : ("{" + results.join(",") + "}")) : "{}";
27424 }
27425 // Remove the object from the traversed object stack.
27426 stack.pop();
27427 return result;
27428 }
27429 };
27430
27431 // Public: `JSON.stringify`. See ES 5.1 section 15.12.3.
27432 exports.stringify = function (source, filter, width) {
27433 var whitespace, callback, properties, className;
27434 if (objectTypes[typeof filter] && filter) {
27435 if ((className = getClass.call(filter)) == functionClass) {
27436 callback = filter;
27437 } else if (className == arrayClass) {
27438 // Convert the property names array into a makeshift set.
27439 properties = {};
27440 for (var index = 0, length = filter.length, value; index < length; value = filter[index++], ((className = getClass.call(value)), className == stringClass || className == numberClass) && (properties[value] = 1));
27441 }
27442 }
27443 if (width) {
27444 if ((className = getClass.call(width)) == numberClass) {
27445 // Convert the `width` to an integer and create a string containing
27446 // `width` number of space characters.
27447 if ((width -= width % 1) > 0) {
27448 for (whitespace = "", width > 10 && (width = 10); whitespace.length < width; whitespace += " ");
27449 }
27450 } else if (className == stringClass) {
27451 whitespace = width.length <= 10 ? width : width.slice(0, 10);
27452 }
27453 }
27454 // Opera <= 7.54u2 discards the values associated with empty string keys
27455 // (`""`) only if they are used directly within an object member list
27456 // (e.g., `!("" in { "": 1})`).
27457 return serialize("", (value = {}, value[""] = source, value), callback, properties, whitespace, "", []);
27458 };
27459 }
27460
27461 // Public: Parses a JSON source string.
27462 if (!has("json-parse")) {
27463 var fromCharCode = String.fromCharCode;
27464
27465 // Internal: A map of escaped control characters and their unescaped
27466 // equivalents.
27467 var Unescapes = {
27468 92: "\\",
27469 34: '"',
27470 47: "/",
27471 98: "\b",
27472 116: "\t",
27473 110: "\n",
27474 102: "\f",
27475 114: "\r"
27476 };
27477
27478 // Internal: Stores the parser state.
27479 var Index, Source;
27480
27481 // Internal: Resets the parser state and throws a `SyntaxError`.
27482 var abort = function () {
27483 Index = Source = null;
27484 throw SyntaxError();
27485 };
27486
27487 // Internal: Returns the next token, or `"$"` if the parser has reached
27488 // the end of the source string. A token may be a string, number, `null`
27489 // literal, or Boolean literal.
27490 var lex = function () {
27491 var source = Source, length = source.length, value, begin, position, isSigned, charCode;
27492 while (Index < length) {
27493 charCode = source.charCodeAt(Index);
27494 switch (charCode) {
27495 case 9: case 10: case 13: case 32:
27496 // Skip whitespace tokens, including tabs, carriage returns, line
27497 // feeds, and space characters.
27498 Index++;
27499 break;
27500 case 123: case 125: case 91: case 93: case 58: case 44:
27501 // Parse a punctuator token (`{`, `}`, `[`, `]`, `:`, or `,`) at
27502 // the current position.
27503 value = charIndexBuggy ? source.charAt(Index) : source[Index];
27504 Index++;
27505 return value;
27506 case 34:
27507 // `"` delimits a JSON string; advance to the next character and
27508 // begin parsing the string. String tokens are prefixed with the
27509 // sentinel `@` character to distinguish them from punctuators and
27510 // end-of-string tokens.
27511 for (value = "@", Index++; Index < length;) {
27512 charCode = source.charCodeAt(Index);
27513 if (charCode < 32) {
27514 // Unescaped ASCII control characters (those with a code unit
27515 // less than the space character) are not permitted.
27516 abort();
27517 } else if (charCode == 92) {
27518 // A reverse solidus (`\`) marks the beginning of an escaped
27519 // control character (including `"`, `\`, and `/`) or Unicode
27520 // escape sequence.
27521 charCode = source.charCodeAt(++Index);
27522 switch (charCode) {
27523 case 92: case 34: case 47: case 98: case 116: case 110: case 102: case 114:
27524 // Revive escaped control characters.
27525 value += Unescapes[charCode];
27526 Index++;
27527 break;
27528 case 117:
27529 // `\u` marks the beginning of a Unicode escape sequence.
27530 // Advance to the first character and validate the
27531 // four-digit code point.
27532 begin = ++Index;
27533 for (position = Index + 4; Index < position; Index++) {
27534 charCode = source.charCodeAt(Index);
27535 // A valid sequence comprises four hexdigits (case-
27536 // insensitive) that form a single hexadecimal value.
27537 if (!(charCode >= 48 && charCode <= 57 || charCode >= 97 && charCode <= 102 || charCode >= 65 && charCode <= 70)) {
27538 // Invalid Unicode escape sequence.
27539 abort();
27540 }
27541 }
27542 // Revive the escaped character.
27543 value += fromCharCode("0x" + source.slice(begin, Index));
27544 break;
27545 default:
27546 // Invalid escape sequence.
27547 abort();
27548 }
27549 } else {
27550 if (charCode == 34) {
27551 // An unescaped double-quote character marks the end of the
27552 // string.
27553 break;
27554 }
27555 charCode = source.charCodeAt(Index);
27556 begin = Index;
27557 // Optimize for the common case where a string is valid.
27558 while (charCode >= 32 && charCode != 92 && charCode != 34) {
27559 charCode = source.charCodeAt(++Index);
27560 }
27561 // Append the string as-is.
27562 value += source.slice(begin, Index);
27563 }
27564 }
27565 if (source.charCodeAt(Index) == 34) {
27566 // Advance to the next character and return the revived string.
27567 Index++;
27568 return value;
27569 }
27570 // Unterminated string.
27571 abort();
27572 default:
27573 // Parse numbers and literals.
27574 begin = Index;
27575 // Advance past the negative sign, if one is specified.
27576 if (charCode == 45) {
27577 isSigned = true;
27578 charCode = source.charCodeAt(++Index);
27579 }
27580 // Parse an integer or floating-point value.
27581 if (charCode >= 48 && charCode <= 57) {
27582 // Leading zeroes are interpreted as octal literals.
27583 if (charCode == 48 && ((charCode = source.charCodeAt(Index + 1)), charCode >= 48 && charCode <= 57)) {
27584 // Illegal octal literal.
27585 abort();
27586 }
27587 isSigned = false;
27588 // Parse the integer component.
27589 for (; Index < length && ((charCode = source.charCodeAt(Index)), charCode >= 48 && charCode <= 57); Index++);
27590 // Floats cannot contain a leading decimal point; however, this
27591 // case is already accounted for by the parser.
27592 if (source.charCodeAt(Index) == 46) {
27593 position = ++Index;
27594 // Parse the decimal component.
27595 for (; position < length && ((charCode = source.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++);
27596 if (position == Index) {
27597 // Illegal trailing decimal.
27598 abort();
27599 }
27600 Index = position;
27601 }
27602 // Parse exponents. The `e` denoting the exponent is
27603 // case-insensitive.
27604 charCode = source.charCodeAt(Index);
27605 if (charCode == 101 || charCode == 69) {
27606 charCode = source.charCodeAt(++Index);
27607 // Skip past the sign following the exponent, if one is
27608 // specified.
27609 if (charCode == 43 || charCode == 45) {
27610 Index++;
27611 }
27612 // Parse the exponential component.
27613 for (position = Index; position < length && ((charCode = source.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++);
27614 if (position == Index) {
27615 // Illegal empty exponent.
27616 abort();
27617 }
27618 Index = position;
27619 }
27620 // Coerce the parsed value to a JavaScript number.
27621 return +source.slice(begin, Index);
27622 }
27623 // A negative sign may only precede numbers.
27624 if (isSigned) {
27625 abort();
27626 }
27627 // `true`, `false`, and `null` literals.
27628 if (source.slice(Index, Index + 4) == "true") {
27629 Index += 4;
27630 return true;
27631 } else if (source.slice(Index, Index + 5) == "false") {
27632 Index += 5;
27633 return false;
27634 } else if (source.slice(Index, Index + 4) == "null") {
27635 Index += 4;
27636 return null;
27637 }
27638 // Unrecognized token.
27639 abort();
27640 }
27641 }
27642 // Return the sentinel `$` character if the parser has reached the end
27643 // of the source string.
27644 return "$";
27645 };
27646
27647 // Internal: Parses a JSON `value` token.
27648 var get = function (value) {
27649 var results, hasMembers;
27650 if (value == "$") {
27651 // Unexpected end of input.
27652 abort();
27653 }
27654 if (typeof value == "string") {
27655 if ((charIndexBuggy ? value.charAt(0) : value[0]) == "@") {
27656 // Remove the sentinel `@` character.
27657 return value.slice(1);
27658 }
27659 // Parse object and array literals.
27660 if (value == "[") {
27661 // Parses a JSON array, returning a new JavaScript array.
27662 results = [];
27663 for (;; hasMembers || (hasMembers = true)) {
27664 value = lex();
27665 // A closing square bracket marks the end of the array literal.
27666 if (value == "]") {
27667 break;
27668 }
27669 // If the array literal contains elements, the current token
27670 // should be a comma separating the previous element from the
27671 // next.
27672 if (hasMembers) {
27673 if (value == ",") {
27674 value = lex();
27675 if (value == "]") {
27676 // Unexpected trailing `,` in array literal.
27677 abort();
27678 }
27679 } else {
27680 // A `,` must separate each array element.
27681 abort();
27682 }
27683 }
27684 // Elisions and leading commas are not permitted.
27685 if (value == ",") {
27686 abort();
27687 }
27688 results.push(get(value));
27689 }
27690 return results;
27691 } else if (value == "{") {
27692 // Parses a JSON object, returning a new JavaScript object.
27693 results = {};
27694 for (;; hasMembers || (hasMembers = true)) {
27695 value = lex();
27696 // A closing curly brace marks the end of the object literal.
27697 if (value == "}") {
27698 break;
27699 }
27700 // If the object literal contains members, the current token
27701 // should be a comma separator.
27702 if (hasMembers) {
27703 if (value == ",") {
27704 value = lex();
27705 if (value == "}") {
27706 // Unexpected trailing `,` in object literal.
27707 abort();
27708 }
27709 } else {
27710 // A `,` must separate each object member.
27711 abort();
27712 }
27713 }
27714 // Leading commas are not permitted, object property names must be
27715 // double-quoted strings, and a `:` must separate each property
27716 // name and value.
27717 if (value == "," || typeof value != "string" || (charIndexBuggy ? value.charAt(0) : value[0]) != "@" || lex() != ":") {
27718 abort();
27719 }
27720 results[value.slice(1)] = get(lex());
27721 }
27722 return results;
27723 }
27724 // Unexpected token encountered.
27725 abort();
27726 }
27727 return value;
27728 };
27729
27730 // Internal: Updates a traversed object member.
27731 var update = function (source, property, callback) {
27732 var element = walk(source, property, callback);
27733 if (element === undef) {
27734 delete source[property];
27735 } else {
27736 source[property] = element;
27737 }
27738 };
27739
27740 // Internal: Recursively traverses a parsed JSON object, invoking the
27741 // `callback` function for each value. This is an implementation of the
27742 // `Walk(holder, name)` operation defined in ES 5.1 section 15.12.2.
27743 var walk = function (source, property, callback) {
27744 var value = source[property], length;
27745 if (typeof value == "object" && value) {
27746 // `forEach` can't be used to traverse an array in Opera <= 8.54
27747 // because its `Object#hasOwnProperty` implementation returns `false`
27748 // for array indices (e.g., `![1, 2, 3].hasOwnProperty("0")`).
27749 if (getClass.call(value) == arrayClass) {
27750 for (length = value.length; length--;) {
27751 update(value, length, callback);
27752 }
27753 } else {
27754 forEach(value, function (property) {
27755 update(value, property, callback);
27756 });
27757 }
27758 }
27759 return callback.call(source, property, value);
27760 };
27761
27762 // Public: `JSON.parse`. See ES 5.1 section 15.12.2.
27763 exports.parse = function (source, callback) {
27764 var result, value;
27765 Index = 0;
27766 Source = "" + source;
27767 result = get(lex());
27768 // If a JSON string contains multiple tokens, it is invalid.
27769 if (lex() != "$") {
27770 abort();
27771 }
27772 // Reset the parser state.
27773 Index = Source = null;
27774 return callback && getClass.call(callback) == functionClass ? walk((value = {}, value[""] = result, value), "", callback) : result;
27775 };
27776 }
27777 }
27778
27779 exports["runInContext"] = runInContext;
27780 return exports;
27781 }
27782
27783 if (freeExports && !isLoader) {
27784 // Export for CommonJS environments.
27785 runInContext(root, freeExports);
27786 } else {
27787 // Export for web browsers and JavaScript engines.
27788 var nativeJSON = root.JSON,
27789 previousJSON = root["JSON3"],
27790 isRestored = false;
27791
27792 var JSON3 = runInContext(root, (root["JSON3"] = {
27793 // Public: Restores the original value of the global `JSON` object and
27794 // returns a reference to the `JSON3` object.
27795 "noConflict": function () {
27796 if (!isRestored) {
27797 isRestored = true;
27798 root.JSON = nativeJSON;
27799 root["JSON3"] = previousJSON;
27800 nativeJSON = previousJSON = null;
27801 }
27802 return JSON3;
27803 }
27804 }));
27805
27806 root.JSON = {
27807 "parse": JSON3.parse,
27808 "stringify": JSON3.stringify
27809 };
27810 }
27811
27812 // Export for asynchronous module loaders.
27813 if (isLoader) {
27814 define(function () {
27815 return JSON3;
27816 });
27817 }
27818}).call(this);
27819
27820}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
27821},{}],"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/node_modules/to-array/index.js":[function(require,module,exports){
27822module.exports = toArray
27823
27824function toArray(list, index) {
27825 var array = []
27826
27827 index = index || 0
27828
27829 for (var i = index || 0; i < list.length; i++) {
27830 array[i - index] = list[i]
27831 }
27832
27833 return array
27834}
27835
27836},{}],"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/src/index.js":[function(require,module,exports){
27837var HttpClient = require('./lib/http-client');
27838var events = require('events');
27839var inherits = require('inherits');
27840var StreamAPI = require('./lib/stream_api');
27841var _ = require('lodash');
27842var Logger = require('./lib/logger');
27843
27844function Klic(options){
27845 options = options || {};
27846 this.base_url = options.url || "https://api.2klic.io";
27847 this.apiVersion = options.apiVersion || "1.0";
27848 this.auth = options.auth || {};
27849
27850 this.logger = new Logger(options.log_level || 6);
27851
27852 this.http = new HttpClient(this.base_url, {app_key: options.app_key, unsafe: options.unsafe, logger: this.logger, api_version: this.api_version, app_type: options.app_type });
27853
27854 // Install all supported API endpoints
27855 this.alarm = require("./lib/methods/alarm/alarm")({ platform: this });
27856 this.zones = require("./lib/methods/alarm/zones")({ platform: this });
27857 //this.sectors = require("./lib/methods/sectors")({ platform: this });
27858 this.noc = require("./lib/methods/noc/noc")({ platform: this });
27859 this.cameras = require("./lib/methods/cameras")({ platform: this });
27860 this.streams = require("./lib/methods/streams")({ platform: this });
27861 this.devices = require("./lib/methods/devices")({ platform: this });
27862 this.zwave = require("./lib/methods/zwave")({ platform: this });
27863 this.events = require("./lib/methods/events")({ platform: this });
27864 this.locations = require("./lib/methods/locations")({ platform: this });
27865 this.scenarios = require("./lib/methods/scenarios")({ platform: this });
27866 this.models = require("./lib/methods/models")({ platform: this });
27867 this.notifications = require("./lib/methods/notifications")({ platform: this });
27868 this.translations = require("./lib/methods/translations")({ platform: this });
27869 this.user = require("./lib/methods/user")({ platform: this });
27870 this.templates = require("./lib/methods/templates")({ platform: this });
27871 this.system = require("./lib/methods/system")({ platform: this });
27872 this.access = require("./lib/methods/access/access")({ platform: this });
27873}
27874
27875inherits(Klic, events.EventEmitter);
27876
27877Klic.prototype.authenticate = require('./lib/methods/authenticate');
27878Klic.prototype.register = require('./lib/methods/register');
27879
27880module.exports = Klic;
27881
27882},{"./lib/http-client":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/src/lib/http-client.js","./lib/logger":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/src/lib/logger.js","./lib/methods/access/access":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/src/lib/methods/access/access.js","./lib/methods/alarm/alarm":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/src/lib/methods/alarm/alarm.js","./lib/methods/alarm/zones":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/src/lib/methods/alarm/zones.js","./lib/methods/authenticate":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/src/lib/methods/authenticate.js","./lib/methods/cameras":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/src/lib/methods/cameras.js","./lib/methods/devices":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/src/lib/methods/devices.js","./lib/methods/events":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/src/lib/methods/events.js","./lib/methods/locations":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/src/lib/methods/locations.js","./lib/methods/models":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/src/lib/methods/models.js","./lib/methods/noc/noc":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/src/lib/methods/noc/noc.js","./lib/methods/notifications":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/src/lib/methods/notifications.js","./lib/methods/register":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/src/lib/methods/register.js","./lib/methods/scenarios":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/src/lib/methods/scenarios.js","./lib/methods/streams":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/src/lib/methods/streams.js","./lib/methods/system":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/src/lib/methods/system.js","./lib/methods/templates":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/src/lib/methods/templates.js","./lib/methods/translations":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/src/lib/methods/translations.js","./lib/methods/user":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/src/lib/methods/user.js","./lib/methods/zwave":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/src/lib/methods/zwave.js","./lib/stream_api":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/src/lib/stream_api.js","events":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/browserify/node_modules/events/events.js","inherits":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/inherits/inherits_browser.js","lodash":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/lodash/index.js"}],"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/src/lib/http-client.js":[function(require,module,exports){
27883(function (Buffer){
27884var request = require('request');
27885
27886var MixinPromise = require('./mixin_promise');
27887var _ = require('lodash');
27888
27889function HttpClient(baseUrl, options) {
27890 options = options || {};
27891 this.url = baseUrl;
27892 this.app_key = options.app_key;
27893 this.app_type = options.app_type || 'browser';
27894 this.app_secret = options.app_secret;
27895 this.unsafe = options.unsafe;
27896 this.logger = options.logger;
27897 this.api_version = options.api_version;
27898 this.callback = _.noop;
27899 this.enableCallback = options.enableCallback || true;
27900}
27901
27902HttpClient.prototype.request = function(method, path, body, options) {
27903 var _this = this;
27904 this.logger.trace("Executing HTTP request " + method + " " + path);
27905
27906 if(arguments.length === 3) {
27907 options = body;
27908 body = undefined;
27909 }
27910 else if(arguments.length === 2) {
27911 options = {};
27912 }
27913
27914 options = options || {};
27915
27916 return new MixinPromise(function(resolve, reject) {
27917
27918 var headers = {};
27919
27920 if (options.token) {
27921 _this.logger.trace("Token was provided. Adding Authorization header");
27922 headers['authorization'] = "Bearer " + options.token;
27923 _this.logger.trace(headers['authorization']);
27924 }
27925 else if (options.basic) {
27926 _this.logger.trace("Basic credentials were provided. Adding Authorization header");
27927 var str = new Buffer(options.basic.username + ":" + options.basic.password, "utf8").toString("base64");
27928 headers['authorization'] = "Basic " + str;
27929 }
27930
27931 if (options.app_key || _this.app_key) {
27932 _this.logger.trace("Configuring X-App-Key to ", options.app_key || _this.app_key);
27933 headers['x-app-key'] = options.app_key || _this.app_key;
27934 }
27935
27936 if (options.unsafe || _this.unsafe) {
27937 _this.logger.trace("Indicating to the platform that we are in the browser (unsafe)");
27938 headers['x-unsafe-auth'] = options.unsafe || _this.unsafe;
27939 }
27940
27941 if (options.api_version || _this.api_version) {
27942 headers['x-api-version'] = options.api_version || _this.api_version;
27943 }
27944
27945 if (options.app_type || _this.app_type) {
27946 headers['x-app-type'] = options.app_type || _this.app_type;
27947 }
27948
27949 _this.logger.trace("Request URL is: " + method + " " + _this.url + path);
27950
27951 return new MixinPromise(function (resolve, reject) {
27952 request({
27953 method: method,
27954 url: _this.url + path,
27955 json: body,
27956 headers: headers,
27957 verbose: false,
27958 //withCredentials: true,
27959 timeout: options.timeout || 30000,
27960 qs: options.query || null
27961 }, function (err, resp, body) {
27962 if (err) {
27963 _this.logger.error("HTTP ERROR:", err);
27964 reject(err);
27965 }
27966 else {
27967 _this.logger.trace("Receive a valid HTTP response");
27968 if (resp.statusCode >= 400) {
27969 _this.logger.error("Receive status code %d", resp.statusCode);
27970 err = new Error("HTTP " + resp.statusCode + ": " + method + " " + path);
27971 err.statusCode = resp.statusCode;
27972 err.statusText = resp.statusText;
27973
27974 if (_isJson(body)) body = JSON.parse(body);
27975 err.code = body.code;
27976 err.parameters = body.parameters;
27977 err.message = body.message;
27978
27979 if (body.details) err.details = body.details;
27980
27981 err.error = resp.error;
27982 err.body = body;
27983 reject(err);
27984 }
27985 else if (resp.statusCode === 0) {
27986 _this.logger.error("Unable to connect to platform");
27987 err = new Error("Unable to connect to server");
27988 err.statusCode = 0;
27989 reject(err);
27990 }
27991 else if (body) {
27992 _this.logger.trace("Receive a valid body");
27993 if (_.isString(body)) {
27994 body = JSON.parse(body);
27995 }
27996
27997 if (body.data) {
27998 resolve(body);
27999 }
28000 else {
28001 _this.logger.trace("Resolving response promise. Status Code=", resp.statusCode);
28002 resolve({statusCode: resp.statusCode, data: body});
28003 }
28004 }
28005 else {
28006 _this.logger.trace("Resolving without body. Status code = %d", resp.statusCode);
28007 resolve({statusCode: resp.statusCode});
28008 }
28009 }
28010 });
28011 }).then(function (res) {
28012 resolve(res);
28013 }).catch(function (error) {
28014 if (_this.enableCallback) {
28015 var p = _this.callback(error);
28016 var isPromise = _.isObject(p) && _.isFunction(p.then);
28017
28018 if (isPromise) {
28019 p.then(function () {
28020 reject(error);
28021 });
28022 }
28023 else reject(error);
28024 }
28025 });
28026 });
28027};
28028
28029HttpClient.prototype.post = function(path, body, options) {
28030 if(typeof(body) === 'object') body = _.omit(body, function(prop){ if(typeof(prop)==='string' && !prop.length) return true });
28031 return this.request('POST', path, body, options);
28032};
28033
28034HttpClient.prototype.delete = function(path, options) {
28035 return this.request('DELETE', path, options);
28036};
28037
28038HttpClient.prototype.get = function(path, options) {
28039 return this.request('GET', path, options);
28040};
28041
28042HttpClient.prototype.put = function(path, body, options) {
28043 if(typeof(body) === 'object') body = _.omit(body, function(prop){ if(typeof(prop)==='string' && !prop.length) return true });
28044 if(arguments.length === 2) {
28045 options = body;
28046 body = undefined;
28047 }
28048 return this.request('PUT', path, body, options);
28049};
28050
28051HttpClient.prototype.patch = function(path, body, options) {
28052 if(typeof(body) === 'object') body = _.omit(body, function(prop){ if(typeof(prop)==='string' && !prop.length) return true });
28053 return this.request('PATCH', path, body, options);
28054};
28055
28056function _isJson(str) {
28057 try {
28058 JSON.parse(str);
28059 } catch (e) {
28060 return false;
28061 }
28062 return true;
28063}
28064
28065module.exports = HttpClient;
28066}).call(this,require("buffer").Buffer)
28067},{"./mixin_promise":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/src/lib/mixin_promise.js","buffer":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/browserify/node_modules/buffer/index.js","lodash":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/lodash/index.js","request":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/browser-request/index.js"}],"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/src/lib/logger.js":[function(require,module,exports){
28068function Logger(level) {
28069 this.level = level;
28070}
28071
28072Logger.prototype.trace = function() {
28073 if(this.level > 9) {
28074 console.log.apply(console, arguments);
28075 }
28076};
28077
28078Logger.prototype.debug = function() {
28079 if(this.level > 7) {
28080 console.log.apply(console, arguments);
28081 }
28082};
28083
28084Logger.prototype.info = function() {
28085 if(this.level > 5) {
28086 console.log.apply(console, arguments);
28087 }
28088};
28089
28090Logger.prototype.warn = function() {
28091 if(this.level > 3) {
28092 console.log.apply(console, arguments);
28093 }
28094};
28095
28096Logger.prototype.error = function() {
28097 if(this.level > 1) {
28098 console.log.apply(console, arguments);
28099 }
28100};
28101
28102Logger.prototype.fatal = function() {
28103 console.log.apply(console, arguments);
28104};
28105
28106module.exports = Logger;
28107},{}],"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/src/lib/methods/access/access.js":[function(require,module,exports){
28108'use strict';
28109var Cards = require("./cards");
28110
28111function Access(options) {
28112 options = options || {};
28113 this.platform = options.platform;
28114 this.cards = new Cards ({ platform: this.platform });
28115}
28116
28117Access.prototype.list = function(params){
28118 return this.platform.http.get('/access/', { query: params, token: this.platform.auth.token });
28119};
28120
28121Access.prototype.get = function(id, params){
28122 return this.platform.http.get('/access/'+id, { query: params, token: this.platform.auth.token });
28123};
28124
28125Access.prototype.create = function(accessData){
28126 return this.platform.http.post('/access', accessData, { token: this.platform.auth.token });
28127};
28128
28129Access.prototype.update = function(id, accessData){
28130 return this.platform.http.put('/access/' + id, accessData, { token: this.platform.auth.token });
28131};
28132
28133Access.prototype.patch = function(id, accessData){
28134 return this.platform.http.patch('/access/' + d, accessData, { token: this.platform.auth.token });
28135};
28136
28137Access.prototype.patch = function(id, accessData){
28138 return this.platform.http.patch('/access/' + id, accessData, { token: this.platform.auth.token });
28139};
28140
28141
28142module.exports = function(options) {
28143 options = options || {};
28144 return new Access(options);
28145};
28146
28147},{"./cards":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/src/lib/methods/access/cards.js"}],"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/src/lib/methods/access/cards.js":[function(require,module,exports){
28148'use strict';
28149
28150function Cards(options) {
28151 options = options || {};
28152 this.platform = options.platform;
28153}
28154
28155Cards.prototype.list= function(){
28156 return this.platform.http.get('/access/cards', { token: this.platform.auth.token });
28157};
28158
28159Cards.prototype.get= function(id){
28160 return this.platform.http.get('/access/cards/' + id, { token: this.platform.auth.token });
28161};
28162
28163Cards.prototype.create= function(cardData){
28164 return this.platform.http.post('/access/cards', cardData, { token: this.platform.auth.token });
28165};
28166
28167Cards.prototype.update= function(id, cardData){
28168 return this.platform.http.put('/access/cards/' + id, cardData, { token: this.platform.auth.token });
28169};
28170
28171Cards.prototype.patch = function(id, cardData){
28172 return this.platform.http.patch ('/access/cards/' + id, cardData, { token: this.platform.auth.token });
28173};
28174
28175module.exports = function(options) {
28176 options = options || {};
28177 return new Cards(options);
28178};
28179
28180},{}],"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/src/lib/methods/alarm/alarm.js":[function(require,module,exports){
28181'use strict';
28182var User = require("./user");
28183var Pin = require("./pin");
28184var Zone = require("./zones");
28185
28186function Alarm(options) {
28187 options = options || {};
28188 this.platform = options.platform;
28189 this.user = new User({ platform: this.platform });
28190 this.pin = new Pin({ platform: this.platform });
28191 this.zones = new Zone({ platform: this.platform });
28192}
28193
28194// Provision an alarm system
28195Alarm.prototype.create = function(alarm){
28196 return this.platform.http.post('/alarms', alarm, { token: this.platform.auth.token });
28197};
28198
28199// Get a an alarm system state
28200Alarm.prototype.get = function(alarmId){
28201 return this.platform.http.get('/alarms/'+alarmId, { token: this.platform.auth.token });
28202};
28203
28204Alarm.prototype.list = function(){
28205 return this.platform.http.get('/alarms', { token: this.platform.auth.token });
28206};
28207
28208Alarm.prototype.patch = function(alarm, alarmId){
28209 return this.platform.http.patch('/alarms/'+alarmId, alarm, { token: this.platform.auth.token });
28210};
28211
28212Alarm.prototype.delete = function(alarmId){
28213 return this.platform.http.delete('/alarms/'+alarmId, { token: this.platform.auth.token });
28214};
28215
28216Alarm.prototype.getToken = function(alarmId, pin){
28217 return this.platform.http.post('/alarms/'+alarmId+'/auth/token', { pin: pin }, { token: this.platform.auth.token });
28218};
28219
28220// Reset the alarm service
28221Alarm.prototype.reset = function(alarmId){
28222 return this.platform.http.post('/alarms/'+alarmId+'/reset', {}, { token: this.platform.auth.token });
28223};
28224
28225Alarm.prototype.arm = function(alarmId, armToken, state, bypassedZoneIds){
28226 return this.platform.http.put('/alarms/'+alarmId, { state: state, bypassed: bypassedZoneIds }, { query: { armToken: armToken }, token: this.platform.auth.token });
28227};
28228
28229module.exports = function(options) {
28230 options = options || {};
28231 return new Alarm(options);
28232};
28233
28234
28235},{"./pin":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/src/lib/methods/alarm/pin.js","./user":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/src/lib/methods/alarm/user.js","./zones":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/src/lib/methods/alarm/zones.js"}],"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/src/lib/methods/alarm/pin.js":[function(require,module,exports){
28236'use strict';
28237
28238function Pin(options) {
28239 options = options || {};
28240 this.platform = options.platform;
28241}
28242
28243Pin.prototype.update = function(alarmId, userId, pin){
28244 return this.platform.http.put('/alarms/'+alarmId+'/users/'+userId+'/pin', pin, { token: this.platform.auth.token });
28245};
28246
28247module.exports = function(options) {
28248 options = options || {};
28249 return new Pin(options);
28250};
28251
28252
28253},{}],"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/src/lib/methods/alarm/user.js":[function(require,module,exports){
28254'use strict';
28255
28256function User(options) {
28257 options = options || {};
28258 this.platform = options.platform;
28259}
28260
28261// Add a user to an alarm system
28262User.prototype.create = function(alarmId, userId){
28263 return this.platform.http.post('/alarms/'+alarmId+'/users/'+userId, {}, { token: this.platform.auth.token });
28264};
28265
28266// List users in an alarm system
28267User.prototype.list = function(alarmId){
28268 return this.platform.http.get('/alarms/'+alarmId+'/users', { token: this.platform.auth.token });
28269};
28270
28271// Delete a user in an alarm system
28272User.prototype.delete = function(alarmId, userId){
28273 if(userId) return this.platform.http.delete('/alarms/'+alarmId+'/users/'+userId, { token: this.platform.auth.token });
28274 else return this.platform.http.delete('/alarms/'+alarmId+'/users', { token: this.platform.auth.token });
28275};
28276
28277
28278
28279module.exports = function(options) {
28280 options = options || {};
28281 return new User(options);
28282};
28283
28284
28285},{}],"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/src/lib/methods/alarm/zones.js":[function(require,module,exports){
28286'use strict';
28287
28288var _ = require('lodash');
28289
28290function Zones(options) {
28291 options = options || {};
28292 this.platform = options.platform;
28293}
28294
28295// Zones
28296Zones.prototype.create = function(alarmId, zone, query){
28297 if(_.get(query, 'populate')) query.populate = query.populate.toString();
28298 return this.platform.http.post('/alarms/'+alarmId+'/zones', zone, { query: query, token: this.platform.auth.token });
28299};
28300
28301Zones.prototype.list = function(alarmId, query){
28302 if(_.get(query, 'populate')) query.populate = query.populate.toString();
28303 return this.platform.http.get('/alarms/'+alarmId+'/zones', { query: query, token: this.platform.auth.token });
28304};
28305
28306Zones.prototype.get = function(alarmId, zoneId, query){
28307 if(_.get(query, 'populate')) query.populate = query.populate.toString();
28308 return this.platform.http.get('/alarms/'+alarmId+'/zones/'+zoneId, { query: query, token: this.platform.auth.token });
28309};
28310
28311Zones.prototype.update = function(alarmId, zone, query){
28312 if(_.get(query, 'populate')) query.populate = query.populate.toString();
28313 return this.platform.http.put('/alarms/'+alarmId+'/zones/'+zone._id, zone, { query: query, token: this.platform.auth.token });
28314};
28315
28316Zones.prototype.patch = function(alarmId, obj, zoneId, query){
28317 if(_.get(query, 'populate')) query.populate = query.populate.toString();
28318 return this.platform.http.patch('/alarms/'+alarmId+'/zones/'+zoneId, obj, { query: query, token: this.platform.auth.token });
28319};
28320
28321Zones.prototype.delete = function(alarmId, zoneId, query){
28322 if(_.get(query, 'populate')) query.populate = query.populate.toString();
28323 if(zoneId) return this.platform.http.delete('/alarms/'+alarmId+'/zones/'+zoneId, { token: this.platform.auth.token });
28324 else return this.platform.http.delete('/alarms/'+alarmId+'/zones', { query: query, token: this.platform.auth.token });
28325};
28326
28327module.exports = function(options) {
28328 options = options || {};
28329 return new Zones(options);
28330};
28331
28332
28333},{"lodash":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/lodash/index.js"}],"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/src/lib/methods/authenticate.js":[function(require,module,exports){
28334module.exports = (function() {
28335
28336 return function(credentials, options) {
28337 var _this = this, logger = this.logger;
28338 options = options || {};
28339
28340 logger.debug("Executing HTTP request GET /auth/token");
28341 return this.http.post("/auth/token", {}, {
28342 basic: {
28343 username: credentials.username,
28344 password: credentials.password
28345 }
28346 }).then(function(resp) {
28347 logger.trace(resp);
28348 if(!_this.auth) {
28349 logger.debug("No existing platform auth field. Initializing it");
28350 _this.auth = {};
28351 }
28352 if(resp) {
28353 logger.debug("Installing token %s as default platform auth mechanism", resp.data.token);
28354 _this.auth.token = resp.data.token;
28355 return resp.data;
28356 }
28357 else {
28358 logger.error("Invalid response received from platform");
28359 }
28360
28361 });
28362
28363 };
28364
28365})();
28366},{}],"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/src/lib/methods/cameras.js":[function(require,module,exports){
28367'use strict';
28368
28369function Cameras(options) {
28370 options = options || {};
28371 this.platform = options.platform;
28372}
28373
28374Cameras.prototype.get = function(propertyId){
28375 return this.platform.http.get('/homes/'+propertyId+'/cameras/stream/all', { token: this.platform.auth.token });
28376};
28377
28378module.exports = function(options) {
28379 options = options || {};
28380 return new Cameras(options);
28381};
28382
28383
28384},{}],"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/src/lib/methods/devices.js":[function(require,module,exports){
28385'use strict';
28386
28387var _ = require('lodash');
28388
28389function Devices(options) {
28390 options = options || {};
28391 this.platform = options.platform;
28392}
28393
28394Devices.prototype.list = function(query){
28395 if(_.get(query, 'populate')) query.populate = query.populate.toString();
28396 return this.platform.http.get('/devices', { query: query, token: this.platform.auth.token });
28397};
28398
28399Devices.prototype.get = function(deviceId, query){
28400 if(_.get(query, 'populate')) query.populate = query.populate.toString();
28401 return this.platform.http.get('/devices/'+deviceId, { query: query, token: this.platform.auth.token });
28402};
28403
28404Devices.prototype.getChildren = function(deviceId, level, query){
28405 if(_.get(query, 'populate')) query.populate = query.populate.toString();
28406 var query = _.merge({ showChildren: true, level: level }, query);
28407 return this.platform.http.get('/devices/'+deviceId, { query: query, token: this.platform.auth.token });
28408};
28409
28410Devices.prototype.create = function(device, query){
28411 if(_.get(query, 'populate')) query.populate = query.populate.toString();
28412 return this.platform.http.post('/devices', device, { query: query, token: this.platform.auth.token });
28413};
28414
28415Devices.prototype.update = function(device, query){
28416 if(_.get(query, 'populate')) query.populate = query.populate.toString();
28417 return this.platform.http.put('/devices/'+device._id, device, { query: query, token: this.platform.auth.token });
28418};
28419
28420Devices.prototype.patch = function(obj, deviceId, query){
28421 if(_.get(query, 'populate')) query.populate = query.populate.toString();
28422 return this.platform.http.patch('/devices/'+deviceId, obj, { query: query, token: this.platform.auth.token });
28423};
28424
28425Devices.prototype.delete = function(deviceId, query){
28426 if(_.get(query, 'populate')) query.populate = query.populate.toString();
28427 return this.platform.http.delete('/devices/'+deviceId, { query: query, token: this.platform.auth.token });
28428};
28429
28430// Reset a hub
28431Devices.prototype.reset = function(deviceId){
28432 return this.platform.http.put('/devices/'+deviceId+'/reset', {}, { token: this.platform.auth.token });
28433};
28434
28435Devices.prototype.updateCapability = function(deviceId, capabilityId, value, unit, timestamp){
28436 return this.platform.http.put('/devices/'+deviceId+'/caps/'+capabilityId, { value: value, unit: unit, timestamp: timestamp }, { token: this.platform.auth.token });
28437};
28438
28439Devices.prototype.patchCapability = function(deviceId, capabilityId, obj){
28440 return this.platform.http.patch('/devices/'+deviceId+'/caps/'+capabilityId, obj, { token: this.platform.auth.token });
28441};
28442
28443Devices.prototype.getCapability = function(deviceId, capabilityId){
28444 return this.platform.http.get('/devices/'+deviceId+'/caps/'+capabilityId, { token: this.platform.auth.token });
28445};
28446
28447Devices.prototype.listCapability = function(deviceId){
28448 return this.platform.http.get('/devices/'+deviceId+'/caps', { token: this.platform.auth.token });
28449};
28450
28451// Hub provisioning
28452Devices.prototype.provision = function(name, mac, model, location){
28453 var _this = this;
28454 var obj = _.merge({ name:name, mac:mac, model:model }, { location: location }); // optional location parameter
28455 return this.platform.http.post('/devices', obj)
28456 .then(function(res){
28457 //logger.debug("Installing token %s as default platform auth mechanism", resp.data.token);
28458 if(res.data.token) _this.platform.auth.token = res.data.token;
28459 return res;
28460 })
28461};
28462
28463// Controller Heartbeat
28464Devices.prototype.heartbeat = function(deviceId, sysHealth){
28465 return this.platform.http.post('/devices/'+deviceId+'/heartbeat', sysHealth, { token: this.platform.auth.token });
28466};
28467
28468Devices.prototype.listHeartbeat = function(deviceId, query){
28469 return this.platform.http.get('/devices/'+deviceId+'/heartbeat', { query: query, token: this.platform.auth.token });
28470};
28471
28472// Controller ping
28473Devices.prototype.ping = function(deviceId){
28474 return this.platform.http.post('/devices/'+deviceId+'/ping', {}, { token: this.platform.auth.token });
28475};
28476
28477module.exports = function(options) {
28478 options = options || {};
28479 return new Devices(options);
28480};
28481
28482
28483},{"lodash":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/lodash/index.js"}],"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/src/lib/methods/events.js":[function(require,module,exports){
28484'use strict';
28485
28486function Events(options) {
28487 options = options || {};
28488 this.platform = options.platform;
28489}
28490
28491Events.prototype.create = function(resourcePath, eventType, resource, timestamp, requestId){
28492 return this.platform.http.post('/events', { path: resourcePath, resource: resource, timestamp: timestamp, type: eventType, request: requestId }, { token: this.platform.auth.token });
28493};
28494
28495module.exports = function(options) {
28496 options = options || {};
28497 return new Events(options);
28498};
28499
28500
28501},{}],"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/src/lib/methods/locations.js":[function(require,module,exports){
28502'use strict';
28503
28504function Locations(options) {
28505 options = options || {};
28506 this.platform = options.platform;
28507}
28508
28509Locations.prototype.list = function(level){
28510 return this.platform.http.get('/locations', { query:{ level: level }, token: this.platform.auth.token });
28511};
28512
28513Locations.prototype.get = function(locationId, level){
28514 return this.platform.http.get('/locations/'+locationId, { query: { level: level }, token: this.platform.auth.token });
28515};
28516
28517Locations.prototype.getRoot = function(locationId, level){
28518 return this.platform.http.get('/locations/'+locationId, { query: { root: true, level: level }, token: this.platform.auth.token });
28519};
28520
28521Locations.prototype.create = function(location){
28522 return this.platform.http.post('/locations', location, { token: this.platform.auth.token });
28523};
28524
28525Locations.prototype.update = function(location){
28526 return this.platform.http.put('/locations/'+location._id, location, { token: this.platform.auth.token });
28527};
28528
28529Locations.prototype.patch = function(obj, locationId){
28530 return this.platform.http.patch('/locations/'+locationId, obj, { token: this.platform.auth.token });
28531};
28532
28533Locations.prototype.delete = function(locationId){
28534 return this.platform.http.delete('/locations/'+locationId, { token: this.platform.auth.token });
28535};
28536
28537module.exports = function(options) {
28538 options = options || {};
28539 return new Locations(options);
28540};
28541
28542
28543},{}],"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/src/lib/methods/models.js":[function(require,module,exports){
28544'use strict';
28545
28546function Models(options) {
28547 options = options || {};
28548 this.platform = options.platform;
28549}
28550
28551Models.prototype.list = function(query){
28552 return this.platform.http.get('/models', { query: query, token: this.platform.auth.token });
28553};
28554
28555Models.prototype.get = function(id, query){
28556 return this.platform.http.get('/models/'+id, { query: query, token: this.platform.auth.token });
28557};
28558
28559Models.prototype.search = function(query){
28560 return this.platform.http.get('/models', { query: query, token: this.platform.auth.token });
28561};
28562
28563module.exports = function(options) {
28564 options = options || {};
28565 return new Models(options);
28566};
28567
28568
28569},{}],"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/src/lib/methods/noc/customers.js":[function(require,module,exports){
28570'use strict';
28571
28572function NocCustomers(options) {
28573 options = options || {};
28574 this.platform = options.platform;
28575}
28576
28577NocCustomers.prototype.list= function(nocId){
28578 return this.platform.http.get('/nocs/' + nocId + '/customers', { token: this.platform.auth.token });
28579};
28580
28581NocCustomers.prototype.get= function(nocId, customerId){
28582 return this.platform.http.get('/nocs/' + nocId + '/customers/' + customerId, { token: this.platform.auth.token });
28583};
28584
28585NocCustomers.prototype.create= function(nocId, customer){
28586 return this.platform.http.post('/nocs/' + nocId + '/customers', customer, { token: this.platform.auth.token });
28587};
28588
28589NocCustomers.prototype.update= function(nocId, customerId, customer){
28590 return this.platform.http.put('/nocs/' + nocId + '/customers/' + customerId, customer, { token: this.platform.auth.token });
28591};
28592
28593NocCustomers.prototype.patch = function(nocId, customerId, customer){
28594 return this.platform.http.patch ('/nocs/' + nocId + '/customers/' + customerId, customer, { token: this.platform.auth.token });
28595};
28596
28597NocCustomers.prototype.listDevices = function(nocId, customerId, alarmSystemId){
28598 return this.platform.http.get('/nocs/' + nocId + '/customers/' + customerId + '/devices/' + alarmSystemId, { token: this.platform.auth.token });
28599};
28600
28601NocCustomers.prototype.getPredefinedServiceActions= function(nocId, customerId, alarmSystemId){
28602 return this.platform.http.get('/nocs/' + nocId + '/customers/' + customerId + '/alarmsystem/' + alarmSystemId + '/predefined-service-actions', { token: this.platform.auth.token });
28603};
28604
28605NocCustomers.prototype.listServiceActions= function(nocId, customerId){
28606 return this.platform.http.get('/nocs/' + nocId + '/customers/' + customerId + '/actions', { token: this.platform.auth.token });
28607};
28608
28609NocCustomers.prototype.getServiceAction= function(nocId, customerId, actionId){
28610 return this.platform.http.get('/nocs/' + nocId + '/customers/' + customerId + '/actions/' + actionId, { token: this.platform.auth.token });
28611};
28612
28613NocCustomers.prototype.createServiceAction= function(nocId, customerId, actionData){
28614 return this.platform.http.post('/nocs/' + nocId + '/customers/' + customerId + '/actions', actionData, { token: this.platform.auth.token });
28615};
28616
28617NocCustomers.prototype.updateServiceAction = function(nocId, customerId, actionId, actionData){
28618 return this.platform.http.put('/nocs/' + nocId + '/customers/' + customerId + '/actions/' + actionId, actionData, { token: this.platform.auth.token });
28619};
28620
28621NocCustomers.prototype.listInstallations= function(nocId){
28622 return this.platform.http.get('/nocs/' + nocId + '/customers/installations', { token: this.platform.auth.token });
28623};
28624
28625NocCustomers.prototype.getInstallation= function(nocId, installationId){
28626 return this.platform.http.get('/nocs/' + nocId + '/customers/installations/' + installationId, { token: this.platform.auth.token });
28627};
28628
28629NocCustomers.prototype.createInstallation= function(nocId, installationData){
28630 return this.platform.http.post('/nocs/' + nocId + '/customers/installations', installationData, { token: this.platform.auth.token });
28631};
28632
28633NocCustomers.prototype.updateInstallation= function(nocId, installationId, installationData){
28634 return this.platform.http.put('/nocs/' + nocId + '/customers/installations/' + installationId, installationData, { token: this.platform.auth.token });
28635};
28636
28637
28638module.exports = function(options) {
28639 options = options || {};
28640 return new NocCustomers(options);
28641};
28642
28643},{}],"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/src/lib/methods/noc/noc.js":[function(require,module,exports){
28644'use strict';
28645var NocCustomers = require("./customers");
28646var NocTickets = require("./tickets");
28647var NocServices = require("./services");
28648var NocServiceActions = require("./service_actions");
28649
28650function Noc(options) {
28651 options = options || {};
28652 this.platform = options.platform;
28653 this.customers = new NocCustomers({ platform: this.platform });
28654 this.tickets = new NocTickets({ platform: this.platform });
28655 this.services = new NocServices({ platform: this.platform });
28656 this.service_actions = new NocServiceActions({ platform: this.platform });
28657}
28658
28659Noc.prototype.list = function() {
28660 return this.platform.http.get('/nocs/', { token: this.platform.auth.token });
28661};
28662
28663Noc.prototype.get = function(nocId){
28664 return this.platform.http.get('/nocs/' + nocId, { token: this.platform.auth.token });
28665};
28666
28667Noc.prototype.create = function(noc){
28668 return this.platform.http.post('/nocs', noc, { token: this.platform.auth.token });
28669};
28670
28671Noc.prototype.update = function(nocId, noc){
28672 return this.platform.http.put('/nocs/' + nocId, noc, { token: this.platform.auth.token });
28673};
28674
28675Noc.prototype.patch = function(nocId, noc){
28676 return this.platform.http.patch('/nocs/' + nocId, noc, { token: this.platform.auth.token });
28677};
28678
28679Noc.prototype.approve = function(nocId, approvalToken){
28680 return this.platform.http.put('/nocs/' + nocId + '/approve/' + approvalToken);
28681};
28682
28683Noc.prototype.approval_link = function(email){
28684 return this.platform.http.get('/nocs/approval-link/' + email);
28685};
28686
28687module.exports = function(options) {
28688 options = options || {};
28689 return new Noc(options);
28690};
28691
28692},{"./customers":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/src/lib/methods/noc/customers.js","./service_actions":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/src/lib/methods/noc/service_actions.js","./services":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/src/lib/methods/noc/services.js","./tickets":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/src/lib/methods/noc/tickets.js"}],"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/src/lib/methods/noc/service_actions.js":[function(require,module,exports){
28693'use strict';
28694
28695function NocServiceActions(options) {
28696 options = options || {};
28697 this.platform = options.platform;
28698}
28699
28700NocServiceActions.prototype.list= function(nocId){
28701 return this.platform.http.get('/nocs/' + nocId + '/service_actions', { token: this.platform.auth.token });
28702};
28703
28704NocServiceActions.prototype.get= function(nocId, serviceId){
28705 return this.platform.http.get('/nocs/' + nocId + '/service_actions/' + serviceId, { token: this.platform.auth.token });
28706};
28707
28708NocServiceActions.prototype.getPredefinedServiceActions= function(nocId){
28709 return this.platform.http.get('/nocs/' + nocId + '/service_actions/predefined', { token: this.platform.auth.token });
28710};
28711
28712NocServiceActions.prototype.create= function(nocId, serviceActions){
28713 return this.platform.http.post('/nocs/' + nocId + '/service_actions', serviceActions, { token: this.platform.auth.token });
28714};
28715
28716NocServiceActions.prototype.update= function(nocId, serviceId, serviceActions){
28717 return this.platform.http.put('/nocs/' + nocId + '/service_actions/' + serviceId, serviceActions, { token: this.platform.auth.token });
28718};
28719
28720NocServiceActions.prototype.patch = function(nocId, serviceId, serviceActions){
28721 return this.platform.http.patch ('/nocs/' + nocId + '/service_actions/' + serviceId, serviceActions, { token: this.platform.auth.token });
28722};
28723
28724module.exports = function(options) {
28725 options = options || {};
28726 return new NocServiceActions(options);
28727};
28728
28729},{}],"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/src/lib/methods/noc/services.js":[function(require,module,exports){
28730'use strict';
28731
28732function NocServices(options) {
28733 options = options || {};
28734 this.platform = options.platform;
28735}
28736
28737NocServices.prototype.list= function(nocId){
28738 return this.platform.http.get('/nocs/' + nocId + '/services', { token: this.platform.auth.token });
28739};
28740
28741NocServices.prototype.get= function(nocId, serviceId){
28742 return this.platform.http.get('/nocs/' + nocId + '/services/' + serviceId, { token: this.platform.auth.token });
28743};
28744
28745NocServices.prototype.create= function(nocId, service){
28746 return this.platform.http.post('/nocs/' + nocId + '/services', service, { token: this.platform.auth.token });
28747};
28748
28749NocServices.prototype.update= function(nocId, serviceId, service){
28750 return this.platform.http.put('/nocs/' + nocId + '/services/' + serviceId, service, { token: this.platform.auth.token });
28751};
28752
28753NocServices.prototype.patch = function(nocId, serviceId, service){
28754 return this.platform.http.patch ('/nocs/' + nocId + '/services/' + serviceId, service, { token: this.platform.auth.token });
28755};
28756
28757module.exports = function(options) {
28758 options = options || {};
28759 return new NocServices(options);
28760};
28761
28762},{}],"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/src/lib/methods/noc/tickets.js":[function(require,module,exports){
28763'use strict';
28764
28765function NocTickets(options) {
28766 options = options || {};
28767 this.platform = options.platform;
28768}
28769
28770NocTickets.prototype.list = function(nocId){
28771 return this.platform.http.get('/nocs/' + nocId + '/noc_tickets', { token: this.platform.auth.token });
28772};
28773
28774NocTickets.prototype.get = function(nocId, ticketId){
28775 return this.platform.http.get('/nocs/' + nocId + '/noc_tickets/' + ticketId, { token: this.platform.auth.token });
28776};
28777
28778NocTickets.prototype.update = function(nocId, ticketId, ticket){
28779 return this.platform.http.put('/nocs/' + nocId + '/noc_tickets/' + ticketId, ticket, { token: this.platform.auth.token });
28780};
28781
28782NocTickets.prototype.patch = function(nocId, ticketId, ticket){
28783 return this.platform.http.patch ('/nocs/' + nocId + '/noc_tickets/' + ticketId, ticket, { token: this.platform.auth.token });
28784};
28785
28786NocTickets.prototype.create = function(nocId, ticket){
28787 return this.platform.http.post('/nocs' + nocId + '/noc_ticket', ticket, { token: this.platform.auth.token });
28788};
28789
28790NocTickets.prototype.listDevices = function(nocId, ticketId){
28791 return this.platform.http.get('/nocs/' + nocId + '/noc_tickets/' + ticketId + '/devices', { token: this.platform.auth.token });
28792};
28793
28794NocTickets.prototype.listEvents = function(nocId, ticketId){
28795 return this.platform.http.get('/nocs/' + nocId + '/noc_tickets/' + ticketId + '/noc_ticket_events', { token: this.platform.auth.token });
28796};
28797
28798NocTickets.prototype.getEvent = function(nocId, ticketId, ticketEventId){
28799 return this.platform.http.get('/nocs/' + nocId + '/noc_tickets/' + ticketId + '/noc_ticket_events/' + ticketEventId, { token: this.platform.auth.token });
28800};
28801
28802NocTickets.prototype.createEvent = function(nocId, ticketId, ticketEvent){
28803 return this.platform.http.post('/nocs/' + nocId + '/noc_tickets/' + ticketId + '/noc_ticket_events', ticketEvent, { token: this.platform.auth.token });
28804};
28805
28806NocTickets.prototype.updateEvent= function(nocId, ticketId, ticketEventId, ticketEvent){
28807 return this.platform.http.put('/nocs/' + nocId + '/noc_tickets/' + ticketId + '/noc_ticket_events/' + ticketEventId, ticketEvent, { token: this.platform.auth.token });
28808};
28809
28810NocTickets.prototype.patchEvent = function(nocId, ticketId, ticketEventId, ticketEvent){
28811 return this.platform.http.patch ('/nocs/' + nocId + '/noc_tickets/' + ticketId + '/noc_ticket_events/' + ticketEventId, ticketEvent, { token: this.platform.auth.token });
28812};
28813
28814module.exports = function(options) {
28815 options = options || {};
28816 return new NocTickets(options);
28817};
28818
28819},{}],"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/src/lib/methods/notifications.js":[function(require,module,exports){
28820'use strict';
28821
28822function Notifications(options) {
28823 options = options || {};
28824 this.platform = options.platform;
28825}
28826
28827Notifications.prototype.list = function(params){
28828 return this.platform.http.get('/notifications', { query: params, token: this.platform.auth.token });
28829};
28830
28831Notifications.prototype.get = function(locationId, params){
28832 return this.platform.http.get('/locations/'+locationId+'/notifications', { query: params, token: this.platform.auth.token });
28833};
28834
28835Notifications.prototype.patch = function(notificationId, obj){
28836 return this.platform.http.patch('/notifications/'+notificationId, obj, { token: this.platform.auth.token });
28837};
28838
28839Notifications.prototype.markRead = function(notificationId){
28840 return this.platform.http.patch('/notifications/'+notificationId, { read: true, readTs: Date.now() }, { token: this.platform.auth.token });
28841};
28842
28843Notifications.prototype.getConfig = function(){
28844 return this.platform.http.get('/notifications/config', { token: this.platform.auth.token });
28845};
28846
28847Notifications.prototype.updateConfig = function(config){
28848 return this.platform.http.put('/notifications/config' + (config._id ? "/"+config._id:""), config, { token: this.platform.auth.token });
28849};
28850
28851module.exports = function(options) {
28852 options = options || {};
28853 return new Notifications(options);
28854};
28855
28856
28857},{}],"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/src/lib/methods/register.js":[function(require,module,exports){
28858module.exports = (function() {
28859
28860 return function(user, options) {
28861 var _this = this, logger = this.logger;
28862 options = options || {};
28863
28864 logger.debug("Executing HTTP request GET /auth/register");
28865 return this.http.post("/auth/register", user, options).then(function(resp) {
28866 logger.debug(resp);
28867 if(resp) {
28868 return resp.data;
28869 }
28870 else {
28871 logger.error("Invalid response received from platform");
28872 }
28873
28874 });
28875
28876 };
28877
28878})();
28879
28880},{}],"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/src/lib/methods/scenarios.js":[function(require,module,exports){
28881'use strict';
28882
28883function Scenarios(options) {
28884 options = options || {};
28885 this.platform = options.platform;
28886}
28887
28888Scenarios.prototype.list = function(){
28889 return this.platform.http.get('/scenarios', { token: this.platform.auth.token });
28890};
28891
28892Scenarios.prototype.get = function(scenarioId){
28893 return this.platform.http.get('/scenarios/'+scenarioId, { token: this.platform.auth.token });
28894};
28895
28896Scenarios.prototype.create = function(scenario){
28897 return this.platform.http.post('/scenarios', scenario, { token: this.platform.auth.token });
28898};
28899
28900Scenarios.prototype.update = function(scenario){
28901 return this.platform.http.put('/scenarios/'+scenario._id, scenario, { token: this.platform.auth.token });
28902};
28903
28904Scenarios.prototype.patch = function(scenarioId, obj){
28905 return this.platform.http.patch('/scenarios/'+scenarioId, obj, { token: this.platform.auth.token });
28906};
28907
28908Scenarios.prototype.delete = function(scenarioId){
28909 return this.platform.http.delete('/scenarios/'+scenarioId, { token: this.platform.auth.token });
28910};
28911
28912module.exports = function(options) {
28913 options = options || {};
28914 return new Scenarios(options);
28915};
28916
28917
28918},{}],"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/src/lib/methods/streams.js":[function(require,module,exports){
28919'use strict';
28920
28921function Streams(options) {
28922 options = options || {};
28923 this.platform = options.platform;
28924}
28925
28926//Streams.prototype.get = function(propertyId){
28927Streams.prototype.list = function(){
28928 //return this.platform.http.get('/homes/'+propertyId+'/cameras/stream/all', { token: this.platform.auth.token });
28929 return this.platform.http.get('/streams', { token: this.platform.auth.token });
28930};
28931
28932module.exports = function(options) {
28933 options = options || {};
28934 return new Streams(options);
28935};
28936
28937
28938},{}],"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/src/lib/methods/system.js":[function(require,module,exports){
28939'use strict';
28940
28941function System(options) {
28942 options = options || {};
28943 this.platform = options.platform;
28944}
28945
28946System.prototype.info = function(){
28947 return this.platform.http.get('/system/info');
28948};
28949
28950module.exports = function(options) {
28951 options = options || {};
28952 return new System(options);
28953};
28954
28955},{}],"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/src/lib/methods/templates.js":[function(require,module,exports){
28956'use strict';
28957
28958function Templates(options) {
28959 options = options || {};
28960 this.platform = options.platform;
28961}
28962
28963Templates.prototype.list = function(){
28964 return this.platform.http.get('/templates', { token: this.platform.auth.token });
28965};
28966
28967Templates.prototype.get = function(templateId, level){
28968 return this.platform.http.get('/templates/'+templateId, { query: { level: level }, token: this.platform.auth.token });
28969};
28970
28971Templates.prototype.create = function(template){
28972 return this.platform.http.post('/templates', template, { token: this.platform.auth.token });
28973};
28974
28975Templates.prototype.patch = function(obj, templateId){
28976 return this.platform.http.patch('/templates/'+templateId, obj, { token: this.platform.auth.token });
28977};
28978
28979Templates.prototype.delete = function(templateId){
28980 return this.platform.http.delete('/templates/'+templateId, { token: this.platform.auth.token });
28981};
28982
28983module.exports = function(options) {
28984 options = options || {};
28985 return new Templates(options);
28986};
28987
28988},{}],"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/src/lib/methods/translations.js":[function(require,module,exports){
28989'use strict';
28990
28991function Translations(options) {
28992 options = options || {};
28993 this.platform = options.platform;
28994}
28995
28996Translations.prototype.list = function(){
28997 return this.platform.http.get('/translations', { token: this.platform.auth.token });
28998};
28999
29000Translations.prototype.get = function(key){
29001 return this.platform.http.get('/translations/'+key, { token: this.platform.auth.token });
29002};
29003
29004Translations.prototype.create = function(translation){
29005 return this.platform.http.post('/translations', translation, { token: this.platform.auth.token });
29006};
29007
29008Translations.prototype.update = function(key, translation){
29009 return this.platform.http.put('/translations/'+key, translation, { token: this.platform.auth.token });
29010};
29011
29012
29013module.exports = function(options) {
29014 options = options || {};
29015 return new Translations(options);
29016};
29017
29018
29019},{}],"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/src/lib/methods/user.js":[function(require,module,exports){
29020'use strict';
29021
29022function User(options) {
29023 options = options || {};
29024 this.platform = options.platform;
29025}
29026
29027User.prototype.get = function(username){
29028 return this.platform.http.get('/users/'+username, { token: this.platform.auth.token });
29029};
29030
29031User.prototype.register = function(user){
29032 return this.platform.http.post('/auth/register', user);
29033};
29034
29035User.prototype.forgot = function(email){
29036 return this.platform.http.get('/auth/forgot/'+email);
29037};
29038
29039User.prototype.reset = function(resetToken){
29040 return this.platform.http.get('/auth/reset/'+resetToken);
29041};
29042
29043User.prototype.resetPassword = function(resetToken, passwordInfo){
29044 return this.platform.http.post('/auth/reset/'+resetToken, passwordInfo);
29045};
29046
29047User.prototype.confirm = function(key){
29048 return this.platform.http.get('/auth/confirm/'+key);
29049};
29050
29051User.prototype.changePassword = function(username, currentPassword, password){
29052 return this.platform.http.put('/users/'+username+'/password', { current:currentPassword, password:password }, { token: this.platform.auth.token });
29053};
29054
29055User.prototype.list = function(){
29056 return this.platform.http.get('/users', { token: this.platform.auth.token });
29057};
29058
29059User.prototype.listAlarmSystems = function(userId){
29060 return this.platform.http.get('/users/' + userId + '/alarms', { token: this.platform.auth.token });
29061};
29062
29063User.prototype.getCurrentUser = function(options){
29064 var token;
29065 options ? token = options.token : token = undefined;
29066 return this.platform.http.get('/users/me', { token: token || this.platform.auth.token });
29067};
29068
29069User.prototype.update = function(username, user){
29070 return this.platform.http.put('/users/'+username, user, { token: this.platform.auth.token });
29071};
29072
29073User.prototype.patch = function(username, obj){
29074 return this.platform.http.patch('/users/'+username, obj, { token: this.platform.auth.token });
29075};
29076
29077User.prototype.delete = function(username){
29078 return this.platform.http.delete('/users/'+username, { token: this.platform.auth.token });
29079};
29080
29081User.prototype.bindDevice = function(mac, location){
29082 return this.platform.http.post('/devices/bind', { mac: mac, location: location }, { token: this.platform.auth.token });
29083};
29084
29085module.exports = function(options) {
29086 options = options || {};
29087 return new User(options);
29088};
29089
29090},{}],"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/src/lib/methods/zwave.js":[function(require,module,exports){
29091'use strict';
29092
29093function ZWave(options) {
29094 options = options || {};
29095 this.platform = options.platform;
29096}
29097
29098ZWave.prototype.exclusion = function(gatewayId){
29099 return this.platform.http.post('/devices/'+gatewayId+'/zwave/exclude', {}, { token: this.platform.auth.token });
29100};
29101
29102ZWave.prototype.removeFailed = function(gatewayId){
29103 return this.platform.http.delete('/devices/'+gatewayId+'/zwave/failed', {}, { token: this.platform.auth.token });
29104};
29105
29106module.exports = function(options) {
29107 options = options || {};
29108 return new ZWave(options);
29109};
29110
29111
29112},{}],"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/src/lib/mixin_promise.js":[function(require,module,exports){
29113var P = require("bluebird").noConflict();
29114
29115P.prototype.mixin = function(cstor) {
29116 var o = new cstor();
29117 o.__p = this;
29118
29119 o.catch = function(fn) {
29120 this.__p.catch.call(this.__p, fn.bind(this));
29121 return this;
29122 };
29123
29124 o.then = o.ready = function(fn) {
29125 this.__p.then.call(this.__p, fn.bind(this));
29126 return this;
29127 };
29128
29129 o.finally = function(fn) {
29130 this.__p.finally.apply(this.__p, fn.bind(this));
29131 return this;
29132 };
29133
29134 return o;
29135};
29136
29137module.exports = P;
29138},{"bluebird":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/bluebird/js/browser/bluebird.js"}],"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/src/lib/stream_api.js":[function(require,module,exports){
29139var socketIOClient = require('socket.io-client');
29140var events = require('events');
29141var inherits = require('inherits');
29142var _ = require('lodash');
29143
29144function Subscriber(channelString, handler) {
29145 this.channelString = channelString;
29146 this.handler = handler;
29147}
29148
29149Subscriber.prototype.handle = function(event) {
29150
29151 if(this.channelString.indexOf('*') !== -1) {
29152 var channel = this.channelString.split('/')[0];
29153 if(event.type.indexOf(channel) !== -1) {
29154 this.handler(event);
29155 }
29156 }
29157 else if(this.channelString === event.type) {
29158 return this.handler(event);
29159 }
29160
29161};
29162
29163function Channel(key, api) {
29164 this.key = key;
29165 this.api = api;
29166 events.EventEmitter.call(this);
29167}
29168inherits(Channel, events.EventEmitter);
29169
29170/*
29171 * Subscribe to the channel using scope token and
29172 * @param: options
29173 * token: A valid platform token providing access to private events as per the token scope
29174 * type: A string or array of event type to be notified (optional)
29175 * handler: A function that will be called with the event data
29176 * scope: The scope that will be used when calling the callback. default to global.
29177 * persistence: (optional). Provide a persistence strategy for unreceived events. (TBD)
29178 */
29179Channel.subscribe = function(options) {
29180 var subscribeKey = "/" + this.key + "/";
29181 if(_.isString(options.type)) {
29182 subscribeKey += options.type;
29183 }
29184 else {
29185 subscribeKey += "*";
29186 }
29187
29188 return this.api.subscribe(subscribeKey, (function(options) {
29189 var types = [];
29190 if(_.isString(options.type)) {
29191 types = options.type.split(',');
29192 }
29193 else {
29194 types = options.types;
29195 }
29196
29197 return function(event) {
29198 if(types.indexOf(event.type) !== -1) {
29199 options.handler.call(options.scope || this, event);
29200 }
29201 }
29202 })(options), { token: options.token, persistence: options.persistence });
29203};
29204
29205function _handleEvent(event) {
29206 var _this = this;
29207
29208 _.each(this.subscribers, function(subscriber) {
29209
29210 // Provide a simple mechanism to handle replies to specific events
29211 subscriber.handle(event, function(reply) {
29212 _this.socket.emit('reply', {
29213 replyTo: event.id,
29214 data: reply
29215 });
29216 });
29217
29218 });
29219
29220}
29221
29222function StreamAPI(options) {
29223 options = options || {};
29224
29225 this.url = options.url;
29226 this.subscribers = [];
29227
29228 this.socket = socketIOClient(options.url, options.socket);
29229
29230 events.EventEmitter.call(this);
29231
29232 // Connect all stream API event handlers
29233 this.socket.on('connect', function() {
29234 console.log("Stream API is CONNECTED to %s", this.url);
29235 this.emit('connect');
29236 }.bind(this));
29237
29238 this.socket.on('disconnect', function() {
29239 console.log("Stream API is DISCONNECTED from %s", this.url);
29240 this.emit('disconnect');
29241 }.bind(this));
29242
29243 this.socket.on('event', _handleEvent.bind(this));
29244
29245 // Create all secure channels
29246 StreamAPI.catalog = new Channel("catalog", this);
29247 StreamAPI.klic = new Channel("2klic", this);
29248 StreamAPI.marketplace = new Channel("marketplace", this);
29249 StreamAPI.social = new Channel("social", this);
29250 StreamAPI.profile = new Channel("profile", this);
29251 StreamAPI.system = new Channel("system", this);
29252
29253}
29254
29255inherits(StreamAPI, events.EventEmitter);
29256
29257StreamAPI.prototype.subscribe = function(channelString, handler, options) {
29258 options = options || {};
29259
29260 // Register a listener in our socket
29261 this.subscribers.push(new Subscriber(channelString, handler));
29262
29263 this.socket.emit('subscribe', {
29264 channel: channelString,
29265 token: options.token,
29266 persistence: options.persistence
29267 });
29268};
29269
29270module.exports = StreamAPI;
29271},{"events":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/browserify/node_modules/events/events.js","inherits":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/inherits/inherits_browser.js","lodash":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/lodash/index.js","socket.io-client":"/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/node_modules/socket.io-client/lib/index.js"}]},{},["/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/src/index.js"])("/home/employee-2klic/Documents/ioSdk/2klic_io-sdk/src/index.js")
29272});
29273//# sourceMappingURL=2klic.js.map