UNPKG

913 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/projects/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.1.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._isTickUsed = false;
64 this._lateQueue = new Queue(16);
65 this._normalQueue = new Queue(16);
66 this._haveDrainedQueues = false;
67 this._trampolineEnabled = true;
68 var self = this;
69 this.drainQueues = function () {
70 self._drainQueues();
71 };
72 this._schedule = schedule;
73}
74
75Async.prototype.enableTrampoline = function() {
76 this._trampolineEnabled = true;
77};
78
79Async.prototype.disableTrampolineIfNecessary = function() {
80 if (util.hasDevTools) {
81 this._trampolineEnabled = false;
82 }
83};
84
85Async.prototype.haveItemsQueued = function () {
86 return this._isTickUsed || this._haveDrainedQueues;
87};
88
89
90Async.prototype.fatalError = function(e, isNode) {
91 if (isNode) {
92 process.stderr.write("Fatal " + (e instanceof Error ? e.stack : e));
93 process.exit(2);
94 } else {
95 this.throwLater(e);
96 }
97};
98
99Async.prototype.throwLater = function(fn, arg) {
100 if (arguments.length === 1) {
101 arg = fn;
102 fn = function () { throw arg; };
103 }
104 if (typeof setTimeout !== "undefined") {
105 setTimeout(function() {
106 fn(arg);
107 }, 0);
108 } else try {
109 this._schedule(function() {
110 fn(arg);
111 });
112 } catch (e) {
113 throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/MqrFmX\u000a");
114 }
115};
116
117function AsyncInvokeLater(fn, receiver, arg) {
118 this._lateQueue.push(fn, receiver, arg);
119 this._queueTick();
120}
121
122function AsyncInvoke(fn, receiver, arg) {
123 this._normalQueue.push(fn, receiver, arg);
124 this._queueTick();
125}
126
127function AsyncSettlePromises(promise) {
128 this._normalQueue._pushOne(promise);
129 this._queueTick();
130}
131
132if (!util.hasDevTools) {
133 Async.prototype.invokeLater = AsyncInvokeLater;
134 Async.prototype.invoke = AsyncInvoke;
135 Async.prototype.settlePromises = AsyncSettlePromises;
136} else {
137 Async.prototype.invokeLater = function (fn, receiver, arg) {
138 if (this._trampolineEnabled) {
139 AsyncInvokeLater.call(this, fn, receiver, arg);
140 } else {
141 this._schedule(function() {
142 setTimeout(function() {
143 fn.call(receiver, arg);
144 }, 100);
145 });
146 }
147 };
148
149 Async.prototype.invoke = function (fn, receiver, arg) {
150 if (this._trampolineEnabled) {
151 AsyncInvoke.call(this, fn, receiver, arg);
152 } else {
153 this._schedule(function() {
154 fn.call(receiver, arg);
155 });
156 }
157 };
158
159 Async.prototype.settlePromises = function(promise) {
160 if (this._trampolineEnabled) {
161 AsyncSettlePromises.call(this, promise);
162 } else {
163 this._schedule(function() {
164 promise._settlePromises();
165 });
166 }
167 };
168}
169
170Async.prototype.invokeFirst = function (fn, receiver, arg) {
171 this._normalQueue.unshift(fn, receiver, arg);
172 this._queueTick();
173};
174
175Async.prototype._drainQueue = function(queue) {
176 while (queue.length() > 0) {
177 var fn = queue.shift();
178 if (typeof fn !== "function") {
179 fn._settlePromises();
180 continue;
181 }
182 var receiver = queue.shift();
183 var arg = queue.shift();
184 fn.call(receiver, arg);
185 }
186};
187
188Async.prototype._drainQueues = function () {
189 this._drainQueue(this._normalQueue);
190 this._reset();
191 this._haveDrainedQueues = true;
192 this._drainQueue(this._lateQueue);
193};
194
195Async.prototype._queueTick = function () {
196 if (!this._isTickUsed) {
197 this._isTickUsed = true;
198 this._schedule(this.drainQueues);
199 }
200};
201
202Async.prototype._reset = function () {
203 this._isTickUsed = false;
204};
205
206module.exports = Async;
207module.exports.firstLineError = firstLineError;
208
209},{"./queue":26,"./schedule":29,"./util":36}],3:[function(_dereq_,module,exports){
210"use strict";
211module.exports = function(Promise, INTERNAL, tryConvertToPromise, debug) {
212var calledBind = false;
213var rejectThis = function(_, e) {
214 this._reject(e);
215};
216
217var targetRejected = function(e, context) {
218 context.promiseRejectionQueued = true;
219 context.bindingPromise._then(rejectThis, rejectThis, null, this, e);
220};
221
222var bindingResolved = function(thisArg, context) {
223 if (((this._bitField & 50397184) === 0)) {
224 this._resolveCallback(context.target);
225 }
226};
227
228var bindingRejected = function(e, context) {
229 if (!context.promiseRejectionQueued) this._reject(e);
230};
231
232Promise.prototype.bind = function (thisArg) {
233 if (!calledBind) {
234 calledBind = true;
235 Promise.prototype._propagateFrom = debug.propagateFromFunction();
236 Promise.prototype._boundValue = debug.boundValueFunction();
237 }
238 var maybePromise = tryConvertToPromise(thisArg);
239 var ret = new Promise(INTERNAL);
240 ret._propagateFrom(this, 1);
241 var target = this._target();
242 ret._setBoundTo(maybePromise);
243 if (maybePromise instanceof Promise) {
244 var context = {
245 promiseRejectionQueued: false,
246 promise: ret,
247 target: target,
248 bindingPromise: maybePromise
249 };
250 target._then(INTERNAL, targetRejected, undefined, ret, context);
251 maybePromise._then(
252 bindingResolved, bindingRejected, undefined, ret, context);
253 ret._setOnCancel(maybePromise);
254 } else {
255 ret._resolveCallback(target);
256 }
257 return ret;
258};
259
260Promise.prototype._setBoundTo = function (obj) {
261 if (obj !== undefined) {
262 this._bitField = this._bitField | 2097152;
263 this._boundTo = obj;
264 } else {
265 this._bitField = this._bitField & (~2097152);
266 }
267};
268
269Promise.prototype._isBound = function () {
270 return (this._bitField & 2097152) === 2097152;
271};
272
273Promise.bind = function (thisArg, value) {
274 return Promise.resolve(value).bind(thisArg);
275};
276};
277
278},{}],4:[function(_dereq_,module,exports){
279"use strict";
280var old;
281if (typeof Promise !== "undefined") old = Promise;
282function noConflict() {
283 try { if (Promise === bluebird) Promise = old; }
284 catch (e) {}
285 return bluebird;
286}
287var bluebird = _dereq_("./promise")();
288bluebird.noConflict = noConflict;
289module.exports = bluebird;
290
291},{"./promise":22}],5:[function(_dereq_,module,exports){
292"use strict";
293var cr = Object.create;
294if (cr) {
295 var callerCache = cr(null);
296 var getterCache = cr(null);
297 callerCache[" size"] = getterCache[" size"] = 0;
298}
299
300module.exports = function(Promise) {
301var util = _dereq_("./util");
302var canEvaluate = util.canEvaluate;
303var isIdentifier = util.isIdentifier;
304
305var getMethodCaller;
306var getGetter;
307if (!true) {
308var makeMethodCaller = function (methodName) {
309 return new Function("ensureMethod", " \n\
310 return function(obj) { \n\
311 'use strict' \n\
312 var len = this.length; \n\
313 ensureMethod(obj, 'methodName'); \n\
314 switch(len) { \n\
315 case 1: return obj.methodName(this[0]); \n\
316 case 2: return obj.methodName(this[0], this[1]); \n\
317 case 3: return obj.methodName(this[0], this[1], this[2]); \n\
318 case 0: return obj.methodName(); \n\
319 default: \n\
320 return obj.methodName.apply(obj, this); \n\
321 } \n\
322 }; \n\
323 ".replace(/methodName/g, methodName))(ensureMethod);
324};
325
326var makeGetter = function (propertyName) {
327 return new Function("obj", " \n\
328 'use strict'; \n\
329 return obj.propertyName; \n\
330 ".replace("propertyName", propertyName));
331};
332
333var getCompiled = function(name, compiler, cache) {
334 var ret = cache[name];
335 if (typeof ret !== "function") {
336 if (!isIdentifier(name)) {
337 return null;
338 }
339 ret = compiler(name);
340 cache[name] = ret;
341 cache[" size"]++;
342 if (cache[" size"] > 512) {
343 var keys = Object.keys(cache);
344 for (var i = 0; i < 256; ++i) delete cache[keys[i]];
345 cache[" size"] = keys.length - 256;
346 }
347 }
348 return ret;
349};
350
351getMethodCaller = function(name) {
352 return getCompiled(name, makeMethodCaller, callerCache);
353};
354
355getGetter = function(name) {
356 return getCompiled(name, makeGetter, getterCache);
357};
358}
359
360function ensureMethod(obj, methodName) {
361 var fn;
362 if (obj != null) fn = obj[methodName];
363 if (typeof fn !== "function") {
364 var message = "Object " + util.classString(obj) + " has no method '" +
365 util.toString(methodName) + "'";
366 throw new Promise.TypeError(message);
367 }
368 return fn;
369}
370
371function caller(obj) {
372 var methodName = this.pop();
373 var fn = ensureMethod(obj, methodName);
374 return fn.apply(obj, this);
375}
376Promise.prototype.call = function (methodName) {
377 var args = [].slice.call(arguments, 1);;
378 if (!true) {
379 if (canEvaluate) {
380 var maybeCaller = getMethodCaller(methodName);
381 if (maybeCaller !== null) {
382 return this._then(
383 maybeCaller, undefined, undefined, args, undefined);
384 }
385 }
386 }
387 args.push(methodName);
388 return this._then(caller, undefined, undefined, args, undefined);
389};
390
391function namedGetter(obj) {
392 return obj[this];
393}
394function indexedGetter(obj) {
395 var index = +this;
396 if (index < 0) index = Math.max(0, index + obj.length);
397 return obj[index];
398}
399Promise.prototype.get = function (propertyName) {
400 var isIndex = (typeof propertyName === "number");
401 var getter;
402 if (!isIndex) {
403 if (canEvaluate) {
404 var maybeGetter = getGetter(propertyName);
405 getter = maybeGetter !== null ? maybeGetter : namedGetter;
406 } else {
407 getter = namedGetter;
408 }
409 } else {
410 getter = indexedGetter;
411 }
412 return this._then(getter, undefined, undefined, propertyName, undefined);
413};
414};
415
416},{"./util":36}],6:[function(_dereq_,module,exports){
417"use strict";
418module.exports = function(Promise, PromiseArray, apiRejection, debug) {
419var util = _dereq_("./util");
420var tryCatch = util.tryCatch;
421var errorObj = util.errorObj;
422var async = Promise._async;
423
424Promise.prototype["break"] = Promise.prototype.cancel = function() {
425 if (!debug.cancellation()) return this._warn("cancellation is disabled");
426
427 var promise = this;
428 var child = promise;
429 while (promise.isCancellable()) {
430 if (!promise._cancelBy(child)) {
431 if (child._isFollowing()) {
432 child._followee().cancel();
433 } else {
434 child._cancelBranched();
435 }
436 break;
437 }
438
439 var parent = promise._cancellationParent;
440 if (parent == null || !parent.isCancellable()) {
441 if (promise._isFollowing()) {
442 promise._followee().cancel();
443 } else {
444 promise._cancelBranched();
445 }
446 break;
447 } else {
448 if (promise._isFollowing()) promise._followee().cancel();
449 child = promise;
450 promise = parent;
451 }
452 }
453};
454
455Promise.prototype._branchHasCancelled = function() {
456 this._branchesRemainingToCancel--;
457};
458
459Promise.prototype._enoughBranchesHaveCancelled = function() {
460 return this._branchesRemainingToCancel === undefined ||
461 this._branchesRemainingToCancel <= 0;
462};
463
464Promise.prototype._cancelBy = function(canceller) {
465 if (canceller === this) {
466 this._branchesRemainingToCancel = 0;
467 this._invokeOnCancel();
468 return true;
469 } else {
470 this._branchHasCancelled();
471 if (this._enoughBranchesHaveCancelled()) {
472 this._invokeOnCancel();
473 return true;
474 }
475 }
476 return false;
477};
478
479Promise.prototype._cancelBranched = function() {
480 if (this._enoughBranchesHaveCancelled()) {
481 this._cancel();
482 }
483};
484
485Promise.prototype._cancel = function() {
486 if (!this.isCancellable()) return;
487
488 this._setCancelled();
489 async.invoke(this._cancelPromises, this, undefined);
490};
491
492Promise.prototype._cancelPromises = function() {
493 if (this._length() > 0) this._settlePromises();
494};
495
496Promise.prototype._unsetOnCancel = function() {
497 this._onCancelField = undefined;
498};
499
500Promise.prototype.isCancellable = function() {
501 return this.isPending() && !this.isCancelled();
502};
503
504Promise.prototype._doInvokeOnCancel = function(onCancelCallback, internalOnly) {
505 if (util.isArray(onCancelCallback)) {
506 for (var i = 0; i < onCancelCallback.length; ++i) {
507 this._doInvokeOnCancel(onCancelCallback[i], internalOnly);
508 }
509 } else if (onCancelCallback !== undefined) {
510 if (typeof onCancelCallback === "function") {
511 if (!internalOnly) {
512 var e = tryCatch(onCancelCallback).call(this._boundValue());
513 if (e === errorObj) {
514 this._attachExtraTrace(e.e);
515 async.throwLater(e.e);
516 }
517 }
518 } else {
519 onCancelCallback._resultCancelled(this);
520 }
521 }
522};
523
524Promise.prototype._invokeOnCancel = function() {
525 var onCancelCallback = this._onCancel();
526 this._unsetOnCancel();
527 async.invoke(this._doInvokeOnCancel, this, onCancelCallback);
528};
529
530Promise.prototype._invokeInternalOnCancel = function() {
531 if (this.isCancellable()) {
532 this._doInvokeOnCancel(this._onCancel(), true);
533 this._unsetOnCancel();
534 }
535};
536
537Promise.prototype._resultCancelled = function() {
538 this.cancel();
539};
540
541};
542
543},{"./util":36}],7:[function(_dereq_,module,exports){
544"use strict";
545module.exports = function(NEXT_FILTER) {
546var util = _dereq_("./util");
547var getKeys = _dereq_("./es5").keys;
548var tryCatch = util.tryCatch;
549var errorObj = util.errorObj;
550
551function catchFilter(instances, cb, promise) {
552 return function(e) {
553 var boundTo = promise._boundValue();
554 predicateLoop: for (var i = 0; i < instances.length; ++i) {
555 var item = instances[i];
556
557 if (item === Error ||
558 (item != null && item.prototype instanceof Error)) {
559 if (e instanceof item) {
560 return tryCatch(cb).call(boundTo, e);
561 }
562 } else if (typeof item === "function") {
563 var matchesPredicate = tryCatch(item).call(boundTo, e);
564 if (matchesPredicate === errorObj) {
565 return matchesPredicate;
566 } else if (matchesPredicate) {
567 return tryCatch(cb).call(boundTo, e);
568 }
569 } else if (util.isObject(e)) {
570 var keys = getKeys(item);
571 for (var j = 0; j < keys.length; ++j) {
572 var key = keys[j];
573 if (item[key] != e[key]) {
574 continue predicateLoop;
575 }
576 }
577 return tryCatch(cb).call(boundTo, e);
578 }
579 }
580 return NEXT_FILTER;
581 };
582}
583
584return catchFilter;
585};
586
587},{"./es5":13,"./util":36}],8:[function(_dereq_,module,exports){
588"use strict";
589module.exports = function(Promise) {
590var longStackTraces = false;
591var contextStack = [];
592
593Promise.prototype._promiseCreated = function() {};
594Promise.prototype._pushContext = function() {};
595Promise.prototype._popContext = function() {return null;};
596Promise._peekContext = Promise.prototype._peekContext = function() {};
597
598function Context() {
599 this._trace = new Context.CapturedTrace(peekContext());
600}
601Context.prototype._pushContext = function () {
602 if (this._trace !== undefined) {
603 this._trace._promiseCreated = null;
604 contextStack.push(this._trace);
605 }
606};
607
608Context.prototype._popContext = function () {
609 if (this._trace !== undefined) {
610 var trace = contextStack.pop();
611 var ret = trace._promiseCreated;
612 trace._promiseCreated = null;
613 return ret;
614 }
615 return null;
616};
617
618function createContext() {
619 if (longStackTraces) return new Context();
620}
621
622function peekContext() {
623 var lastIndex = contextStack.length - 1;
624 if (lastIndex >= 0) {
625 return contextStack[lastIndex];
626 }
627 return undefined;
628}
629Context.CapturedTrace = null;
630Context.create = createContext;
631Context.deactivateLongStackTraces = function() {};
632Context.activateLongStackTraces = function() {
633 var Promise_pushContext = Promise.prototype._pushContext;
634 var Promise_popContext = Promise.prototype._popContext;
635 var Promise_PeekContext = Promise._peekContext;
636 var Promise_peekContext = Promise.prototype._peekContext;
637 var Promise_promiseCreated = Promise.prototype._promiseCreated;
638 Context.deactivateLongStackTraces = function() {
639 Promise.prototype._pushContext = Promise_pushContext;
640 Promise.prototype._popContext = Promise_popContext;
641 Promise._peekContext = Promise_PeekContext;
642 Promise.prototype._peekContext = Promise_peekContext;
643 Promise.prototype._promiseCreated = Promise_promiseCreated;
644 longStackTraces = false;
645 };
646 longStackTraces = true;
647 Promise.prototype._pushContext = Context.prototype._pushContext;
648 Promise.prototype._popContext = Context.prototype._popContext;
649 Promise._peekContext = Promise.prototype._peekContext = peekContext;
650 Promise.prototype._promiseCreated = function() {
651 var ctx = this._peekContext();
652 if (ctx && ctx._promiseCreated == null) ctx._promiseCreated = this;
653 };
654};
655return Context;
656};
657
658},{}],9:[function(_dereq_,module,exports){
659"use strict";
660module.exports = function(Promise, Context) {
661var getDomain = Promise._getDomain;
662var async = Promise._async;
663var Warning = _dereq_("./errors").Warning;
664var util = _dereq_("./util");
665var canAttachTrace = util.canAttachTrace;
666var unhandledRejectionHandled;
667var possiblyUnhandledRejection;
668var bluebirdFramePattern =
669 /[\\\/]bluebird[\\\/]js[\\\/](release|debug|instrumented)/;
670var stackFramePattern = null;
671var formatStack = null;
672var indentStackFrames = false;
673var printWarning;
674var debugging = !!(util.env("BLUEBIRD_DEBUG") != 0 &&
675 (true ||
676 util.env("BLUEBIRD_DEBUG") ||
677 util.env("NODE_ENV") === "development"));
678
679var warnings = !!(util.env("BLUEBIRD_WARNINGS") != 0 &&
680 (debugging || util.env("BLUEBIRD_WARNINGS")));
681
682var longStackTraces = !!(util.env("BLUEBIRD_LONG_STACK_TRACES") != 0 &&
683 (debugging || util.env("BLUEBIRD_LONG_STACK_TRACES")));
684
685var wForgottenReturn = util.env("BLUEBIRD_W_FORGOTTEN_RETURN") != 0 &&
686 (warnings || !!util.env("BLUEBIRD_W_FORGOTTEN_RETURN"));
687
688Promise.prototype.suppressUnhandledRejections = function() {
689 var target = this._target();
690 target._bitField = ((target._bitField & (~1048576)) |
691 524288);
692};
693
694Promise.prototype._ensurePossibleRejectionHandled = function () {
695 if ((this._bitField & 524288) !== 0) return;
696 this._setRejectionIsUnhandled();
697 async.invokeLater(this._notifyUnhandledRejection, this, undefined);
698};
699
700Promise.prototype._notifyUnhandledRejectionIsHandled = function () {
701 fireRejectionEvent("rejectionHandled",
702 unhandledRejectionHandled, undefined, this);
703};
704
705Promise.prototype._setReturnedNonUndefined = function() {
706 this._bitField = this._bitField | 268435456;
707};
708
709Promise.prototype._returnedNonUndefined = function() {
710 return (this._bitField & 268435456) !== 0;
711};
712
713Promise.prototype._notifyUnhandledRejection = function () {
714 if (this._isRejectionUnhandled()) {
715 var reason = this._settledValue();
716 this._setUnhandledRejectionIsNotified();
717 fireRejectionEvent("unhandledRejection",
718 possiblyUnhandledRejection, reason, this);
719 }
720};
721
722Promise.prototype._setUnhandledRejectionIsNotified = function () {
723 this._bitField = this._bitField | 262144;
724};
725
726Promise.prototype._unsetUnhandledRejectionIsNotified = function () {
727 this._bitField = this._bitField & (~262144);
728};
729
730Promise.prototype._isUnhandledRejectionNotified = function () {
731 return (this._bitField & 262144) > 0;
732};
733
734Promise.prototype._setRejectionIsUnhandled = function () {
735 this._bitField = this._bitField | 1048576;
736};
737
738Promise.prototype._unsetRejectionIsUnhandled = function () {
739 this._bitField = this._bitField & (~1048576);
740 if (this._isUnhandledRejectionNotified()) {
741 this._unsetUnhandledRejectionIsNotified();
742 this._notifyUnhandledRejectionIsHandled();
743 }
744};
745
746Promise.prototype._isRejectionUnhandled = function () {
747 return (this._bitField & 1048576) > 0;
748};
749
750Promise.prototype._warn = function(message, shouldUseOwnTrace, promise) {
751 return warn(message, shouldUseOwnTrace, promise || this);
752};
753
754Promise.onPossiblyUnhandledRejection = function (fn) {
755 var domain = getDomain();
756 possiblyUnhandledRejection =
757 typeof fn === "function" ? (domain === null ? fn : domain.bind(fn))
758 : undefined;
759};
760
761Promise.onUnhandledRejectionHandled = function (fn) {
762 var domain = getDomain();
763 unhandledRejectionHandled =
764 typeof fn === "function" ? (domain === null ? fn : domain.bind(fn))
765 : undefined;
766};
767
768var disableLongStackTraces = function() {};
769Promise.longStackTraces = function () {
770 if (async.haveItemsQueued() && !config.longStackTraces) {
771 throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a");
772 }
773 if (!config.longStackTraces && longStackTracesIsSupported()) {
774 var Promise_captureStackTrace = Promise.prototype._captureStackTrace;
775 var Promise_attachExtraTrace = Promise.prototype._attachExtraTrace;
776 config.longStackTraces = true;
777 disableLongStackTraces = function() {
778 if (async.haveItemsQueued() && !config.longStackTraces) {
779 throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a");
780 }
781 Promise.prototype._captureStackTrace = Promise_captureStackTrace;
782 Promise.prototype._attachExtraTrace = Promise_attachExtraTrace;
783 Context.deactivateLongStackTraces();
784 async.enableTrampoline();
785 config.longStackTraces = false;
786 };
787 Promise.prototype._captureStackTrace = longStackTracesCaptureStackTrace;
788 Promise.prototype._attachExtraTrace = longStackTracesAttachExtraTrace;
789 Context.activateLongStackTraces();
790 async.disableTrampolineIfNecessary();
791 }
792};
793
794Promise.hasLongStackTraces = function () {
795 return config.longStackTraces && longStackTracesIsSupported();
796};
797
798Promise.config = function(opts) {
799 opts = Object(opts);
800 if ("longStackTraces" in opts) {
801 if (opts.longStackTraces) {
802 Promise.longStackTraces();
803 } else if (!opts.longStackTraces && Promise.hasLongStackTraces()) {
804 disableLongStackTraces();
805 }
806 }
807 if ("warnings" in opts) {
808 var warningsOption = opts.warnings;
809 config.warnings = !!warningsOption;
810 wForgottenReturn = config.warnings;
811
812 if (util.isObject(warningsOption)) {
813 if ("wForgottenReturn" in warningsOption) {
814 wForgottenReturn = !!warningsOption.wForgottenReturn;
815 }
816 }
817 }
818 if ("cancellation" in opts && opts.cancellation && !config.cancellation) {
819 if (async.haveItemsQueued()) {
820 throw new Error(
821 "cannot enable cancellation after promises are in use");
822 }
823 Promise.prototype._clearCancellationData =
824 cancellationClearCancellationData;
825 Promise.prototype._propagateFrom = cancellationPropagateFrom;
826 Promise.prototype._onCancel = cancellationOnCancel;
827 Promise.prototype._setOnCancel = cancellationSetOnCancel;
828 Promise.prototype._attachCancellationCallback =
829 cancellationAttachCancellationCallback;
830 Promise.prototype._execute = cancellationExecute;
831 propagateFromFunction = cancellationPropagateFrom;
832 config.cancellation = true;
833 }
834};
835
836Promise.prototype._execute = function(executor, resolve, reject) {
837 try {
838 executor(resolve, reject);
839 } catch (e) {
840 return e;
841 }
842};
843Promise.prototype._onCancel = function () {};
844Promise.prototype._setOnCancel = function (handler) { ; };
845Promise.prototype._attachCancellationCallback = function(onCancel) {
846 ;
847};
848Promise.prototype._captureStackTrace = function () {};
849Promise.prototype._attachExtraTrace = function () {};
850Promise.prototype._clearCancellationData = function() {};
851Promise.prototype._propagateFrom = function (parent, flags) {
852 ;
853 ;
854};
855
856function cancellationExecute(executor, resolve, reject) {
857 var promise = this;
858 try {
859 executor(resolve, reject, function(onCancel) {
860 if (typeof onCancel !== "function") {
861 throw new TypeError("onCancel must be a function, got: " +
862 util.toString(onCancel));
863 }
864 promise._attachCancellationCallback(onCancel);
865 });
866 } catch (e) {
867 return e;
868 }
869}
870
871function cancellationAttachCancellationCallback(onCancel) {
872 if (!this.isCancellable()) return this;
873
874 var previousOnCancel = this._onCancel();
875 if (previousOnCancel !== undefined) {
876 if (util.isArray(previousOnCancel)) {
877 previousOnCancel.push(onCancel);
878 } else {
879 this._setOnCancel([previousOnCancel, onCancel]);
880 }
881 } else {
882 this._setOnCancel(onCancel);
883 }
884}
885
886function cancellationOnCancel() {
887 return this._onCancelField;
888}
889
890function cancellationSetOnCancel(onCancel) {
891 this._onCancelField = onCancel;
892}
893
894function cancellationClearCancellationData() {
895 this._cancellationParent = undefined;
896 this._onCancelField = undefined;
897}
898
899function cancellationPropagateFrom(parent, flags) {
900 if ((flags & 1) !== 0) {
901 this._cancellationParent = parent;
902 var branchesRemainingToCancel = parent._branchesRemainingToCancel;
903 if (branchesRemainingToCancel === undefined) {
904 branchesRemainingToCancel = 0;
905 }
906 parent._branchesRemainingToCancel = branchesRemainingToCancel + 1;
907 }
908 if ((flags & 2) !== 0 && parent._isBound()) {
909 this._setBoundTo(parent._boundTo);
910 }
911}
912
913function bindingPropagateFrom(parent, flags) {
914 if ((flags & 2) !== 0 && parent._isBound()) {
915 this._setBoundTo(parent._boundTo);
916 }
917}
918var propagateFromFunction = bindingPropagateFrom;
919
920function boundValueFunction() {
921 var ret = this._boundTo;
922 if (ret !== undefined) {
923 if (ret instanceof Promise) {
924 if (ret.isFulfilled()) {
925 return ret.value();
926 } else {
927 return undefined;
928 }
929 }
930 }
931 return ret;
932}
933
934function longStackTracesCaptureStackTrace() {
935 this._trace = new CapturedTrace(this._peekContext());
936}
937
938function longStackTracesAttachExtraTrace(error, ignoreSelf) {
939 if (canAttachTrace(error)) {
940 var trace = this._trace;
941 if (trace !== undefined) {
942 if (ignoreSelf) trace = trace._parent;
943 }
944 if (trace !== undefined) {
945 trace.attachExtraTrace(error);
946 } else if (!error.__stackCleaned__) {
947 var parsed = parseStackAndMessage(error);
948 util.notEnumerableProp(error, "stack",
949 parsed.message + "\n" + parsed.stack.join("\n"));
950 util.notEnumerableProp(error, "__stackCleaned__", true);
951 }
952 }
953}
954
955function checkForgottenReturns(returnValue, promiseCreated, name, promise,
956 parent) {
957 if (returnValue === undefined && promiseCreated !== null &&
958 wForgottenReturn) {
959 if (parent !== undefined && parent._returnedNonUndefined()) return;
960
961 if (name) name = name + " ";
962 var msg = "a promise was created in a " + name +
963 "handler but was not returned from it";
964 promise._warn(msg, true, promiseCreated);
965 }
966}
967
968function deprecated(name, replacement) {
969 var message = name +
970 " is deprecated and will be removed in a future version.";
971 if (replacement) message += " Use " + replacement + " instead.";
972 return warn(message);
973}
974
975function warn(message, shouldUseOwnTrace, promise) {
976 if (!config.warnings) return;
977 var warning = new Warning(message);
978 var ctx;
979 if (shouldUseOwnTrace) {
980 promise._attachExtraTrace(warning);
981 } else if (config.longStackTraces && (ctx = Promise._peekContext())) {
982 ctx.attachExtraTrace(warning);
983 } else {
984 var parsed = parseStackAndMessage(warning);
985 warning.stack = parsed.message + "\n" + parsed.stack.join("\n");
986 }
987 formatAndLogError(warning, "", true);
988}
989
990function reconstructStack(message, stacks) {
991 for (var i = 0; i < stacks.length - 1; ++i) {
992 stacks[i].push("From previous event:");
993 stacks[i] = stacks[i].join("\n");
994 }
995 if (i < stacks.length) {
996 stacks[i] = stacks[i].join("\n");
997 }
998 return message + "\n" + stacks.join("\n");
999}
1000
1001function removeDuplicateOrEmptyJumps(stacks) {
1002 for (var i = 0; i < stacks.length; ++i) {
1003 if (stacks[i].length === 0 ||
1004 ((i + 1 < stacks.length) && stacks[i][0] === stacks[i+1][0])) {
1005 stacks.splice(i, 1);
1006 i--;
1007 }
1008 }
1009}
1010
1011function removeCommonRoots(stacks) {
1012 var current = stacks[0];
1013 for (var i = 1; i < stacks.length; ++i) {
1014 var prev = stacks[i];
1015 var currentLastIndex = current.length - 1;
1016 var currentLastLine = current[currentLastIndex];
1017 var commonRootMeetPoint = -1;
1018
1019 for (var j = prev.length - 1; j >= 0; --j) {
1020 if (prev[j] === currentLastLine) {
1021 commonRootMeetPoint = j;
1022 break;
1023 }
1024 }
1025
1026 for (var j = commonRootMeetPoint; j >= 0; --j) {
1027 var line = prev[j];
1028 if (current[currentLastIndex] === line) {
1029 current.pop();
1030 currentLastIndex--;
1031 } else {
1032 break;
1033 }
1034 }
1035 current = prev;
1036 }
1037}
1038
1039function cleanStack(stack) {
1040 var ret = [];
1041 for (var i = 0; i < stack.length; ++i) {
1042 var line = stack[i];
1043 var isTraceLine = " (No stack trace)" === line ||
1044 stackFramePattern.test(line);
1045 var isInternalFrame = isTraceLine && shouldIgnore(line);
1046 if (isTraceLine && !isInternalFrame) {
1047 if (indentStackFrames && line.charAt(0) !== " ") {
1048 line = " " + line;
1049 }
1050 ret.push(line);
1051 }
1052 }
1053 return ret;
1054}
1055
1056function stackFramesAsArray(error) {
1057 var stack = error.stack.replace(/\s+$/g, "").split("\n");
1058 for (var i = 0; i < stack.length; ++i) {
1059 var line = stack[i];
1060 if (" (No stack trace)" === line || stackFramePattern.test(line)) {
1061 break;
1062 }
1063 }
1064 if (i > 0) {
1065 stack = stack.slice(i);
1066 }
1067 return stack;
1068}
1069
1070function parseStackAndMessage(error) {
1071 var stack = error.stack;
1072 var message = error.toString();
1073 stack = typeof stack === "string" && stack.length > 0
1074 ? stackFramesAsArray(error) : [" (No stack trace)"];
1075 return {
1076 message: message,
1077 stack: cleanStack(stack)
1078 };
1079}
1080
1081function formatAndLogError(error, title, isSoft) {
1082 if (typeof console !== "undefined") {
1083 var message;
1084 if (util.isObject(error)) {
1085 var stack = error.stack;
1086 message = title + formatStack(stack, error);
1087 } else {
1088 message = title + String(error);
1089 }
1090 if (typeof printWarning === "function") {
1091 printWarning(message, isSoft);
1092 } else if (typeof console.log === "function" ||
1093 typeof console.log === "object") {
1094 console.log(message);
1095 }
1096 }
1097}
1098
1099function fireRejectionEvent(name, localHandler, reason, promise) {
1100 var localEventFired = false;
1101 try {
1102 if (typeof localHandler === "function") {
1103 localEventFired = true;
1104 if (name === "rejectionHandled") {
1105 localHandler(promise);
1106 } else {
1107 localHandler(reason, promise);
1108 }
1109 }
1110 } catch (e) {
1111 async.throwLater(e);
1112 }
1113
1114 var globalEventFired = false;
1115 try {
1116 globalEventFired = fireGlobalEvent(name, reason, promise);
1117 } catch (e) {
1118 globalEventFired = true;
1119 async.throwLater(e);
1120 }
1121
1122 var domEventFired = false;
1123 if (fireDomEvent) {
1124 try {
1125 domEventFired = fireDomEvent(name.toLowerCase(), {
1126 reason: reason,
1127 promise: promise
1128 });
1129 } catch (e) {
1130 domEventFired = true;
1131 async.throwLater(e);
1132 }
1133 }
1134
1135 if (!globalEventFired && !localEventFired && !domEventFired &&
1136 name === "unhandledRejection") {
1137 formatAndLogError(reason, "Unhandled rejection ");
1138 }
1139}
1140
1141function formatNonError(obj) {
1142 var str;
1143 if (typeof obj === "function") {
1144 str = "[function " +
1145 (obj.name || "anonymous") +
1146 "]";
1147 } else {
1148 str = obj && typeof obj.toString === "function"
1149 ? obj.toString() : util.toString(obj);
1150 var ruselessToString = /\[object [a-zA-Z0-9$_]+\]/;
1151 if (ruselessToString.test(str)) {
1152 try {
1153 var newStr = JSON.stringify(obj);
1154 str = newStr;
1155 }
1156 catch(e) {
1157
1158 }
1159 }
1160 if (str.length === 0) {
1161 str = "(empty array)";
1162 }
1163 }
1164 return ("(<" + snip(str) + ">, no stack trace)");
1165}
1166
1167function snip(str) {
1168 var maxChars = 41;
1169 if (str.length < maxChars) {
1170 return str;
1171 }
1172 return str.substr(0, maxChars - 3) + "...";
1173}
1174
1175function longStackTracesIsSupported() {
1176 return typeof captureStackTrace === "function";
1177}
1178
1179var shouldIgnore = function() { return false; };
1180var parseLineInfoRegex = /[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/;
1181function parseLineInfo(line) {
1182 var matches = line.match(parseLineInfoRegex);
1183 if (matches) {
1184 return {
1185 fileName: matches[1],
1186 line: parseInt(matches[2], 10)
1187 };
1188 }
1189}
1190
1191function setBounds(firstLineError, lastLineError) {
1192 if (!longStackTracesIsSupported()) return;
1193 var firstStackLines = firstLineError.stack.split("\n");
1194 var lastStackLines = lastLineError.stack.split("\n");
1195 var firstIndex = -1;
1196 var lastIndex = -1;
1197 var firstFileName;
1198 var lastFileName;
1199 for (var i = 0; i < firstStackLines.length; ++i) {
1200 var result = parseLineInfo(firstStackLines[i]);
1201 if (result) {
1202 firstFileName = result.fileName;
1203 firstIndex = result.line;
1204 break;
1205 }
1206 }
1207 for (var i = 0; i < lastStackLines.length; ++i) {
1208 var result = parseLineInfo(lastStackLines[i]);
1209 if (result) {
1210 lastFileName = result.fileName;
1211 lastIndex = result.line;
1212 break;
1213 }
1214 }
1215 if (firstIndex < 0 || lastIndex < 0 || !firstFileName || !lastFileName ||
1216 firstFileName !== lastFileName || firstIndex >= lastIndex) {
1217 return;
1218 }
1219
1220 shouldIgnore = function(line) {
1221 if (bluebirdFramePattern.test(line)) return true;
1222 var info = parseLineInfo(line);
1223 if (info) {
1224 if (info.fileName === firstFileName &&
1225 (firstIndex <= info.line && info.line <= lastIndex)) {
1226 return true;
1227 }
1228 }
1229 return false;
1230 };
1231}
1232
1233function CapturedTrace(parent) {
1234 this._parent = parent;
1235 this._promisesCreated = 0;
1236 var length = this._length = 1 + (parent === undefined ? 0 : parent._length);
1237 captureStackTrace(this, CapturedTrace);
1238 if (length > 32) this.uncycle();
1239}
1240util.inherits(CapturedTrace, Error);
1241Context.CapturedTrace = CapturedTrace;
1242
1243CapturedTrace.prototype.uncycle = function() {
1244 var length = this._length;
1245 if (length < 2) return;
1246 var nodes = [];
1247 var stackToIndex = {};
1248
1249 for (var i = 0, node = this; node !== undefined; ++i) {
1250 nodes.push(node);
1251 node = node._parent;
1252 }
1253 length = this._length = i;
1254 for (var i = length - 1; i >= 0; --i) {
1255 var stack = nodes[i].stack;
1256 if (stackToIndex[stack] === undefined) {
1257 stackToIndex[stack] = i;
1258 }
1259 }
1260 for (var i = 0; i < length; ++i) {
1261 var currentStack = nodes[i].stack;
1262 var index = stackToIndex[currentStack];
1263 if (index !== undefined && index !== i) {
1264 if (index > 0) {
1265 nodes[index - 1]._parent = undefined;
1266 nodes[index - 1]._length = 1;
1267 }
1268 nodes[i]._parent = undefined;
1269 nodes[i]._length = 1;
1270 var cycleEdgeNode = i > 0 ? nodes[i - 1] : this;
1271
1272 if (index < length - 1) {
1273 cycleEdgeNode._parent = nodes[index + 1];
1274 cycleEdgeNode._parent.uncycle();
1275 cycleEdgeNode._length =
1276 cycleEdgeNode._parent._length + 1;
1277 } else {
1278 cycleEdgeNode._parent = undefined;
1279 cycleEdgeNode._length = 1;
1280 }
1281 var currentChildLength = cycleEdgeNode._length + 1;
1282 for (var j = i - 2; j >= 0; --j) {
1283 nodes[j]._length = currentChildLength;
1284 currentChildLength++;
1285 }
1286 return;
1287 }
1288 }
1289};
1290
1291CapturedTrace.prototype.attachExtraTrace = function(error) {
1292 if (error.__stackCleaned__) return;
1293 this.uncycle();
1294 var parsed = parseStackAndMessage(error);
1295 var message = parsed.message;
1296 var stacks = [parsed.stack];
1297
1298 var trace = this;
1299 while (trace !== undefined) {
1300 stacks.push(cleanStack(trace.stack.split("\n")));
1301 trace = trace._parent;
1302 }
1303 removeCommonRoots(stacks);
1304 removeDuplicateOrEmptyJumps(stacks);
1305 util.notEnumerableProp(error, "stack", reconstructStack(message, stacks));
1306 util.notEnumerableProp(error, "__stackCleaned__", true);
1307};
1308
1309var captureStackTrace = (function stackDetection() {
1310 var v8stackFramePattern = /^\s*at\s*/;
1311 var v8stackFormatter = function(stack, error) {
1312 if (typeof stack === "string") return stack;
1313
1314 if (error.name !== undefined &&
1315 error.message !== undefined) {
1316 return error.toString();
1317 }
1318 return formatNonError(error);
1319 };
1320
1321 if (typeof Error.stackTraceLimit === "number" &&
1322 typeof Error.captureStackTrace === "function") {
1323 Error.stackTraceLimit += 6;
1324 stackFramePattern = v8stackFramePattern;
1325 formatStack = v8stackFormatter;
1326 var captureStackTrace = Error.captureStackTrace;
1327
1328 shouldIgnore = function(line) {
1329 return bluebirdFramePattern.test(line);
1330 };
1331 return function(receiver, ignoreUntil) {
1332 Error.stackTraceLimit += 6;
1333 captureStackTrace(receiver, ignoreUntil);
1334 Error.stackTraceLimit -= 6;
1335 };
1336 }
1337 var err = new Error();
1338
1339 if (typeof err.stack === "string" &&
1340 err.stack.split("\n")[0].indexOf("stackDetection@") >= 0) {
1341 stackFramePattern = /@/;
1342 formatStack = v8stackFormatter;
1343 indentStackFrames = true;
1344 return function captureStackTrace(o) {
1345 o.stack = new Error().stack;
1346 };
1347 }
1348
1349 var hasStackAfterThrow;
1350 try { throw new Error(); }
1351 catch(e) {
1352 hasStackAfterThrow = ("stack" in e);
1353 }
1354 if (!("stack" in err) && hasStackAfterThrow &&
1355 typeof Error.stackTraceLimit === "number") {
1356 stackFramePattern = v8stackFramePattern;
1357 formatStack = v8stackFormatter;
1358 return function captureStackTrace(o) {
1359 Error.stackTraceLimit += 6;
1360 try { throw new Error(); }
1361 catch(e) { o.stack = e.stack; }
1362 Error.stackTraceLimit -= 6;
1363 };
1364 }
1365
1366 formatStack = function(stack, error) {
1367 if (typeof stack === "string") return stack;
1368
1369 if ((typeof error === "object" ||
1370 typeof error === "function") &&
1371 error.name !== undefined &&
1372 error.message !== undefined) {
1373 return error.toString();
1374 }
1375 return formatNonError(error);
1376 };
1377
1378 return null;
1379
1380})([]);
1381
1382var fireDomEvent;
1383var fireGlobalEvent = (function() {
1384 if (util.isNode) {
1385 return function(name, reason, promise) {
1386 if (name === "rejectionHandled") {
1387 return process.emit(name, promise);
1388 } else {
1389 return process.emit(name, reason, promise);
1390 }
1391 };
1392 } else {
1393 var globalObject = typeof self !== "undefined" ? self :
1394 typeof window !== "undefined" ? window :
1395 typeof global !== "undefined" ? global :
1396 this !== undefined ? this : null;
1397
1398 if (!globalObject) {
1399 return function() {
1400 return false;
1401 };
1402 }
1403
1404 try {
1405 var event = document.createEvent("CustomEvent");
1406 event.initCustomEvent("testingtheevent", false, true, {});
1407 globalObject.dispatchEvent(event);
1408 fireDomEvent = function(type, detail) {
1409 var event = document.createEvent("CustomEvent");
1410 event.initCustomEvent(type, false, true, detail);
1411 return !globalObject.dispatchEvent(event);
1412 };
1413 } catch (e) {}
1414
1415 var toWindowMethodNameMap = {};
1416 toWindowMethodNameMap["unhandledRejection"] = ("on" +
1417 "unhandledRejection").toLowerCase();
1418 toWindowMethodNameMap["rejectionHandled"] = ("on" +
1419 "rejectionHandled").toLowerCase();
1420
1421 return function(name, reason, promise) {
1422 var methodName = toWindowMethodNameMap[name];
1423 var method = globalObject[methodName];
1424 if (!method) return false;
1425 if (name === "rejectionHandled") {
1426 method.call(globalObject, promise);
1427 } else {
1428 method.call(globalObject, reason, promise);
1429 }
1430 return true;
1431 };
1432 }
1433})();
1434
1435if (typeof console !== "undefined" && typeof console.warn !== "undefined") {
1436 printWarning = function (message) {
1437 console.warn(message);
1438 };
1439 if (util.isNode && process.stderr.isTTY) {
1440 printWarning = function(message, isSoft) {
1441 var color = isSoft ? "\u001b[33m" : "\u001b[31m";
1442 console.warn(color + message + "\u001b[0m\n");
1443 };
1444 } else if (!util.isNode && typeof (new Error().stack) === "string") {
1445 printWarning = function(message, isSoft) {
1446 console.warn("%c" + message,
1447 isSoft ? "color: darkorange" : "color: red");
1448 };
1449 }
1450}
1451
1452var config = {
1453 warnings: warnings,
1454 longStackTraces: false,
1455 cancellation: false
1456};
1457
1458if (longStackTraces) Promise.longStackTraces();
1459
1460return {
1461 longStackTraces: function() {
1462 return config.longStackTraces;
1463 },
1464 warnings: function() {
1465 return config.warnings;
1466 },
1467 cancellation: function() {
1468 return config.cancellation;
1469 },
1470 propagateFromFunction: function() {
1471 return propagateFromFunction;
1472 },
1473 boundValueFunction: function() {
1474 return boundValueFunction;
1475 },
1476 checkForgottenReturns: checkForgottenReturns,
1477 setBounds: setBounds,
1478 warn: warn,
1479 deprecated: deprecated,
1480 CapturedTrace: CapturedTrace
1481};
1482};
1483
1484},{"./errors":12,"./util":36}],10:[function(_dereq_,module,exports){
1485"use strict";
1486module.exports = function(Promise) {
1487function returner() {
1488 return this.value;
1489}
1490function thrower() {
1491 throw this.reason;
1492}
1493
1494Promise.prototype["return"] =
1495Promise.prototype.thenReturn = function (value) {
1496 if (value instanceof Promise) value.suppressUnhandledRejections();
1497 return this._then(
1498 returner, undefined, undefined, {value: value}, undefined);
1499};
1500
1501Promise.prototype["throw"] =
1502Promise.prototype.thenThrow = function (reason) {
1503 return this._then(
1504 thrower, undefined, undefined, {reason: reason}, undefined);
1505};
1506
1507Promise.prototype.catchThrow = function (reason) {
1508 if (arguments.length <= 1) {
1509 return this._then(
1510 undefined, thrower, undefined, {reason: reason}, undefined);
1511 } else {
1512 var _reason = arguments[1];
1513 var handler = function() {throw _reason;};
1514 return this.caught(reason, handler);
1515 }
1516};
1517
1518Promise.prototype.catchReturn = function (value) {
1519 if (arguments.length <= 1) {
1520 if (value instanceof Promise) value.suppressUnhandledRejections();
1521 return this._then(
1522 undefined, returner, undefined, {value: value}, undefined);
1523 } else {
1524 var _value = arguments[1];
1525 if (_value instanceof Promise) _value.suppressUnhandledRejections();
1526 var handler = function() {return _value;};
1527 return this.caught(value, handler);
1528 }
1529};
1530};
1531
1532},{}],11:[function(_dereq_,module,exports){
1533"use strict";
1534module.exports = function(Promise, INTERNAL) {
1535var PromiseReduce = Promise.reduce;
1536var PromiseAll = Promise.all;
1537
1538function promiseAllThis() {
1539 return PromiseAll(this);
1540}
1541
1542function PromiseMapSeries(promises, fn) {
1543 return PromiseReduce(promises, fn, INTERNAL, INTERNAL);
1544}
1545
1546Promise.prototype.each = function (fn) {
1547 return this.mapSeries(fn)
1548 ._then(promiseAllThis, undefined, undefined, this, undefined);
1549};
1550
1551Promise.prototype.mapSeries = function (fn) {
1552 return PromiseReduce(this, fn, INTERNAL, INTERNAL);
1553};
1554
1555Promise.each = function (promises, fn) {
1556 return PromiseMapSeries(promises, fn)
1557 ._then(promiseAllThis, undefined, undefined, promises, undefined);
1558};
1559
1560Promise.mapSeries = PromiseMapSeries;
1561};
1562
1563},{}],12:[function(_dereq_,module,exports){
1564"use strict";
1565var es5 = _dereq_("./es5");
1566var Objectfreeze = es5.freeze;
1567var util = _dereq_("./util");
1568var inherits = util.inherits;
1569var notEnumerableProp = util.notEnumerableProp;
1570
1571function subError(nameProperty, defaultMessage) {
1572 function SubError(message) {
1573 if (!(this instanceof SubError)) return new SubError(message);
1574 notEnumerableProp(this, "message",
1575 typeof message === "string" ? message : defaultMessage);
1576 notEnumerableProp(this, "name", nameProperty);
1577 if (Error.captureStackTrace) {
1578 Error.captureStackTrace(this, this.constructor);
1579 } else {
1580 Error.call(this);
1581 }
1582 }
1583 inherits(SubError, Error);
1584 return SubError;
1585}
1586
1587var _TypeError, _RangeError;
1588var Warning = subError("Warning", "warning");
1589var CancellationError = subError("CancellationError", "cancellation error");
1590var TimeoutError = subError("TimeoutError", "timeout error");
1591var AggregateError = subError("AggregateError", "aggregate error");
1592try {
1593 _TypeError = TypeError;
1594 _RangeError = RangeError;
1595} catch(e) {
1596 _TypeError = subError("TypeError", "type error");
1597 _RangeError = subError("RangeError", "range error");
1598}
1599
1600var methods = ("join pop push shift unshift slice filter forEach some " +
1601 "every map indexOf lastIndexOf reduce reduceRight sort reverse").split(" ");
1602
1603for (var i = 0; i < methods.length; ++i) {
1604 if (typeof Array.prototype[methods[i]] === "function") {
1605 AggregateError.prototype[methods[i]] = Array.prototype[methods[i]];
1606 }
1607}
1608
1609es5.defineProperty(AggregateError.prototype, "length", {
1610 value: 0,
1611 configurable: false,
1612 writable: true,
1613 enumerable: true
1614});
1615AggregateError.prototype["isOperational"] = true;
1616var level = 0;
1617AggregateError.prototype.toString = function() {
1618 var indent = Array(level * 4 + 1).join(" ");
1619 var ret = "\n" + indent + "AggregateError of:" + "\n";
1620 level++;
1621 indent = Array(level * 4 + 1).join(" ");
1622 for (var i = 0; i < this.length; ++i) {
1623 var str = this[i] === this ? "[Circular AggregateError]" : this[i] + "";
1624 var lines = str.split("\n");
1625 for (var j = 0; j < lines.length; ++j) {
1626 lines[j] = indent + lines[j];
1627 }
1628 str = lines.join("\n");
1629 ret += str + "\n";
1630 }
1631 level--;
1632 return ret;
1633};
1634
1635function OperationalError(message) {
1636 if (!(this instanceof OperationalError))
1637 return new OperationalError(message);
1638 notEnumerableProp(this, "name", "OperationalError");
1639 notEnumerableProp(this, "message", message);
1640 this.cause = message;
1641 this["isOperational"] = true;
1642
1643 if (message instanceof Error) {
1644 notEnumerableProp(this, "message", message.message);
1645 notEnumerableProp(this, "stack", message.stack);
1646 } else if (Error.captureStackTrace) {
1647 Error.captureStackTrace(this, this.constructor);
1648 }
1649
1650}
1651inherits(OperationalError, Error);
1652
1653var errorTypes = Error["__BluebirdErrorTypes__"];
1654if (!errorTypes) {
1655 errorTypes = Objectfreeze({
1656 CancellationError: CancellationError,
1657 TimeoutError: TimeoutError,
1658 OperationalError: OperationalError,
1659 RejectionError: OperationalError,
1660 AggregateError: AggregateError
1661 });
1662 notEnumerableProp(Error, "__BluebirdErrorTypes__", errorTypes);
1663}
1664
1665module.exports = {
1666 Error: Error,
1667 TypeError: _TypeError,
1668 RangeError: _RangeError,
1669 CancellationError: errorTypes.CancellationError,
1670 OperationalError: errorTypes.OperationalError,
1671 TimeoutError: errorTypes.TimeoutError,
1672 AggregateError: errorTypes.AggregateError,
1673 Warning: Warning
1674};
1675
1676},{"./es5":13,"./util":36}],13:[function(_dereq_,module,exports){
1677var isES5 = (function(){
1678 "use strict";
1679 return this === undefined;
1680})();
1681
1682if (isES5) {
1683 module.exports = {
1684 freeze: Object.freeze,
1685 defineProperty: Object.defineProperty,
1686 getDescriptor: Object.getOwnPropertyDescriptor,
1687 keys: Object.keys,
1688 names: Object.getOwnPropertyNames,
1689 getPrototypeOf: Object.getPrototypeOf,
1690 isArray: Array.isArray,
1691 isES5: isES5,
1692 propertyIsWritable: function(obj, prop) {
1693 var descriptor = Object.getOwnPropertyDescriptor(obj, prop);
1694 return !!(!descriptor || descriptor.writable || descriptor.set);
1695 }
1696 };
1697} else {
1698 var has = {}.hasOwnProperty;
1699 var str = {}.toString;
1700 var proto = {}.constructor.prototype;
1701
1702 var ObjectKeys = function (o) {
1703 var ret = [];
1704 for (var key in o) {
1705 if (has.call(o, key)) {
1706 ret.push(key);
1707 }
1708 }
1709 return ret;
1710 };
1711
1712 var ObjectGetDescriptor = function(o, key) {
1713 return {value: o[key]};
1714 };
1715
1716 var ObjectDefineProperty = function (o, key, desc) {
1717 o[key] = desc.value;
1718 return o;
1719 };
1720
1721 var ObjectFreeze = function (obj) {
1722 return obj;
1723 };
1724
1725 var ObjectGetPrototypeOf = function (obj) {
1726 try {
1727 return Object(obj).constructor.prototype;
1728 }
1729 catch (e) {
1730 return proto;
1731 }
1732 };
1733
1734 var ArrayIsArray = function (obj) {
1735 try {
1736 return str.call(obj) === "[object Array]";
1737 }
1738 catch(e) {
1739 return false;
1740 }
1741 };
1742
1743 module.exports = {
1744 isArray: ArrayIsArray,
1745 keys: ObjectKeys,
1746 names: ObjectKeys,
1747 defineProperty: ObjectDefineProperty,
1748 getDescriptor: ObjectGetDescriptor,
1749 freeze: ObjectFreeze,
1750 getPrototypeOf: ObjectGetPrototypeOf,
1751 isES5: isES5,
1752 propertyIsWritable: function() {
1753 return true;
1754 }
1755 };
1756}
1757
1758},{}],14:[function(_dereq_,module,exports){
1759"use strict";
1760module.exports = function(Promise, INTERNAL) {
1761var PromiseMap = Promise.map;
1762
1763Promise.prototype.filter = function (fn, options) {
1764 return PromiseMap(this, fn, options, INTERNAL);
1765};
1766
1767Promise.filter = function (promises, fn, options) {
1768 return PromiseMap(promises, fn, options, INTERNAL);
1769};
1770};
1771
1772},{}],15:[function(_dereq_,module,exports){
1773"use strict";
1774module.exports = function(Promise, tryConvertToPromise) {
1775var util = _dereq_("./util");
1776var CancellationError = Promise.CancellationError;
1777var errorObj = util.errorObj;
1778
1779function FinallyHandlerCancelReaction(finallyHandler) {
1780 this.finallyHandler = finallyHandler;
1781}
1782
1783FinallyHandlerCancelReaction.prototype._resultCancelled = function() {
1784 checkCancel(this.finallyHandler);
1785};
1786
1787function checkCancel(ctx, reason) {
1788 if (ctx.cancelPromise != null) {
1789 if (arguments.length > 1) {
1790 ctx.cancelPromise._reject(reason);
1791 } else {
1792 ctx.cancelPromise._cancel();
1793 }
1794 ctx.cancelPromise = null;
1795 return true;
1796 }
1797 return false;
1798}
1799
1800function succeed() {
1801 return finallyHandler.call(this, this.promise._target()._settledValue());
1802}
1803function fail(reason) {
1804 if (checkCancel(this, reason)) return;
1805 errorObj.e = reason;
1806 return errorObj;
1807}
1808function finallyHandler(reasonOrValue) {
1809 var promise = this.promise;
1810 var handler = this.handler;
1811
1812 if (!this.called) {
1813 this.called = true;
1814 var ret = this.type === 0
1815 ? handler.call(promise._boundValue())
1816 : handler.call(promise._boundValue(), reasonOrValue);
1817 if (ret !== undefined) {
1818 promise._setReturnedNonUndefined();
1819 var maybePromise = tryConvertToPromise(ret, promise);
1820 if (maybePromise instanceof Promise) {
1821 if (this.cancelPromise != null) {
1822 if (maybePromise.isCancelled()) {
1823 var reason =
1824 new CancellationError("late cancellation observer");
1825 promise._attachExtraTrace(reason);
1826 errorObj.e = reason;
1827 return errorObj;
1828 } else if (maybePromise.isPending()) {
1829 maybePromise._attachCancellationCallback(
1830 new FinallyHandlerCancelReaction(this));
1831 }
1832 }
1833 return maybePromise._then(
1834 succeed, fail, undefined, this, undefined);
1835 }
1836 }
1837 }
1838
1839 if (promise.isRejected()) {
1840 checkCancel(this);
1841 errorObj.e = reasonOrValue;
1842 return errorObj;
1843 } else {
1844 checkCancel(this);
1845 return reasonOrValue;
1846 }
1847}
1848
1849Promise.prototype._passThrough = function(handler, type, success, fail) {
1850 if (typeof handler !== "function") return this.then();
1851 return this._then(success, fail, undefined, {
1852 promise: this,
1853 handler: handler,
1854 called: false,
1855 cancelPromise: null,
1856 type: type
1857 }, undefined);
1858};
1859
1860Promise.prototype.lastly =
1861Promise.prototype["finally"] = function (handler) {
1862 return this._passThrough(handler,
1863 0,
1864 finallyHandler,
1865 finallyHandler);
1866};
1867
1868Promise.prototype.tap = function (handler) {
1869 return this._passThrough(handler, 1, finallyHandler);
1870};
1871
1872return finallyHandler;
1873};
1874
1875},{"./util":36}],16:[function(_dereq_,module,exports){
1876"use strict";
1877module.exports = function(Promise,
1878 apiRejection,
1879 INTERNAL,
1880 tryConvertToPromise,
1881 Proxyable,
1882 debug) {
1883var errors = _dereq_("./errors");
1884var TypeError = errors.TypeError;
1885var util = _dereq_("./util");
1886var errorObj = util.errorObj;
1887var tryCatch = util.tryCatch;
1888var yieldHandlers = [];
1889
1890function promiseFromYieldHandler(value, yieldHandlers, traceParent) {
1891 for (var i = 0; i < yieldHandlers.length; ++i) {
1892 traceParent._pushContext();
1893 var result = tryCatch(yieldHandlers[i])(value);
1894 traceParent._popContext();
1895 if (result === errorObj) {
1896 traceParent._pushContext();
1897 var ret = Promise.reject(errorObj.e);
1898 traceParent._popContext();
1899 return ret;
1900 }
1901 var maybePromise = tryConvertToPromise(result, traceParent);
1902 if (maybePromise instanceof Promise) return maybePromise;
1903 }
1904 return null;
1905}
1906
1907function PromiseSpawn(generatorFunction, receiver, yieldHandler, stack) {
1908 var promise = this._promise = new Promise(INTERNAL);
1909 promise._captureStackTrace();
1910 promise._setOnCancel(this);
1911 this._stack = stack;
1912 this._generatorFunction = generatorFunction;
1913 this._receiver = receiver;
1914 this._generator = undefined;
1915 this._yieldHandlers = typeof yieldHandler === "function"
1916 ? [yieldHandler].concat(yieldHandlers)
1917 : yieldHandlers;
1918 this._yieldedPromise = null;
1919}
1920util.inherits(PromiseSpawn, Proxyable);
1921
1922PromiseSpawn.prototype._isResolved = function() {
1923 return this._promise === null;
1924};
1925
1926PromiseSpawn.prototype._cleanup = function() {
1927 this._promise = this._generator = null;
1928};
1929
1930PromiseSpawn.prototype._promiseCancelled = function() {
1931 if (this._isResolved()) return;
1932 var implementsReturn = typeof this._generator["return"] !== "undefined";
1933
1934 var result;
1935 if (!implementsReturn) {
1936 var reason = new Promise.CancellationError(
1937 "generator .return() sentinel");
1938 Promise.coroutine.returnSentinel = reason;
1939 this._promise._attachExtraTrace(reason);
1940 this._promise._pushContext();
1941 result = tryCatch(this._generator["throw"]).call(this._generator,
1942 reason);
1943 this._promise._popContext();
1944 if (result === errorObj && result.e === reason) {
1945 result = null;
1946 }
1947 } else {
1948 this._promise._pushContext();
1949 result = tryCatch(this._generator["return"]).call(this._generator,
1950 undefined);
1951 this._promise._popContext();
1952 }
1953 var promise = this._promise;
1954 this._cleanup();
1955 if (result === errorObj) {
1956 promise._rejectCallback(result.e, false);
1957 } else {
1958 promise.cancel();
1959 }
1960};
1961
1962PromiseSpawn.prototype._promiseFulfilled = function(value) {
1963 this._yieldedPromise = null;
1964 this._promise._pushContext();
1965 var result = tryCatch(this._generator.next).call(this._generator, value);
1966 this._promise._popContext();
1967 this._continue(result);
1968};
1969
1970PromiseSpawn.prototype._promiseRejected = function(reason) {
1971 this._yieldedPromise = null;
1972 this._promise._attachExtraTrace(reason);
1973 this._promise._pushContext();
1974 var result = tryCatch(this._generator["throw"])
1975 .call(this._generator, reason);
1976 this._promise._popContext();
1977 this._continue(result);
1978};
1979
1980PromiseSpawn.prototype._resultCancelled = function() {
1981 if (this._yieldedPromise instanceof Promise) {
1982 var promise = this._yieldedPromise;
1983 this._yieldedPromise = null;
1984 promise.cancel();
1985 }
1986};
1987
1988PromiseSpawn.prototype.promise = function () {
1989 return this._promise;
1990};
1991
1992PromiseSpawn.prototype._run = function () {
1993 this._generator = this._generatorFunction.call(this._receiver);
1994 this._receiver =
1995 this._generatorFunction = undefined;
1996 this._promiseFulfilled(undefined);
1997};
1998
1999PromiseSpawn.prototype._continue = function (result) {
2000 var promise = this._promise;
2001 if (result === errorObj) {
2002 this._cleanup();
2003 return promise._rejectCallback(result.e, false);
2004 }
2005
2006 var value = result.value;
2007 if (result.done === true) {
2008 this._cleanup();
2009 return promise._resolveCallback(value);
2010 } else {
2011 var maybePromise = tryConvertToPromise(value, this._promise);
2012 if (!(maybePromise instanceof Promise)) {
2013 maybePromise =
2014 promiseFromYieldHandler(maybePromise,
2015 this._yieldHandlers,
2016 this._promise);
2017 if (maybePromise === null) {
2018 this._promiseRejected(
2019 new TypeError(
2020 "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) +
2021 "From coroutine:\u000a" +
2022 this._stack.split("\n").slice(1, -7).join("\n")
2023 )
2024 );
2025 return;
2026 }
2027 }
2028 maybePromise = maybePromise._target();
2029 var bitField = maybePromise._bitField;
2030 ;
2031 if (((bitField & 50397184) === 0)) {
2032 this._yieldedPromise = maybePromise;
2033 maybePromise._proxy(this, null);
2034 } else if (((bitField & 33554432) !== 0)) {
2035 this._promiseFulfilled(maybePromise._value());
2036 } else if (((bitField & 16777216) !== 0)) {
2037 this._promiseRejected(maybePromise._reason());
2038 } else {
2039 this._promiseCancelled();
2040 }
2041 }
2042};
2043
2044Promise.coroutine = function (generatorFunction, options) {
2045 if (typeof generatorFunction !== "function") {
2046 throw new TypeError("generatorFunction must be a function\u000a\u000a See http://goo.gl/MqrFmX\u000a");
2047 }
2048 var yieldHandler = Object(options).yieldHandler;
2049 var PromiseSpawn$ = PromiseSpawn;
2050 var stack = new Error().stack;
2051 return function () {
2052 var generator = generatorFunction.apply(this, arguments);
2053 var spawn = new PromiseSpawn$(undefined, undefined, yieldHandler,
2054 stack);
2055 var ret = spawn.promise();
2056 spawn._generator = generator;
2057 spawn._promiseFulfilled(undefined);
2058 return ret;
2059 };
2060};
2061
2062Promise.coroutine.addYieldHandler = function(fn) {
2063 if (typeof fn !== "function") {
2064 throw new TypeError("expecting a function but got " + util.classString(fn));
2065 }
2066 yieldHandlers.push(fn);
2067};
2068
2069Promise.spawn = function (generatorFunction) {
2070 debug.deprecated("Promise.spawn()", "Promise.coroutine()");
2071 if (typeof generatorFunction !== "function") {
2072 return apiRejection("generatorFunction must be a function\u000a\u000a See http://goo.gl/MqrFmX\u000a");
2073 }
2074 var spawn = new PromiseSpawn(generatorFunction, this);
2075 var ret = spawn.promise();
2076 spawn._run(Promise.spawn);
2077 return ret;
2078};
2079};
2080
2081},{"./errors":12,"./util":36}],17:[function(_dereq_,module,exports){
2082"use strict";
2083module.exports =
2084function(Promise, PromiseArray, tryConvertToPromise, INTERNAL) {
2085var util = _dereq_("./util");
2086var canEvaluate = util.canEvaluate;
2087var tryCatch = util.tryCatch;
2088var errorObj = util.errorObj;
2089var reject;
2090
2091if (!true) {
2092if (canEvaluate) {
2093 var thenCallback = function(i) {
2094 return new Function("value", "holder", " \n\
2095 'use strict'; \n\
2096 holder.pIndex = value; \n\
2097 holder.checkFulfillment(this); \n\
2098 ".replace(/Index/g, i));
2099 };
2100
2101 var promiseSetter = function(i) {
2102 return new Function("promise", "holder", " \n\
2103 'use strict'; \n\
2104 holder.pIndex = promise; \n\
2105 ".replace(/Index/g, i));
2106 };
2107
2108 var generateHolderClass = function(total) {
2109 var props = new Array(total);
2110 for (var i = 0; i < props.length; ++i) {
2111 props[i] = "this.p" + (i+1);
2112 }
2113 var assignment = props.join(" = ") + " = null;";
2114 var cancellationCode= "var promise;\n" + props.map(function(prop) {
2115 return " \n\
2116 promise = " + prop + "; \n\
2117 if (promise instanceof Promise) { \n\
2118 promise.cancel(); \n\
2119 } \n\
2120 ";
2121 }).join("\n");
2122 var passedArguments = props.join(", ");
2123 var name = "Holder$" + total;
2124
2125
2126 var code = "return function(tryCatch, errorObj, Promise) { \n\
2127 'use strict'; \n\
2128 function [TheName](fn) { \n\
2129 [TheProperties] \n\
2130 this.fn = fn; \n\
2131 this.now = 0; \n\
2132 } \n\
2133 [TheName].prototype.checkFulfillment = function(promise) { \n\
2134 var now = ++this.now; \n\
2135 if (now === [TheTotal]) { \n\
2136 promise._pushContext(); \n\
2137 var callback = this.fn; \n\
2138 var ret = tryCatch(callback)([ThePassedArguments]); \n\
2139 promise._popContext(); \n\
2140 if (ret === errorObj) { \n\
2141 promise._rejectCallback(ret.e, false); \n\
2142 } else { \n\
2143 promise._resolveCallback(ret); \n\
2144 } \n\
2145 } \n\
2146 }; \n\
2147 \n\
2148 [TheName].prototype._resultCancelled = function() { \n\
2149 [CancellationCode] \n\
2150 }; \n\
2151 \n\
2152 return [TheName]; \n\
2153 }(tryCatch, errorObj, Promise); \n\
2154 ";
2155
2156 code = code.replace(/\[TheName\]/g, name)
2157 .replace(/\[TheTotal\]/g, total)
2158 .replace(/\[ThePassedArguments\]/g, passedArguments)
2159 .replace(/\[TheProperties\]/g, assignment)
2160 .replace(/\[CancellationCode\]/g, cancellationCode);
2161
2162 return new Function("tryCatch", "errorObj", "Promise", code)
2163 (tryCatch, errorObj, Promise);
2164 };
2165
2166 var holderClasses = [];
2167 var thenCallbacks = [];
2168 var promiseSetters = [];
2169
2170 for (var i = 0; i < 8; ++i) {
2171 holderClasses.push(generateHolderClass(i + 1));
2172 thenCallbacks.push(thenCallback(i + 1));
2173 promiseSetters.push(promiseSetter(i + 1));
2174 }
2175
2176 reject = function (reason) {
2177 this._reject(reason);
2178 };
2179}}
2180
2181Promise.join = function () {
2182 var last = arguments.length - 1;
2183 var fn;
2184 if (last > 0 && typeof arguments[last] === "function") {
2185 fn = arguments[last];
2186 if (!true) {
2187 if (last <= 8 && canEvaluate) {
2188 var ret = new Promise(INTERNAL);
2189 ret._captureStackTrace();
2190 var HolderClass = holderClasses[last - 1];
2191 var holder = new HolderClass(fn);
2192 var callbacks = thenCallbacks;
2193
2194 for (var i = 0; i < last; ++i) {
2195 var maybePromise = tryConvertToPromise(arguments[i], ret);
2196 if (maybePromise instanceof Promise) {
2197 maybePromise = maybePromise._target();
2198 var bitField = maybePromise._bitField;
2199 ;
2200 if (((bitField & 50397184) === 0)) {
2201 maybePromise._then(callbacks[i], reject,
2202 undefined, ret, holder);
2203 promiseSetters[i](maybePromise, holder);
2204 } else if (((bitField & 33554432) !== 0)) {
2205 callbacks[i].call(ret,
2206 maybePromise._value(), holder);
2207 } else if (((bitField & 16777216) !== 0)) {
2208 ret._reject(maybePromise._reason());
2209 } else {
2210 ret._cancel();
2211 }
2212 } else {
2213 callbacks[i].call(ret, maybePromise, holder);
2214 }
2215 }
2216 if (!ret._isFateSealed()) {
2217 ret._setAsyncGuaranteed();
2218 ret._setOnCancel(holder);
2219 }
2220 return ret;
2221 }
2222 }
2223 }
2224 var args = [].slice.call(arguments);;
2225 if (fn) args.pop();
2226 var ret = new PromiseArray(args).promise();
2227 return fn !== undefined ? ret.spread(fn) : ret;
2228};
2229
2230};
2231
2232},{"./util":36}],18:[function(_dereq_,module,exports){
2233"use strict";
2234module.exports = function(Promise,
2235 PromiseArray,
2236 apiRejection,
2237 tryConvertToPromise,
2238 INTERNAL,
2239 debug) {
2240var getDomain = Promise._getDomain;
2241var util = _dereq_("./util");
2242var tryCatch = util.tryCatch;
2243var errorObj = util.errorObj;
2244var EMPTY_ARRAY = [];
2245
2246function MappingPromiseArray(promises, fn, limit, _filter) {
2247 this.constructor$(promises);
2248 this._promise._captureStackTrace();
2249 var domain = getDomain();
2250 this._callback = domain === null ? fn : domain.bind(fn);
2251 this._preservedValues = _filter === INTERNAL
2252 ? new Array(this.length())
2253 : null;
2254 this._limit = limit;
2255 this._inFlight = 0;
2256 this._queue = limit >= 1 ? [] : EMPTY_ARRAY;
2257 this._init$(undefined, -2);
2258}
2259util.inherits(MappingPromiseArray, PromiseArray);
2260
2261MappingPromiseArray.prototype._init = function () {};
2262
2263MappingPromiseArray.prototype._promiseFulfilled = function (value, index) {
2264 var values = this._values;
2265 var length = this.length();
2266 var preservedValues = this._preservedValues;
2267 var limit = this._limit;
2268
2269 if (index < 0) {
2270 index = (index * -1) - 1;
2271 values[index] = value;
2272 if (limit >= 1) {
2273 this._inFlight--;
2274 this._drainQueue();
2275 if (this._isResolved()) return true;
2276 }
2277 } else {
2278 if (limit >= 1 && this._inFlight >= limit) {
2279 values[index] = value;
2280 this._queue.push(index);
2281 return false;
2282 }
2283 if (preservedValues !== null) preservedValues[index] = value;
2284
2285 var promise = this._promise;
2286 var callback = this._callback;
2287 var receiver = promise._boundValue();
2288 promise._pushContext();
2289 var ret = tryCatch(callback).call(receiver, value, index, length);
2290 var promiseCreated = promise._popContext();
2291 debug.checkForgottenReturns(
2292 ret,
2293 promiseCreated,
2294 preservedValues !== null ? "Promise.filter" : "Promise.map",
2295 promise
2296 );
2297 if (ret === errorObj) {
2298 this._reject(ret.e);
2299 return true;
2300 }
2301
2302 var maybePromise = tryConvertToPromise(ret, this._promise);
2303 if (maybePromise instanceof Promise) {
2304 maybePromise = maybePromise._target();
2305 var bitField = maybePromise._bitField;
2306 ;
2307 if (((bitField & 50397184) === 0)) {
2308 if (limit >= 1) this._inFlight++;
2309 values[index] = maybePromise;
2310 maybePromise._proxy(this, (index + 1) * -1);
2311 return false;
2312 } else if (((bitField & 33554432) !== 0)) {
2313 ret = maybePromise._value();
2314 } else if (((bitField & 16777216) !== 0)) {
2315 this._reject(maybePromise._reason());
2316 return true;
2317 } else {
2318 this._cancel();
2319 return true;
2320 }
2321 }
2322 values[index] = ret;
2323 }
2324 var totalResolved = ++this._totalResolved;
2325 if (totalResolved >= length) {
2326 if (preservedValues !== null) {
2327 this._filter(values, preservedValues);
2328 } else {
2329 this._resolve(values);
2330 }
2331 return true;
2332 }
2333 return false;
2334};
2335
2336MappingPromiseArray.prototype._drainQueue = function () {
2337 var queue = this._queue;
2338 var limit = this._limit;
2339 var values = this._values;
2340 while (queue.length > 0 && this._inFlight < limit) {
2341 if (this._isResolved()) return;
2342 var index = queue.pop();
2343 this._promiseFulfilled(values[index], index);
2344 }
2345};
2346
2347MappingPromiseArray.prototype._filter = function (booleans, values) {
2348 var len = values.length;
2349 var ret = new Array(len);
2350 var j = 0;
2351 for (var i = 0; i < len; ++i) {
2352 if (booleans[i]) ret[j++] = values[i];
2353 }
2354 ret.length = j;
2355 this._resolve(ret);
2356};
2357
2358MappingPromiseArray.prototype.preservedValues = function () {
2359 return this._preservedValues;
2360};
2361
2362function map(promises, fn, options, _filter) {
2363 if (typeof fn !== "function") {
2364 return apiRejection("expecting a function but got " + util.classString(fn));
2365 }
2366 var limit = typeof options === "object" && options !== null
2367 ? options.concurrency
2368 : 0;
2369 limit = typeof limit === "number" &&
2370 isFinite(limit) && limit >= 1 ? limit : 0;
2371 return new MappingPromiseArray(promises, fn, limit, _filter).promise();
2372}
2373
2374Promise.prototype.map = function (fn, options) {
2375 return map(this, fn, options, null);
2376};
2377
2378Promise.map = function (promises, fn, options, _filter) {
2379 return map(promises, fn, options, _filter);
2380};
2381
2382
2383};
2384
2385},{"./util":36}],19:[function(_dereq_,module,exports){
2386"use strict";
2387module.exports =
2388function(Promise, INTERNAL, tryConvertToPromise, apiRejection, debug) {
2389var util = _dereq_("./util");
2390var tryCatch = util.tryCatch;
2391
2392Promise.method = function (fn) {
2393 if (typeof fn !== "function") {
2394 throw new Promise.TypeError("expecting a function but got " + util.classString(fn));
2395 }
2396 return function () {
2397 var ret = new Promise(INTERNAL);
2398 ret._captureStackTrace();
2399 ret._pushContext();
2400 var value = tryCatch(fn).apply(this, arguments);
2401 var promiseCreated = ret._popContext();
2402 debug.checkForgottenReturns(
2403 value, promiseCreated, "Promise.method", ret);
2404 ret._resolveFromSyncValue(value);
2405 return ret;
2406 };
2407};
2408
2409Promise.attempt = Promise["try"] = function (fn) {
2410 if (typeof fn !== "function") {
2411 return apiRejection("expecting a function but got " + util.classString(fn));
2412 }
2413 var ret = new Promise(INTERNAL);
2414 ret._captureStackTrace();
2415 ret._pushContext();
2416 var value;
2417 if (arguments.length > 1) {
2418 debug.deprecated("calling Promise.try with more than 1 argument");
2419 var arg = arguments[1];
2420 var ctx = arguments[2];
2421 value = util.isArray(arg) ? tryCatch(fn).apply(ctx, arg)
2422 : tryCatch(fn).call(ctx, arg);
2423 } else {
2424 value = tryCatch(fn)();
2425 }
2426 var promiseCreated = ret._popContext();
2427 debug.checkForgottenReturns(
2428 value, promiseCreated, "Promise.try", ret);
2429 ret._resolveFromSyncValue(value);
2430 return ret;
2431};
2432
2433Promise.prototype._resolveFromSyncValue = function (value) {
2434 if (value === util.errorObj) {
2435 this._rejectCallback(value.e, false);
2436 } else {
2437 this._resolveCallback(value, true);
2438 }
2439};
2440};
2441
2442},{"./util":36}],20:[function(_dereq_,module,exports){
2443"use strict";
2444var util = _dereq_("./util");
2445var maybeWrapAsError = util.maybeWrapAsError;
2446var errors = _dereq_("./errors");
2447var OperationalError = errors.OperationalError;
2448var es5 = _dereq_("./es5");
2449
2450function isUntypedError(obj) {
2451 return obj instanceof Error &&
2452 es5.getPrototypeOf(obj) === Error.prototype;
2453}
2454
2455var rErrorKey = /^(?:name|message|stack|cause)$/;
2456function wrapAsOperationalError(obj) {
2457 var ret;
2458 if (isUntypedError(obj)) {
2459 ret = new OperationalError(obj);
2460 ret.name = obj.name;
2461 ret.message = obj.message;
2462 ret.stack = obj.stack;
2463 var keys = es5.keys(obj);
2464 for (var i = 0; i < keys.length; ++i) {
2465 var key = keys[i];
2466 if (!rErrorKey.test(key)) {
2467 ret[key] = obj[key];
2468 }
2469 }
2470 return ret;
2471 }
2472 util.markAsOriginatingFromRejection(obj);
2473 return obj;
2474}
2475
2476function nodebackForPromise(promise, multiArgs) {
2477 return function(err, value) {
2478 if (promise === null) return;
2479 if (err) {
2480 var wrapped = wrapAsOperationalError(maybeWrapAsError(err));
2481 promise._attachExtraTrace(wrapped);
2482 promise._reject(wrapped);
2483 } else if (!multiArgs) {
2484 promise._fulfill(value);
2485 } else {
2486 var args = [].slice.call(arguments, 1);;
2487 promise._fulfill(args);
2488 }
2489 promise = null;
2490 };
2491}
2492
2493module.exports = nodebackForPromise;
2494
2495},{"./errors":12,"./es5":13,"./util":36}],21:[function(_dereq_,module,exports){
2496"use strict";
2497module.exports = function(Promise) {
2498var util = _dereq_("./util");
2499var async = Promise._async;
2500var tryCatch = util.tryCatch;
2501var errorObj = util.errorObj;
2502
2503function spreadAdapter(val, nodeback) {
2504 var promise = this;
2505 if (!util.isArray(val)) return successAdapter.call(promise, val, nodeback);
2506 var ret =
2507 tryCatch(nodeback).apply(promise._boundValue(), [null].concat(val));
2508 if (ret === errorObj) {
2509 async.throwLater(ret.e);
2510 }
2511}
2512
2513function successAdapter(val, nodeback) {
2514 var promise = this;
2515 var receiver = promise._boundValue();
2516 var ret = val === undefined
2517 ? tryCatch(nodeback).call(receiver, null)
2518 : tryCatch(nodeback).call(receiver, null, val);
2519 if (ret === errorObj) {
2520 async.throwLater(ret.e);
2521 }
2522}
2523function errorAdapter(reason, nodeback) {
2524 var promise = this;
2525 if (!reason) {
2526 var newReason = new Error(reason + "");
2527 newReason.cause = reason;
2528 reason = newReason;
2529 }
2530 var ret = tryCatch(nodeback).call(promise._boundValue(), reason);
2531 if (ret === errorObj) {
2532 async.throwLater(ret.e);
2533 }
2534}
2535
2536Promise.prototype.asCallback = Promise.prototype.nodeify = function (nodeback,
2537 options) {
2538 if (typeof nodeback == "function") {
2539 var adapter = successAdapter;
2540 if (options !== undefined && Object(options).spread) {
2541 adapter = spreadAdapter;
2542 }
2543 this._then(
2544 adapter,
2545 errorAdapter,
2546 undefined,
2547 this,
2548 nodeback
2549 );
2550 }
2551 return this;
2552};
2553};
2554
2555},{"./util":36}],22:[function(_dereq_,module,exports){
2556"use strict";
2557module.exports = function() {
2558var makeSelfResolutionError = function () {
2559 return new TypeError("circular promise resolution chain\u000a\u000a See http://goo.gl/MqrFmX\u000a");
2560};
2561var reflectHandler = function() {
2562 return new Promise.PromiseInspection(this._target());
2563};
2564var apiRejection = function(msg) {
2565 return Promise.reject(new TypeError(msg));
2566};
2567function Proxyable() {}
2568var UNDEFINED_BINDING = {};
2569var util = _dereq_("./util");
2570
2571var getDomain;
2572if (util.isNode) {
2573 getDomain = function() {
2574 var ret = process.domain;
2575 if (ret === undefined) ret = null;
2576 return ret;
2577 };
2578} else {
2579 getDomain = function() {
2580 return null;
2581 };
2582}
2583util.notEnumerableProp(Promise, "_getDomain", getDomain);
2584
2585var es5 = _dereq_("./es5");
2586var Async = _dereq_("./async");
2587var async = new Async();
2588es5.defineProperty(Promise, "_async", {value: async});
2589var errors = _dereq_("./errors");
2590var TypeError = Promise.TypeError = errors.TypeError;
2591Promise.RangeError = errors.RangeError;
2592var CancellationError = Promise.CancellationError = errors.CancellationError;
2593Promise.TimeoutError = errors.TimeoutError;
2594Promise.OperationalError = errors.OperationalError;
2595Promise.RejectionError = errors.OperationalError;
2596Promise.AggregateError = errors.AggregateError;
2597var INTERNAL = function(){};
2598var APPLY = {};
2599var NEXT_FILTER = {};
2600var tryConvertToPromise = _dereq_("./thenables")(Promise, INTERNAL);
2601var PromiseArray =
2602 _dereq_("./promise_array")(Promise, INTERNAL,
2603 tryConvertToPromise, apiRejection, Proxyable);
2604var Context = _dereq_("./context")(Promise);
2605 /*jshint unused:false*/
2606var createContext = Context.create;
2607var debug = _dereq_("./debuggability")(Promise, Context);
2608var CapturedTrace = debug.CapturedTrace;
2609var finallyHandler = _dereq_("./finally")(Promise, tryConvertToPromise);
2610var catchFilter = _dereq_("./catch_filter")(NEXT_FILTER);
2611var nodebackForPromise = _dereq_("./nodeback");
2612var errorObj = util.errorObj;
2613var tryCatch = util.tryCatch;
2614function check(self, executor) {
2615 if (typeof executor !== "function") {
2616 throw new TypeError("expecting a function but got " + util.classString(executor));
2617 }
2618 if (self.constructor !== Promise) {
2619 throw new TypeError("the promise constructor cannot be invoked directly\u000a\u000a See http://goo.gl/MqrFmX\u000a");
2620 }
2621}
2622
2623function Promise(executor) {
2624 this._bitField = 0;
2625 this._fulfillmentHandler0 = undefined;
2626 this._rejectionHandler0 = undefined;
2627 this._promise0 = undefined;
2628 this._receiver0 = undefined;
2629 if (executor !== INTERNAL) {
2630 check(this, executor);
2631 this._resolveFromExecutor(executor);
2632 }
2633 this._promiseCreated();
2634}
2635
2636Promise.prototype.toString = function () {
2637 return "[object Promise]";
2638};
2639
2640Promise.prototype.caught = Promise.prototype["catch"] = function (fn) {
2641 var len = arguments.length;
2642 if (len > 1) {
2643 var catchInstances = new Array(len - 1),
2644 j = 0, i;
2645 for (i = 0; i < len - 1; ++i) {
2646 var item = arguments[i];
2647 if (util.isObject(item)) {
2648 catchInstances[j++] = item;
2649 } else {
2650 return apiRejection("expecting an object but got " + util.classString(item));
2651 }
2652 }
2653 catchInstances.length = j;
2654 fn = arguments[i];
2655 return this.then(undefined, catchFilter(catchInstances, fn, this));
2656 }
2657 return this.then(undefined, fn);
2658};
2659
2660Promise.prototype.reflect = function () {
2661 return this._then(reflectHandler,
2662 reflectHandler, undefined, this, undefined);
2663};
2664
2665Promise.prototype.then = function (didFulfill, didReject) {
2666 if (debug.warnings() && arguments.length > 0 &&
2667 typeof didFulfill !== "function" &&
2668 typeof didReject !== "function") {
2669 var msg = ".then() only accepts functions but was passed: " +
2670 util.classString(didFulfill);
2671 if (arguments.length > 1) {
2672 msg += ", " + util.classString(didReject);
2673 }
2674 this._warn(msg);
2675 }
2676 return this._then(didFulfill, didReject, undefined, undefined, undefined);
2677};
2678
2679Promise.prototype.done = function (didFulfill, didReject) {
2680 var promise =
2681 this._then(didFulfill, didReject, undefined, undefined, undefined);
2682 promise._setIsFinal();
2683};
2684
2685Promise.prototype.spread = function (fn) {
2686 if (typeof fn !== "function") {
2687 return apiRejection("expecting a function but got " + util.classString(fn));
2688 }
2689 return this.all()._then(fn, undefined, undefined, APPLY, undefined);
2690};
2691
2692Promise.prototype.toJSON = function () {
2693 var ret = {
2694 isFulfilled: false,
2695 isRejected: false,
2696 fulfillmentValue: undefined,
2697 rejectionReason: undefined
2698 };
2699 if (this.isFulfilled()) {
2700 ret.fulfillmentValue = this.value();
2701 ret.isFulfilled = true;
2702 } else if (this.isRejected()) {
2703 ret.rejectionReason = this.reason();
2704 ret.isRejected = true;
2705 }
2706 return ret;
2707};
2708
2709Promise.prototype.all = function () {
2710 if (arguments.length > 0) {
2711 this._warn(".all() was passed arguments but it does not take any");
2712 }
2713 return new PromiseArray(this).promise();
2714};
2715
2716Promise.prototype.error = function (fn) {
2717 return this.caught(util.originatesFromRejection, fn);
2718};
2719
2720Promise.is = function (val) {
2721 return val instanceof Promise;
2722};
2723
2724Promise.fromNode = Promise.fromCallback = function(fn) {
2725 var ret = new Promise(INTERNAL);
2726 var multiArgs = arguments.length > 1 ? !!Object(arguments[1]).multiArgs
2727 : false;
2728 var result = tryCatch(fn)(nodebackForPromise(ret, multiArgs));
2729 if (result === errorObj) {
2730 ret._rejectCallback(result.e, true);
2731 }
2732 if (!ret._isFateSealed()) ret._setAsyncGuaranteed();
2733 return ret;
2734};
2735
2736Promise.all = function (promises) {
2737 return new PromiseArray(promises).promise();
2738};
2739
2740Promise.cast = function (obj) {
2741 var ret = tryConvertToPromise(obj);
2742 if (!(ret instanceof Promise)) {
2743 ret = new Promise(INTERNAL);
2744 ret._captureStackTrace();
2745 ret._setFulfilled();
2746 ret._rejectionHandler0 = obj;
2747 }
2748 return ret;
2749};
2750
2751Promise.resolve = Promise.fulfilled = Promise.cast;
2752
2753Promise.reject = Promise.rejected = function (reason) {
2754 var ret = new Promise(INTERNAL);
2755 ret._captureStackTrace();
2756 ret._rejectCallback(reason, true);
2757 return ret;
2758};
2759
2760Promise.setScheduler = function(fn) {
2761 if (typeof fn !== "function") {
2762 throw new TypeError("expecting a function but got " + util.classString(fn));
2763 }
2764 var prev = async._schedule;
2765 async._schedule = fn;
2766 return prev;
2767};
2768
2769Promise.prototype._then = function (
2770 didFulfill,
2771 didReject,
2772 _, receiver,
2773 internalData
2774) {
2775 var haveInternalData = internalData !== undefined;
2776 var promise = haveInternalData ? internalData : new Promise(INTERNAL);
2777 var target = this._target();
2778 var bitField = target._bitField;
2779
2780 if (!haveInternalData) {
2781 promise._propagateFrom(this, 3);
2782 promise._captureStackTrace();
2783 if (receiver === undefined &&
2784 ((this._bitField & 2097152) !== 0)) {
2785 if (!((bitField & 50397184) === 0)) {
2786 receiver = this._boundValue();
2787 } else {
2788 receiver = target === this ? undefined : this._boundTo;
2789 }
2790 }
2791 }
2792
2793 var domain = getDomain();
2794 if (!((bitField & 50397184) === 0)) {
2795 var handler, value, settler = target._settlePromiseCtx;
2796 if (((bitField & 33554432) !== 0)) {
2797 value = target._rejectionHandler0;
2798 handler = didFulfill;
2799 } else if (((bitField & 16777216) !== 0)) {
2800 value = target._fulfillmentHandler0;
2801 handler = didReject;
2802 target._unsetRejectionIsUnhandled();
2803 } else {
2804 settler = target._settlePromiseLateCancellationObserver;
2805 value = new CancellationError("late cancellation observer");
2806 target._attachExtraTrace(value);
2807 handler = didReject;
2808 }
2809
2810 async.invoke(settler, target, {
2811 handler: domain === null ? handler
2812 : (typeof handler === "function" && domain.bind(handler)),
2813 promise: promise,
2814 receiver: receiver,
2815 value: value
2816 });
2817 } else {
2818 target._addCallbacks(didFulfill, didReject, promise, receiver, domain);
2819 }
2820
2821 return promise;
2822};
2823
2824Promise.prototype._length = function () {
2825 return this._bitField & 65535;
2826};
2827
2828Promise.prototype._isFateSealed = function () {
2829 return (this._bitField & 117506048) !== 0;
2830};
2831
2832Promise.prototype._isFollowing = function () {
2833 return (this._bitField & 67108864) === 67108864;
2834};
2835
2836Promise.prototype._setLength = function (len) {
2837 this._bitField = (this._bitField & -65536) |
2838 (len & 65535);
2839};
2840
2841Promise.prototype._setFulfilled = function () {
2842 this._bitField = this._bitField | 33554432;
2843};
2844
2845Promise.prototype._setRejected = function () {
2846 this._bitField = this._bitField | 16777216;
2847};
2848
2849Promise.prototype._setFollowing = function () {
2850 this._bitField = this._bitField | 67108864;
2851};
2852
2853Promise.prototype._setIsFinal = function () {
2854 this._bitField = this._bitField | 4194304;
2855};
2856
2857Promise.prototype._isFinal = function () {
2858 return (this._bitField & 4194304) > 0;
2859};
2860
2861Promise.prototype._unsetCancelled = function() {
2862 this._bitField = this._bitField & (~65536);
2863};
2864
2865Promise.prototype._setCancelled = function() {
2866 this._bitField = this._bitField | 65536;
2867};
2868
2869Promise.prototype._setAsyncGuaranteed = function() {
2870 this._bitField = this._bitField | 134217728;
2871};
2872
2873Promise.prototype._receiverAt = function (index) {
2874 var ret = index === 0 ? this._receiver0 : this[
2875 index * 4 - 4 + 3];
2876 if (ret === UNDEFINED_BINDING) {
2877 return undefined;
2878 } else if (ret === undefined && this._isBound()) {
2879 return this._boundValue();
2880 }
2881 return ret;
2882};
2883
2884Promise.prototype._promiseAt = function (index) {
2885 return this[
2886 index * 4 - 4 + 2];
2887};
2888
2889Promise.prototype._fulfillmentHandlerAt = function (index) {
2890 return this[
2891 index * 4 - 4 + 0];
2892};
2893
2894Promise.prototype._rejectionHandlerAt = function (index) {
2895 return this[
2896 index * 4 - 4 + 1];
2897};
2898
2899Promise.prototype._boundValue = function() {};
2900
2901Promise.prototype._migrateCallback0 = function (follower) {
2902 var bitField = follower._bitField;
2903 var fulfill = follower._fulfillmentHandler0;
2904 var reject = follower._rejectionHandler0;
2905 var promise = follower._promise0;
2906 var receiver = follower._receiverAt(0);
2907 if (receiver === undefined) receiver = UNDEFINED_BINDING;
2908 this._addCallbacks(fulfill, reject, promise, receiver, null);
2909};
2910
2911Promise.prototype._migrateCallbackAt = function (follower, index) {
2912 var fulfill = follower._fulfillmentHandlerAt(index);
2913 var reject = follower._rejectionHandlerAt(index);
2914 var promise = follower._promiseAt(index);
2915 var receiver = follower._receiverAt(index);
2916 if (receiver === undefined) receiver = UNDEFINED_BINDING;
2917 this._addCallbacks(fulfill, reject, promise, receiver, null);
2918};
2919
2920Promise.prototype._addCallbacks = function (
2921 fulfill,
2922 reject,
2923 promise,
2924 receiver,
2925 domain
2926) {
2927 var index = this._length();
2928
2929 if (index >= 65535 - 4) {
2930 index = 0;
2931 this._setLength(0);
2932 }
2933
2934 if (index === 0) {
2935 this._promise0 = promise;
2936 this._receiver0 = receiver;
2937 if (typeof fulfill === "function") {
2938 this._fulfillmentHandler0 =
2939 domain === null ? fulfill : domain.bind(fulfill);
2940 }
2941 if (typeof reject === "function") {
2942 this._rejectionHandler0 =
2943 domain === null ? reject : domain.bind(reject);
2944 }
2945 } else {
2946 var base = index * 4 - 4;
2947 this[base + 2] = promise;
2948 this[base + 3] = receiver;
2949 if (typeof fulfill === "function") {
2950 this[base + 0] =
2951 domain === null ? fulfill : domain.bind(fulfill);
2952 }
2953 if (typeof reject === "function") {
2954 this[base + 1] =
2955 domain === null ? reject : domain.bind(reject);
2956 }
2957 }
2958 this._setLength(index + 1);
2959 return index;
2960};
2961
2962Promise.prototype._proxy = function (proxyable, arg) {
2963 this._addCallbacks(undefined, undefined, arg, proxyable, null);
2964};
2965
2966Promise.prototype._resolveCallback = function(value, shouldBind) {
2967 if (((this._bitField & 117506048) !== 0)) return;
2968 if (value === this)
2969 return this._rejectCallback(makeSelfResolutionError(), false);
2970 var maybePromise = tryConvertToPromise(value, this);
2971 if (!(maybePromise instanceof Promise)) return this._fulfill(value);
2972
2973 if (shouldBind) this._propagateFrom(maybePromise, 2);
2974
2975 var promise = maybePromise._target();
2976 var bitField = promise._bitField;
2977 if (((bitField & 50397184) === 0)) {
2978 var len = this._length();
2979 if (len > 0) promise._migrateCallback0(this);
2980 for (var i = 1; i < len; ++i) {
2981 promise._migrateCallbackAt(this, i);
2982 }
2983 this._setFollowing();
2984 this._setLength(0);
2985 this._setFollowee(promise);
2986 } else if (((bitField & 33554432) !== 0)) {
2987 this._fulfill(promise._value());
2988 } else if (((bitField & 16777216) !== 0)) {
2989 this._reject(promise._reason());
2990 } else {
2991 var reason = new CancellationError("late cancellation observer");
2992 promise._attachExtraTrace(reason);
2993 this._reject(reason);
2994 }
2995};
2996
2997Promise.prototype._rejectCallback =
2998function(reason, synchronous, ignoreNonErrorWarnings) {
2999 var trace = util.ensureErrorObject(reason);
3000 var hasStack = trace === reason;
3001 if (!hasStack && !ignoreNonErrorWarnings && debug.warnings()) {
3002 var message = "a promise was rejected with a non-error: " +
3003 util.classString(reason);
3004 this._warn(message, true);
3005 }
3006 this._attachExtraTrace(trace, synchronous ? hasStack : false);
3007 this._reject(reason);
3008};
3009
3010Promise.prototype._resolveFromExecutor = function (executor) {
3011 var promise = this;
3012 this._captureStackTrace();
3013 this._pushContext();
3014 var synchronous = true;
3015 var r = this._execute(executor, function(value) {
3016 promise._resolveCallback(value);
3017 }, function (reason) {
3018 promise._rejectCallback(reason, synchronous);
3019 });
3020 synchronous = false;
3021 this._popContext();
3022
3023 if (r !== undefined) {
3024 promise._rejectCallback(r, true);
3025 }
3026};
3027
3028Promise.prototype._settlePromiseFromHandler = function (
3029 handler, receiver, value, promise
3030) {
3031 var bitField = promise._bitField;
3032 if (((bitField & 65536) !== 0)) return;
3033 promise._pushContext();
3034 var x;
3035 if (receiver === APPLY) {
3036 if (!value || typeof value.length !== "number") {
3037 x = errorObj;
3038 x.e = new TypeError("cannot .spread() a non-array: " +
3039 util.classString(value));
3040 } else {
3041 x = tryCatch(handler).apply(this._boundValue(), value);
3042 }
3043 } else {
3044 x = tryCatch(handler).call(receiver, value);
3045 }
3046 var promiseCreated = promise._popContext();
3047 bitField = promise._bitField;
3048 if (((bitField & 65536) !== 0)) return;
3049
3050 if (x === NEXT_FILTER) {
3051 promise._reject(value);
3052 } else if (x === errorObj || x === promise) {
3053 var err = x === promise ? makeSelfResolutionError() : x.e;
3054 promise._rejectCallback(err, false);
3055 } else {
3056 debug.checkForgottenReturns(x, promiseCreated, "", promise, this);
3057 promise._resolveCallback(x);
3058 }
3059};
3060
3061Promise.prototype._target = function() {
3062 var ret = this;
3063 while (ret._isFollowing()) ret = ret._followee();
3064 return ret;
3065};
3066
3067Promise.prototype._followee = function() {
3068 return this._rejectionHandler0;
3069};
3070
3071Promise.prototype._setFollowee = function(promise) {
3072 this._rejectionHandler0 = promise;
3073};
3074
3075Promise.prototype._settlePromise = function(promise, handler, receiver, value) {
3076 var isPromise = promise instanceof Promise;
3077 var bitField = this._bitField;
3078 var asyncGuaranteed = ((bitField & 134217728) !== 0);
3079 if (((bitField & 65536) !== 0)) {
3080 if (isPromise) promise._invokeInternalOnCancel();
3081
3082 if (handler === finallyHandler) {
3083 receiver.cancelPromise = promise;
3084 if (tryCatch(handler).call(receiver, value) === errorObj) {
3085 promise._reject(errorObj.e);
3086 }
3087 } else if (handler === reflectHandler) {
3088 promise._fulfill(reflectHandler.call(receiver));
3089 } else if (receiver instanceof Proxyable) {
3090 receiver._promiseCancelled(promise);
3091 } else if (isPromise || promise instanceof PromiseArray) {
3092 promise._cancel();
3093 } else {
3094 receiver.cancel();
3095 }
3096 } else if (typeof handler === "function") {
3097 if (!isPromise) {
3098 handler.call(receiver, value, promise);
3099 } else {
3100 if (asyncGuaranteed) promise._setAsyncGuaranteed();
3101 this._settlePromiseFromHandler(handler, receiver, value, promise);
3102 }
3103 } else if (receiver instanceof Proxyable) {
3104 if (!receiver._isResolved()) {
3105 if (((bitField & 33554432) !== 0)) {
3106 receiver._promiseFulfilled(value, promise);
3107 } else {
3108 receiver._promiseRejected(value, promise);
3109 }
3110 }
3111 } else if (isPromise) {
3112 if (asyncGuaranteed) promise._setAsyncGuaranteed();
3113 if (((bitField & 33554432) !== 0)) {
3114 promise._fulfill(value);
3115 } else {
3116 promise._reject(value);
3117 }
3118 }
3119};
3120
3121Promise.prototype._settlePromiseLateCancellationObserver = function(ctx) {
3122 var handler = ctx.handler;
3123 var promise = ctx.promise;
3124 var receiver = ctx.receiver;
3125 var value = ctx.value;
3126 if (typeof handler === "function") {
3127 if (!(promise instanceof Promise)) {
3128 handler.call(receiver, value, promise);
3129 } else {
3130 this._settlePromiseFromHandler(handler, receiver, value, promise);
3131 }
3132 } else if (promise instanceof Promise) {
3133 promise._reject(value);
3134 }
3135};
3136
3137Promise.prototype._settlePromiseCtx = function(ctx) {
3138 this._settlePromise(ctx.promise, ctx.handler, ctx.receiver, ctx.value);
3139};
3140
3141Promise.prototype._settlePromise0 = function(handler, value, bitField) {
3142 var promise = this._promise0;
3143 var receiver = this._receiverAt(0);
3144 this._promise0 = undefined;
3145 this._receiver0 = undefined;
3146 this._settlePromise(promise, handler, receiver, value);
3147};
3148
3149Promise.prototype._clearCallbackDataAtIndex = function(index) {
3150 var base = index * 4 - 4;
3151 this[base + 2] =
3152 this[base + 3] =
3153 this[base + 0] =
3154 this[base + 1] = undefined;
3155};
3156
3157Promise.prototype._fulfill = function (value) {
3158 var bitField = this._bitField;
3159 if (((bitField & 117506048) >>> 16)) return;
3160 if (value === this) {
3161 var err = makeSelfResolutionError();
3162 this._attachExtraTrace(err);
3163 return this._reject(err);
3164 }
3165 this._setFulfilled();
3166 this._rejectionHandler0 = value;
3167
3168 if ((bitField & 65535) > 0) {
3169 if (((bitField & 134217728) !== 0)) {
3170 this._settlePromises();
3171 } else {
3172 async.settlePromises(this);
3173 }
3174 }
3175};
3176
3177Promise.prototype._reject = function (reason) {
3178 var bitField = this._bitField;
3179 if (((bitField & 117506048) >>> 16)) return;
3180 this._setRejected();
3181 this._fulfillmentHandler0 = reason;
3182
3183 if (this._isFinal()) {
3184 return async.fatalError(reason, util.isNode);
3185 }
3186
3187 if ((bitField & 65535) > 0) {
3188 if (((bitField & 134217728) !== 0)) {
3189 this._settlePromises();
3190 } else {
3191 async.settlePromises(this);
3192 }
3193 } else {
3194 this._ensurePossibleRejectionHandled();
3195 }
3196};
3197
3198Promise.prototype._fulfillPromises = function (len, value) {
3199 for (var i = 1; i < len; i++) {
3200 var handler = this._fulfillmentHandlerAt(i);
3201 var promise = this._promiseAt(i);
3202 var receiver = this._receiverAt(i);
3203 this._clearCallbackDataAtIndex(i);
3204 this._settlePromise(promise, handler, receiver, value);
3205 }
3206};
3207
3208Promise.prototype._rejectPromises = function (len, reason) {
3209 for (var i = 1; i < len; i++) {
3210 var handler = this._rejectionHandlerAt(i);
3211 var promise = this._promiseAt(i);
3212 var receiver = this._receiverAt(i);
3213 this._clearCallbackDataAtIndex(i);
3214 this._settlePromise(promise, handler, receiver, reason);
3215 }
3216};
3217
3218Promise.prototype._settlePromises = function () {
3219 var bitField = this._bitField;
3220 var len = (bitField & 65535);
3221
3222 if (len > 0) {
3223 if (((bitField & 16842752) !== 0)) {
3224 var reason = this._fulfillmentHandler0;
3225 this._settlePromise0(this._rejectionHandler0, reason, bitField);
3226 this._rejectPromises(len, reason);
3227 } else {
3228 var value = this._rejectionHandler0;
3229 this._settlePromise0(this._fulfillmentHandler0, value, bitField);
3230 this._fulfillPromises(len, value);
3231 }
3232 this._setLength(0);
3233 }
3234 this._clearCancellationData();
3235};
3236
3237Promise.prototype._settledValue = function() {
3238 var bitField = this._bitField;
3239 if (((bitField & 33554432) !== 0)) {
3240 return this._rejectionHandler0;
3241 } else if (((bitField & 16777216) !== 0)) {
3242 return this._fulfillmentHandler0;
3243 }
3244};
3245
3246function deferResolve(v) {this.promise._resolveCallback(v);}
3247function deferReject(v) {this.promise._rejectCallback(v, false);}
3248
3249Promise.defer = Promise.pending = function() {
3250 debug.deprecated("Promise.defer", "new Promise");
3251 var promise = new Promise(INTERNAL);
3252 return {
3253 promise: promise,
3254 resolve: deferResolve,
3255 reject: deferReject
3256 };
3257};
3258
3259util.notEnumerableProp(Promise,
3260 "_makeSelfResolutionError",
3261 makeSelfResolutionError);
3262
3263_dereq_("./method")(Promise, INTERNAL, tryConvertToPromise, apiRejection,
3264 debug);
3265_dereq_("./bind")(Promise, INTERNAL, tryConvertToPromise, debug);
3266_dereq_("./cancel")(Promise, PromiseArray, apiRejection, debug);
3267_dereq_("./direct_resolve")(Promise);
3268_dereq_("./synchronous_inspection")(Promise);
3269_dereq_("./join")(
3270 Promise, PromiseArray, tryConvertToPromise, INTERNAL, debug);
3271Promise.Promise = Promise;
3272_dereq_('./map.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug);
3273_dereq_('./using.js')(Promise, apiRejection, tryConvertToPromise, createContext, INTERNAL, debug);
3274_dereq_('./timers.js')(Promise, INTERNAL);
3275_dereq_('./generators.js')(Promise, apiRejection, INTERNAL, tryConvertToPromise, Proxyable, debug);
3276_dereq_('./nodeify.js')(Promise);
3277_dereq_('./call_get.js')(Promise);
3278_dereq_('./props.js')(Promise, PromiseArray, tryConvertToPromise, apiRejection);
3279_dereq_('./race.js')(Promise, INTERNAL, tryConvertToPromise, apiRejection);
3280_dereq_('./reduce.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug);
3281_dereq_('./settle.js')(Promise, PromiseArray, debug);
3282_dereq_('./some.js')(Promise, PromiseArray, apiRejection);
3283_dereq_('./promisify.js')(Promise, INTERNAL);
3284_dereq_('./any.js')(Promise);
3285_dereq_('./each.js')(Promise, INTERNAL);
3286_dereq_('./filter.js')(Promise, INTERNAL);
3287
3288 util.toFastProperties(Promise);
3289 util.toFastProperties(Promise.prototype);
3290 function fillTypes(value) {
3291 var p = new Promise(INTERNAL);
3292 p._fulfillmentHandler0 = value;
3293 p._rejectionHandler0 = value;
3294 p._promise0 = value;
3295 p._receiver0 = value;
3296 }
3297 // Complete slack tracking, opt out of field-type tracking and
3298 // stabilize map
3299 fillTypes({a: 1});
3300 fillTypes({b: 2});
3301 fillTypes({c: 3});
3302 fillTypes(1);
3303 fillTypes(function(){});
3304 fillTypes(undefined);
3305 fillTypes(false);
3306 fillTypes(new Promise(INTERNAL));
3307 debug.setBounds(Async.firstLineError, util.lastLineError);
3308 return Promise;
3309
3310};
3311
3312},{"./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){
3313"use strict";
3314module.exports = function(Promise, INTERNAL, tryConvertToPromise,
3315 apiRejection, Proxyable) {
3316var util = _dereq_("./util");
3317var isArray = util.isArray;
3318
3319function toResolutionValue(val) {
3320 switch(val) {
3321 case -2: return [];
3322 case -3: return {};
3323 }
3324}
3325
3326function PromiseArray(values) {
3327 var promise = this._promise = new Promise(INTERNAL);
3328 if (values instanceof Promise) {
3329 promise._propagateFrom(values, 3);
3330 }
3331 promise._setOnCancel(this);
3332 this._values = values;
3333 this._length = 0;
3334 this._totalResolved = 0;
3335 this._init(undefined, -2);
3336}
3337util.inherits(PromiseArray, Proxyable);
3338
3339PromiseArray.prototype.length = function () {
3340 return this._length;
3341};
3342
3343PromiseArray.prototype.promise = function () {
3344 return this._promise;
3345};
3346
3347PromiseArray.prototype._init = function init(_, resolveValueIfEmpty) {
3348 var values = tryConvertToPromise(this._values, this._promise);
3349 if (values instanceof Promise) {
3350 values = values._target();
3351 var bitField = values._bitField;
3352 ;
3353 this._values = values;
3354
3355 if (((bitField & 50397184) === 0)) {
3356 this._promise._setAsyncGuaranteed();
3357 return values._then(
3358 init,
3359 this._reject,
3360 undefined,
3361 this,
3362 resolveValueIfEmpty
3363 );
3364 } else if (((bitField & 33554432) !== 0)) {
3365 values = values._value();
3366 } else if (((bitField & 16777216) !== 0)) {
3367 return this._reject(values._reason());
3368 } else {
3369 return this._cancel();
3370 }
3371 }
3372 values = util.asArray(values);
3373 if (values === null) {
3374 var err = apiRejection(
3375 "expecting an array or an iterable object but got " + util.classString(values)).reason();
3376 this._promise._rejectCallback(err, false);
3377 return;
3378 }
3379
3380 if (values.length === 0) {
3381 if (resolveValueIfEmpty === -5) {
3382 this._resolveEmptyArray();
3383 }
3384 else {
3385 this._resolve(toResolutionValue(resolveValueIfEmpty));
3386 }
3387 return;
3388 }
3389 this._iterate(values);
3390};
3391
3392PromiseArray.prototype._iterate = function(values) {
3393 var len = this.getActualLength(values.length);
3394 this._length = len;
3395 this._values = this.shouldCopyValues() ? new Array(len) : this._values;
3396 var result = this._promise;
3397 var isResolved = false;
3398 var bitField = null;
3399 for (var i = 0; i < len; ++i) {
3400 var maybePromise = tryConvertToPromise(values[i], result);
3401
3402 if (maybePromise instanceof Promise) {
3403 maybePromise = maybePromise._target();
3404 bitField = maybePromise._bitField;
3405 } else {
3406 bitField = null;
3407 }
3408
3409 if (isResolved) {
3410 if (bitField !== null) {
3411 maybePromise.suppressUnhandledRejections();
3412 }
3413 } else if (bitField !== null) {
3414 if (((bitField & 50397184) === 0)) {
3415 maybePromise._proxy(this, i);
3416 this._values[i] = maybePromise;
3417 } else if (((bitField & 33554432) !== 0)) {
3418 isResolved = this._promiseFulfilled(maybePromise._value(), i);
3419 } else if (((bitField & 16777216) !== 0)) {
3420 isResolved = this._promiseRejected(maybePromise._reason(), i);
3421 } else {
3422 isResolved = this._promiseCancelled(i);
3423 }
3424 } else {
3425 isResolved = this._promiseFulfilled(maybePromise, i);
3426 }
3427 }
3428 if (!isResolved) result._setAsyncGuaranteed();
3429};
3430
3431PromiseArray.prototype._isResolved = function () {
3432 return this._values === null;
3433};
3434
3435PromiseArray.prototype._resolve = function (value) {
3436 this._values = null;
3437 this._promise._fulfill(value);
3438};
3439
3440PromiseArray.prototype._cancel = function() {
3441 if (this._isResolved() || !this._promise.isCancellable()) return;
3442 this._values = null;
3443 this._promise._cancel();
3444};
3445
3446PromiseArray.prototype._reject = function (reason) {
3447 this._values = null;
3448 this._promise._rejectCallback(reason, false);
3449};
3450
3451PromiseArray.prototype._promiseFulfilled = function (value, index) {
3452 this._values[index] = value;
3453 var totalResolved = ++this._totalResolved;
3454 if (totalResolved >= this._length) {
3455 this._resolve(this._values);
3456 return true;
3457 }
3458 return false;
3459};
3460
3461PromiseArray.prototype._promiseCancelled = function() {
3462 this._cancel();
3463 return true;
3464};
3465
3466PromiseArray.prototype._promiseRejected = function (reason) {
3467 this._totalResolved++;
3468 this._reject(reason);
3469 return true;
3470};
3471
3472PromiseArray.prototype._resultCancelled = function() {
3473 if (this._isResolved()) return;
3474 var values = this._values;
3475 this._cancel();
3476 if (values instanceof Promise) {
3477 values.cancel();
3478 } else {
3479 for (var i = 0; i < values.length; ++i) {
3480 if (values[i] instanceof Promise) {
3481 values[i].cancel();
3482 }
3483 }
3484 }
3485};
3486
3487PromiseArray.prototype.shouldCopyValues = function () {
3488 return true;
3489};
3490
3491PromiseArray.prototype.getActualLength = function (len) {
3492 return len;
3493};
3494
3495return PromiseArray;
3496};
3497
3498},{"./util":36}],24:[function(_dereq_,module,exports){
3499"use strict";
3500module.exports = function(Promise, INTERNAL) {
3501var THIS = {};
3502var util = _dereq_("./util");
3503var nodebackForPromise = _dereq_("./nodeback");
3504var withAppended = util.withAppended;
3505var maybeWrapAsError = util.maybeWrapAsError;
3506var canEvaluate = util.canEvaluate;
3507var TypeError = _dereq_("./errors").TypeError;
3508var defaultSuffix = "Async";
3509var defaultPromisified = {__isPromisified__: true};
3510var noCopyProps = [
3511 "arity", "length",
3512 "name",
3513 "arguments",
3514 "caller",
3515 "callee",
3516 "prototype",
3517 "__isPromisified__"
3518];
3519var noCopyPropsPattern = new RegExp("^(?:" + noCopyProps.join("|") + ")$");
3520
3521var defaultFilter = function(name) {
3522 return util.isIdentifier(name) &&
3523 name.charAt(0) !== "_" &&
3524 name !== "constructor";
3525};
3526
3527function propsFilter(key) {
3528 return !noCopyPropsPattern.test(key);
3529}
3530
3531function isPromisified(fn) {
3532 try {
3533 return fn.__isPromisified__ === true;
3534 }
3535 catch (e) {
3536 return false;
3537 }
3538}
3539
3540function hasPromisified(obj, key, suffix) {
3541 var val = util.getDataPropertyOrDefault(obj, key + suffix,
3542 defaultPromisified);
3543 return val ? isPromisified(val) : false;
3544}
3545function checkValid(ret, suffix, suffixRegexp) {
3546 for (var i = 0; i < ret.length; i += 2) {
3547 var key = ret[i];
3548 if (suffixRegexp.test(key)) {
3549 var keyWithoutAsyncSuffix = key.replace(suffixRegexp, "");
3550 for (var j = 0; j < ret.length; j += 2) {
3551 if (ret[j] === keyWithoutAsyncSuffix) {
3552 throw new TypeError("Cannot promisify an API that has normal methods with '%s'-suffix\u000a\u000a See http://goo.gl/MqrFmX\u000a"
3553 .replace("%s", suffix));
3554 }
3555 }
3556 }
3557 }
3558}
3559
3560function promisifiableMethods(obj, suffix, suffixRegexp, filter) {
3561 var keys = util.inheritedDataKeys(obj);
3562 var ret = [];
3563 for (var i = 0; i < keys.length; ++i) {
3564 var key = keys[i];
3565 var value = obj[key];
3566 var passesDefaultFilter = filter === defaultFilter
3567 ? true : defaultFilter(key, value, obj);
3568 if (typeof value === "function" &&
3569 !isPromisified(value) &&
3570 !hasPromisified(obj, key, suffix) &&
3571 filter(key, value, obj, passesDefaultFilter)) {
3572 ret.push(key, value);
3573 }
3574 }
3575 checkValid(ret, suffix, suffixRegexp);
3576 return ret;
3577}
3578
3579var escapeIdentRegex = function(str) {
3580 return str.replace(/([$])/, "\\$");
3581};
3582
3583var makeNodePromisifiedEval;
3584if (!true) {
3585var switchCaseArgumentOrder = function(likelyArgumentCount) {
3586 var ret = [likelyArgumentCount];
3587 var min = Math.max(0, likelyArgumentCount - 1 - 3);
3588 for(var i = likelyArgumentCount - 1; i >= min; --i) {
3589 ret.push(i);
3590 }
3591 for(var i = likelyArgumentCount + 1; i <= 3; ++i) {
3592 ret.push(i);
3593 }
3594 return ret;
3595};
3596
3597var argumentSequence = function(argumentCount) {
3598 return util.filledRange(argumentCount, "_arg", "");
3599};
3600
3601var parameterDeclaration = function(parameterCount) {
3602 return util.filledRange(
3603 Math.max(parameterCount, 3), "_arg", "");
3604};
3605
3606var parameterCount = function(fn) {
3607 if (typeof fn.length === "number") {
3608 return Math.max(Math.min(fn.length, 1023 + 1), 0);
3609 }
3610 return 0;
3611};
3612
3613makeNodePromisifiedEval =
3614function(callback, receiver, originalName, fn, _, multiArgs) {
3615 var newParameterCount = Math.max(0, parameterCount(fn) - 1);
3616 var argumentOrder = switchCaseArgumentOrder(newParameterCount);
3617 var shouldProxyThis = typeof callback === "string" || receiver === THIS;
3618
3619 function generateCallForArgumentCount(count) {
3620 var args = argumentSequence(count).join(", ");
3621 var comma = count > 0 ? ", " : "";
3622 var ret;
3623 if (shouldProxyThis) {
3624 ret = "ret = callback.call(this, {{args}}, nodeback); break;\n";
3625 } else {
3626 ret = receiver === undefined
3627 ? "ret = callback({{args}}, nodeback); break;\n"
3628 : "ret = callback.call(receiver, {{args}}, nodeback); break;\n";
3629 }
3630 return ret.replace("{{args}}", args).replace(", ", comma);
3631 }
3632
3633 function generateArgumentSwitchCase() {
3634 var ret = "";
3635 for (var i = 0; i < argumentOrder.length; ++i) {
3636 ret += "case " + argumentOrder[i] +":" +
3637 generateCallForArgumentCount(argumentOrder[i]);
3638 }
3639
3640 ret += " \n\
3641 default: \n\
3642 var args = new Array(len + 1); \n\
3643 var i = 0; \n\
3644 for (var i = 0; i < len; ++i) { \n\
3645 args[i] = arguments[i]; \n\
3646 } \n\
3647 args[i] = nodeback; \n\
3648 [CodeForCall] \n\
3649 break; \n\
3650 ".replace("[CodeForCall]", (shouldProxyThis
3651 ? "ret = callback.apply(this, args);\n"
3652 : "ret = callback.apply(receiver, args);\n"));
3653 return ret;
3654 }
3655
3656 var getFunctionCode = typeof callback === "string"
3657 ? ("this != null ? this['"+callback+"'] : fn")
3658 : "fn";
3659 var body = "'use strict'; \n\
3660 var ret = function (Parameters) { \n\
3661 'use strict'; \n\
3662 var len = arguments.length; \n\
3663 var promise = new Promise(INTERNAL); \n\
3664 promise._captureStackTrace(); \n\
3665 var nodeback = nodebackForPromise(promise, " + multiArgs + "); \n\
3666 var ret; \n\
3667 var callback = tryCatch([GetFunctionCode]); \n\
3668 switch(len) { \n\
3669 [CodeForSwitchCase] \n\
3670 } \n\
3671 if (ret === errorObj) { \n\
3672 promise._rejectCallback(maybeWrapAsError(ret.e), true, true);\n\
3673 } \n\
3674 if (!promise._isFateSealed()) promise._setAsyncGuaranteed(); \n\
3675 return promise; \n\
3676 }; \n\
3677 notEnumerableProp(ret, '__isPromisified__', true); \n\
3678 return ret; \n\
3679 ".replace("[CodeForSwitchCase]", generateArgumentSwitchCase())
3680 .replace("[GetFunctionCode]", getFunctionCode);
3681 body = body.replace("Parameters", parameterDeclaration(newParameterCount));
3682 return new Function("Promise",
3683 "fn",
3684 "receiver",
3685 "withAppended",
3686 "maybeWrapAsError",
3687 "nodebackForPromise",
3688 "tryCatch",
3689 "errorObj",
3690 "notEnumerableProp",
3691 "INTERNAL",
3692 body)(
3693 Promise,
3694 fn,
3695 receiver,
3696 withAppended,
3697 maybeWrapAsError,
3698 nodebackForPromise,
3699 util.tryCatch,
3700 util.errorObj,
3701 util.notEnumerableProp,
3702 INTERNAL);
3703};
3704}
3705
3706function makeNodePromisifiedClosure(callback, receiver, _, fn, __, multiArgs) {
3707 var defaultThis = (function() {return this;})();
3708 var method = callback;
3709 if (typeof method === "string") {
3710 callback = fn;
3711 }
3712 function promisified() {
3713 var _receiver = receiver;
3714 if (receiver === THIS) _receiver = this;
3715 var promise = new Promise(INTERNAL);
3716 promise._captureStackTrace();
3717 var cb = typeof method === "string" && this !== defaultThis
3718 ? this[method] : callback;
3719 var fn = nodebackForPromise(promise, multiArgs);
3720 try {
3721 cb.apply(_receiver, withAppended(arguments, fn));
3722 } catch(e) {
3723 promise._rejectCallback(maybeWrapAsError(e), true, true);
3724 }
3725 if (!promise._isFateSealed()) promise._setAsyncGuaranteed();
3726 return promise;
3727 }
3728 util.notEnumerableProp(promisified, "__isPromisified__", true);
3729 return promisified;
3730}
3731
3732var makeNodePromisified = canEvaluate
3733 ? makeNodePromisifiedEval
3734 : makeNodePromisifiedClosure;
3735
3736function promisifyAll(obj, suffix, filter, promisifier, multiArgs) {
3737 var suffixRegexp = new RegExp(escapeIdentRegex(suffix) + "$");
3738 var methods =
3739 promisifiableMethods(obj, suffix, suffixRegexp, filter);
3740
3741 for (var i = 0, len = methods.length; i < len; i+= 2) {
3742 var key = methods[i];
3743 var fn = methods[i+1];
3744 var promisifiedKey = key + suffix;
3745 if (promisifier === makeNodePromisified) {
3746 obj[promisifiedKey] =
3747 makeNodePromisified(key, THIS, key, fn, suffix, multiArgs);
3748 } else {
3749 var promisified = promisifier(fn, function() {
3750 return makeNodePromisified(key, THIS, key,
3751 fn, suffix, multiArgs);
3752 });
3753 util.notEnumerableProp(promisified, "__isPromisified__", true);
3754 obj[promisifiedKey] = promisified;
3755 }
3756 }
3757 util.toFastProperties(obj);
3758 return obj;
3759}
3760
3761function promisify(callback, receiver, multiArgs) {
3762 return makeNodePromisified(callback, receiver, undefined,
3763 callback, null, multiArgs);
3764}
3765
3766Promise.promisify = function (fn, options) {
3767 if (typeof fn !== "function") {
3768 throw new TypeError("expecting a function but got " + util.classString(fn));
3769 }
3770 if (isPromisified(fn)) {
3771 return fn;
3772 }
3773 options = Object(options);
3774 var receiver = options.context === undefined ? THIS : options.context;
3775 var multiArgs = !!options.multiArgs;
3776 var ret = promisify(fn, receiver, multiArgs);
3777 util.copyDescriptors(fn, ret, propsFilter);
3778 return ret;
3779};
3780
3781Promise.promisifyAll = function (target, options) {
3782 if (typeof target !== "function" && typeof target !== "object") {
3783 throw new TypeError("the target of promisifyAll must be an object or a function\u000a\u000a See http://goo.gl/MqrFmX\u000a");
3784 }
3785 options = Object(options);
3786 var multiArgs = !!options.multiArgs;
3787 var suffix = options.suffix;
3788 if (typeof suffix !== "string") suffix = defaultSuffix;
3789 var filter = options.filter;
3790 if (typeof filter !== "function") filter = defaultFilter;
3791 var promisifier = options.promisifier;
3792 if (typeof promisifier !== "function") promisifier = makeNodePromisified;
3793
3794 if (!util.isIdentifier(suffix)) {
3795 throw new RangeError("suffix must be a valid identifier\u000a\u000a See http://goo.gl/MqrFmX\u000a");
3796 }
3797
3798 var keys = util.inheritedDataKeys(target);
3799 for (var i = 0; i < keys.length; ++i) {
3800 var value = target[keys[i]];
3801 if (keys[i] !== "constructor" &&
3802 util.isClass(value)) {
3803 promisifyAll(value.prototype, suffix, filter, promisifier,
3804 multiArgs);
3805 promisifyAll(value, suffix, filter, promisifier, multiArgs);
3806 }
3807 }
3808
3809 return promisifyAll(target, suffix, filter, promisifier, multiArgs);
3810};
3811};
3812
3813
3814},{"./errors":12,"./nodeback":20,"./util":36}],25:[function(_dereq_,module,exports){
3815"use strict";
3816module.exports = function(
3817 Promise, PromiseArray, tryConvertToPromise, apiRejection) {
3818var util = _dereq_("./util");
3819var isObject = util.isObject;
3820var es5 = _dereq_("./es5");
3821var Es6Map;
3822if (typeof Map === "function") Es6Map = Map;
3823
3824var mapToEntries = (function() {
3825 var index = 0;
3826 var size = 0;
3827
3828 function extractEntry(value, key) {
3829 this[index] = value;
3830 this[index + size] = key;
3831 index++;
3832 }
3833
3834 return function mapToEntries(map) {
3835 size = map.size;
3836 index = 0;
3837 var ret = new Array(map.size * 2);
3838 map.forEach(extractEntry, ret);
3839 return ret;
3840 };
3841})();
3842
3843var entriesToMap = function(entries) {
3844 var ret = new Es6Map();
3845 var length = entries.length / 2 | 0;
3846 for (var i = 0; i < length; ++i) {
3847 var key = entries[length + i];
3848 var value = entries[i];
3849 ret.set(key, value);
3850 }
3851 return ret;
3852};
3853
3854function PropertiesPromiseArray(obj) {
3855 var isMap = false;
3856 var entries;
3857 if (Es6Map !== undefined && obj instanceof Es6Map) {
3858 entries = mapToEntries(obj);
3859 isMap = true;
3860 } else {
3861 var keys = es5.keys(obj);
3862 var len = keys.length;
3863 entries = new Array(len * 2);
3864 for (var i = 0; i < len; ++i) {
3865 var key = keys[i];
3866 entries[i] = obj[key];
3867 entries[i + len] = key;
3868 }
3869 }
3870 this.constructor$(entries);
3871 this._isMap = isMap;
3872 this._init$(undefined, -3);
3873}
3874util.inherits(PropertiesPromiseArray, PromiseArray);
3875
3876PropertiesPromiseArray.prototype._init = function () {};
3877
3878PropertiesPromiseArray.prototype._promiseFulfilled = function (value, index) {
3879 this._values[index] = value;
3880 var totalResolved = ++this._totalResolved;
3881 if (totalResolved >= this._length) {
3882 var val;
3883 if (this._isMap) {
3884 val = entriesToMap(this._values);
3885 } else {
3886 val = {};
3887 var keyOffset = this.length();
3888 for (var i = 0, len = this.length(); i < len; ++i) {
3889 val[this._values[i + keyOffset]] = this._values[i];
3890 }
3891 }
3892 this._resolve(val);
3893 return true;
3894 }
3895 return false;
3896};
3897
3898PropertiesPromiseArray.prototype.shouldCopyValues = function () {
3899 return false;
3900};
3901
3902PropertiesPromiseArray.prototype.getActualLength = function (len) {
3903 return len >> 1;
3904};
3905
3906function props(promises) {
3907 var ret;
3908 var castValue = tryConvertToPromise(promises);
3909
3910 if (!isObject(castValue)) {
3911 return apiRejection("cannot await properties of a non-object\u000a\u000a See http://goo.gl/MqrFmX\u000a");
3912 } else if (castValue instanceof Promise) {
3913 ret = castValue._then(
3914 Promise.props, undefined, undefined, undefined, undefined);
3915 } else {
3916 ret = new PropertiesPromiseArray(castValue).promise();
3917 }
3918
3919 if (castValue instanceof Promise) {
3920 ret._propagateFrom(castValue, 2);
3921 }
3922 return ret;
3923}
3924
3925Promise.prototype.props = function () {
3926 return props(this);
3927};
3928
3929Promise.props = function (promises) {
3930 return props(promises);
3931};
3932};
3933
3934},{"./es5":13,"./util":36}],26:[function(_dereq_,module,exports){
3935"use strict";
3936function arrayMove(src, srcIndex, dst, dstIndex, len) {
3937 for (var j = 0; j < len; ++j) {
3938 dst[j + dstIndex] = src[j + srcIndex];
3939 src[j + srcIndex] = void 0;
3940 }
3941}
3942
3943function Queue(capacity) {
3944 this._capacity = capacity;
3945 this._length = 0;
3946 this._front = 0;
3947}
3948
3949Queue.prototype._willBeOverCapacity = function (size) {
3950 return this._capacity < size;
3951};
3952
3953Queue.prototype._pushOne = function (arg) {
3954 var length = this.length();
3955 this._checkCapacity(length + 1);
3956 var i = (this._front + length) & (this._capacity - 1);
3957 this[i] = arg;
3958 this._length = length + 1;
3959};
3960
3961Queue.prototype._unshiftOne = function(value) {
3962 var capacity = this._capacity;
3963 this._checkCapacity(this.length() + 1);
3964 var front = this._front;
3965 var i = (((( front - 1 ) &
3966 ( capacity - 1) ) ^ capacity ) - capacity );
3967 this[i] = value;
3968 this._front = i;
3969 this._length = this.length() + 1;
3970};
3971
3972Queue.prototype.unshift = function(fn, receiver, arg) {
3973 this._unshiftOne(arg);
3974 this._unshiftOne(receiver);
3975 this._unshiftOne(fn);
3976};
3977
3978Queue.prototype.push = function (fn, receiver, arg) {
3979 var length = this.length() + 3;
3980 if (this._willBeOverCapacity(length)) {
3981 this._pushOne(fn);
3982 this._pushOne(receiver);
3983 this._pushOne(arg);
3984 return;
3985 }
3986 var j = this._front + length - 3;
3987 this._checkCapacity(length);
3988 var wrapMask = this._capacity - 1;
3989 this[(j + 0) & wrapMask] = fn;
3990 this[(j + 1) & wrapMask] = receiver;
3991 this[(j + 2) & wrapMask] = arg;
3992 this._length = length;
3993};
3994
3995Queue.prototype.shift = function () {
3996 var front = this._front,
3997 ret = this[front];
3998
3999 this[front] = undefined;
4000 this._front = (front + 1) & (this._capacity - 1);
4001 this._length--;
4002 return ret;
4003};
4004
4005Queue.prototype.length = function () {
4006 return this._length;
4007};
4008
4009Queue.prototype._checkCapacity = function (size) {
4010 if (this._capacity < size) {
4011 this._resizeTo(this._capacity << 1);
4012 }
4013};
4014
4015Queue.prototype._resizeTo = function (capacity) {
4016 var oldCapacity = this._capacity;
4017 this._capacity = capacity;
4018 var front = this._front;
4019 var length = this._length;
4020 var moveItemsCount = (front + length) & (oldCapacity - 1);
4021 arrayMove(this, 0, this, oldCapacity, moveItemsCount);
4022};
4023
4024module.exports = Queue;
4025
4026},{}],27:[function(_dereq_,module,exports){
4027"use strict";
4028module.exports = function(
4029 Promise, INTERNAL, tryConvertToPromise, apiRejection) {
4030var util = _dereq_("./util");
4031
4032var raceLater = function (promise) {
4033 return promise.then(function(array) {
4034 return race(array, promise);
4035 });
4036};
4037
4038function race(promises, parent) {
4039 var maybePromise = tryConvertToPromise(promises);
4040
4041 if (maybePromise instanceof Promise) {
4042 return raceLater(maybePromise);
4043 } else {
4044 promises = util.asArray(promises);
4045 if (promises === null)
4046 return apiRejection("expecting an array or an iterable object but got " + util.classString(promises));
4047 }
4048
4049 var ret = new Promise(INTERNAL);
4050 if (parent !== undefined) {
4051 ret._propagateFrom(parent, 3);
4052 }
4053 var fulfill = ret._fulfill;
4054 var reject = ret._reject;
4055 for (var i = 0, len = promises.length; i < len; ++i) {
4056 var val = promises[i];
4057
4058 if (val === undefined && !(i in promises)) {
4059 continue;
4060 }
4061
4062 Promise.cast(val)._then(fulfill, reject, undefined, ret, null);
4063 }
4064 return ret;
4065}
4066
4067Promise.race = function (promises) {
4068 return race(promises, undefined);
4069};
4070
4071Promise.prototype.race = function () {
4072 return race(this, undefined);
4073};
4074
4075};
4076
4077},{"./util":36}],28:[function(_dereq_,module,exports){
4078"use strict";
4079module.exports = function(Promise,
4080 PromiseArray,
4081 apiRejection,
4082 tryConvertToPromise,
4083 INTERNAL,
4084 debug) {
4085var getDomain = Promise._getDomain;
4086var util = _dereq_("./util");
4087var tryCatch = util.tryCatch;
4088
4089function ReductionPromiseArray(promises, fn, initialValue, _each) {
4090 this.constructor$(promises);
4091 var domain = getDomain();
4092 this._fn = domain === null ? fn : domain.bind(fn);
4093 if (initialValue !== undefined) {
4094 initialValue = Promise.resolve(initialValue);
4095 initialValue._attachCancellationCallback(this);
4096 }
4097 this._initialValue = initialValue;
4098 this._currentCancellable = null;
4099 this._eachValues = _each === INTERNAL ? [] : undefined;
4100 this._promise._captureStackTrace();
4101 this._init$(undefined, -5);
4102}
4103util.inherits(ReductionPromiseArray, PromiseArray);
4104
4105ReductionPromiseArray.prototype._gotAccum = function(accum) {
4106 if (this._eachValues !== undefined && accum !== INTERNAL) {
4107 this._eachValues.push(accum);
4108 }
4109};
4110
4111ReductionPromiseArray.prototype._eachComplete = function(value) {
4112 this._eachValues.push(value);
4113 return this._eachValues;
4114};
4115
4116ReductionPromiseArray.prototype._init = function() {};
4117
4118ReductionPromiseArray.prototype._resolveEmptyArray = function() {
4119 this._resolve(this._eachValues !== undefined ? this._eachValues
4120 : this._initialValue);
4121};
4122
4123ReductionPromiseArray.prototype.shouldCopyValues = function () {
4124 return false;
4125};
4126
4127ReductionPromiseArray.prototype._resolve = function(value) {
4128 this._promise._resolveCallback(value);
4129 this._values = null;
4130};
4131
4132ReductionPromiseArray.prototype._resultCancelled = function(sender) {
4133 if (sender === this._initialValue) return this._cancel();
4134 if (this._isResolved()) return;
4135 this._resultCancelled$();
4136 if (this._currentCancellable instanceof Promise) {
4137 this._currentCancellable.cancel();
4138 }
4139 if (this._initialValue instanceof Promise) {
4140 this._initialValue.cancel();
4141 }
4142};
4143
4144ReductionPromiseArray.prototype._iterate = function (values) {
4145 this._values = values;
4146 var value;
4147 var i;
4148 var length = values.length;
4149 if (this._initialValue !== undefined) {
4150 value = this._initialValue;
4151 i = 0;
4152 } else {
4153 value = Promise.resolve(values[0]);
4154 i = 1;
4155 }
4156
4157 this._currentCancellable = value;
4158
4159 if (!value.isRejected()) {
4160 for (; i < length; ++i) {
4161 var ctx = {
4162 accum: null,
4163 value: values[i],
4164 index: i,
4165 length: length,
4166 array: this
4167 };
4168 value = value._then(gotAccum, undefined, undefined, ctx, undefined);
4169 }
4170 }
4171
4172 if (this._eachValues !== undefined) {
4173 value = value
4174 ._then(this._eachComplete, undefined, undefined, this, undefined);
4175 }
4176 value._then(completed, completed, undefined, value, this);
4177};
4178
4179Promise.prototype.reduce = function (fn, initialValue) {
4180 return reduce(this, fn, initialValue, null);
4181};
4182
4183Promise.reduce = function (promises, fn, initialValue, _each) {
4184 return reduce(promises, fn, initialValue, _each);
4185};
4186
4187function completed(valueOrReason, array) {
4188 if (this.isFulfilled()) {
4189 array._resolve(valueOrReason);
4190 } else {
4191 array._reject(valueOrReason);
4192 }
4193}
4194
4195function reduce(promises, fn, initialValue, _each) {
4196 if (typeof fn !== "function") {
4197 return apiRejection("expecting a function but got " + util.classString(fn));
4198 }
4199 var array = new ReductionPromiseArray(promises, fn, initialValue, _each);
4200 return array.promise();
4201}
4202
4203function gotAccum(accum) {
4204 this.accum = accum;
4205 this.array._gotAccum(accum);
4206 var value = tryConvertToPromise(this.value, this.array._promise);
4207 if (value instanceof Promise) {
4208 this.array._currentCancellable = value;
4209 return value._then(gotValue, undefined, undefined, this, undefined);
4210 } else {
4211 return gotValue.call(this, value);
4212 }
4213}
4214
4215function gotValue(value) {
4216 var array = this.array;
4217 var promise = array._promise;
4218 var fn = tryCatch(array._fn);
4219 promise._pushContext();
4220 var ret;
4221 if (array._eachValues !== undefined) {
4222 ret = fn.call(promise._boundValue(), value, this.index, this.length);
4223 } else {
4224 ret = fn.call(promise._boundValue(),
4225 this.accum, value, this.index, this.length);
4226 }
4227 if (ret instanceof Promise) {
4228 array._currentCancellable = ret;
4229 }
4230 var promiseCreated = promise._popContext();
4231 debug.checkForgottenReturns(
4232 ret,
4233 promiseCreated,
4234 array._eachValues !== undefined ? "Promise.each" : "Promise.reduce",
4235 promise
4236 );
4237 return ret;
4238}
4239};
4240
4241},{"./util":36}],29:[function(_dereq_,module,exports){
4242"use strict";
4243var util = _dereq_("./util");
4244var schedule;
4245var noAsyncScheduler = function() {
4246 throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/MqrFmX\u000a");
4247};
4248if (util.isNode && typeof MutationObserver === "undefined") {
4249 var GlobalSetImmediate = global.setImmediate;
4250 var ProcessNextTick = process.nextTick;
4251 schedule = util.isRecentNode
4252 ? function(fn) { GlobalSetImmediate.call(global, fn); }
4253 : function(fn) { ProcessNextTick.call(process, fn); };
4254} else if ((typeof MutationObserver !== "undefined") &&
4255 !(typeof window !== "undefined" &&
4256 window.navigator &&
4257 window.navigator.standalone)) {
4258 schedule = (function() {
4259 var div = document.createElement("div");
4260 var opts = {attributes: true};
4261 var toggleScheduled = false;
4262 var div2 = document.createElement("div");
4263 var o2 = new MutationObserver(function() {
4264 div.classList.toggle("foo");
4265 toggleScheduled = false;
4266 });
4267 o2.observe(div2, opts);
4268
4269 var scheduleToggle = function() {
4270 if (toggleScheduled) return;
4271 toggleScheduled = true;
4272 div2.classList.toggle("foo");
4273 };
4274
4275 return function schedule(fn) {
4276 var o = new MutationObserver(function() {
4277 o.disconnect();
4278 fn();
4279 });
4280 o.observe(div, opts);
4281 scheduleToggle();
4282 };
4283 })();
4284} else if (typeof setImmediate !== "undefined") {
4285 schedule = function (fn) {
4286 setImmediate(fn);
4287 };
4288} else if (typeof setTimeout !== "undefined") {
4289 schedule = function (fn) {
4290 setTimeout(fn, 0);
4291 };
4292} else {
4293 schedule = noAsyncScheduler;
4294}
4295module.exports = schedule;
4296
4297},{"./util":36}],30:[function(_dereq_,module,exports){
4298"use strict";
4299module.exports =
4300 function(Promise, PromiseArray, debug) {
4301var PromiseInspection = Promise.PromiseInspection;
4302var util = _dereq_("./util");
4303
4304function SettledPromiseArray(values) {
4305 this.constructor$(values);
4306}
4307util.inherits(SettledPromiseArray, PromiseArray);
4308
4309SettledPromiseArray.prototype._promiseResolved = function (index, inspection) {
4310 this._values[index] = inspection;
4311 var totalResolved = ++this._totalResolved;
4312 if (totalResolved >= this._length) {
4313 this._resolve(this._values);
4314 return true;
4315 }
4316 return false;
4317};
4318
4319SettledPromiseArray.prototype._promiseFulfilled = function (value, index) {
4320 var ret = new PromiseInspection();
4321 ret._bitField = 33554432;
4322 ret._settledValueField = value;
4323 return this._promiseResolved(index, ret);
4324};
4325SettledPromiseArray.prototype._promiseRejected = function (reason, index) {
4326 var ret = new PromiseInspection();
4327 ret._bitField = 16777216;
4328 ret._settledValueField = reason;
4329 return this._promiseResolved(index, ret);
4330};
4331
4332Promise.settle = function (promises) {
4333 debug.deprecated(".settle()", ".reflect()");
4334 return new SettledPromiseArray(promises).promise();
4335};
4336
4337Promise.prototype.settle = function () {
4338 return Promise.settle(this);
4339};
4340};
4341
4342},{"./util":36}],31:[function(_dereq_,module,exports){
4343"use strict";
4344module.exports =
4345function(Promise, PromiseArray, apiRejection) {
4346var util = _dereq_("./util");
4347var RangeError = _dereq_("./errors").RangeError;
4348var AggregateError = _dereq_("./errors").AggregateError;
4349var isArray = util.isArray;
4350var CANCELLATION = {};
4351
4352
4353function SomePromiseArray(values) {
4354 this.constructor$(values);
4355 this._howMany = 0;
4356 this._unwrap = false;
4357 this._initialized = false;
4358}
4359util.inherits(SomePromiseArray, PromiseArray);
4360
4361SomePromiseArray.prototype._init = function () {
4362 if (!this._initialized) {
4363 return;
4364 }
4365 if (this._howMany === 0) {
4366 this._resolve([]);
4367 return;
4368 }
4369 this._init$(undefined, -5);
4370 var isArrayResolved = isArray(this._values);
4371 if (!this._isResolved() &&
4372 isArrayResolved &&
4373 this._howMany > this._canPossiblyFulfill()) {
4374 this._reject(this._getRangeError(this.length()));
4375 }
4376};
4377
4378SomePromiseArray.prototype.init = function () {
4379 this._initialized = true;
4380 this._init();
4381};
4382
4383SomePromiseArray.prototype.setUnwrap = function () {
4384 this._unwrap = true;
4385};
4386
4387SomePromiseArray.prototype.howMany = function () {
4388 return this._howMany;
4389};
4390
4391SomePromiseArray.prototype.setHowMany = function (count) {
4392 this._howMany = count;
4393};
4394
4395SomePromiseArray.prototype._promiseFulfilled = function (value) {
4396 this._addFulfilled(value);
4397 if (this._fulfilled() === this.howMany()) {
4398 this._values.length = this.howMany();
4399 if (this.howMany() === 1 && this._unwrap) {
4400 this._resolve(this._values[0]);
4401 } else {
4402 this._resolve(this._values);
4403 }
4404 return true;
4405 }
4406 return false;
4407
4408};
4409SomePromiseArray.prototype._promiseRejected = function (reason) {
4410 this._addRejected(reason);
4411 return this._checkOutcome();
4412};
4413
4414SomePromiseArray.prototype._promiseCancelled = function () {
4415 if (this._values instanceof Promise || this._values == null) {
4416 return this._cancel();
4417 }
4418 this._addRejected(CANCELLATION);
4419 return this._checkOutcome();
4420};
4421
4422SomePromiseArray.prototype._checkOutcome = function() {
4423 if (this.howMany() > this._canPossiblyFulfill()) {
4424 var e = new AggregateError();
4425 for (var i = this.length(); i < this._values.length; ++i) {
4426 if (this._values[i] !== CANCELLATION) {
4427 e.push(this._values[i]);
4428 }
4429 }
4430 if (e.length > 0) {
4431 this._reject(e);
4432 } else {
4433 this._cancel();
4434 }
4435 return true;
4436 }
4437 return false;
4438};
4439
4440SomePromiseArray.prototype._fulfilled = function () {
4441 return this._totalResolved;
4442};
4443
4444SomePromiseArray.prototype._rejected = function () {
4445 return this._values.length - this.length();
4446};
4447
4448SomePromiseArray.prototype._addRejected = function (reason) {
4449 this._values.push(reason);
4450};
4451
4452SomePromiseArray.prototype._addFulfilled = function (value) {
4453 this._values[this._totalResolved++] = value;
4454};
4455
4456SomePromiseArray.prototype._canPossiblyFulfill = function () {
4457 return this.length() - this._rejected();
4458};
4459
4460SomePromiseArray.prototype._getRangeError = function (count) {
4461 var message = "Input array must contain at least " +
4462 this._howMany + " items but contains only " + count + " items";
4463 return new RangeError(message);
4464};
4465
4466SomePromiseArray.prototype._resolveEmptyArray = function () {
4467 this._reject(this._getRangeError(0));
4468};
4469
4470function some(promises, howMany) {
4471 if ((howMany | 0) !== howMany || howMany < 0) {
4472 return apiRejection("expecting a positive integer\u000a\u000a See http://goo.gl/MqrFmX\u000a");
4473 }
4474 var ret = new SomePromiseArray(promises);
4475 var promise = ret.promise();
4476 ret.setHowMany(howMany);
4477 ret.init();
4478 return promise;
4479}
4480
4481Promise.some = function (promises, howMany) {
4482 return some(promises, howMany);
4483};
4484
4485Promise.prototype.some = function (howMany) {
4486 return some(this, howMany);
4487};
4488
4489Promise._SomePromiseArray = SomePromiseArray;
4490};
4491
4492},{"./errors":12,"./util":36}],32:[function(_dereq_,module,exports){
4493"use strict";
4494module.exports = function(Promise) {
4495function PromiseInspection(promise) {
4496 if (promise !== undefined) {
4497 promise = promise._target();
4498 this._bitField = promise._bitField;
4499 this._settledValueField = promise._isFateSealed()
4500 ? promise._settledValue() : undefined;
4501 }
4502 else {
4503 this._bitField = 0;
4504 this._settledValueField = undefined;
4505 }
4506}
4507
4508PromiseInspection.prototype._settledValue = function() {
4509 return this._settledValueField;
4510};
4511
4512var value = PromiseInspection.prototype.value = function () {
4513 if (!this.isFulfilled()) {
4514 throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\u000a\u000a See http://goo.gl/MqrFmX\u000a");
4515 }
4516 return this._settledValue();
4517};
4518
4519var reason = PromiseInspection.prototype.error =
4520PromiseInspection.prototype.reason = function () {
4521 if (!this.isRejected()) {
4522 throw new TypeError("cannot get rejection reason of a non-rejected promise\u000a\u000a See http://goo.gl/MqrFmX\u000a");
4523 }
4524 return this._settledValue();
4525};
4526
4527var isFulfilled = PromiseInspection.prototype.isFulfilled = function() {
4528 return (this._bitField & 33554432) !== 0;
4529};
4530
4531var isRejected = PromiseInspection.prototype.isRejected = function () {
4532 return (this._bitField & 16777216) !== 0;
4533};
4534
4535var isPending = PromiseInspection.prototype.isPending = function () {
4536 return (this._bitField & 50397184) === 0;
4537};
4538
4539var isResolved = PromiseInspection.prototype.isResolved = function () {
4540 return (this._bitField & 50331648) !== 0;
4541};
4542
4543PromiseInspection.prototype.isCancelled =
4544Promise.prototype._isCancelled = function() {
4545 return (this._bitField & 65536) === 65536;
4546};
4547
4548Promise.prototype.isCancelled = function() {
4549 return this._target()._isCancelled();
4550};
4551
4552Promise.prototype.isPending = function() {
4553 return isPending.call(this._target());
4554};
4555
4556Promise.prototype.isRejected = function() {
4557 return isRejected.call(this._target());
4558};
4559
4560Promise.prototype.isFulfilled = function() {
4561 return isFulfilled.call(this._target());
4562};
4563
4564Promise.prototype.isResolved = function() {
4565 return isResolved.call(this._target());
4566};
4567
4568Promise.prototype.value = function() {
4569 return value.call(this._target());
4570};
4571
4572Promise.prototype.reason = function() {
4573 var target = this._target();
4574 target._unsetRejectionIsUnhandled();
4575 return reason.call(target);
4576};
4577
4578Promise.prototype._value = function() {
4579 return this._settledValue();
4580};
4581
4582Promise.prototype._reason = function() {
4583 this._unsetRejectionIsUnhandled();
4584 return this._settledValue();
4585};
4586
4587Promise.PromiseInspection = PromiseInspection;
4588};
4589
4590},{}],33:[function(_dereq_,module,exports){
4591"use strict";
4592module.exports = function(Promise, INTERNAL) {
4593var util = _dereq_("./util");
4594var errorObj = util.errorObj;
4595var isObject = util.isObject;
4596
4597function tryConvertToPromise(obj, context) {
4598 if (isObject(obj)) {
4599 if (obj instanceof Promise) return obj;
4600 var then = getThen(obj);
4601 if (then === errorObj) {
4602 if (context) context._pushContext();
4603 var ret = Promise.reject(then.e);
4604 if (context) context._popContext();
4605 return ret;
4606 } else if (typeof then === "function") {
4607 if (isAnyBluebirdPromise(obj)) {
4608 var ret = new Promise(INTERNAL);
4609 obj._then(
4610 ret._fulfill,
4611 ret._reject,
4612 undefined,
4613 ret,
4614 null
4615 );
4616 return ret;
4617 }
4618 return doThenable(obj, then, context);
4619 }
4620 }
4621 return obj;
4622}
4623
4624function doGetThen(obj) {
4625 return obj.then;
4626}
4627
4628function getThen(obj) {
4629 try {
4630 return doGetThen(obj);
4631 } catch (e) {
4632 errorObj.e = e;
4633 return errorObj;
4634 }
4635}
4636
4637var hasProp = {}.hasOwnProperty;
4638function isAnyBluebirdPromise(obj) {
4639 return hasProp.call(obj, "_promise0");
4640}
4641
4642function doThenable(x, then, context) {
4643 var promise = new Promise(INTERNAL);
4644 var ret = promise;
4645 if (context) context._pushContext();
4646 promise._captureStackTrace();
4647 if (context) context._popContext();
4648 var synchronous = true;
4649 var result = util.tryCatch(then).call(x, resolve, reject);
4650 synchronous = false;
4651
4652 if (promise && result === errorObj) {
4653 promise._rejectCallback(result.e, true, true);
4654 promise = null;
4655 }
4656
4657 function resolve(value) {
4658 if (!promise) return;
4659 promise._resolveCallback(value);
4660 promise = null;
4661 }
4662
4663 function reject(reason) {
4664 if (!promise) return;
4665 promise._rejectCallback(reason, synchronous, true);
4666 promise = null;
4667 }
4668 return ret;
4669}
4670
4671return tryConvertToPromise;
4672};
4673
4674},{"./util":36}],34:[function(_dereq_,module,exports){
4675"use strict";
4676module.exports = function(Promise, INTERNAL) {
4677var util = _dereq_("./util");
4678var TimeoutError = Promise.TimeoutError;
4679
4680var afterTimeout = function (promise, message, parent) {
4681 if (!promise.isPending()) return;
4682 var err;
4683 if (typeof message !== "string") {
4684 if (message instanceof Error) {
4685 err = message;
4686 } else {
4687 err = new TimeoutError("operation timed out");
4688 }
4689 } else {
4690 err = new TimeoutError(message);
4691 }
4692 util.markAsOriginatingFromRejection(err);
4693 promise._attachExtraTrace(err);
4694 promise._reject(err);
4695 parent.cancel();
4696};
4697
4698var afterValue = function(value) { return delay(+this).thenReturn(value); };
4699var delay = Promise.delay = function (ms, value) {
4700 var ret;
4701 if (value !== undefined) {
4702 ret = Promise.resolve(value)
4703 ._then(afterValue, null, null, ms, undefined);
4704 } else {
4705 ret = new Promise(INTERNAL);
4706 setTimeout(function() { ret._fulfill(); }, +ms);
4707 }
4708 ret._setAsyncGuaranteed();
4709 return ret;
4710};
4711
4712Promise.prototype.delay = function (ms) {
4713 return delay(ms, this);
4714};
4715
4716function successClear(value) {
4717 var handle = this;
4718 if (handle instanceof Number) handle = +handle;
4719 clearTimeout(handle);
4720 return value;
4721}
4722
4723function failureClear(reason) {
4724 var handle = this;
4725 if (handle instanceof Number) handle = +handle;
4726 clearTimeout(handle);
4727 throw reason;
4728}
4729
4730Promise.prototype.timeout = function (ms, message) {
4731 ms = +ms;
4732 var parent = this.then();
4733 var ret = parent.then();
4734 var handle = setTimeout(function timeoutTimeout() {
4735 afterTimeout(ret, message, parent);
4736 }, ms);
4737 return ret._then(successClear, failureClear, undefined, handle, undefined);
4738};
4739
4740};
4741
4742},{"./util":36}],35:[function(_dereq_,module,exports){
4743"use strict";
4744module.exports = function (Promise, apiRejection, tryConvertToPromise,
4745 createContext, INTERNAL, debug) {
4746 var util = _dereq_("./util");
4747 var TypeError = _dereq_("./errors").TypeError;
4748 var inherits = _dereq_("./util").inherits;
4749 var errorObj = util.errorObj;
4750 var tryCatch = util.tryCatch;
4751
4752 function thrower(e) {
4753 setTimeout(function(){throw e;}, 0);
4754 }
4755
4756 function castPreservingDisposable(thenable) {
4757 var maybePromise = tryConvertToPromise(thenable);
4758 if (maybePromise !== thenable &&
4759 typeof thenable._isDisposable === "function" &&
4760 typeof thenable._getDisposer === "function" &&
4761 thenable._isDisposable()) {
4762 maybePromise._setDisposable(thenable._getDisposer());
4763 }
4764 return maybePromise;
4765 }
4766 function dispose(resources, inspection) {
4767 var i = 0;
4768 var len = resources.length;
4769 var ret = new Promise(INTERNAL);
4770 function iterator() {
4771 if (i >= len) return ret._fulfill();
4772 var maybePromise = castPreservingDisposable(resources[i++]);
4773 if (maybePromise instanceof Promise &&
4774 maybePromise._isDisposable()) {
4775 try {
4776 maybePromise = tryConvertToPromise(
4777 maybePromise._getDisposer().tryDispose(inspection),
4778 resources.promise);
4779 } catch (e) {
4780 return thrower(e);
4781 }
4782 if (maybePromise instanceof Promise) {
4783 return maybePromise._then(iterator, thrower,
4784 null, null, null);
4785 }
4786 }
4787 iterator();
4788 }
4789 iterator();
4790 return ret;
4791 }
4792
4793 function Disposer(data, promise, context) {
4794 this._data = data;
4795 this._promise = promise;
4796 this._context = context;
4797 }
4798
4799 Disposer.prototype.data = function () {
4800 return this._data;
4801 };
4802
4803 Disposer.prototype.promise = function () {
4804 return this._promise;
4805 };
4806
4807 Disposer.prototype.resource = function () {
4808 if (this.promise().isFulfilled()) {
4809 return this.promise().value();
4810 }
4811 return null;
4812 };
4813
4814 Disposer.prototype.tryDispose = function(inspection) {
4815 var resource = this.resource();
4816 var context = this._context;
4817 if (context !== undefined) context._pushContext();
4818 var ret = resource !== null
4819 ? this.doDispose(resource, inspection) : null;
4820 if (context !== undefined) context._popContext();
4821 this._promise._unsetDisposable();
4822 this._data = null;
4823 return ret;
4824 };
4825
4826 Disposer.isDisposer = function (d) {
4827 return (d != null &&
4828 typeof d.resource === "function" &&
4829 typeof d.tryDispose === "function");
4830 };
4831
4832 function FunctionDisposer(fn, promise, context) {
4833 this.constructor$(fn, promise, context);
4834 }
4835 inherits(FunctionDisposer, Disposer);
4836
4837 FunctionDisposer.prototype.doDispose = function (resource, inspection) {
4838 var fn = this.data();
4839 return fn.call(resource, resource, inspection);
4840 };
4841
4842 function maybeUnwrapDisposer(value) {
4843 if (Disposer.isDisposer(value)) {
4844 this.resources[this.index]._setDisposable(value);
4845 return value.promise();
4846 }
4847 return value;
4848 }
4849
4850 function ResourceList(length) {
4851 this.length = length;
4852 this.promise = null;
4853 this[length-1] = null;
4854 }
4855
4856 ResourceList.prototype._resultCancelled = function() {
4857 var len = this.length;
4858 for (var i = 0; i < len; ++i) {
4859 var item = this[i];
4860 if (item instanceof Promise) {
4861 item.cancel();
4862 }
4863 }
4864 };
4865
4866 Promise.using = function () {
4867 var len = arguments.length;
4868 if (len < 2) return apiRejection(
4869 "you must pass at least 2 arguments to Promise.using");
4870 var fn = arguments[len - 1];
4871 if (typeof fn !== "function") {
4872 return apiRejection("expecting a function but got " + util.classString(fn));
4873 }
4874 var input;
4875 var spreadArgs = true;
4876 if (len === 2 && Array.isArray(arguments[0])) {
4877 input = arguments[0];
4878 len = input.length;
4879 spreadArgs = false;
4880 } else {
4881 input = arguments;
4882 len--;
4883 }
4884 var resources = new ResourceList(len);
4885 for (var i = 0; i < len; ++i) {
4886 var resource = input[i];
4887 if (Disposer.isDisposer(resource)) {
4888 var disposer = resource;
4889 resource = resource.promise();
4890 resource._setDisposable(disposer);
4891 } else {
4892 var maybePromise = tryConvertToPromise(resource);
4893 if (maybePromise instanceof Promise) {
4894 resource =
4895 maybePromise._then(maybeUnwrapDisposer, null, null, {
4896 resources: resources,
4897 index: i
4898 }, undefined);
4899 }
4900 }
4901 resources[i] = resource;
4902 }
4903
4904 var reflectedResources = new Array(resources.length);
4905 for (var i = 0; i < reflectedResources.length; ++i) {
4906 reflectedResources[i] = Promise.resolve(resources[i]).reflect();
4907 }
4908
4909 var resultPromise = Promise.all(reflectedResources)
4910 .then(function(inspections) {
4911 for (var i = 0; i < inspections.length; ++i) {
4912 var inspection = inspections[i];
4913 if (inspection.isRejected()) {
4914 errorObj.e = inspection.error();
4915 return errorObj;
4916 } else if (!inspection.isFulfilled()) {
4917 resultPromise.cancel();
4918 return;
4919 }
4920 inspections[i] = inspection.value();
4921 }
4922 promise._pushContext();
4923
4924 fn = tryCatch(fn);
4925 var ret = spreadArgs
4926 ? fn.apply(undefined, inspections) : fn(inspections);
4927 var promiseCreated = promise._popContext();
4928 debug.checkForgottenReturns(
4929 ret, promiseCreated, "Promise.using", promise);
4930 return ret;
4931 });
4932
4933 var promise = resultPromise.lastly(function() {
4934 var inspection = new Promise.PromiseInspection(resultPromise);
4935 return dispose(resources, inspection);
4936 });
4937 resources.promise = promise;
4938 promise._setOnCancel(resources);
4939 return promise;
4940 };
4941
4942 Promise.prototype._setDisposable = function (disposer) {
4943 this._bitField = this._bitField | 131072;
4944 this._disposer = disposer;
4945 };
4946
4947 Promise.prototype._isDisposable = function () {
4948 return (this._bitField & 131072) > 0;
4949 };
4950
4951 Promise.prototype._getDisposer = function () {
4952 return this._disposer;
4953 };
4954
4955 Promise.prototype._unsetDisposable = function () {
4956 this._bitField = this._bitField & (~131072);
4957 this._disposer = undefined;
4958 };
4959
4960 Promise.prototype.disposer = function (fn) {
4961 if (typeof fn === "function") {
4962 return new FunctionDisposer(fn, this, createContext());
4963 }
4964 throw new TypeError();
4965 };
4966
4967};
4968
4969},{"./errors":12,"./util":36}],36:[function(_dereq_,module,exports){
4970"use strict";
4971var es5 = _dereq_("./es5");
4972var canEvaluate = typeof navigator == "undefined";
4973
4974var errorObj = {e: {}};
4975var tryCatchTarget;
4976function tryCatcher() {
4977 try {
4978 var target = tryCatchTarget;
4979 tryCatchTarget = null;
4980 return target.apply(this, arguments);
4981 } catch (e) {
4982 errorObj.e = e;
4983 return errorObj;
4984 }
4985}
4986function tryCatch(fn) {
4987 tryCatchTarget = fn;
4988 return tryCatcher;
4989}
4990
4991var inherits = function(Child, Parent) {
4992 var hasProp = {}.hasOwnProperty;
4993
4994 function T() {
4995 this.constructor = Child;
4996 this.constructor$ = Parent;
4997 for (var propertyName in Parent.prototype) {
4998 if (hasProp.call(Parent.prototype, propertyName) &&
4999 propertyName.charAt(propertyName.length-1) !== "$"
5000 ) {
5001 this[propertyName + "$"] = Parent.prototype[propertyName];
5002 }
5003 }
5004 }
5005 T.prototype = Parent.prototype;
5006 Child.prototype = new T();
5007 return Child.prototype;
5008};
5009
5010
5011function isPrimitive(val) {
5012 return val == null || val === true || val === false ||
5013 typeof val === "string" || typeof val === "number";
5014
5015}
5016
5017function isObject(value) {
5018 return typeof value === "function" ||
5019 typeof value === "object" && value !== null;
5020}
5021
5022function maybeWrapAsError(maybeError) {
5023 if (!isPrimitive(maybeError)) return maybeError;
5024
5025 return new Error(safeToString(maybeError));
5026}
5027
5028function withAppended(target, appendee) {
5029 var len = target.length;
5030 var ret = new Array(len + 1);
5031 var i;
5032 for (i = 0; i < len; ++i) {
5033 ret[i] = target[i];
5034 }
5035 ret[i] = appendee;
5036 return ret;
5037}
5038
5039function getDataPropertyOrDefault(obj, key, defaultValue) {
5040 if (es5.isES5) {
5041 var desc = Object.getOwnPropertyDescriptor(obj, key);
5042
5043 if (desc != null) {
5044 return desc.get == null && desc.set == null
5045 ? desc.value
5046 : defaultValue;
5047 }
5048 } else {
5049 return {}.hasOwnProperty.call(obj, key) ? obj[key] : undefined;
5050 }
5051}
5052
5053function notEnumerableProp(obj, name, value) {
5054 if (isPrimitive(obj)) return obj;
5055 var descriptor = {
5056 value: value,
5057 configurable: true,
5058 enumerable: false,
5059 writable: true
5060 };
5061 es5.defineProperty(obj, name, descriptor);
5062 return obj;
5063}
5064
5065function thrower(r) {
5066 throw r;
5067}
5068
5069var inheritedDataKeys = (function() {
5070 var excludedPrototypes = [
5071 Array.prototype,
5072 Object.prototype,
5073 Function.prototype
5074 ];
5075
5076 var isExcludedProto = function(val) {
5077 for (var i = 0; i < excludedPrototypes.length; ++i) {
5078 if (excludedPrototypes[i] === val) {
5079 return true;
5080 }
5081 }
5082 return false;
5083 };
5084
5085 if (es5.isES5) {
5086 var getKeys = Object.getOwnPropertyNames;
5087 return function(obj) {
5088 var ret = [];
5089 var visitedKeys = Object.create(null);
5090 while (obj != null && !isExcludedProto(obj)) {
5091 var keys;
5092 try {
5093 keys = getKeys(obj);
5094 } catch (e) {
5095 return ret;
5096 }
5097 for (var i = 0; i < keys.length; ++i) {
5098 var key = keys[i];
5099 if (visitedKeys[key]) continue;
5100 visitedKeys[key] = true;
5101 var desc = Object.getOwnPropertyDescriptor(obj, key);
5102 if (desc != null && desc.get == null && desc.set == null) {
5103 ret.push(key);
5104 }
5105 }
5106 obj = es5.getPrototypeOf(obj);
5107 }
5108 return ret;
5109 };
5110 } else {
5111 var hasProp = {}.hasOwnProperty;
5112 return function(obj) {
5113 if (isExcludedProto(obj)) return [];
5114 var ret = [];
5115
5116 /*jshint forin:false */
5117 enumeration: for (var key in obj) {
5118 if (hasProp.call(obj, key)) {
5119 ret.push(key);
5120 } else {
5121 for (var i = 0; i < excludedPrototypes.length; ++i) {
5122 if (hasProp.call(excludedPrototypes[i], key)) {
5123 continue enumeration;
5124 }
5125 }
5126 ret.push(key);
5127 }
5128 }
5129 return ret;
5130 };
5131 }
5132
5133})();
5134
5135var thisAssignmentPattern = /this\s*\.\s*\S+\s*=/;
5136function isClass(fn) {
5137 try {
5138 if (typeof fn === "function") {
5139 var keys = es5.names(fn.prototype);
5140
5141 var hasMethods = es5.isES5 && keys.length > 1;
5142 var hasMethodsOtherThanConstructor = keys.length > 0 &&
5143 !(keys.length === 1 && keys[0] === "constructor");
5144 var hasThisAssignmentAndStaticMethods =
5145 thisAssignmentPattern.test(fn + "") && es5.names(fn).length > 0;
5146
5147 if (hasMethods || hasMethodsOtherThanConstructor ||
5148 hasThisAssignmentAndStaticMethods) {
5149 return true;
5150 }
5151 }
5152 return false;
5153 } catch (e) {
5154 return false;
5155 }
5156}
5157
5158function toFastProperties(obj) {
5159 /*jshint -W027,-W055,-W031*/
5160 function FakeConstructor() {}
5161 FakeConstructor.prototype = obj;
5162 var l = 8;
5163 while (l--) new FakeConstructor();
5164 return obj;
5165 eval(obj);
5166}
5167
5168var rident = /^[a-z$_][a-z$_0-9]*$/i;
5169function isIdentifier(str) {
5170 return rident.test(str);
5171}
5172
5173function filledRange(count, prefix, suffix) {
5174 var ret = new Array(count);
5175 for(var i = 0; i < count; ++i) {
5176 ret[i] = prefix + i + suffix;
5177 }
5178 return ret;
5179}
5180
5181function safeToString(obj) {
5182 try {
5183 return obj + "";
5184 } catch (e) {
5185 return "[no string representation]";
5186 }
5187}
5188
5189function markAsOriginatingFromRejection(e) {
5190 try {
5191 notEnumerableProp(e, "isOperational", true);
5192 }
5193 catch(ignore) {}
5194}
5195
5196function originatesFromRejection(e) {
5197 if (e == null) return false;
5198 return ((e instanceof Error["__BluebirdErrorTypes__"].OperationalError) ||
5199 e["isOperational"] === true);
5200}
5201
5202function canAttachTrace(obj) {
5203 return obj instanceof Error && es5.propertyIsWritable(obj, "stack");
5204}
5205
5206var ensureErrorObject = (function() {
5207 if (!("stack" in new Error())) {
5208 return function(value) {
5209 if (canAttachTrace(value)) return value;
5210 try {throw new Error(safeToString(value));}
5211 catch(err) {return err;}
5212 };
5213 } else {
5214 return function(value) {
5215 if (canAttachTrace(value)) return value;
5216 return new Error(safeToString(value));
5217 };
5218 }
5219})();
5220
5221function classString(obj) {
5222 return {}.toString.call(obj);
5223}
5224
5225function copyDescriptors(from, to, filter) {
5226 var keys = es5.names(from);
5227 for (var i = 0; i < keys.length; ++i) {
5228 var key = keys[i];
5229 if (filter(key)) {
5230 try {
5231 es5.defineProperty(to, key, es5.getDescriptor(from, key));
5232 } catch (ignore) {}
5233 }
5234 }
5235}
5236
5237var asArray = function(v) {
5238 if (es5.isArray(v)) {
5239 return v;
5240 }
5241 return null;
5242};
5243
5244if (typeof Symbol !== "undefined" && Symbol.iterator) {
5245 var ArrayFrom = typeof Array.from === "function" ? function(v) {
5246 return Array.from(v);
5247 } : function(v) {
5248 var ret = [];
5249 var it = v[Symbol.iterator]();
5250 var itResult;
5251 while (!((itResult = it.next()).done)) {
5252 ret.push(itResult.value);
5253 }
5254 return ret;
5255 };
5256
5257 asArray = function(v) {
5258 if (es5.isArray(v)) {
5259 return v;
5260 } else if (v != null && typeof v[Symbol.iterator] === "function") {
5261 return ArrayFrom(v);
5262 }
5263 return null;
5264 };
5265}
5266
5267var isNode = typeof process !== "undefined" &&
5268 classString(process).toLowerCase() === "[object process]";
5269
5270function env(key, def) {
5271 return isNode ? process.env[key] : def;
5272}
5273
5274var ret = {
5275 isClass: isClass,
5276 isIdentifier: isIdentifier,
5277 inheritedDataKeys: inheritedDataKeys,
5278 getDataPropertyOrDefault: getDataPropertyOrDefault,
5279 thrower: thrower,
5280 isArray: es5.isArray,
5281 asArray: asArray,
5282 notEnumerableProp: notEnumerableProp,
5283 isPrimitive: isPrimitive,
5284 isObject: isObject,
5285 canEvaluate: canEvaluate,
5286 errorObj: errorObj,
5287 tryCatch: tryCatch,
5288 inherits: inherits,
5289 withAppended: withAppended,
5290 maybeWrapAsError: maybeWrapAsError,
5291 toFastProperties: toFastProperties,
5292 filledRange: filledRange,
5293 toString: safeToString,
5294 canAttachTrace: canAttachTrace,
5295 ensureErrorObject: ensureErrorObject,
5296 originatesFromRejection: originatesFromRejection,
5297 markAsOriginatingFromRejection: markAsOriginatingFromRejection,
5298 classString: classString,
5299 copyDescriptors: copyDescriptors,
5300 hasDevTools: typeof chrome !== "undefined" && chrome &&
5301 typeof chrome.loadTimes === "function",
5302 isNode: isNode,
5303 env: env
5304};
5305ret.isRecentNode = ret.isNode && (function() {
5306 var version = process.versions.node.split(".").map(Number);
5307 return (version[0] === 0 && version[1] > 10) || (version[0] > 0);
5308})();
5309
5310if (ret.isNode) ret.toFastProperties(process);
5311
5312try {throw new Error(); } catch (e) {ret.lastLineError = e;}
5313module.exports = ret;
5314
5315},{"./es5":13}]},{},[4])(4)
5316}); ;if (typeof window !== 'undefined' && window !== null) { window.P = window.Promise; } else if (typeof self !== 'undefined' && self !== null) { self.P = self.Promise; }
5317}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
5318},{"_process":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/browserify/node_modules/process/browser.js"}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/browser-request/index.js":[function(require,module,exports){
5319// Browser Request
5320//
5321// Licensed under the Apache License, Version 2.0 (the "License");
5322// you may not use this file except in compliance with the License.
5323// You may obtain a copy of the License at
5324//
5325// http://www.apache.org/licenses/LICENSE-2.0
5326//
5327// Unless required by applicable law or agreed to in writing, software
5328// distributed under the License is distributed on an "AS IS" BASIS,
5329// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
5330// See the License for the specific language governing permissions and
5331// limitations under the License.
5332
5333// UMD HEADER START
5334(function (root, factory) {
5335 if (typeof define === 'function' && define.amd) {
5336 // AMD. Register as an anonymous module.
5337 define([], factory);
5338 } else if (typeof exports === 'object') {
5339 // Node. Does not work with strict CommonJS, but
5340 // only CommonJS-like enviroments that support module.exports,
5341 // like Node.
5342 module.exports = factory();
5343 } else {
5344 // Browser globals (root is window)
5345 root.returnExports = factory();
5346 }
5347}(this, function () {
5348// UMD HEADER END
5349
5350var XHR = XMLHttpRequest
5351if (!XHR) throw new Error('missing XMLHttpRequest')
5352request.log = {
5353 'trace': noop, 'debug': noop, 'info': noop, 'warn': noop, 'error': noop
5354}
5355
5356var DEFAULT_TIMEOUT = 3 * 60 * 1000 // 3 minutes
5357
5358//
5359// request
5360//
5361
5362function request(options, callback) {
5363 // The entry-point to the API: prep the options object and pass the real work to run_xhr.
5364 if(typeof callback !== 'function')
5365 throw new Error('Bad callback given: ' + callback)
5366
5367 if(!options)
5368 throw new Error('No options given')
5369
5370 var options_onResponse = options.onResponse; // Save this for later.
5371
5372 if(typeof options === 'string')
5373 options = {'uri':options};
5374 else
5375 options = JSON.parse(JSON.stringify(options)); // Use a duplicate for mutating.
5376
5377 options.onResponse = options_onResponse // And put it back.
5378
5379 if (options.verbose) request.log = getLogger();
5380
5381 if(options.url) {
5382 options.uri = options.url;
5383 delete options.url;
5384 }
5385
5386 if(!options.uri && options.uri !== "")
5387 throw new Error("options.uri is a required argument");
5388
5389 if(typeof options.uri != "string")
5390 throw new Error("options.uri must be a string");
5391
5392 var unsupported_options = ['proxy', '_redirectsFollowed', 'maxRedirects', 'followRedirect']
5393 for (var i = 0; i < unsupported_options.length; i++)
5394 if(options[ unsupported_options[i] ])
5395 throw new Error("options." + unsupported_options[i] + " is not supported")
5396
5397 options.callback = callback
5398 options.method = options.method || 'GET';
5399 options.headers = options.headers || {};
5400 options.body = options.body || null
5401 options.timeout = options.timeout || request.DEFAULT_TIMEOUT
5402
5403 if(options.headers.host)
5404 throw new Error("Options.headers.host is not supported");
5405
5406 if(options.json) {
5407 options.headers.accept = options.headers.accept || 'application/json'
5408 if(options.method !== 'GET')
5409 options.headers['content-type'] = 'application/json'
5410
5411 if(typeof options.json !== 'boolean')
5412 options.body = JSON.stringify(options.json)
5413 else if(typeof options.body !== 'string')
5414 options.body = JSON.stringify(options.body)
5415 }
5416
5417 //BEGIN QS Hack
5418 var serialize = function(obj) {
5419 var str = [];
5420 for(var p in obj)
5421 if (obj.hasOwnProperty(p)) {
5422 str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
5423 }
5424 return str.join("&");
5425 }
5426
5427 if(options.qs){
5428 var qs = (typeof options.qs == 'string')? options.qs : serialize(options.qs);
5429 if(options.uri.indexOf('?') !== -1){ //no get params
5430 options.uri = options.uri+'&'+qs;
5431 }else{ //existing get params
5432 options.uri = options.uri+'?'+qs;
5433 }
5434 }
5435 //END QS Hack
5436
5437 //BEGIN FORM Hack
5438 var multipart = function(obj) {
5439 //todo: support file type (useful?)
5440 var result = {};
5441 result.boundry = '-------------------------------'+Math.floor(Math.random()*1000000000);
5442 var lines = [];
5443 for(var p in obj){
5444 if (obj.hasOwnProperty(p)) {
5445 lines.push(
5446 '--'+result.boundry+"\n"+
5447 'Content-Disposition: form-data; name="'+p+'"'+"\n"+
5448 "\n"+
5449 obj[p]+"\n"
5450 );
5451 }
5452 }
5453 lines.push( '--'+result.boundry+'--' );
5454 result.body = lines.join('');
5455 result.length = result.body.length;
5456 result.type = 'multipart/form-data; boundary='+result.boundry;
5457 return result;
5458 }
5459
5460 if(options.form){
5461 if(typeof options.form == 'string') throw('form name unsupported');
5462 if(options.method === 'POST'){
5463 var encoding = (options.encoding || 'application/x-www-form-urlencoded').toLowerCase();
5464 options.headers['content-type'] = encoding;
5465 switch(encoding){
5466 case 'application/x-www-form-urlencoded':
5467 options.body = serialize(options.form).replace(/%20/g, "+");
5468 break;
5469 case 'multipart/form-data':
5470 var multi = multipart(options.form);
5471 //options.headers['content-length'] = multi.length;
5472 options.body = multi.body;
5473 options.headers['content-type'] = multi.type;
5474 break;
5475 default : throw new Error('unsupported encoding:'+encoding);
5476 }
5477 }
5478 }
5479 //END FORM Hack
5480
5481 // If onResponse is boolean true, call back immediately when the response is known,
5482 // not when the full request is complete.
5483 options.onResponse = options.onResponse || noop
5484 if(options.onResponse === true) {
5485 options.onResponse = callback
5486 options.callback = noop
5487 }
5488
5489 // XXX Browsers do not like this.
5490 //if(options.body)
5491 // options.headers['content-length'] = options.body.length;
5492
5493 // HTTP basic authentication
5494 if(!options.headers.authorization && options.auth)
5495 options.headers.authorization = 'Basic ' + b64_enc(options.auth.username + ':' + options.auth.password);
5496
5497 return run_xhr(options)
5498}
5499
5500var req_seq = 0
5501function run_xhr(options) {
5502 var xhr = new XHR
5503 , timed_out = false
5504 , is_cors = is_crossDomain(options.uri)
5505 , supports_cors = ('withCredentials' in xhr)
5506
5507 req_seq += 1
5508 xhr.seq_id = req_seq
5509 xhr.id = req_seq + ': ' + options.method + ' ' + options.uri
5510 xhr._id = xhr.id // I know I will type "_id" from habit all the time.
5511
5512 if(is_cors && !supports_cors) {
5513 var cors_err = new Error('Browser does not support cross-origin request: ' + options.uri)
5514 cors_err.cors = 'unsupported'
5515 return options.callback(cors_err, xhr)
5516 }
5517
5518 xhr.timeoutTimer = setTimeout(too_late, options.timeout)
5519 function too_late() {
5520 timed_out = true
5521 var er = new Error('ETIMEDOUT')
5522 er.code = 'ETIMEDOUT'
5523 er.duration = options.timeout
5524
5525 request.log.error('Timeout', { 'id':xhr._id, 'milliseconds':options.timeout })
5526 return options.callback(er, xhr)
5527 }
5528
5529 // Some states can be skipped over, so remember what is still incomplete.
5530 var did = {'response':false, 'loading':false, 'end':false}
5531
5532 xhr.onreadystatechange = on_state_change
5533 xhr.open(options.method, options.uri, true) // asynchronous
5534 if(is_cors)
5535 xhr.withCredentials = !! options.withCredentials
5536 xhr.send(options.body)
5537 return xhr
5538
5539 function on_state_change(event) {
5540 if(timed_out)
5541 return request.log.debug('Ignoring timed out state change', {'state':xhr.readyState, 'id':xhr.id})
5542
5543 request.log.debug('State change', {'state':xhr.readyState, 'id':xhr.id, 'timed_out':timed_out})
5544
5545 if(xhr.readyState === XHR.OPENED) {
5546 request.log.debug('Request started', {'id':xhr.id})
5547 for (var key in options.headers)
5548 xhr.setRequestHeader(key, options.headers[key])
5549 }
5550
5551 else if(xhr.readyState === XHR.HEADERS_RECEIVED)
5552 on_response()
5553
5554 else if(xhr.readyState === XHR.LOADING) {
5555 on_response()
5556 on_loading()
5557 }
5558
5559 else if(xhr.readyState === XHR.DONE) {
5560 on_response()
5561 on_loading()
5562 on_end()
5563 }
5564 }
5565
5566 function on_response() {
5567 if(did.response)
5568 return
5569
5570 did.response = true
5571 request.log.debug('Got response', {'id':xhr.id, 'status':xhr.status})
5572 clearTimeout(xhr.timeoutTimer)
5573 xhr.statusCode = xhr.status // Node request compatibility
5574
5575 // Detect failed CORS requests.
5576 if(is_cors && xhr.statusCode == 0) {
5577 var cors_err = new Error('CORS request rejected: ' + options.uri)
5578 cors_err.cors = 'rejected'
5579
5580 // Do not process this request further.
5581 did.loading = true
5582 did.end = true
5583
5584 return options.callback(cors_err, xhr)
5585 }
5586
5587 options.onResponse(null, xhr)
5588 }
5589
5590 function on_loading() {
5591 if(did.loading)
5592 return
5593
5594 did.loading = true
5595 request.log.debug('Response body loading', {'id':xhr.id})
5596 // TODO: Maybe simulate "data" events by watching xhr.responseText
5597 }
5598
5599 function on_end() {
5600 if(did.end)
5601 return
5602
5603 did.end = true
5604 request.log.debug('Request done', {'id':xhr.id})
5605
5606 xhr.body = xhr.responseText
5607 if(options.json) {
5608 try { xhr.body = JSON.parse(xhr.responseText) }
5609 catch (er) { return options.callback(er, xhr) }
5610 }
5611
5612 options.callback(null, xhr, xhr.body)
5613 }
5614
5615} // request
5616
5617request.withCredentials = false;
5618request.DEFAULT_TIMEOUT = DEFAULT_TIMEOUT;
5619
5620//
5621// defaults
5622//
5623
5624request.defaults = function(options, requester) {
5625 var def = function (method) {
5626 var d = function (params, callback) {
5627 if(typeof params === 'string')
5628 params = {'uri': params};
5629 else {
5630 params = JSON.parse(JSON.stringify(params));
5631 }
5632 for (var i in options) {
5633 if (params[i] === undefined) params[i] = options[i]
5634 }
5635 return method(params, callback)
5636 }
5637 return d
5638 }
5639 var de = def(request)
5640 de.get = def(request.get)
5641 de.post = def(request.post)
5642 de.put = def(request.put)
5643 de.head = def(request.head)
5644 return de
5645}
5646
5647//
5648// HTTP method shortcuts
5649//
5650
5651var shortcuts = [ 'get', 'put', 'post', 'head' ];
5652shortcuts.forEach(function(shortcut) {
5653 var method = shortcut.toUpperCase();
5654 var func = shortcut.toLowerCase();
5655
5656 request[func] = function(opts) {
5657 if(typeof opts === 'string')
5658 opts = {'method':method, 'uri':opts};
5659 else {
5660 opts = JSON.parse(JSON.stringify(opts));
5661 opts.method = method;
5662 }
5663
5664 var args = [opts].concat(Array.prototype.slice.apply(arguments, [1]));
5665 return request.apply(this, args);
5666 }
5667})
5668
5669//
5670// CouchDB shortcut
5671//
5672
5673request.couch = function(options, callback) {
5674 if(typeof options === 'string')
5675 options = {'uri':options}
5676
5677 // Just use the request API to do JSON.
5678 options.json = true
5679 if(options.body)
5680 options.json = options.body
5681 delete options.body
5682
5683 callback = callback || noop
5684
5685 var xhr = request(options, couch_handler)
5686 return xhr
5687
5688 function couch_handler(er, resp, body) {
5689 if(er)
5690 return callback(er, resp, body)
5691
5692 if((resp.statusCode < 200 || resp.statusCode > 299) && body.error) {
5693 // The body is a Couch JSON object indicating the error.
5694 er = new Error('CouchDB error: ' + (body.error.reason || body.error.error))
5695 for (var key in body)
5696 er[key] = body[key]
5697 return callback(er, resp, body);
5698 }
5699
5700 return callback(er, resp, body);
5701 }
5702}
5703
5704//
5705// Utility
5706//
5707
5708function noop() {}
5709
5710function getLogger() {
5711 var logger = {}
5712 , levels = ['trace', 'debug', 'info', 'warn', 'error']
5713 , level, i
5714
5715 for(i = 0; i < levels.length; i++) {
5716 level = levels[i]
5717
5718 logger[level] = noop
5719 if(typeof console !== 'undefined' && console && console[level])
5720 logger[level] = formatted(console, level)
5721 }
5722
5723 return logger
5724}
5725
5726function formatted(obj, method) {
5727 return formatted_logger
5728
5729 function formatted_logger(str, context) {
5730 if(typeof context === 'object')
5731 str += ' ' + JSON.stringify(context)
5732
5733 return obj[method].call(obj, str)
5734 }
5735}
5736
5737// Return whether a URL is a cross-domain request.
5738function is_crossDomain(url) {
5739 var rurl = /^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/
5740
5741 // jQuery #8138, IE may throw an exception when accessing
5742 // a field from window.location if document.domain has been set
5743 var ajaxLocation
5744 try { ajaxLocation = location.href }
5745 catch (e) {
5746 // Use the href attribute of an A element since IE will modify it given document.location
5747 ajaxLocation = document.createElement( "a" );
5748 ajaxLocation.href = "";
5749 ajaxLocation = ajaxLocation.href;
5750 }
5751
5752 var ajaxLocParts = rurl.exec(ajaxLocation.toLowerCase()) || []
5753 , parts = rurl.exec(url.toLowerCase() )
5754
5755 var result = !!(
5756 parts &&
5757 ( parts[1] != ajaxLocParts[1]
5758 || parts[2] != ajaxLocParts[2]
5759 || (parts[3] || (parts[1] === "http:" ? 80 : 443)) != (ajaxLocParts[3] || (ajaxLocParts[1] === "http:" ? 80 : 443))
5760 )
5761 )
5762
5763 //console.debug('is_crossDomain('+url+') -> ' + result)
5764 return result
5765}
5766
5767// MIT License from http://phpjs.org/functions/base64_encode:358
5768function b64_enc (data) {
5769 // Encodes string using MIME base64 algorithm
5770 var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
5771 var o1, o2, o3, h1, h2, h3, h4, bits, i = 0, ac = 0, enc="", tmp_arr = [];
5772
5773 if (!data) {
5774 return data;
5775 }
5776
5777 // assume utf8 data
5778 // data = this.utf8_encode(data+'');
5779
5780 do { // pack three octets into four hexets
5781 o1 = data.charCodeAt(i++);
5782 o2 = data.charCodeAt(i++);
5783 o3 = data.charCodeAt(i++);
5784
5785 bits = o1<<16 | o2<<8 | o3;
5786
5787 h1 = bits>>18 & 0x3f;
5788 h2 = bits>>12 & 0x3f;
5789 h3 = bits>>6 & 0x3f;
5790 h4 = bits & 0x3f;
5791
5792 // use hexets to index into b64, and append result to encoded string
5793 tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
5794 } while (i < data.length);
5795
5796 enc = tmp_arr.join('');
5797
5798 switch (data.length % 3) {
5799 case 1:
5800 enc = enc.slice(0, -2) + '==';
5801 break;
5802 case 2:
5803 enc = enc.slice(0, -1) + '=';
5804 break;
5805 }
5806
5807 return enc;
5808}
5809 return request;
5810//UMD FOOTER START
5811}));
5812//UMD FOOTER END
5813
5814},{}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/browserify/node_modules/buffer/index.js":[function(require,module,exports){
5815(function (global){
5816/*!
5817 * The buffer module from node.js, for the browser.
5818 *
5819 * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
5820 * @license MIT
5821 */
5822/* eslint-disable no-proto */
5823
5824'use strict'
5825
5826var base64 = require('base64-js')
5827var ieee754 = require('ieee754')
5828var isArray = require('isarray')
5829
5830exports.Buffer = Buffer
5831exports.SlowBuffer = SlowBuffer
5832exports.INSPECT_MAX_BYTES = 50
5833Buffer.poolSize = 8192 // not used by this implementation
5834
5835var rootParent = {}
5836
5837/**
5838 * If `Buffer.TYPED_ARRAY_SUPPORT`:
5839 * === true Use Uint8Array implementation (fastest)
5840 * === false Use Object implementation (most compatible, even IE6)
5841 *
5842 * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
5843 * Opera 11.6+, iOS 4.2+.
5844 *
5845 * Due to various browser bugs, sometimes the Object implementation will be used even
5846 * when the browser supports typed arrays.
5847 *
5848 * Note:
5849 *
5850 * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
5851 * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
5852 *
5853 * - Safari 5-7 lacks support for changing the `Object.prototype.constructor` property
5854 * on objects.
5855 *
5856 * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
5857 *
5858 * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
5859 * incorrect length in some situations.
5860
5861 * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
5862 * get the Object implementation, which is slower but behaves correctly.
5863 */
5864Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined
5865 ? global.TYPED_ARRAY_SUPPORT
5866 : typedArraySupport()
5867
5868function typedArraySupport () {
5869 function Bar () {}
5870 try {
5871 var arr = new Uint8Array(1)
5872 arr.foo = function () { return 42 }
5873 arr.constructor = Bar
5874 return arr.foo() === 42 && // typed array instances can be augmented
5875 arr.constructor === Bar && // constructor can be set
5876 typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`
5877 arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`
5878 } catch (e) {
5879 return false
5880 }
5881}
5882
5883function kMaxLength () {
5884 return Buffer.TYPED_ARRAY_SUPPORT
5885 ? 0x7fffffff
5886 : 0x3fffffff
5887}
5888
5889/**
5890 * Class: Buffer
5891 * =============
5892 *
5893 * The Buffer constructor returns instances of `Uint8Array` that are augmented
5894 * with function properties for all the node `Buffer` API functions. We use
5895 * `Uint8Array` so that square bracket notation works as expected -- it returns
5896 * a single octet.
5897 *
5898 * By augmenting the instances, we can avoid modifying the `Uint8Array`
5899 * prototype.
5900 */
5901function Buffer (arg) {
5902 if (!(this instanceof Buffer)) {
5903 // Avoid going through an ArgumentsAdaptorTrampoline in the common case.
5904 if (arguments.length > 1) return new Buffer(arg, arguments[1])
5905 return new Buffer(arg)
5906 }
5907
5908 if (!Buffer.TYPED_ARRAY_SUPPORT) {
5909 this.length = 0
5910 this.parent = undefined
5911 }
5912
5913 // Common case.
5914 if (typeof arg === 'number') {
5915 return fromNumber(this, arg)
5916 }
5917
5918 // Slightly less common case.
5919 if (typeof arg === 'string') {
5920 return fromString(this, arg, arguments.length > 1 ? arguments[1] : 'utf8')
5921 }
5922
5923 // Unusual.
5924 return fromObject(this, arg)
5925}
5926
5927function fromNumber (that, length) {
5928 that = allocate(that, length < 0 ? 0 : checked(length) | 0)
5929 if (!Buffer.TYPED_ARRAY_SUPPORT) {
5930 for (var i = 0; i < length; i++) {
5931 that[i] = 0
5932 }
5933 }
5934 return that
5935}
5936
5937function fromString (that, string, encoding) {
5938 if (typeof encoding !== 'string' || encoding === '') encoding = 'utf8'
5939
5940 // Assumption: byteLength() return value is always < kMaxLength.
5941 var length = byteLength(string, encoding) | 0
5942 that = allocate(that, length)
5943
5944 that.write(string, encoding)
5945 return that
5946}
5947
5948function fromObject (that, object) {
5949 if (Buffer.isBuffer(object)) return fromBuffer(that, object)
5950
5951 if (isArray(object)) return fromArray(that, object)
5952
5953 if (object == null) {
5954 throw new TypeError('must start with number, buffer, array or string')
5955 }
5956
5957 if (typeof ArrayBuffer !== 'undefined') {
5958 if (object.buffer instanceof ArrayBuffer) {
5959 return fromTypedArray(that, object)
5960 }
5961 if (object instanceof ArrayBuffer) {
5962 return fromArrayBuffer(that, object)
5963 }
5964 }
5965
5966 if (object.length) return fromArrayLike(that, object)
5967
5968 return fromJsonObject(that, object)
5969}
5970
5971function fromBuffer (that, buffer) {
5972 var length = checked(buffer.length) | 0
5973 that = allocate(that, length)
5974 buffer.copy(that, 0, 0, length)
5975 return that
5976}
5977
5978function fromArray (that, array) {
5979 var length = checked(array.length) | 0
5980 that = allocate(that, length)
5981 for (var i = 0; i < length; i += 1) {
5982 that[i] = array[i] & 255
5983 }
5984 return that
5985}
5986
5987// Duplicate of fromArray() to keep fromArray() monomorphic.
5988function fromTypedArray (that, array) {
5989 var length = checked(array.length) | 0
5990 that = allocate(that, length)
5991 // Truncating the elements is probably not what people expect from typed
5992 // arrays with BYTES_PER_ELEMENT > 1 but it's compatible with the behavior
5993 // of the old Buffer constructor.
5994 for (var i = 0; i < length; i += 1) {
5995 that[i] = array[i] & 255
5996 }
5997 return that
5998}
5999
6000function fromArrayBuffer (that, array) {
6001 if (Buffer.TYPED_ARRAY_SUPPORT) {
6002 // Return an augmented `Uint8Array` instance, for best performance
6003 array.byteLength
6004 that = Buffer._augment(new Uint8Array(array))
6005 } else {
6006 // Fallback: Return an object instance of the Buffer class
6007 that = fromTypedArray(that, new Uint8Array(array))
6008 }
6009 return that
6010}
6011
6012function fromArrayLike (that, array) {
6013 var length = checked(array.length) | 0
6014 that = allocate(that, length)
6015 for (var i = 0; i < length; i += 1) {
6016 that[i] = array[i] & 255
6017 }
6018 return that
6019}
6020
6021// Deserialize { type: 'Buffer', data: [1,2,3,...] } into a Buffer object.
6022// Returns a zero-length buffer for inputs that don't conform to the spec.
6023function fromJsonObject (that, object) {
6024 var array
6025 var length = 0
6026
6027 if (object.type === 'Buffer' && isArray(object.data)) {
6028 array = object.data
6029 length = checked(array.length) | 0
6030 }
6031 that = allocate(that, length)
6032
6033 for (var i = 0; i < length; i += 1) {
6034 that[i] = array[i] & 255
6035 }
6036 return that
6037}
6038
6039if (Buffer.TYPED_ARRAY_SUPPORT) {
6040 Buffer.prototype.__proto__ = Uint8Array.prototype
6041 Buffer.__proto__ = Uint8Array
6042} else {
6043 // pre-set for values that may exist in the future
6044 Buffer.prototype.length = undefined
6045 Buffer.prototype.parent = undefined
6046}
6047
6048function allocate (that, length) {
6049 if (Buffer.TYPED_ARRAY_SUPPORT) {
6050 // Return an augmented `Uint8Array` instance, for best performance
6051 that = Buffer._augment(new Uint8Array(length))
6052 that.__proto__ = Buffer.prototype
6053 } else {
6054 // Fallback: Return an object instance of the Buffer class
6055 that.length = length
6056 that._isBuffer = true
6057 }
6058
6059 var fromPool = length !== 0 && length <= Buffer.poolSize >>> 1
6060 if (fromPool) that.parent = rootParent
6061
6062 return that
6063}
6064
6065function checked (length) {
6066 // Note: cannot use `length < kMaxLength` here because that fails when
6067 // length is NaN (which is otherwise coerced to zero.)
6068 if (length >= kMaxLength()) {
6069 throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
6070 'size: 0x' + kMaxLength().toString(16) + ' bytes')
6071 }
6072 return length | 0
6073}
6074
6075function SlowBuffer (subject, encoding) {
6076 if (!(this instanceof SlowBuffer)) return new SlowBuffer(subject, encoding)
6077
6078 var buf = new Buffer(subject, encoding)
6079 delete buf.parent
6080 return buf
6081}
6082
6083Buffer.isBuffer = function isBuffer (b) {
6084 return !!(b != null && b._isBuffer)
6085}
6086
6087Buffer.compare = function compare (a, b) {
6088 if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
6089 throw new TypeError('Arguments must be Buffers')
6090 }
6091
6092 if (a === b) return 0
6093
6094 var x = a.length
6095 var y = b.length
6096
6097 var i = 0
6098 var len = Math.min(x, y)
6099 while (i < len) {
6100 if (a[i] !== b[i]) break
6101
6102 ++i
6103 }
6104
6105 if (i !== len) {
6106 x = a[i]
6107 y = b[i]
6108 }
6109
6110 if (x < y) return -1
6111 if (y < x) return 1
6112 return 0
6113}
6114
6115Buffer.isEncoding = function isEncoding (encoding) {
6116 switch (String(encoding).toLowerCase()) {
6117 case 'hex':
6118 case 'utf8':
6119 case 'utf-8':
6120 case 'ascii':
6121 case 'binary':
6122 case 'base64':
6123 case 'raw':
6124 case 'ucs2':
6125 case 'ucs-2':
6126 case 'utf16le':
6127 case 'utf-16le':
6128 return true
6129 default:
6130 return false
6131 }
6132}
6133
6134Buffer.concat = function concat (list, length) {
6135 if (!isArray(list)) throw new TypeError('list argument must be an Array of Buffers.')
6136
6137 if (list.length === 0) {
6138 return new Buffer(0)
6139 }
6140
6141 var i
6142 if (length === undefined) {
6143 length = 0
6144 for (i = 0; i < list.length; i++) {
6145 length += list[i].length
6146 }
6147 }
6148
6149 var buf = new Buffer(length)
6150 var pos = 0
6151 for (i = 0; i < list.length; i++) {
6152 var item = list[i]
6153 item.copy(buf, pos)
6154 pos += item.length
6155 }
6156 return buf
6157}
6158
6159function byteLength (string, encoding) {
6160 if (typeof string !== 'string') string = '' + string
6161
6162 var len = string.length
6163 if (len === 0) return 0
6164
6165 // Use a for loop to avoid recursion
6166 var loweredCase = false
6167 for (;;) {
6168 switch (encoding) {
6169 case 'ascii':
6170 case 'binary':
6171 // Deprecated
6172 case 'raw':
6173 case 'raws':
6174 return len
6175 case 'utf8':
6176 case 'utf-8':
6177 return utf8ToBytes(string).length
6178 case 'ucs2':
6179 case 'ucs-2':
6180 case 'utf16le':
6181 case 'utf-16le':
6182 return len * 2
6183 case 'hex':
6184 return len >>> 1
6185 case 'base64':
6186 return base64ToBytes(string).length
6187 default:
6188 if (loweredCase) return utf8ToBytes(string).length // assume utf8
6189 encoding = ('' + encoding).toLowerCase()
6190 loweredCase = true
6191 }
6192 }
6193}
6194Buffer.byteLength = byteLength
6195
6196function slowToString (encoding, start, end) {
6197 var loweredCase = false
6198
6199 start = start | 0
6200 end = end === undefined || end === Infinity ? this.length : end | 0
6201
6202 if (!encoding) encoding = 'utf8'
6203 if (start < 0) start = 0
6204 if (end > this.length) end = this.length
6205 if (end <= start) return ''
6206
6207 while (true) {
6208 switch (encoding) {
6209 case 'hex':
6210 return hexSlice(this, start, end)
6211
6212 case 'utf8':
6213 case 'utf-8':
6214 return utf8Slice(this, start, end)
6215
6216 case 'ascii':
6217 return asciiSlice(this, start, end)
6218
6219 case 'binary':
6220 return binarySlice(this, start, end)
6221
6222 case 'base64':
6223 return base64Slice(this, start, end)
6224
6225 case 'ucs2':
6226 case 'ucs-2':
6227 case 'utf16le':
6228 case 'utf-16le':
6229 return utf16leSlice(this, start, end)
6230
6231 default:
6232 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
6233 encoding = (encoding + '').toLowerCase()
6234 loweredCase = true
6235 }
6236 }
6237}
6238
6239Buffer.prototype.toString = function toString () {
6240 var length = this.length | 0
6241 if (length === 0) return ''
6242 if (arguments.length === 0) return utf8Slice(this, 0, length)
6243 return slowToString.apply(this, arguments)
6244}
6245
6246Buffer.prototype.equals = function equals (b) {
6247 if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
6248 if (this === b) return true
6249 return Buffer.compare(this, b) === 0
6250}
6251
6252Buffer.prototype.inspect = function inspect () {
6253 var str = ''
6254 var max = exports.INSPECT_MAX_BYTES
6255 if (this.length > 0) {
6256 str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
6257 if (this.length > max) str += ' ... '
6258 }
6259 return '<Buffer ' + str + '>'
6260}
6261
6262Buffer.prototype.compare = function compare (b) {
6263 if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
6264 if (this === b) return 0
6265 return Buffer.compare(this, b)
6266}
6267
6268Buffer.prototype.indexOf = function indexOf (val, byteOffset) {
6269 if (byteOffset > 0x7fffffff) byteOffset = 0x7fffffff
6270 else if (byteOffset < -0x80000000) byteOffset = -0x80000000
6271 byteOffset >>= 0
6272
6273 if (this.length === 0) return -1
6274 if (byteOffset >= this.length) return -1
6275
6276 // Negative offsets start from the end of the buffer
6277 if (byteOffset < 0) byteOffset = Math.max(this.length + byteOffset, 0)
6278
6279 if (typeof val === 'string') {
6280 if (val.length === 0) return -1 // special case: looking for empty string always fails
6281 return String.prototype.indexOf.call(this, val, byteOffset)
6282 }
6283 if (Buffer.isBuffer(val)) {
6284 return arrayIndexOf(this, val, byteOffset)
6285 }
6286 if (typeof val === 'number') {
6287 if (Buffer.TYPED_ARRAY_SUPPORT && Uint8Array.prototype.indexOf === 'function') {
6288 return Uint8Array.prototype.indexOf.call(this, val, byteOffset)
6289 }
6290 return arrayIndexOf(this, [ val ], byteOffset)
6291 }
6292
6293 function arrayIndexOf (arr, val, byteOffset) {
6294 var foundIndex = -1
6295 for (var i = 0; byteOffset + i < arr.length; i++) {
6296 if (arr[byteOffset + i] === val[foundIndex === -1 ? 0 : i - foundIndex]) {
6297 if (foundIndex === -1) foundIndex = i
6298 if (i - foundIndex + 1 === val.length) return byteOffset + foundIndex
6299 } else {
6300 foundIndex = -1
6301 }
6302 }
6303 return -1
6304 }
6305
6306 throw new TypeError('val must be string, number or Buffer')
6307}
6308
6309// `get` is deprecated
6310Buffer.prototype.get = function get (offset) {
6311 console.log('.get() is deprecated. Access using array indexes instead.')
6312 return this.readUInt8(offset)
6313}
6314
6315// `set` is deprecated
6316Buffer.prototype.set = function set (v, offset) {
6317 console.log('.set() is deprecated. Access using array indexes instead.')
6318 return this.writeUInt8(v, offset)
6319}
6320
6321function hexWrite (buf, string, offset, length) {
6322 offset = Number(offset) || 0
6323 var remaining = buf.length - offset
6324 if (!length) {
6325 length = remaining
6326 } else {
6327 length = Number(length)
6328 if (length > remaining) {
6329 length = remaining
6330 }
6331 }
6332
6333 // must be an even number of digits
6334 var strLen = string.length
6335 if (strLen % 2 !== 0) throw new Error('Invalid hex string')
6336
6337 if (length > strLen / 2) {
6338 length = strLen / 2
6339 }
6340 for (var i = 0; i < length; i++) {
6341 var parsed = parseInt(string.substr(i * 2, 2), 16)
6342 if (isNaN(parsed)) throw new Error('Invalid hex string')
6343 buf[offset + i] = parsed
6344 }
6345 return i
6346}
6347
6348function utf8Write (buf, string, offset, length) {
6349 return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
6350}
6351
6352function asciiWrite (buf, string, offset, length) {
6353 return blitBuffer(asciiToBytes(string), buf, offset, length)
6354}
6355
6356function binaryWrite (buf, string, offset, length) {
6357 return asciiWrite(buf, string, offset, length)
6358}
6359
6360function base64Write (buf, string, offset, length) {
6361 return blitBuffer(base64ToBytes(string), buf, offset, length)
6362}
6363
6364function ucs2Write (buf, string, offset, length) {
6365 return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
6366}
6367
6368Buffer.prototype.write = function write (string, offset, length, encoding) {
6369 // Buffer#write(string)
6370 if (offset === undefined) {
6371 encoding = 'utf8'
6372 length = this.length
6373 offset = 0
6374 // Buffer#write(string, encoding)
6375 } else if (length === undefined && typeof offset === 'string') {
6376 encoding = offset
6377 length = this.length
6378 offset = 0
6379 // Buffer#write(string, offset[, length][, encoding])
6380 } else if (isFinite(offset)) {
6381 offset = offset | 0
6382 if (isFinite(length)) {
6383 length = length | 0
6384 if (encoding === undefined) encoding = 'utf8'
6385 } else {
6386 encoding = length
6387 length = undefined
6388 }
6389 // legacy write(string, encoding, offset, length) - remove in v0.13
6390 } else {
6391 var swap = encoding
6392 encoding = offset
6393 offset = length | 0
6394 length = swap
6395 }
6396
6397 var remaining = this.length - offset
6398 if (length === undefined || length > remaining) length = remaining
6399
6400 if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
6401 throw new RangeError('attempt to write outside buffer bounds')
6402 }
6403
6404 if (!encoding) encoding = 'utf8'
6405
6406 var loweredCase = false
6407 for (;;) {
6408 switch (encoding) {
6409 case 'hex':
6410 return hexWrite(this, string, offset, length)
6411
6412 case 'utf8':
6413 case 'utf-8':
6414 return utf8Write(this, string, offset, length)
6415
6416 case 'ascii':
6417 return asciiWrite(this, string, offset, length)
6418
6419 case 'binary':
6420 return binaryWrite(this, string, offset, length)
6421
6422 case 'base64':
6423 // Warning: maxLength not taken into account in base64Write
6424 return base64Write(this, string, offset, length)
6425
6426 case 'ucs2':
6427 case 'ucs-2':
6428 case 'utf16le':
6429 case 'utf-16le':
6430 return ucs2Write(this, string, offset, length)
6431
6432 default:
6433 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
6434 encoding = ('' + encoding).toLowerCase()
6435 loweredCase = true
6436 }
6437 }
6438}
6439
6440Buffer.prototype.toJSON = function toJSON () {
6441 return {
6442 type: 'Buffer',
6443 data: Array.prototype.slice.call(this._arr || this, 0)
6444 }
6445}
6446
6447function base64Slice (buf, start, end) {
6448 if (start === 0 && end === buf.length) {
6449 return base64.fromByteArray(buf)
6450 } else {
6451 return base64.fromByteArray(buf.slice(start, end))
6452 }
6453}
6454
6455function utf8Slice (buf, start, end) {
6456 end = Math.min(buf.length, end)
6457 var res = []
6458
6459 var i = start
6460 while (i < end) {
6461 var firstByte = buf[i]
6462 var codePoint = null
6463 var bytesPerSequence = (firstByte > 0xEF) ? 4
6464 : (firstByte > 0xDF) ? 3
6465 : (firstByte > 0xBF) ? 2
6466 : 1
6467
6468 if (i + bytesPerSequence <= end) {
6469 var secondByte, thirdByte, fourthByte, tempCodePoint
6470
6471 switch (bytesPerSequence) {
6472 case 1:
6473 if (firstByte < 0x80) {
6474 codePoint = firstByte
6475 }
6476 break
6477 case 2:
6478 secondByte = buf[i + 1]
6479 if ((secondByte & 0xC0) === 0x80) {
6480 tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
6481 if (tempCodePoint > 0x7F) {
6482 codePoint = tempCodePoint
6483 }
6484 }
6485 break
6486 case 3:
6487 secondByte = buf[i + 1]
6488 thirdByte = buf[i + 2]
6489 if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
6490 tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
6491 if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
6492 codePoint = tempCodePoint
6493 }
6494 }
6495 break
6496 case 4:
6497 secondByte = buf[i + 1]
6498 thirdByte = buf[i + 2]
6499 fourthByte = buf[i + 3]
6500 if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
6501 tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
6502 if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
6503 codePoint = tempCodePoint
6504 }
6505 }
6506 }
6507 }
6508
6509 if (codePoint === null) {
6510 // we did not generate a valid codePoint so insert a
6511 // replacement char (U+FFFD) and advance only 1 byte
6512 codePoint = 0xFFFD
6513 bytesPerSequence = 1
6514 } else if (codePoint > 0xFFFF) {
6515 // encode to utf16 (surrogate pair dance)
6516 codePoint -= 0x10000
6517 res.push(codePoint >>> 10 & 0x3FF | 0xD800)
6518 codePoint = 0xDC00 | codePoint & 0x3FF
6519 }
6520
6521 res.push(codePoint)
6522 i += bytesPerSequence
6523 }
6524
6525 return decodeCodePointsArray(res)
6526}
6527
6528// Based on http://stackoverflow.com/a/22747272/680742, the browser with
6529// the lowest limit is Chrome, with 0x10000 args.
6530// We go 1 magnitude less, for safety
6531var MAX_ARGUMENTS_LENGTH = 0x1000
6532
6533function decodeCodePointsArray (codePoints) {
6534 var len = codePoints.length
6535 if (len <= MAX_ARGUMENTS_LENGTH) {
6536 return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
6537 }
6538
6539 // Decode in chunks to avoid "call stack size exceeded".
6540 var res = ''
6541 var i = 0
6542 while (i < len) {
6543 res += String.fromCharCode.apply(
6544 String,
6545 codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
6546 )
6547 }
6548 return res
6549}
6550
6551function asciiSlice (buf, start, end) {
6552 var ret = ''
6553 end = Math.min(buf.length, end)
6554
6555 for (var i = start; i < end; i++) {
6556 ret += String.fromCharCode(buf[i] & 0x7F)
6557 }
6558 return ret
6559}
6560
6561function binarySlice (buf, start, end) {
6562 var ret = ''
6563 end = Math.min(buf.length, end)
6564
6565 for (var i = start; i < end; i++) {
6566 ret += String.fromCharCode(buf[i])
6567 }
6568 return ret
6569}
6570
6571function hexSlice (buf, start, end) {
6572 var len = buf.length
6573
6574 if (!start || start < 0) start = 0
6575 if (!end || end < 0 || end > len) end = len
6576
6577 var out = ''
6578 for (var i = start; i < end; i++) {
6579 out += toHex(buf[i])
6580 }
6581 return out
6582}
6583
6584function utf16leSlice (buf, start, end) {
6585 var bytes = buf.slice(start, end)
6586 var res = ''
6587 for (var i = 0; i < bytes.length; i += 2) {
6588 res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)
6589 }
6590 return res
6591}
6592
6593Buffer.prototype.slice = function slice (start, end) {
6594 var len = this.length
6595 start = ~~start
6596 end = end === undefined ? len : ~~end
6597
6598 if (start < 0) {
6599 start += len
6600 if (start < 0) start = 0
6601 } else if (start > len) {
6602 start = len
6603 }
6604
6605 if (end < 0) {
6606 end += len
6607 if (end < 0) end = 0
6608 } else if (end > len) {
6609 end = len
6610 }
6611
6612 if (end < start) end = start
6613
6614 var newBuf
6615 if (Buffer.TYPED_ARRAY_SUPPORT) {
6616 newBuf = Buffer._augment(this.subarray(start, end))
6617 } else {
6618 var sliceLen = end - start
6619 newBuf = new Buffer(sliceLen, undefined)
6620 for (var i = 0; i < sliceLen; i++) {
6621 newBuf[i] = this[i + start]
6622 }
6623 }
6624
6625 if (newBuf.length) newBuf.parent = this.parent || this
6626
6627 return newBuf
6628}
6629
6630/*
6631 * Need to make sure that buffer isn't trying to write out of bounds.
6632 */
6633function checkOffset (offset, ext, length) {
6634 if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
6635 if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
6636}
6637
6638Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
6639 offset = offset | 0
6640 byteLength = byteLength | 0
6641 if (!noAssert) checkOffset(offset, byteLength, this.length)
6642
6643 var val = this[offset]
6644 var mul = 1
6645 var i = 0
6646 while (++i < byteLength && (mul *= 0x100)) {
6647 val += this[offset + i] * mul
6648 }
6649
6650 return val
6651}
6652
6653Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
6654 offset = offset | 0
6655 byteLength = byteLength | 0
6656 if (!noAssert) {
6657 checkOffset(offset, byteLength, this.length)
6658 }
6659
6660 var val = this[offset + --byteLength]
6661 var mul = 1
6662 while (byteLength > 0 && (mul *= 0x100)) {
6663 val += this[offset + --byteLength] * mul
6664 }
6665
6666 return val
6667}
6668
6669Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
6670 if (!noAssert) checkOffset(offset, 1, this.length)
6671 return this[offset]
6672}
6673
6674Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
6675 if (!noAssert) checkOffset(offset, 2, this.length)
6676 return this[offset] | (this[offset + 1] << 8)
6677}
6678
6679Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
6680 if (!noAssert) checkOffset(offset, 2, this.length)
6681 return (this[offset] << 8) | this[offset + 1]
6682}
6683
6684Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
6685 if (!noAssert) checkOffset(offset, 4, this.length)
6686
6687 return ((this[offset]) |
6688 (this[offset + 1] << 8) |
6689 (this[offset + 2] << 16)) +
6690 (this[offset + 3] * 0x1000000)
6691}
6692
6693Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
6694 if (!noAssert) checkOffset(offset, 4, this.length)
6695
6696 return (this[offset] * 0x1000000) +
6697 ((this[offset + 1] << 16) |
6698 (this[offset + 2] << 8) |
6699 this[offset + 3])
6700}
6701
6702Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
6703 offset = offset | 0
6704 byteLength = byteLength | 0
6705 if (!noAssert) checkOffset(offset, byteLength, this.length)
6706
6707 var val = this[offset]
6708 var mul = 1
6709 var i = 0
6710 while (++i < byteLength && (mul *= 0x100)) {
6711 val += this[offset + i] * mul
6712 }
6713 mul *= 0x80
6714
6715 if (val >= mul) val -= Math.pow(2, 8 * byteLength)
6716
6717 return val
6718}
6719
6720Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
6721 offset = offset | 0
6722 byteLength = byteLength | 0
6723 if (!noAssert) checkOffset(offset, byteLength, this.length)
6724
6725 var i = byteLength
6726 var mul = 1
6727 var val = this[offset + --i]
6728 while (i > 0 && (mul *= 0x100)) {
6729 val += this[offset + --i] * mul
6730 }
6731 mul *= 0x80
6732
6733 if (val >= mul) val -= Math.pow(2, 8 * byteLength)
6734
6735 return val
6736}
6737
6738Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
6739 if (!noAssert) checkOffset(offset, 1, this.length)
6740 if (!(this[offset] & 0x80)) return (this[offset])
6741 return ((0xff - this[offset] + 1) * -1)
6742}
6743
6744Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
6745 if (!noAssert) checkOffset(offset, 2, this.length)
6746 var val = this[offset] | (this[offset + 1] << 8)
6747 return (val & 0x8000) ? val | 0xFFFF0000 : val
6748}
6749
6750Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
6751 if (!noAssert) checkOffset(offset, 2, this.length)
6752 var val = this[offset + 1] | (this[offset] << 8)
6753 return (val & 0x8000) ? val | 0xFFFF0000 : val
6754}
6755
6756Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
6757 if (!noAssert) checkOffset(offset, 4, this.length)
6758
6759 return (this[offset]) |
6760 (this[offset + 1] << 8) |
6761 (this[offset + 2] << 16) |
6762 (this[offset + 3] << 24)
6763}
6764
6765Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
6766 if (!noAssert) checkOffset(offset, 4, this.length)
6767
6768 return (this[offset] << 24) |
6769 (this[offset + 1] << 16) |
6770 (this[offset + 2] << 8) |
6771 (this[offset + 3])
6772}
6773
6774Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
6775 if (!noAssert) checkOffset(offset, 4, this.length)
6776 return ieee754.read(this, offset, true, 23, 4)
6777}
6778
6779Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
6780 if (!noAssert) checkOffset(offset, 4, this.length)
6781 return ieee754.read(this, offset, false, 23, 4)
6782}
6783
6784Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
6785 if (!noAssert) checkOffset(offset, 8, this.length)
6786 return ieee754.read(this, offset, true, 52, 8)
6787}
6788
6789Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
6790 if (!noAssert) checkOffset(offset, 8, this.length)
6791 return ieee754.read(this, offset, false, 52, 8)
6792}
6793
6794function checkInt (buf, value, offset, ext, max, min) {
6795 if (!Buffer.isBuffer(buf)) throw new TypeError('buffer must be a Buffer instance')
6796 if (value > max || value < min) throw new RangeError('value is out of bounds')
6797 if (offset + ext > buf.length) throw new RangeError('index out of range')
6798}
6799
6800Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
6801 value = +value
6802 offset = offset | 0
6803 byteLength = byteLength | 0
6804 if (!noAssert) checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0)
6805
6806 var mul = 1
6807 var i = 0
6808 this[offset] = value & 0xFF
6809 while (++i < byteLength && (mul *= 0x100)) {
6810 this[offset + i] = (value / mul) & 0xFF
6811 }
6812
6813 return offset + byteLength
6814}
6815
6816Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
6817 value = +value
6818 offset = offset | 0
6819 byteLength = byteLength | 0
6820 if (!noAssert) checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0)
6821
6822 var i = byteLength - 1
6823 var mul = 1
6824 this[offset + i] = value & 0xFF
6825 while (--i >= 0 && (mul *= 0x100)) {
6826 this[offset + i] = (value / mul) & 0xFF
6827 }
6828
6829 return offset + byteLength
6830}
6831
6832Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
6833 value = +value
6834 offset = offset | 0
6835 if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
6836 if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
6837 this[offset] = (value & 0xff)
6838 return offset + 1
6839}
6840
6841function objectWriteUInt16 (buf, value, offset, littleEndian) {
6842 if (value < 0) value = 0xffff + value + 1
6843 for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; i++) {
6844 buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
6845 (littleEndian ? i : 1 - i) * 8
6846 }
6847}
6848
6849Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
6850 value = +value
6851 offset = offset | 0
6852 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
6853 if (Buffer.TYPED_ARRAY_SUPPORT) {
6854 this[offset] = (value & 0xff)
6855 this[offset + 1] = (value >>> 8)
6856 } else {
6857 objectWriteUInt16(this, value, offset, true)
6858 }
6859 return offset + 2
6860}
6861
6862Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
6863 value = +value
6864 offset = offset | 0
6865 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
6866 if (Buffer.TYPED_ARRAY_SUPPORT) {
6867 this[offset] = (value >>> 8)
6868 this[offset + 1] = (value & 0xff)
6869 } else {
6870 objectWriteUInt16(this, value, offset, false)
6871 }
6872 return offset + 2
6873}
6874
6875function objectWriteUInt32 (buf, value, offset, littleEndian) {
6876 if (value < 0) value = 0xffffffff + value + 1
6877 for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; i++) {
6878 buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff
6879 }
6880}
6881
6882Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
6883 value = +value
6884 offset = offset | 0
6885 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
6886 if (Buffer.TYPED_ARRAY_SUPPORT) {
6887 this[offset + 3] = (value >>> 24)
6888 this[offset + 2] = (value >>> 16)
6889 this[offset + 1] = (value >>> 8)
6890 this[offset] = (value & 0xff)
6891 } else {
6892 objectWriteUInt32(this, value, offset, true)
6893 }
6894 return offset + 4
6895}
6896
6897Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
6898 value = +value
6899 offset = offset | 0
6900 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
6901 if (Buffer.TYPED_ARRAY_SUPPORT) {
6902 this[offset] = (value >>> 24)
6903 this[offset + 1] = (value >>> 16)
6904 this[offset + 2] = (value >>> 8)
6905 this[offset + 3] = (value & 0xff)
6906 } else {
6907 objectWriteUInt32(this, value, offset, false)
6908 }
6909 return offset + 4
6910}
6911
6912Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
6913 value = +value
6914 offset = offset | 0
6915 if (!noAssert) {
6916 var limit = Math.pow(2, 8 * byteLength - 1)
6917
6918 checkInt(this, value, offset, byteLength, limit - 1, -limit)
6919 }
6920
6921 var i = 0
6922 var mul = 1
6923 var sub = value < 0 ? 1 : 0
6924 this[offset] = value & 0xFF
6925 while (++i < byteLength && (mul *= 0x100)) {
6926 this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
6927 }
6928
6929 return offset + byteLength
6930}
6931
6932Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
6933 value = +value
6934 offset = offset | 0
6935 if (!noAssert) {
6936 var limit = Math.pow(2, 8 * byteLength - 1)
6937
6938 checkInt(this, value, offset, byteLength, limit - 1, -limit)
6939 }
6940
6941 var i = byteLength - 1
6942 var mul = 1
6943 var sub = value < 0 ? 1 : 0
6944 this[offset + i] = value & 0xFF
6945 while (--i >= 0 && (mul *= 0x100)) {
6946 this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
6947 }
6948
6949 return offset + byteLength
6950}
6951
6952Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
6953 value = +value
6954 offset = offset | 0
6955 if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
6956 if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
6957 if (value < 0) value = 0xff + value + 1
6958 this[offset] = (value & 0xff)
6959 return offset + 1
6960}
6961
6962Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
6963 value = +value
6964 offset = offset | 0
6965 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
6966 if (Buffer.TYPED_ARRAY_SUPPORT) {
6967 this[offset] = (value & 0xff)
6968 this[offset + 1] = (value >>> 8)
6969 } else {
6970 objectWriteUInt16(this, value, offset, true)
6971 }
6972 return offset + 2
6973}
6974
6975Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
6976 value = +value
6977 offset = offset | 0
6978 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
6979 if (Buffer.TYPED_ARRAY_SUPPORT) {
6980 this[offset] = (value >>> 8)
6981 this[offset + 1] = (value & 0xff)
6982 } else {
6983 objectWriteUInt16(this, value, offset, false)
6984 }
6985 return offset + 2
6986}
6987
6988Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
6989 value = +value
6990 offset = offset | 0
6991 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
6992 if (Buffer.TYPED_ARRAY_SUPPORT) {
6993 this[offset] = (value & 0xff)
6994 this[offset + 1] = (value >>> 8)
6995 this[offset + 2] = (value >>> 16)
6996 this[offset + 3] = (value >>> 24)
6997 } else {
6998 objectWriteUInt32(this, value, offset, true)
6999 }
7000 return offset + 4
7001}
7002
7003Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
7004 value = +value
7005 offset = offset | 0
7006 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
7007 if (value < 0) value = 0xffffffff + value + 1
7008 if (Buffer.TYPED_ARRAY_SUPPORT) {
7009 this[offset] = (value >>> 24)
7010 this[offset + 1] = (value >>> 16)
7011 this[offset + 2] = (value >>> 8)
7012 this[offset + 3] = (value & 0xff)
7013 } else {
7014 objectWriteUInt32(this, value, offset, false)
7015 }
7016 return offset + 4
7017}
7018
7019function checkIEEE754 (buf, value, offset, ext, max, min) {
7020 if (value > max || value < min) throw new RangeError('value is out of bounds')
7021 if (offset + ext > buf.length) throw new RangeError('index out of range')
7022 if (offset < 0) throw new RangeError('index out of range')
7023}
7024
7025function writeFloat (buf, value, offset, littleEndian, noAssert) {
7026 if (!noAssert) {
7027 checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
7028 }
7029 ieee754.write(buf, value, offset, littleEndian, 23, 4)
7030 return offset + 4
7031}
7032
7033Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
7034 return writeFloat(this, value, offset, true, noAssert)
7035}
7036
7037Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
7038 return writeFloat(this, value, offset, false, noAssert)
7039}
7040
7041function writeDouble (buf, value, offset, littleEndian, noAssert) {
7042 if (!noAssert) {
7043 checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
7044 }
7045 ieee754.write(buf, value, offset, littleEndian, 52, 8)
7046 return offset + 8
7047}
7048
7049Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
7050 return writeDouble(this, value, offset, true, noAssert)
7051}
7052
7053Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
7054 return writeDouble(this, value, offset, false, noAssert)
7055}
7056
7057// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
7058Buffer.prototype.copy = function copy (target, targetStart, start, end) {
7059 if (!start) start = 0
7060 if (!end && end !== 0) end = this.length
7061 if (targetStart >= target.length) targetStart = target.length
7062 if (!targetStart) targetStart = 0
7063 if (end > 0 && end < start) end = start
7064
7065 // Copy 0 bytes; we're done
7066 if (end === start) return 0
7067 if (target.length === 0 || this.length === 0) return 0
7068
7069 // Fatal error conditions
7070 if (targetStart < 0) {
7071 throw new RangeError('targetStart out of bounds')
7072 }
7073 if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
7074 if (end < 0) throw new RangeError('sourceEnd out of bounds')
7075
7076 // Are we oob?
7077 if (end > this.length) end = this.length
7078 if (target.length - targetStart < end - start) {
7079 end = target.length - targetStart + start
7080 }
7081
7082 var len = end - start
7083 var i
7084
7085 if (this === target && start < targetStart && targetStart < end) {
7086 // descending copy from end
7087 for (i = len - 1; i >= 0; i--) {
7088 target[i + targetStart] = this[i + start]
7089 }
7090 } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
7091 // ascending copy from start
7092 for (i = 0; i < len; i++) {
7093 target[i + targetStart] = this[i + start]
7094 }
7095 } else {
7096 target._set(this.subarray(start, start + len), targetStart)
7097 }
7098
7099 return len
7100}
7101
7102// fill(value, start=0, end=buffer.length)
7103Buffer.prototype.fill = function fill (value, start, end) {
7104 if (!value) value = 0
7105 if (!start) start = 0
7106 if (!end) end = this.length
7107
7108 if (end < start) throw new RangeError('end < start')
7109
7110 // Fill 0 bytes; we're done
7111 if (end === start) return
7112 if (this.length === 0) return
7113
7114 if (start < 0 || start >= this.length) throw new RangeError('start out of bounds')
7115 if (end < 0 || end > this.length) throw new RangeError('end out of bounds')
7116
7117 var i
7118 if (typeof value === 'number') {
7119 for (i = start; i < end; i++) {
7120 this[i] = value
7121 }
7122 } else {
7123 var bytes = utf8ToBytes(value.toString())
7124 var len = bytes.length
7125 for (i = start; i < end; i++) {
7126 this[i] = bytes[i % len]
7127 }
7128 }
7129
7130 return this
7131}
7132
7133/**
7134 * Creates a new `ArrayBuffer` with the *copied* memory of the buffer instance.
7135 * Added in Node 0.12. Only available in browsers that support ArrayBuffer.
7136 */
7137Buffer.prototype.toArrayBuffer = function toArrayBuffer () {
7138 if (typeof Uint8Array !== 'undefined') {
7139 if (Buffer.TYPED_ARRAY_SUPPORT) {
7140 return (new Buffer(this)).buffer
7141 } else {
7142 var buf = new Uint8Array(this.length)
7143 for (var i = 0, len = buf.length; i < len; i += 1) {
7144 buf[i] = this[i]
7145 }
7146 return buf.buffer
7147 }
7148 } else {
7149 throw new TypeError('Buffer.toArrayBuffer not supported in this browser')
7150 }
7151}
7152
7153// HELPER FUNCTIONS
7154// ================
7155
7156var BP = Buffer.prototype
7157
7158/**
7159 * Augment a Uint8Array *instance* (not the Uint8Array class!) with Buffer methods
7160 */
7161Buffer._augment = function _augment (arr) {
7162 arr.constructor = Buffer
7163 arr._isBuffer = true
7164
7165 // save reference to original Uint8Array set method before overwriting
7166 arr._set = arr.set
7167
7168 // deprecated
7169 arr.get = BP.get
7170 arr.set = BP.set
7171
7172 arr.write = BP.write
7173 arr.toString = BP.toString
7174 arr.toLocaleString = BP.toString
7175 arr.toJSON = BP.toJSON
7176 arr.equals = BP.equals
7177 arr.compare = BP.compare
7178 arr.indexOf = BP.indexOf
7179 arr.copy = BP.copy
7180 arr.slice = BP.slice
7181 arr.readUIntLE = BP.readUIntLE
7182 arr.readUIntBE = BP.readUIntBE
7183 arr.readUInt8 = BP.readUInt8
7184 arr.readUInt16LE = BP.readUInt16LE
7185 arr.readUInt16BE = BP.readUInt16BE
7186 arr.readUInt32LE = BP.readUInt32LE
7187 arr.readUInt32BE = BP.readUInt32BE
7188 arr.readIntLE = BP.readIntLE
7189 arr.readIntBE = BP.readIntBE
7190 arr.readInt8 = BP.readInt8
7191 arr.readInt16LE = BP.readInt16LE
7192 arr.readInt16BE = BP.readInt16BE
7193 arr.readInt32LE = BP.readInt32LE
7194 arr.readInt32BE = BP.readInt32BE
7195 arr.readFloatLE = BP.readFloatLE
7196 arr.readFloatBE = BP.readFloatBE
7197 arr.readDoubleLE = BP.readDoubleLE
7198 arr.readDoubleBE = BP.readDoubleBE
7199 arr.writeUInt8 = BP.writeUInt8
7200 arr.writeUIntLE = BP.writeUIntLE
7201 arr.writeUIntBE = BP.writeUIntBE
7202 arr.writeUInt16LE = BP.writeUInt16LE
7203 arr.writeUInt16BE = BP.writeUInt16BE
7204 arr.writeUInt32LE = BP.writeUInt32LE
7205 arr.writeUInt32BE = BP.writeUInt32BE
7206 arr.writeIntLE = BP.writeIntLE
7207 arr.writeIntBE = BP.writeIntBE
7208 arr.writeInt8 = BP.writeInt8
7209 arr.writeInt16LE = BP.writeInt16LE
7210 arr.writeInt16BE = BP.writeInt16BE
7211 arr.writeInt32LE = BP.writeInt32LE
7212 arr.writeInt32BE = BP.writeInt32BE
7213 arr.writeFloatLE = BP.writeFloatLE
7214 arr.writeFloatBE = BP.writeFloatBE
7215 arr.writeDoubleLE = BP.writeDoubleLE
7216 arr.writeDoubleBE = BP.writeDoubleBE
7217 arr.fill = BP.fill
7218 arr.inspect = BP.inspect
7219 arr.toArrayBuffer = BP.toArrayBuffer
7220
7221 return arr
7222}
7223
7224var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g
7225
7226function base64clean (str) {
7227 // Node strips out invalid characters like \n and \t from the string, base64-js does not
7228 str = stringtrim(str).replace(INVALID_BASE64_RE, '')
7229 // Node converts strings with length < 2 to ''
7230 if (str.length < 2) return ''
7231 // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
7232 while (str.length % 4 !== 0) {
7233 str = str + '='
7234 }
7235 return str
7236}
7237
7238function stringtrim (str) {
7239 if (str.trim) return str.trim()
7240 return str.replace(/^\s+|\s+$/g, '')
7241}
7242
7243function toHex (n) {
7244 if (n < 16) return '0' + n.toString(16)
7245 return n.toString(16)
7246}
7247
7248function utf8ToBytes (string, units) {
7249 units = units || Infinity
7250 var codePoint
7251 var length = string.length
7252 var leadSurrogate = null
7253 var bytes = []
7254
7255 for (var i = 0; i < length; i++) {
7256 codePoint = string.charCodeAt(i)
7257
7258 // is surrogate component
7259 if (codePoint > 0xD7FF && codePoint < 0xE000) {
7260 // last char was a lead
7261 if (!leadSurrogate) {
7262 // no lead yet
7263 if (codePoint > 0xDBFF) {
7264 // unexpected trail
7265 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
7266 continue
7267 } else if (i + 1 === length) {
7268 // unpaired lead
7269 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
7270 continue
7271 }
7272
7273 // valid lead
7274 leadSurrogate = codePoint
7275
7276 continue
7277 }
7278
7279 // 2 leads in a row
7280 if (codePoint < 0xDC00) {
7281 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
7282 leadSurrogate = codePoint
7283 continue
7284 }
7285
7286 // valid surrogate pair
7287 codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
7288 } else if (leadSurrogate) {
7289 // valid bmp char, but last char was a lead
7290 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
7291 }
7292
7293 leadSurrogate = null
7294
7295 // encode utf8
7296 if (codePoint < 0x80) {
7297 if ((units -= 1) < 0) break
7298 bytes.push(codePoint)
7299 } else if (codePoint < 0x800) {
7300 if ((units -= 2) < 0) break
7301 bytes.push(
7302 codePoint >> 0x6 | 0xC0,
7303 codePoint & 0x3F | 0x80
7304 )
7305 } else if (codePoint < 0x10000) {
7306 if ((units -= 3) < 0) break
7307 bytes.push(
7308 codePoint >> 0xC | 0xE0,
7309 codePoint >> 0x6 & 0x3F | 0x80,
7310 codePoint & 0x3F | 0x80
7311 )
7312 } else if (codePoint < 0x110000) {
7313 if ((units -= 4) < 0) break
7314 bytes.push(
7315 codePoint >> 0x12 | 0xF0,
7316 codePoint >> 0xC & 0x3F | 0x80,
7317 codePoint >> 0x6 & 0x3F | 0x80,
7318 codePoint & 0x3F | 0x80
7319 )
7320 } else {
7321 throw new Error('Invalid code point')
7322 }
7323 }
7324
7325 return bytes
7326}
7327
7328function asciiToBytes (str) {
7329 var byteArray = []
7330 for (var i = 0; i < str.length; i++) {
7331 // Node's code seems to be doing this and not & 0x7F..
7332 byteArray.push(str.charCodeAt(i) & 0xFF)
7333 }
7334 return byteArray
7335}
7336
7337function utf16leToBytes (str, units) {
7338 var c, hi, lo
7339 var byteArray = []
7340 for (var i = 0; i < str.length; i++) {
7341 if ((units -= 2) < 0) break
7342
7343 c = str.charCodeAt(i)
7344 hi = c >> 8
7345 lo = c % 256
7346 byteArray.push(lo)
7347 byteArray.push(hi)
7348 }
7349
7350 return byteArray
7351}
7352
7353function base64ToBytes (str) {
7354 return base64.toByteArray(base64clean(str))
7355}
7356
7357function blitBuffer (src, dst, offset, length) {
7358 for (var i = 0; i < length; i++) {
7359 if ((i + offset >= dst.length) || (i >= src.length)) break
7360 dst[i + offset] = src[i]
7361 }
7362 return i
7363}
7364
7365}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
7366},{"base64-js":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/browserify/node_modules/buffer/node_modules/base64-js/lib/b64.js","ieee754":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/browserify/node_modules/buffer/node_modules/ieee754/index.js","isarray":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/browserify/node_modules/buffer/node_modules/isarray/index.js"}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/browserify/node_modules/buffer/node_modules/base64-js/lib/b64.js":[function(require,module,exports){
7367var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
7368
7369;(function (exports) {
7370 'use strict';
7371
7372 var Arr = (typeof Uint8Array !== 'undefined')
7373 ? Uint8Array
7374 : Array
7375
7376 var PLUS = '+'.charCodeAt(0)
7377 var SLASH = '/'.charCodeAt(0)
7378 var NUMBER = '0'.charCodeAt(0)
7379 var LOWER = 'a'.charCodeAt(0)
7380 var UPPER = 'A'.charCodeAt(0)
7381 var PLUS_URL_SAFE = '-'.charCodeAt(0)
7382 var SLASH_URL_SAFE = '_'.charCodeAt(0)
7383
7384 function decode (elt) {
7385 var code = elt.charCodeAt(0)
7386 if (code === PLUS ||
7387 code === PLUS_URL_SAFE)
7388 return 62 // '+'
7389 if (code === SLASH ||
7390 code === SLASH_URL_SAFE)
7391 return 63 // '/'
7392 if (code < NUMBER)
7393 return -1 //no match
7394 if (code < NUMBER + 10)
7395 return code - NUMBER + 26 + 26
7396 if (code < UPPER + 26)
7397 return code - UPPER
7398 if (code < LOWER + 26)
7399 return code - LOWER + 26
7400 }
7401
7402 function b64ToByteArray (b64) {
7403 var i, j, l, tmp, placeHolders, arr
7404
7405 if (b64.length % 4 > 0) {
7406 throw new Error('Invalid string. Length must be a multiple of 4')
7407 }
7408
7409 // the number of equal signs (place holders)
7410 // if there are two placeholders, than the two characters before it
7411 // represent one byte
7412 // if there is only one, then the three characters before it represent 2 bytes
7413 // this is just a cheap hack to not do indexOf twice
7414 var len = b64.length
7415 placeHolders = '=' === b64.charAt(len - 2) ? 2 : '=' === b64.charAt(len - 1) ? 1 : 0
7416
7417 // base64 is 4/3 + up to two characters of the original data
7418 arr = new Arr(b64.length * 3 / 4 - placeHolders)
7419
7420 // if there are placeholders, only get up to the last complete 4 chars
7421 l = placeHolders > 0 ? b64.length - 4 : b64.length
7422
7423 var L = 0
7424
7425 function push (v) {
7426 arr[L++] = v
7427 }
7428
7429 for (i = 0, j = 0; i < l; i += 4, j += 3) {
7430 tmp = (decode(b64.charAt(i)) << 18) | (decode(b64.charAt(i + 1)) << 12) | (decode(b64.charAt(i + 2)) << 6) | decode(b64.charAt(i + 3))
7431 push((tmp & 0xFF0000) >> 16)
7432 push((tmp & 0xFF00) >> 8)
7433 push(tmp & 0xFF)
7434 }
7435
7436 if (placeHolders === 2) {
7437 tmp = (decode(b64.charAt(i)) << 2) | (decode(b64.charAt(i + 1)) >> 4)
7438 push(tmp & 0xFF)
7439 } else if (placeHolders === 1) {
7440 tmp = (decode(b64.charAt(i)) << 10) | (decode(b64.charAt(i + 1)) << 4) | (decode(b64.charAt(i + 2)) >> 2)
7441 push((tmp >> 8) & 0xFF)
7442 push(tmp & 0xFF)
7443 }
7444
7445 return arr
7446 }
7447
7448 function uint8ToBase64 (uint8) {
7449 var i,
7450 extraBytes = uint8.length % 3, // if we have 1 byte left, pad 2 bytes
7451 output = "",
7452 temp, length
7453
7454 function encode (num) {
7455 return lookup.charAt(num)
7456 }
7457
7458 function tripletToBase64 (num) {
7459 return encode(num >> 18 & 0x3F) + encode(num >> 12 & 0x3F) + encode(num >> 6 & 0x3F) + encode(num & 0x3F)
7460 }
7461
7462 // go through the array every three bytes, we'll deal with trailing stuff later
7463 for (i = 0, length = uint8.length - extraBytes; i < length; i += 3) {
7464 temp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])
7465 output += tripletToBase64(temp)
7466 }
7467
7468 // pad the end with zeros, but make sure to not forget the extra bytes
7469 switch (extraBytes) {
7470 case 1:
7471 temp = uint8[uint8.length - 1]
7472 output += encode(temp >> 2)
7473 output += encode((temp << 4) & 0x3F)
7474 output += '=='
7475 break
7476 case 2:
7477 temp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1])
7478 output += encode(temp >> 10)
7479 output += encode((temp >> 4) & 0x3F)
7480 output += encode((temp << 2) & 0x3F)
7481 output += '='
7482 break
7483 }
7484
7485 return output
7486 }
7487
7488 exports.toByteArray = b64ToByteArray
7489 exports.fromByteArray = uint8ToBase64
7490}(typeof exports === 'undefined' ? (this.base64js = {}) : exports))
7491
7492},{}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/browserify/node_modules/buffer/node_modules/ieee754/index.js":[function(require,module,exports){
7493exports.read = function (buffer, offset, isLE, mLen, nBytes) {
7494 var e, m
7495 var eLen = nBytes * 8 - mLen - 1
7496 var eMax = (1 << eLen) - 1
7497 var eBias = eMax >> 1
7498 var nBits = -7
7499 var i = isLE ? (nBytes - 1) : 0
7500 var d = isLE ? -1 : 1
7501 var s = buffer[offset + i]
7502
7503 i += d
7504
7505 e = s & ((1 << (-nBits)) - 1)
7506 s >>= (-nBits)
7507 nBits += eLen
7508 for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
7509
7510 m = e & ((1 << (-nBits)) - 1)
7511 e >>= (-nBits)
7512 nBits += mLen
7513 for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
7514
7515 if (e === 0) {
7516 e = 1 - eBias
7517 } else if (e === eMax) {
7518 return m ? NaN : ((s ? -1 : 1) * Infinity)
7519 } else {
7520 m = m + Math.pow(2, mLen)
7521 e = e - eBias
7522 }
7523 return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
7524}
7525
7526exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
7527 var e, m, c
7528 var eLen = nBytes * 8 - mLen - 1
7529 var eMax = (1 << eLen) - 1
7530 var eBias = eMax >> 1
7531 var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
7532 var i = isLE ? 0 : (nBytes - 1)
7533 var d = isLE ? 1 : -1
7534 var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
7535
7536 value = Math.abs(value)
7537
7538 if (isNaN(value) || value === Infinity) {
7539 m = isNaN(value) ? 1 : 0
7540 e = eMax
7541 } else {
7542 e = Math.floor(Math.log(value) / Math.LN2)
7543 if (value * (c = Math.pow(2, -e)) < 1) {
7544 e--
7545 c *= 2
7546 }
7547 if (e + eBias >= 1) {
7548 value += rt / c
7549 } else {
7550 value += rt * Math.pow(2, 1 - eBias)
7551 }
7552 if (value * c >= 2) {
7553 e++
7554 c /= 2
7555 }
7556
7557 if (e + eBias >= eMax) {
7558 m = 0
7559 e = eMax
7560 } else if (e + eBias >= 1) {
7561 m = (value * c - 1) * Math.pow(2, mLen)
7562 e = e + eBias
7563 } else {
7564 m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
7565 e = 0
7566 }
7567 }
7568
7569 for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
7570
7571 e = (e << mLen) | m
7572 eLen += mLen
7573 for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
7574
7575 buffer[offset + i - d] |= s * 128
7576}
7577
7578},{}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/browserify/node_modules/buffer/node_modules/isarray/index.js":[function(require,module,exports){
7579var toString = {}.toString;
7580
7581module.exports = Array.isArray || function (arr) {
7582 return toString.call(arr) == '[object Array]';
7583};
7584
7585},{}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/browserify/node_modules/events/events.js":[function(require,module,exports){
7586// Copyright Joyent, Inc. and other Node contributors.
7587//
7588// Permission is hereby granted, free of charge, to any person obtaining a
7589// copy of this software and associated documentation files (the
7590// "Software"), to deal in the Software without restriction, including
7591// without limitation the rights to use, copy, modify, merge, publish,
7592// distribute, sublicense, and/or sell copies of the Software, and to permit
7593// persons to whom the Software is furnished to do so, subject to the
7594// following conditions:
7595//
7596// The above copyright notice and this permission notice shall be included
7597// in all copies or substantial portions of the Software.
7598//
7599// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
7600// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
7601// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
7602// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
7603// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
7604// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
7605// USE OR OTHER DEALINGS IN THE SOFTWARE.
7606
7607function EventEmitter() {
7608 this._events = this._events || {};
7609 this._maxListeners = this._maxListeners || undefined;
7610}
7611module.exports = EventEmitter;
7612
7613// Backwards-compat with node 0.10.x
7614EventEmitter.EventEmitter = EventEmitter;
7615
7616EventEmitter.prototype._events = undefined;
7617EventEmitter.prototype._maxListeners = undefined;
7618
7619// By default EventEmitters will print a warning if more than 10 listeners are
7620// added to it. This is a useful default which helps finding memory leaks.
7621EventEmitter.defaultMaxListeners = 10;
7622
7623// Obviously not all Emitters should be limited to 10. This function allows
7624// that to be increased. Set to zero for unlimited.
7625EventEmitter.prototype.setMaxListeners = function(n) {
7626 if (!isNumber(n) || n < 0 || isNaN(n))
7627 throw TypeError('n must be a positive number');
7628 this._maxListeners = n;
7629 return this;
7630};
7631
7632EventEmitter.prototype.emit = function(type) {
7633 var er, handler, len, args, i, listeners;
7634
7635 if (!this._events)
7636 this._events = {};
7637
7638 // If there is no 'error' event listener then throw.
7639 if (type === 'error') {
7640 if (!this._events.error ||
7641 (isObject(this._events.error) && !this._events.error.length)) {
7642 er = arguments[1];
7643 if (er instanceof Error) {
7644 throw er; // Unhandled 'error' event
7645 }
7646 throw TypeError('Uncaught, unspecified "error" event.');
7647 }
7648 }
7649
7650 handler = this._events[type];
7651
7652 if (isUndefined(handler))
7653 return false;
7654
7655 if (isFunction(handler)) {
7656 switch (arguments.length) {
7657 // fast cases
7658 case 1:
7659 handler.call(this);
7660 break;
7661 case 2:
7662 handler.call(this, arguments[1]);
7663 break;
7664 case 3:
7665 handler.call(this, arguments[1], arguments[2]);
7666 break;
7667 // slower
7668 default:
7669 len = arguments.length;
7670 args = new Array(len - 1);
7671 for (i = 1; i < len; i++)
7672 args[i - 1] = arguments[i];
7673 handler.apply(this, args);
7674 }
7675 } else if (isObject(handler)) {
7676 len = arguments.length;
7677 args = new Array(len - 1);
7678 for (i = 1; i < len; i++)
7679 args[i - 1] = arguments[i];
7680
7681 listeners = handler.slice();
7682 len = listeners.length;
7683 for (i = 0; i < len; i++)
7684 listeners[i].apply(this, args);
7685 }
7686
7687 return true;
7688};
7689
7690EventEmitter.prototype.addListener = function(type, listener) {
7691 var m;
7692
7693 if (!isFunction(listener))
7694 throw TypeError('listener must be a function');
7695
7696 if (!this._events)
7697 this._events = {};
7698
7699 // To avoid recursion in the case that type === "newListener"! Before
7700 // adding it to the listeners, first emit "newListener".
7701 if (this._events.newListener)
7702 this.emit('newListener', type,
7703 isFunction(listener.listener) ?
7704 listener.listener : listener);
7705
7706 if (!this._events[type])
7707 // Optimize the case of one listener. Don't need the extra array object.
7708 this._events[type] = listener;
7709 else if (isObject(this._events[type]))
7710 // If we've already got an array, just append.
7711 this._events[type].push(listener);
7712 else
7713 // Adding the second element, need to change to array.
7714 this._events[type] = [this._events[type], listener];
7715
7716 // Check for listener leak
7717 if (isObject(this._events[type]) && !this._events[type].warned) {
7718 var m;
7719 if (!isUndefined(this._maxListeners)) {
7720 m = this._maxListeners;
7721 } else {
7722 m = EventEmitter.defaultMaxListeners;
7723 }
7724
7725 if (m && m > 0 && this._events[type].length > m) {
7726 this._events[type].warned = true;
7727 console.error('(node) warning: possible EventEmitter memory ' +
7728 'leak detected. %d listeners added. ' +
7729 'Use emitter.setMaxListeners() to increase limit.',
7730 this._events[type].length);
7731 if (typeof console.trace === 'function') {
7732 // not supported in IE 10
7733 console.trace();
7734 }
7735 }
7736 }
7737
7738 return this;
7739};
7740
7741EventEmitter.prototype.on = EventEmitter.prototype.addListener;
7742
7743EventEmitter.prototype.once = function(type, listener) {
7744 if (!isFunction(listener))
7745 throw TypeError('listener must be a function');
7746
7747 var fired = false;
7748
7749 function g() {
7750 this.removeListener(type, g);
7751
7752 if (!fired) {
7753 fired = true;
7754 listener.apply(this, arguments);
7755 }
7756 }
7757
7758 g.listener = listener;
7759 this.on(type, g);
7760
7761 return this;
7762};
7763
7764// emits a 'removeListener' event iff the listener was removed
7765EventEmitter.prototype.removeListener = function(type, listener) {
7766 var list, position, length, i;
7767
7768 if (!isFunction(listener))
7769 throw TypeError('listener must be a function');
7770
7771 if (!this._events || !this._events[type])
7772 return this;
7773
7774 list = this._events[type];
7775 length = list.length;
7776 position = -1;
7777
7778 if (list === listener ||
7779 (isFunction(list.listener) && list.listener === listener)) {
7780 delete this._events[type];
7781 if (this._events.removeListener)
7782 this.emit('removeListener', type, listener);
7783
7784 } else if (isObject(list)) {
7785 for (i = length; i-- > 0;) {
7786 if (list[i] === listener ||
7787 (list[i].listener && list[i].listener === listener)) {
7788 position = i;
7789 break;
7790 }
7791 }
7792
7793 if (position < 0)
7794 return this;
7795
7796 if (list.length === 1) {
7797 list.length = 0;
7798 delete this._events[type];
7799 } else {
7800 list.splice(position, 1);
7801 }
7802
7803 if (this._events.removeListener)
7804 this.emit('removeListener', type, listener);
7805 }
7806
7807 return this;
7808};
7809
7810EventEmitter.prototype.removeAllListeners = function(type) {
7811 var key, listeners;
7812
7813 if (!this._events)
7814 return this;
7815
7816 // not listening for removeListener, no need to emit
7817 if (!this._events.removeListener) {
7818 if (arguments.length === 0)
7819 this._events = {};
7820 else if (this._events[type])
7821 delete this._events[type];
7822 return this;
7823 }
7824
7825 // emit removeListener for all listeners on all events
7826 if (arguments.length === 0) {
7827 for (key in this._events) {
7828 if (key === 'removeListener') continue;
7829 this.removeAllListeners(key);
7830 }
7831 this.removeAllListeners('removeListener');
7832 this._events = {};
7833 return this;
7834 }
7835
7836 listeners = this._events[type];
7837
7838 if (isFunction(listeners)) {
7839 this.removeListener(type, listeners);
7840 } else {
7841 // LIFO order
7842 while (listeners.length)
7843 this.removeListener(type, listeners[listeners.length - 1]);
7844 }
7845 delete this._events[type];
7846
7847 return this;
7848};
7849
7850EventEmitter.prototype.listeners = function(type) {
7851 var ret;
7852 if (!this._events || !this._events[type])
7853 ret = [];
7854 else if (isFunction(this._events[type]))
7855 ret = [this._events[type]];
7856 else
7857 ret = this._events[type].slice();
7858 return ret;
7859};
7860
7861EventEmitter.listenerCount = function(emitter, type) {
7862 var ret;
7863 if (!emitter._events || !emitter._events[type])
7864 ret = 0;
7865 else if (isFunction(emitter._events[type]))
7866 ret = 1;
7867 else
7868 ret = emitter._events[type].length;
7869 return ret;
7870};
7871
7872function isFunction(arg) {
7873 return typeof arg === 'function';
7874}
7875
7876function isNumber(arg) {
7877 return typeof arg === 'number';
7878}
7879
7880function isObject(arg) {
7881 return typeof arg === 'object' && arg !== null;
7882}
7883
7884function isUndefined(arg) {
7885 return arg === void 0;
7886}
7887
7888},{}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/browserify/node_modules/process/browser.js":[function(require,module,exports){
7889// shim for using process in browser
7890
7891var process = module.exports = {};
7892var queue = [];
7893var draining = false;
7894var currentQueue;
7895var queueIndex = -1;
7896
7897function cleanUpNextTick() {
7898 draining = false;
7899 if (currentQueue.length) {
7900 queue = currentQueue.concat(queue);
7901 } else {
7902 queueIndex = -1;
7903 }
7904 if (queue.length) {
7905 drainQueue();
7906 }
7907}
7908
7909function drainQueue() {
7910 if (draining) {
7911 return;
7912 }
7913 var timeout = setTimeout(cleanUpNextTick);
7914 draining = true;
7915
7916 var len = queue.length;
7917 while(len) {
7918 currentQueue = queue;
7919 queue = [];
7920 while (++queueIndex < len) {
7921 if (currentQueue) {
7922 currentQueue[queueIndex].run();
7923 }
7924 }
7925 queueIndex = -1;
7926 len = queue.length;
7927 }
7928 currentQueue = null;
7929 draining = false;
7930 clearTimeout(timeout);
7931}
7932
7933process.nextTick = function (fun) {
7934 var args = new Array(arguments.length - 1);
7935 if (arguments.length > 1) {
7936 for (var i = 1; i < arguments.length; i++) {
7937 args[i - 1] = arguments[i];
7938 }
7939 }
7940 queue.push(new Item(fun, args));
7941 if (queue.length === 1 && !draining) {
7942 setTimeout(drainQueue, 0);
7943 }
7944};
7945
7946// v8 likes predictible objects
7947function Item(fun, array) {
7948 this.fun = fun;
7949 this.array = array;
7950}
7951Item.prototype.run = function () {
7952 this.fun.apply(null, this.array);
7953};
7954process.title = 'browser';
7955process.browser = true;
7956process.env = {};
7957process.argv = [];
7958process.version = ''; // empty string to avoid regexp issues
7959process.versions = {};
7960
7961function noop() {}
7962
7963process.on = noop;
7964process.addListener = noop;
7965process.once = noop;
7966process.off = noop;
7967process.removeListener = noop;
7968process.removeAllListeners = noop;
7969process.emit = noop;
7970
7971process.binding = function (name) {
7972 throw new Error('process.binding is not supported');
7973};
7974
7975process.cwd = function () { return '/' };
7976process.chdir = function (dir) {
7977 throw new Error('process.chdir is not supported');
7978};
7979process.umask = function() { return 0; };
7980
7981},{}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/inherits/inherits_browser.js":[function(require,module,exports){
7982if (typeof Object.create === 'function') {
7983 // implementation from standard node.js 'util' module
7984 module.exports = function inherits(ctor, superCtor) {
7985 ctor.super_ = superCtor
7986 ctor.prototype = Object.create(superCtor.prototype, {
7987 constructor: {
7988 value: ctor,
7989 enumerable: false,
7990 writable: true,
7991 configurable: true
7992 }
7993 });
7994 };
7995} else {
7996 // old school shim for old browsers
7997 module.exports = function inherits(ctor, superCtor) {
7998 ctor.super_ = superCtor
7999 var TempCtor = function () {}
8000 TempCtor.prototype = superCtor.prototype
8001 ctor.prototype = new TempCtor()
8002 ctor.prototype.constructor = ctor
8003 }
8004}
8005
8006},{}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/lodash/index.js":[function(require,module,exports){
8007(function (global){
8008/**
8009 * @license
8010 * lodash 3.10.1 (Custom Build) <https://lodash.com/>
8011 * Build: `lodash modern -d -o ./index.js`
8012 * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
8013 * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
8014 * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
8015 * Available under MIT license <https://lodash.com/license>
8016 */
8017;(function() {
8018
8019 /** Used as a safe reference for `undefined` in pre-ES5 environments. */
8020 var undefined;
8021
8022 /** Used as the semantic version number. */
8023 var VERSION = '3.10.1';
8024
8025 /** Used to compose bitmasks for wrapper metadata. */
8026 var BIND_FLAG = 1,
8027 BIND_KEY_FLAG = 2,
8028 CURRY_BOUND_FLAG = 4,
8029 CURRY_FLAG = 8,
8030 CURRY_RIGHT_FLAG = 16,
8031 PARTIAL_FLAG = 32,
8032 PARTIAL_RIGHT_FLAG = 64,
8033 ARY_FLAG = 128,
8034 REARG_FLAG = 256;
8035
8036 /** Used as default options for `_.trunc`. */
8037 var DEFAULT_TRUNC_LENGTH = 30,
8038 DEFAULT_TRUNC_OMISSION = '...';
8039
8040 /** Used to detect when a function becomes hot. */
8041 var HOT_COUNT = 150,
8042 HOT_SPAN = 16;
8043
8044 /** Used as the size to enable large array optimizations. */
8045 var LARGE_ARRAY_SIZE = 200;
8046
8047 /** Used to indicate the type of lazy iteratees. */
8048 var LAZY_FILTER_FLAG = 1,
8049 LAZY_MAP_FLAG = 2;
8050
8051 /** Used as the `TypeError` message for "Functions" methods. */
8052 var FUNC_ERROR_TEXT = 'Expected a function';
8053
8054 /** Used as the internal argument placeholder. */
8055 var PLACEHOLDER = '__lodash_placeholder__';
8056
8057 /** `Object#toString` result references. */
8058 var argsTag = '[object Arguments]',
8059 arrayTag = '[object Array]',
8060 boolTag = '[object Boolean]',
8061 dateTag = '[object Date]',
8062 errorTag = '[object Error]',
8063 funcTag = '[object Function]',
8064 mapTag = '[object Map]',
8065 numberTag = '[object Number]',
8066 objectTag = '[object Object]',
8067 regexpTag = '[object RegExp]',
8068 setTag = '[object Set]',
8069 stringTag = '[object String]',
8070 weakMapTag = '[object WeakMap]';
8071
8072 var arrayBufferTag = '[object ArrayBuffer]',
8073 float32Tag = '[object Float32Array]',
8074 float64Tag = '[object Float64Array]',
8075 int8Tag = '[object Int8Array]',
8076 int16Tag = '[object Int16Array]',
8077 int32Tag = '[object Int32Array]',
8078 uint8Tag = '[object Uint8Array]',
8079 uint8ClampedTag = '[object Uint8ClampedArray]',
8080 uint16Tag = '[object Uint16Array]',
8081 uint32Tag = '[object Uint32Array]';
8082
8083 /** Used to match empty string literals in compiled template source. */
8084 var reEmptyStringLeading = /\b__p \+= '';/g,
8085 reEmptyStringMiddle = /\b(__p \+=) '' \+/g,
8086 reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g;
8087
8088 /** Used to match HTML entities and HTML characters. */
8089 var reEscapedHtml = /&(?:amp|lt|gt|quot|#39|#96);/g,
8090 reUnescapedHtml = /[&<>"'`]/g,
8091 reHasEscapedHtml = RegExp(reEscapedHtml.source),
8092 reHasUnescapedHtml = RegExp(reUnescapedHtml.source);
8093
8094 /** Used to match template delimiters. */
8095 var reEscape = /<%-([\s\S]+?)%>/g,
8096 reEvaluate = /<%([\s\S]+?)%>/g,
8097 reInterpolate = /<%=([\s\S]+?)%>/g;
8098
8099 /** Used to match property names within property paths. */
8100 var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\n\\]|\\.)*?\1)\]/,
8101 reIsPlainProp = /^\w*$/,
8102 rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\n\\]|\\.)*?)\2)\]/g;
8103
8104 /**
8105 * Used to match `RegExp` [syntax characters](http://ecma-international.org/ecma-262/6.0/#sec-patterns)
8106 * and those outlined by [`EscapeRegExpPattern`](http://ecma-international.org/ecma-262/6.0/#sec-escaperegexppattern).
8107 */
8108 var reRegExpChars = /^[:!,]|[\\^$.*+?()[\]{}|\/]|(^[0-9a-fA-Fnrtuvx])|([\n\r\u2028\u2029])/g,
8109 reHasRegExpChars = RegExp(reRegExpChars.source);
8110
8111 /** Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks). */
8112 var reComboMark = /[\u0300-\u036f\ufe20-\ufe23]/g;
8113
8114 /** Used to match backslashes in property paths. */
8115 var reEscapeChar = /\\(\\)?/g;
8116
8117 /** Used to match [ES template delimiters](http://ecma-international.org/ecma-262/6.0/#sec-template-literal-lexical-components). */
8118 var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g;
8119
8120 /** Used to match `RegExp` flags from their coerced string values. */
8121 var reFlags = /\w*$/;
8122
8123 /** Used to detect hexadecimal string values. */
8124 var reHasHexPrefix = /^0[xX]/;
8125
8126 /** Used to detect host constructors (Safari > 5). */
8127 var reIsHostCtor = /^\[object .+?Constructor\]$/;
8128
8129 /** Used to detect unsigned integer values. */
8130 var reIsUint = /^\d+$/;
8131
8132 /** Used to match latin-1 supplementary letters (excluding mathematical operators). */
8133 var reLatin1 = /[\xc0-\xd6\xd8-\xde\xdf-\xf6\xf8-\xff]/g;
8134
8135 /** Used to ensure capturing order of template delimiters. */
8136 var reNoMatch = /($^)/;
8137
8138 /** Used to match unescaped characters in compiled string literals. */
8139 var reUnescapedString = /['\n\r\u2028\u2029\\]/g;
8140
8141 /** Used to match words to create compound words. */
8142 var reWords = (function() {
8143 var upper = '[A-Z\\xc0-\\xd6\\xd8-\\xde]',
8144 lower = '[a-z\\xdf-\\xf6\\xf8-\\xff]+';
8145
8146 return RegExp(upper + '+(?=' + upper + lower + ')|' + upper + '?' + lower + '|' + upper + '+|[0-9]+', 'g');
8147 }());
8148
8149 /** Used to assign default `context` object properties. */
8150 var contextProps = [
8151 'Array', 'ArrayBuffer', 'Date', 'Error', 'Float32Array', 'Float64Array',
8152 'Function', 'Int8Array', 'Int16Array', 'Int32Array', 'Math', 'Number',
8153 'Object', 'RegExp', 'Set', 'String', '_', 'clearTimeout', 'isFinite',
8154 'parseFloat', 'parseInt', 'setTimeout', 'TypeError', 'Uint8Array',
8155 'Uint8ClampedArray', 'Uint16Array', 'Uint32Array', 'WeakMap'
8156 ];
8157
8158 /** Used to make template sourceURLs easier to identify. */
8159 var templateCounter = -1;
8160
8161 /** Used to identify `toStringTag` values of typed arrays. */
8162 var typedArrayTags = {};
8163 typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =
8164 typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =
8165 typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =
8166 typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =
8167 typedArrayTags[uint32Tag] = true;
8168 typedArrayTags[argsTag] = typedArrayTags[arrayTag] =
8169 typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =
8170 typedArrayTags[dateTag] = typedArrayTags[errorTag] =
8171 typedArrayTags[funcTag] = typedArrayTags[mapTag] =
8172 typedArrayTags[numberTag] = typedArrayTags[objectTag] =
8173 typedArrayTags[regexpTag] = typedArrayTags[setTag] =
8174 typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false;
8175
8176 /** Used to identify `toStringTag` values supported by `_.clone`. */
8177 var cloneableTags = {};
8178 cloneableTags[argsTag] = cloneableTags[arrayTag] =
8179 cloneableTags[arrayBufferTag] = cloneableTags[boolTag] =
8180 cloneableTags[dateTag] = cloneableTags[float32Tag] =
8181 cloneableTags[float64Tag] = cloneableTags[int8Tag] =
8182 cloneableTags[int16Tag] = cloneableTags[int32Tag] =
8183 cloneableTags[numberTag] = cloneableTags[objectTag] =
8184 cloneableTags[regexpTag] = cloneableTags[stringTag] =
8185 cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] =
8186 cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true;
8187 cloneableTags[errorTag] = cloneableTags[funcTag] =
8188 cloneableTags[mapTag] = cloneableTags[setTag] =
8189 cloneableTags[weakMapTag] = false;
8190
8191 /** Used to map latin-1 supplementary letters to basic latin letters. */
8192 var deburredLetters = {
8193 '\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A',
8194 '\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a',
8195 '\xc7': 'C', '\xe7': 'c',
8196 '\xd0': 'D', '\xf0': 'd',
8197 '\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E',
8198 '\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e',
8199 '\xcC': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I',
8200 '\xeC': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i',
8201 '\xd1': 'N', '\xf1': 'n',
8202 '\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O',
8203 '\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o',
8204 '\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U',
8205 '\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u',
8206 '\xdd': 'Y', '\xfd': 'y', '\xff': 'y',
8207 '\xc6': 'Ae', '\xe6': 'ae',
8208 '\xde': 'Th', '\xfe': 'th',
8209 '\xdf': 'ss'
8210 };
8211
8212 /** Used to map characters to HTML entities. */
8213 var htmlEscapes = {
8214 '&': '&amp;',
8215 '<': '&lt;',
8216 '>': '&gt;',
8217 '"': '&quot;',
8218 "'": '&#39;',
8219 '`': '&#96;'
8220 };
8221
8222 /** Used to map HTML entities to characters. */
8223 var htmlUnescapes = {
8224 '&amp;': '&',
8225 '&lt;': '<',
8226 '&gt;': '>',
8227 '&quot;': '"',
8228 '&#39;': "'",
8229 '&#96;': '`'
8230 };
8231
8232 /** Used to determine if values are of the language type `Object`. */
8233 var objectTypes = {
8234 'function': true,
8235 'object': true
8236 };
8237
8238 /** Used to escape characters for inclusion in compiled regexes. */
8239 var regexpEscapes = {
8240 '0': 'x30', '1': 'x31', '2': 'x32', '3': 'x33', '4': 'x34',
8241 '5': 'x35', '6': 'x36', '7': 'x37', '8': 'x38', '9': 'x39',
8242 'A': 'x41', 'B': 'x42', 'C': 'x43', 'D': 'x44', 'E': 'x45', 'F': 'x46',
8243 'a': 'x61', 'b': 'x62', 'c': 'x63', 'd': 'x64', 'e': 'x65', 'f': 'x66',
8244 'n': 'x6e', 'r': 'x72', 't': 'x74', 'u': 'x75', 'v': 'x76', 'x': 'x78'
8245 };
8246
8247 /** Used to escape characters for inclusion in compiled string literals. */
8248 var stringEscapes = {
8249 '\\': '\\',
8250 "'": "'",
8251 '\n': 'n',
8252 '\r': 'r',
8253 '\u2028': 'u2028',
8254 '\u2029': 'u2029'
8255 };
8256
8257 /** Detect free variable `exports`. */
8258 var freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports;
8259
8260 /** Detect free variable `module`. */
8261 var freeModule = objectTypes[typeof module] && module && !module.nodeType && module;
8262
8263 /** Detect free variable `global` from Node.js. */
8264 var freeGlobal = freeExports && freeModule && typeof global == 'object' && global && global.Object && global;
8265
8266 /** Detect free variable `self`. */
8267 var freeSelf = objectTypes[typeof self] && self && self.Object && self;
8268
8269 /** Detect free variable `window`. */
8270 var freeWindow = objectTypes[typeof window] && window && window.Object && window;
8271
8272 /** Detect the popular CommonJS extension `module.exports`. */
8273 var moduleExports = freeModule && freeModule.exports === freeExports && freeExports;
8274
8275 /**
8276 * Used as a reference to the global object.
8277 *
8278 * The `this` value is used if it's the global object to avoid Greasemonkey's
8279 * restricted `window` object, otherwise the `window` object is used.
8280 */
8281 var root = freeGlobal || ((freeWindow !== (this && this.window)) && freeWindow) || freeSelf || this;
8282
8283 /*--------------------------------------------------------------------------*/
8284
8285 /**
8286 * The base implementation of `compareAscending` which compares values and
8287 * sorts them in ascending order without guaranteeing a stable sort.
8288 *
8289 * @private
8290 * @param {*} value The value to compare.
8291 * @param {*} other The other value to compare.
8292 * @returns {number} Returns the sort order indicator for `value`.
8293 */
8294 function baseCompareAscending(value, other) {
8295 if (value !== other) {
8296 var valIsNull = value === null,
8297 valIsUndef = value === undefined,
8298 valIsReflexive = value === value;
8299
8300 var othIsNull = other === null,
8301 othIsUndef = other === undefined,
8302 othIsReflexive = other === other;
8303
8304 if ((value > other && !othIsNull) || !valIsReflexive ||
8305 (valIsNull && !othIsUndef && othIsReflexive) ||
8306 (valIsUndef && othIsReflexive)) {
8307 return 1;
8308 }
8309 if ((value < other && !valIsNull) || !othIsReflexive ||
8310 (othIsNull && !valIsUndef && valIsReflexive) ||
8311 (othIsUndef && valIsReflexive)) {
8312 return -1;
8313 }
8314 }
8315 return 0;
8316 }
8317
8318 /**
8319 * The base implementation of `_.findIndex` and `_.findLastIndex` without
8320 * support for callback shorthands and `this` binding.
8321 *
8322 * @private
8323 * @param {Array} array The array to search.
8324 * @param {Function} predicate The function invoked per iteration.
8325 * @param {boolean} [fromRight] Specify iterating from right to left.
8326 * @returns {number} Returns the index of the matched value, else `-1`.
8327 */
8328 function baseFindIndex(array, predicate, fromRight) {
8329 var length = array.length,
8330 index = fromRight ? length : -1;
8331
8332 while ((fromRight ? index-- : ++index < length)) {
8333 if (predicate(array[index], index, array)) {
8334 return index;
8335 }
8336 }
8337 return -1;
8338 }
8339
8340 /**
8341 * The base implementation of `_.indexOf` without support for binary searches.
8342 *
8343 * @private
8344 * @param {Array} array The array to search.
8345 * @param {*} value The value to search for.
8346 * @param {number} fromIndex The index to search from.
8347 * @returns {number} Returns the index of the matched value, else `-1`.
8348 */
8349 function baseIndexOf(array, value, fromIndex) {
8350 if (value !== value) {
8351 return indexOfNaN(array, fromIndex);
8352 }
8353 var index = fromIndex - 1,
8354 length = array.length;
8355
8356 while (++index < length) {
8357 if (array[index] === value) {
8358 return index;
8359 }
8360 }
8361 return -1;
8362 }
8363
8364 /**
8365 * The base implementation of `_.isFunction` without support for environments
8366 * with incorrect `typeof` results.
8367 *
8368 * @private
8369 * @param {*} value The value to check.
8370 * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
8371 */
8372 function baseIsFunction(value) {
8373 // Avoid a Chakra JIT bug in compatibility modes of IE 11.
8374 // See https://github.com/jashkenas/underscore/issues/1621 for more details.
8375 return typeof value == 'function' || false;
8376 }
8377
8378 /**
8379 * Converts `value` to a string if it's not one. An empty string is returned
8380 * for `null` or `undefined` values.
8381 *
8382 * @private
8383 * @param {*} value The value to process.
8384 * @returns {string} Returns the string.
8385 */
8386 function baseToString(value) {
8387 return value == null ? '' : (value + '');
8388 }
8389
8390 /**
8391 * Used by `_.trim` and `_.trimLeft` to get the index of the first character
8392 * of `string` that is not found in `chars`.
8393 *
8394 * @private
8395 * @param {string} string The string to inspect.
8396 * @param {string} chars The characters to find.
8397 * @returns {number} Returns the index of the first character not found in `chars`.
8398 */
8399 function charsLeftIndex(string, chars) {
8400 var index = -1,
8401 length = string.length;
8402
8403 while (++index < length && chars.indexOf(string.charAt(index)) > -1) {}
8404 return index;
8405 }
8406
8407 /**
8408 * Used by `_.trim` and `_.trimRight` to get the index of the last character
8409 * of `string` that is not found in `chars`.
8410 *
8411 * @private
8412 * @param {string} string The string to inspect.
8413 * @param {string} chars The characters to find.
8414 * @returns {number} Returns the index of the last character not found in `chars`.
8415 */
8416 function charsRightIndex(string, chars) {
8417 var index = string.length;
8418
8419 while (index-- && chars.indexOf(string.charAt(index)) > -1) {}
8420 return index;
8421 }
8422
8423 /**
8424 * Used by `_.sortBy` to compare transformed elements of a collection and stable
8425 * sort them in ascending order.
8426 *
8427 * @private
8428 * @param {Object} object The object to compare.
8429 * @param {Object} other The other object to compare.
8430 * @returns {number} Returns the sort order indicator for `object`.
8431 */
8432 function compareAscending(object, other) {
8433 return baseCompareAscending(object.criteria, other.criteria) || (object.index - other.index);
8434 }
8435
8436 /**
8437 * Used by `_.sortByOrder` to compare multiple properties of a value to another
8438 * and stable sort them.
8439 *
8440 * If `orders` is unspecified, all valuess are sorted in ascending order. Otherwise,
8441 * a value is sorted in ascending order if its corresponding order is "asc", and
8442 * descending if "desc".
8443 *
8444 * @private
8445 * @param {Object} object The object to compare.
8446 * @param {Object} other The other object to compare.
8447 * @param {boolean[]} orders The order to sort by for each property.
8448 * @returns {number} Returns the sort order indicator for `object`.
8449 */
8450 function compareMultiple(object, other, orders) {
8451 var index = -1,
8452 objCriteria = object.criteria,
8453 othCriteria = other.criteria,
8454 length = objCriteria.length,
8455 ordersLength = orders.length;
8456
8457 while (++index < length) {
8458 var result = baseCompareAscending(objCriteria[index], othCriteria[index]);
8459 if (result) {
8460 if (index >= ordersLength) {
8461 return result;
8462 }
8463 var order = orders[index];
8464 return result * ((order === 'asc' || order === true) ? 1 : -1);
8465 }
8466 }
8467 // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications
8468 // that causes it, under certain circumstances, to provide the same value for
8469 // `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247
8470 // for more details.
8471 //
8472 // This also ensures a stable sort in V8 and other engines.
8473 // See https://code.google.com/p/v8/issues/detail?id=90 for more details.
8474 return object.index - other.index;
8475 }
8476
8477 /**
8478 * Used by `_.deburr` to convert latin-1 supplementary letters to basic latin letters.
8479 *
8480 * @private
8481 * @param {string} letter The matched letter to deburr.
8482 * @returns {string} Returns the deburred letter.
8483 */
8484 function deburrLetter(letter) {
8485 return deburredLetters[letter];
8486 }
8487
8488 /**
8489 * Used by `_.escape` to convert characters to HTML entities.
8490 *
8491 * @private
8492 * @param {string} chr The matched character to escape.
8493 * @returns {string} Returns the escaped character.
8494 */
8495 function escapeHtmlChar(chr) {
8496 return htmlEscapes[chr];
8497 }
8498
8499 /**
8500 * Used by `_.escapeRegExp` to escape characters for inclusion in compiled regexes.
8501 *
8502 * @private
8503 * @param {string} chr The matched character to escape.
8504 * @param {string} leadingChar The capture group for a leading character.
8505 * @param {string} whitespaceChar The capture group for a whitespace character.
8506 * @returns {string} Returns the escaped character.
8507 */
8508 function escapeRegExpChar(chr, leadingChar, whitespaceChar) {
8509 if (leadingChar) {
8510 chr = regexpEscapes[chr];
8511 } else if (whitespaceChar) {
8512 chr = stringEscapes[chr];
8513 }
8514 return '\\' + chr;
8515 }
8516
8517 /**
8518 * Used by `_.template` to escape characters for inclusion in compiled string literals.
8519 *
8520 * @private
8521 * @param {string} chr The matched character to escape.
8522 * @returns {string} Returns the escaped character.
8523 */
8524 function escapeStringChar(chr) {
8525 return '\\' + stringEscapes[chr];
8526 }
8527
8528 /**
8529 * Gets the index at which the first occurrence of `NaN` is found in `array`.
8530 *
8531 * @private
8532 * @param {Array} array The array to search.
8533 * @param {number} fromIndex The index to search from.
8534 * @param {boolean} [fromRight] Specify iterating from right to left.
8535 * @returns {number} Returns the index of the matched `NaN`, else `-1`.
8536 */
8537 function indexOfNaN(array, fromIndex, fromRight) {
8538 var length = array.length,
8539 index = fromIndex + (fromRight ? 0 : -1);
8540
8541 while ((fromRight ? index-- : ++index < length)) {
8542 var other = array[index];
8543 if (other !== other) {
8544 return index;
8545 }
8546 }
8547 return -1;
8548 }
8549
8550 /**
8551 * Checks if `value` is object-like.
8552 *
8553 * @private
8554 * @param {*} value The value to check.
8555 * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
8556 */
8557 function isObjectLike(value) {
8558 return !!value && typeof value == 'object';
8559 }
8560
8561 /**
8562 * Used by `trimmedLeftIndex` and `trimmedRightIndex` to determine if a
8563 * character code is whitespace.
8564 *
8565 * @private
8566 * @param {number} charCode The character code to inspect.
8567 * @returns {boolean} Returns `true` if `charCode` is whitespace, else `false`.
8568 */
8569 function isSpace(charCode) {
8570 return ((charCode <= 160 && (charCode >= 9 && charCode <= 13) || charCode == 32 || charCode == 160) || charCode == 5760 || charCode == 6158 ||
8571 (charCode >= 8192 && (charCode <= 8202 || charCode == 8232 || charCode == 8233 || charCode == 8239 || charCode == 8287 || charCode == 12288 || charCode == 65279)));
8572 }
8573
8574 /**
8575 * Replaces all `placeholder` elements in `array` with an internal placeholder
8576 * and returns an array of their indexes.
8577 *
8578 * @private
8579 * @param {Array} array The array to modify.
8580 * @param {*} placeholder The placeholder to replace.
8581 * @returns {Array} Returns the new array of placeholder indexes.
8582 */
8583 function replaceHolders(array, placeholder) {
8584 var index = -1,
8585 length = array.length,
8586 resIndex = -1,
8587 result = [];
8588
8589 while (++index < length) {
8590 if (array[index] === placeholder) {
8591 array[index] = PLACEHOLDER;
8592 result[++resIndex] = index;
8593 }
8594 }
8595 return result;
8596 }
8597
8598 /**
8599 * An implementation of `_.uniq` optimized for sorted arrays without support
8600 * for callback shorthands and `this` binding.
8601 *
8602 * @private
8603 * @param {Array} array The array to inspect.
8604 * @param {Function} [iteratee] The function invoked per iteration.
8605 * @returns {Array} Returns the new duplicate-value-free array.
8606 */
8607 function sortedUniq(array, iteratee) {
8608 var seen,
8609 index = -1,
8610 length = array.length,
8611 resIndex = -1,
8612 result = [];
8613
8614 while (++index < length) {
8615 var value = array[index],
8616 computed = iteratee ? iteratee(value, index, array) : value;
8617
8618 if (!index || seen !== computed) {
8619 seen = computed;
8620 result[++resIndex] = value;
8621 }
8622 }
8623 return result;
8624 }
8625
8626 /**
8627 * Used by `_.trim` and `_.trimLeft` to get the index of the first non-whitespace
8628 * character of `string`.
8629 *
8630 * @private
8631 * @param {string} string The string to inspect.
8632 * @returns {number} Returns the index of the first non-whitespace character.
8633 */
8634 function trimmedLeftIndex(string) {
8635 var index = -1,
8636 length = string.length;
8637
8638 while (++index < length && isSpace(string.charCodeAt(index))) {}
8639 return index;
8640 }
8641
8642 /**
8643 * Used by `_.trim` and `_.trimRight` to get the index of the last non-whitespace
8644 * character of `string`.
8645 *
8646 * @private
8647 * @param {string} string The string to inspect.
8648 * @returns {number} Returns the index of the last non-whitespace character.
8649 */
8650 function trimmedRightIndex(string) {
8651 var index = string.length;
8652
8653 while (index-- && isSpace(string.charCodeAt(index))) {}
8654 return index;
8655 }
8656
8657 /**
8658 * Used by `_.unescape` to convert HTML entities to characters.
8659 *
8660 * @private
8661 * @param {string} chr The matched character to unescape.
8662 * @returns {string} Returns the unescaped character.
8663 */
8664 function unescapeHtmlChar(chr) {
8665 return htmlUnescapes[chr];
8666 }
8667
8668 /*--------------------------------------------------------------------------*/
8669
8670 /**
8671 * Create a new pristine `lodash` function using the given `context` object.
8672 *
8673 * @static
8674 * @memberOf _
8675 * @category Utility
8676 * @param {Object} [context=root] The context object.
8677 * @returns {Function} Returns a new `lodash` function.
8678 * @example
8679 *
8680 * _.mixin({ 'foo': _.constant('foo') });
8681 *
8682 * var lodash = _.runInContext();
8683 * lodash.mixin({ 'bar': lodash.constant('bar') });
8684 *
8685 * _.isFunction(_.foo);
8686 * // => true
8687 * _.isFunction(_.bar);
8688 * // => false
8689 *
8690 * lodash.isFunction(lodash.foo);
8691 * // => false
8692 * lodash.isFunction(lodash.bar);
8693 * // => true
8694 *
8695 * // using `context` to mock `Date#getTime` use in `_.now`
8696 * var mock = _.runInContext({
8697 * 'Date': function() {
8698 * return { 'getTime': getTimeMock };
8699 * }
8700 * });
8701 *
8702 * // or creating a suped-up `defer` in Node.js
8703 * var defer = _.runInContext({ 'setTimeout': setImmediate }).defer;
8704 */
8705 function runInContext(context) {
8706 // Avoid issues with some ES3 environments that attempt to use values, named
8707 // after built-in constructors like `Object`, for the creation of literals.
8708 // ES5 clears this up by stating that literals must use built-in constructors.
8709 // See https://es5.github.io/#x11.1.5 for more details.
8710 context = context ? _.defaults(root.Object(), context, _.pick(root, contextProps)) : root;
8711
8712 /** Native constructor references. */
8713 var Array = context.Array,
8714 Date = context.Date,
8715 Error = context.Error,
8716 Function = context.Function,
8717 Math = context.Math,
8718 Number = context.Number,
8719 Object = context.Object,
8720 RegExp = context.RegExp,
8721 String = context.String,
8722 TypeError = context.TypeError;
8723
8724 /** Used for native method references. */
8725 var arrayProto = Array.prototype,
8726 objectProto = Object.prototype,
8727 stringProto = String.prototype;
8728
8729 /** Used to resolve the decompiled source of functions. */
8730 var fnToString = Function.prototype.toString;
8731
8732 /** Used to check objects for own properties. */
8733 var hasOwnProperty = objectProto.hasOwnProperty;
8734
8735 /** Used to generate unique IDs. */
8736 var idCounter = 0;
8737
8738 /**
8739 * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
8740 * of values.
8741 */
8742 var objToString = objectProto.toString;
8743
8744 /** Used to restore the original `_` reference in `_.noConflict`. */
8745 var oldDash = root._;
8746
8747 /** Used to detect if a method is native. */
8748 var reIsNative = RegExp('^' +
8749 fnToString.call(hasOwnProperty).replace(/[\\^$.*+?()[\]{}|]/g, '\\$&')
8750 .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
8751 );
8752
8753 /** Native method references. */
8754 var ArrayBuffer = context.ArrayBuffer,
8755 clearTimeout = context.clearTimeout,
8756 parseFloat = context.parseFloat,
8757 pow = Math.pow,
8758 propertyIsEnumerable = objectProto.propertyIsEnumerable,
8759 Set = getNative(context, 'Set'),
8760 setTimeout = context.setTimeout,
8761 splice = arrayProto.splice,
8762 Uint8Array = context.Uint8Array,
8763 WeakMap = getNative(context, 'WeakMap');
8764
8765 /* Native method references for those with the same name as other `lodash` methods. */
8766 var nativeCeil = Math.ceil,
8767 nativeCreate = getNative(Object, 'create'),
8768 nativeFloor = Math.floor,
8769 nativeIsArray = getNative(Array, 'isArray'),
8770 nativeIsFinite = context.isFinite,
8771 nativeKeys = getNative(Object, 'keys'),
8772 nativeMax = Math.max,
8773 nativeMin = Math.min,
8774 nativeNow = getNative(Date, 'now'),
8775 nativeParseInt = context.parseInt,
8776 nativeRandom = Math.random;
8777
8778 /** Used as references for `-Infinity` and `Infinity`. */
8779 var NEGATIVE_INFINITY = Number.NEGATIVE_INFINITY,
8780 POSITIVE_INFINITY = Number.POSITIVE_INFINITY;
8781
8782 /** Used as references for the maximum length and index of an array. */
8783 var MAX_ARRAY_LENGTH = 4294967295,
8784 MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1,
8785 HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1;
8786
8787 /**
8788 * Used as the [maximum length](http://ecma-international.org/ecma-262/6.0/#sec-number.max_safe_integer)
8789 * of an array-like value.
8790 */
8791 var MAX_SAFE_INTEGER = 9007199254740991;
8792
8793 /** Used to store function metadata. */
8794 var metaMap = WeakMap && new WeakMap;
8795
8796 /** Used to lookup unminified function names. */
8797 var realNames = {};
8798
8799 /*------------------------------------------------------------------------*/
8800
8801 /**
8802 * Creates a `lodash` object which wraps `value` to enable implicit chaining.
8803 * Methods that operate on and return arrays, collections, and functions can
8804 * be chained together. Methods that retrieve a single value or may return a
8805 * primitive value will automatically end the chain returning the unwrapped
8806 * value. Explicit chaining may be enabled using `_.chain`. The execution of
8807 * chained methods is lazy, that is, execution is deferred until `_#value`
8808 * is implicitly or explicitly called.
8809 *
8810 * Lazy evaluation allows several methods to support shortcut fusion. Shortcut
8811 * fusion is an optimization strategy which merge iteratee calls; this can help
8812 * to avoid the creation of intermediate data structures and greatly reduce the
8813 * number of iteratee executions.
8814 *
8815 * Chaining is supported in custom builds as long as the `_#value` method is
8816 * directly or indirectly included in the build.
8817 *
8818 * In addition to lodash methods, wrappers have `Array` and `String` methods.
8819 *
8820 * The wrapper `Array` methods are:
8821 * `concat`, `join`, `pop`, `push`, `reverse`, `shift`, `slice`, `sort`,
8822 * `splice`, and `unshift`
8823 *
8824 * The wrapper `String` methods are:
8825 * `replace` and `split`
8826 *
8827 * The wrapper methods that support shortcut fusion are:
8828 * `compact`, `drop`, `dropRight`, `dropRightWhile`, `dropWhile`, `filter`,
8829 * `first`, `initial`, `last`, `map`, `pluck`, `reject`, `rest`, `reverse`,
8830 * `slice`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, `toArray`,
8831 * and `where`
8832 *
8833 * The chainable wrapper methods are:
8834 * `after`, `ary`, `assign`, `at`, `before`, `bind`, `bindAll`, `bindKey`,
8835 * `callback`, `chain`, `chunk`, `commit`, `compact`, `concat`, `constant`,
8836 * `countBy`, `create`, `curry`, `debounce`, `defaults`, `defaultsDeep`,
8837 * `defer`, `delay`, `difference`, `drop`, `dropRight`, `dropRightWhile`,
8838 * `dropWhile`, `fill`, `filter`, `flatten`, `flattenDeep`, `flow`, `flowRight`,
8839 * `forEach`, `forEachRight`, `forIn`, `forInRight`, `forOwn`, `forOwnRight`,
8840 * `functions`, `groupBy`, `indexBy`, `initial`, `intersection`, `invert`,
8841 * `invoke`, `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`,
8842 * `matchesProperty`, `memoize`, `merge`, `method`, `methodOf`, `mixin`,
8843 * `modArgs`, `negate`, `omit`, `once`, `pairs`, `partial`, `partialRight`,
8844 * `partition`, `pick`, `plant`, `pluck`, `property`, `propertyOf`, `pull`,
8845 * `pullAt`, `push`, `range`, `rearg`, `reject`, `remove`, `rest`, `restParam`,
8846 * `reverse`, `set`, `shuffle`, `slice`, `sort`, `sortBy`, `sortByAll`,
8847 * `sortByOrder`, `splice`, `spread`, `take`, `takeRight`, `takeRightWhile`,
8848 * `takeWhile`, `tap`, `throttle`, `thru`, `times`, `toArray`, `toPlainObject`,
8849 * `transform`, `union`, `uniq`, `unshift`, `unzip`, `unzipWith`, `values`,
8850 * `valuesIn`, `where`, `without`, `wrap`, `xor`, `zip`, `zipObject`, `zipWith`
8851 *
8852 * The wrapper methods that are **not** chainable by default are:
8853 * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clone`, `cloneDeep`,
8854 * `deburr`, `endsWith`, `escape`, `escapeRegExp`, `every`, `find`, `findIndex`,
8855 * `findKey`, `findLast`, `findLastIndex`, `findLastKey`, `findWhere`, `first`,
8856 * `floor`, `get`, `gt`, `gte`, `has`, `identity`, `includes`, `indexOf`,
8857 * `inRange`, `isArguments`, `isArray`, `isBoolean`, `isDate`, `isElement`,
8858 * `isEmpty`, `isEqual`, `isError`, `isFinite` `isFunction`, `isMatch`,
8859 * `isNative`, `isNaN`, `isNull`, `isNumber`, `isObject`, `isPlainObject`,
8860 * `isRegExp`, `isString`, `isUndefined`, `isTypedArray`, `join`, `kebabCase`,
8861 * `last`, `lastIndexOf`, `lt`, `lte`, `max`, `min`, `noConflict`, `noop`,
8862 * `now`, `pad`, `padLeft`, `padRight`, `parseInt`, `pop`, `random`, `reduce`,
8863 * `reduceRight`, `repeat`, `result`, `round`, `runInContext`, `shift`, `size`,
8864 * `snakeCase`, `some`, `sortedIndex`, `sortedLastIndex`, `startCase`,
8865 * `startsWith`, `sum`, `template`, `trim`, `trimLeft`, `trimRight`, `trunc`,
8866 * `unescape`, `uniqueId`, `value`, and `words`
8867 *
8868 * The wrapper method `sample` will return a wrapped value when `n` is provided,
8869 * otherwise an unwrapped value is returned.
8870 *
8871 * @name _
8872 * @constructor
8873 * @category Chain
8874 * @param {*} value The value to wrap in a `lodash` instance.
8875 * @returns {Object} Returns the new `lodash` wrapper instance.
8876 * @example
8877 *
8878 * var wrapped = _([1, 2, 3]);
8879 *
8880 * // returns an unwrapped value
8881 * wrapped.reduce(function(total, n) {
8882 * return total + n;
8883 * });
8884 * // => 6
8885 *
8886 * // returns a wrapped value
8887 * var squares = wrapped.map(function(n) {
8888 * return n * n;
8889 * });
8890 *
8891 * _.isArray(squares);
8892 * // => false
8893 *
8894 * _.isArray(squares.value());
8895 * // => true
8896 */
8897 function lodash(value) {
8898 if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) {
8899 if (value instanceof LodashWrapper) {
8900 return value;
8901 }
8902 if (hasOwnProperty.call(value, '__chain__') && hasOwnProperty.call(value, '__wrapped__')) {
8903 return wrapperClone(value);
8904 }
8905 }
8906 return new LodashWrapper(value);
8907 }
8908
8909 /**
8910 * The function whose prototype all chaining wrappers inherit from.
8911 *
8912 * @private
8913 */
8914 function baseLodash() {
8915 // No operation performed.
8916 }
8917
8918 /**
8919 * The base constructor for creating `lodash` wrapper objects.
8920 *
8921 * @private
8922 * @param {*} value The value to wrap.
8923 * @param {boolean} [chainAll] Enable chaining for all wrapper methods.
8924 * @param {Array} [actions=[]] Actions to peform to resolve the unwrapped value.
8925 */
8926 function LodashWrapper(value, chainAll, actions) {
8927 this.__wrapped__ = value;
8928 this.__actions__ = actions || [];
8929 this.__chain__ = !!chainAll;
8930 }
8931
8932 /**
8933 * An object environment feature flags.
8934 *
8935 * @static
8936 * @memberOf _
8937 * @type Object
8938 */
8939 var support = lodash.support = {};
8940
8941 /**
8942 * By default, the template delimiters used by lodash are like those in
8943 * embedded Ruby (ERB). Change the following template settings to use
8944 * alternative delimiters.
8945 *
8946 * @static
8947 * @memberOf _
8948 * @type Object
8949 */
8950 lodash.templateSettings = {
8951
8952 /**
8953 * Used to detect `data` property values to be HTML-escaped.
8954 *
8955 * @memberOf _.templateSettings
8956 * @type RegExp
8957 */
8958 'escape': reEscape,
8959
8960 /**
8961 * Used to detect code to be evaluated.
8962 *
8963 * @memberOf _.templateSettings
8964 * @type RegExp
8965 */
8966 'evaluate': reEvaluate,
8967
8968 /**
8969 * Used to detect `data` property values to inject.
8970 *
8971 * @memberOf _.templateSettings
8972 * @type RegExp
8973 */
8974 'interpolate': reInterpolate,
8975
8976 /**
8977 * Used to reference the data object in the template text.
8978 *
8979 * @memberOf _.templateSettings
8980 * @type string
8981 */
8982 'variable': '',
8983
8984 /**
8985 * Used to import variables into the compiled template.
8986 *
8987 * @memberOf _.templateSettings
8988 * @type Object
8989 */
8990 'imports': {
8991
8992 /**
8993 * A reference to the `lodash` function.
8994 *
8995 * @memberOf _.templateSettings.imports
8996 * @type Function
8997 */
8998 '_': lodash
8999 }
9000 };
9001
9002 /*------------------------------------------------------------------------*/
9003
9004 /**
9005 * Creates a lazy wrapper object which wraps `value` to enable lazy evaluation.
9006 *
9007 * @private
9008 * @param {*} value The value to wrap.
9009 */
9010 function LazyWrapper(value) {
9011 this.__wrapped__ = value;
9012 this.__actions__ = [];
9013 this.__dir__ = 1;
9014 this.__filtered__ = false;
9015 this.__iteratees__ = [];
9016 this.__takeCount__ = POSITIVE_INFINITY;
9017 this.__views__ = [];
9018 }
9019
9020 /**
9021 * Creates a clone of the lazy wrapper object.
9022 *
9023 * @private
9024 * @name clone
9025 * @memberOf LazyWrapper
9026 * @returns {Object} Returns the cloned `LazyWrapper` object.
9027 */
9028 function lazyClone() {
9029 var result = new LazyWrapper(this.__wrapped__);
9030 result.__actions__ = arrayCopy(this.__actions__);
9031 result.__dir__ = this.__dir__;
9032 result.__filtered__ = this.__filtered__;
9033 result.__iteratees__ = arrayCopy(this.__iteratees__);
9034 result.__takeCount__ = this.__takeCount__;
9035 result.__views__ = arrayCopy(this.__views__);
9036 return result;
9037 }
9038
9039 /**
9040 * Reverses the direction of lazy iteration.
9041 *
9042 * @private
9043 * @name reverse
9044 * @memberOf LazyWrapper
9045 * @returns {Object} Returns the new reversed `LazyWrapper` object.
9046 */
9047 function lazyReverse() {
9048 if (this.__filtered__) {
9049 var result = new LazyWrapper(this);
9050 result.__dir__ = -1;
9051 result.__filtered__ = true;
9052 } else {
9053 result = this.clone();
9054 result.__dir__ *= -1;
9055 }
9056 return result;
9057 }
9058
9059 /**
9060 * Extracts the unwrapped value from its lazy wrapper.
9061 *
9062 * @private
9063 * @name value
9064 * @memberOf LazyWrapper
9065 * @returns {*} Returns the unwrapped value.
9066 */
9067 function lazyValue() {
9068 var array = this.__wrapped__.value(),
9069 dir = this.__dir__,
9070 isArr = isArray(array),
9071 isRight = dir < 0,
9072 arrLength = isArr ? array.length : 0,
9073 view = getView(0, arrLength, this.__views__),
9074 start = view.start,
9075 end = view.end,
9076 length = end - start,
9077 index = isRight ? end : (start - 1),
9078 iteratees = this.__iteratees__,
9079 iterLength = iteratees.length,
9080 resIndex = 0,
9081 takeCount = nativeMin(length, this.__takeCount__);
9082
9083 if (!isArr || arrLength < LARGE_ARRAY_SIZE || (arrLength == length && takeCount == length)) {
9084 return baseWrapperValue((isRight && isArr) ? array.reverse() : array, this.__actions__);
9085 }
9086 var result = [];
9087
9088 outer:
9089 while (length-- && resIndex < takeCount) {
9090 index += dir;
9091
9092 var iterIndex = -1,
9093 value = array[index];
9094
9095 while (++iterIndex < iterLength) {
9096 var data = iteratees[iterIndex],
9097 iteratee = data.iteratee,
9098 type = data.type,
9099 computed = iteratee(value);
9100
9101 if (type == LAZY_MAP_FLAG) {
9102 value = computed;
9103 } else if (!computed) {
9104 if (type == LAZY_FILTER_FLAG) {
9105 continue outer;
9106 } else {
9107 break outer;
9108 }
9109 }
9110 }
9111 result[resIndex++] = value;
9112 }
9113 return result;
9114 }
9115
9116 /*------------------------------------------------------------------------*/
9117
9118 /**
9119 * Creates a cache object to store key/value pairs.
9120 *
9121 * @private
9122 * @static
9123 * @name Cache
9124 * @memberOf _.memoize
9125 */
9126 function MapCache() {
9127 this.__data__ = {};
9128 }
9129
9130 /**
9131 * Removes `key` and its value from the cache.
9132 *
9133 * @private
9134 * @name delete
9135 * @memberOf _.memoize.Cache
9136 * @param {string} key The key of the value to remove.
9137 * @returns {boolean} Returns `true` if the entry was removed successfully, else `false`.
9138 */
9139 function mapDelete(key) {
9140 return this.has(key) && delete this.__data__[key];
9141 }
9142
9143 /**
9144 * Gets the cached value for `key`.
9145 *
9146 * @private
9147 * @name get
9148 * @memberOf _.memoize.Cache
9149 * @param {string} key The key of the value to get.
9150 * @returns {*} Returns the cached value.
9151 */
9152 function mapGet(key) {
9153 return key == '__proto__' ? undefined : this.__data__[key];
9154 }
9155
9156 /**
9157 * Checks if a cached value for `key` exists.
9158 *
9159 * @private
9160 * @name has
9161 * @memberOf _.memoize.Cache
9162 * @param {string} key The key of the entry to check.
9163 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
9164 */
9165 function mapHas(key) {
9166 return key != '__proto__' && hasOwnProperty.call(this.__data__, key);
9167 }
9168
9169 /**
9170 * Sets `value` to `key` of the cache.
9171 *
9172 * @private
9173 * @name set
9174 * @memberOf _.memoize.Cache
9175 * @param {string} key The key of the value to cache.
9176 * @param {*} value The value to cache.
9177 * @returns {Object} Returns the cache object.
9178 */
9179 function mapSet(key, value) {
9180 if (key != '__proto__') {
9181 this.__data__[key] = value;
9182 }
9183 return this;
9184 }
9185
9186 /*------------------------------------------------------------------------*/
9187
9188 /**
9189 *
9190 * Creates a cache object to store unique values.
9191 *
9192 * @private
9193 * @param {Array} [values] The values to cache.
9194 */
9195 function SetCache(values) {
9196 var length = values ? values.length : 0;
9197
9198 this.data = { 'hash': nativeCreate(null), 'set': new Set };
9199 while (length--) {
9200 this.push(values[length]);
9201 }
9202 }
9203
9204 /**
9205 * Checks if `value` is in `cache` mimicking the return signature of
9206 * `_.indexOf` by returning `0` if the value is found, else `-1`.
9207 *
9208 * @private
9209 * @param {Object} cache The cache to search.
9210 * @param {*} value The value to search for.
9211 * @returns {number} Returns `0` if `value` is found, else `-1`.
9212 */
9213 function cacheIndexOf(cache, value) {
9214 var data = cache.data,
9215 result = (typeof value == 'string' || isObject(value)) ? data.set.has(value) : data.hash[value];
9216
9217 return result ? 0 : -1;
9218 }
9219
9220 /**
9221 * Adds `value` to the cache.
9222 *
9223 * @private
9224 * @name push
9225 * @memberOf SetCache
9226 * @param {*} value The value to cache.
9227 */
9228 function cachePush(value) {
9229 var data = this.data;
9230 if (typeof value == 'string' || isObject(value)) {
9231 data.set.add(value);
9232 } else {
9233 data.hash[value] = true;
9234 }
9235 }
9236
9237 /*------------------------------------------------------------------------*/
9238
9239 /**
9240 * Creates a new array joining `array` with `other`.
9241 *
9242 * @private
9243 * @param {Array} array The array to join.
9244 * @param {Array} other The other array to join.
9245 * @returns {Array} Returns the new concatenated array.
9246 */
9247 function arrayConcat(array, other) {
9248 var index = -1,
9249 length = array.length,
9250 othIndex = -1,
9251 othLength = other.length,
9252 result = Array(length + othLength);
9253
9254 while (++index < length) {
9255 result[index] = array[index];
9256 }
9257 while (++othIndex < othLength) {
9258 result[index++] = other[othIndex];
9259 }
9260 return result;
9261 }
9262
9263 /**
9264 * Copies the values of `source` to `array`.
9265 *
9266 * @private
9267 * @param {Array} source The array to copy values from.
9268 * @param {Array} [array=[]] The array to copy values to.
9269 * @returns {Array} Returns `array`.
9270 */
9271 function arrayCopy(source, array) {
9272 var index = -1,
9273 length = source.length;
9274
9275 array || (array = Array(length));
9276 while (++index < length) {
9277 array[index] = source[index];
9278 }
9279 return array;
9280 }
9281
9282 /**
9283 * A specialized version of `_.forEach` for arrays without support for callback
9284 * shorthands and `this` binding.
9285 *
9286 * @private
9287 * @param {Array} array The array to iterate over.
9288 * @param {Function} iteratee The function invoked per iteration.
9289 * @returns {Array} Returns `array`.
9290 */
9291 function arrayEach(array, iteratee) {
9292 var index = -1,
9293 length = array.length;
9294
9295 while (++index < length) {
9296 if (iteratee(array[index], index, array) === false) {
9297 break;
9298 }
9299 }
9300 return array;
9301 }
9302
9303 /**
9304 * A specialized version of `_.forEachRight` for arrays without support for
9305 * callback shorthands and `this` binding.
9306 *
9307 * @private
9308 * @param {Array} array The array to iterate over.
9309 * @param {Function} iteratee The function invoked per iteration.
9310 * @returns {Array} Returns `array`.
9311 */
9312 function arrayEachRight(array, iteratee) {
9313 var length = array.length;
9314
9315 while (length--) {
9316 if (iteratee(array[length], length, array) === false) {
9317 break;
9318 }
9319 }
9320 return array;
9321 }
9322
9323 /**
9324 * A specialized version of `_.every` for arrays without support for callback
9325 * shorthands and `this` binding.
9326 *
9327 * @private
9328 * @param {Array} array The array to iterate over.
9329 * @param {Function} predicate The function invoked per iteration.
9330 * @returns {boolean} Returns `true` if all elements pass the predicate check,
9331 * else `false`.
9332 */
9333 function arrayEvery(array, predicate) {
9334 var index = -1,
9335 length = array.length;
9336
9337 while (++index < length) {
9338 if (!predicate(array[index], index, array)) {
9339 return false;
9340 }
9341 }
9342 return true;
9343 }
9344
9345 /**
9346 * A specialized version of `baseExtremum` for arrays which invokes `iteratee`
9347 * with one argument: (value).
9348 *
9349 * @private
9350 * @param {Array} array The array to iterate over.
9351 * @param {Function} iteratee The function invoked per iteration.
9352 * @param {Function} comparator The function used to compare values.
9353 * @param {*} exValue The initial extremum value.
9354 * @returns {*} Returns the extremum value.
9355 */
9356 function arrayExtremum(array, iteratee, comparator, exValue) {
9357 var index = -1,
9358 length = array.length,
9359 computed = exValue,
9360 result = computed;
9361
9362 while (++index < length) {
9363 var value = array[index],
9364 current = +iteratee(value);
9365
9366 if (comparator(current, computed)) {
9367 computed = current;
9368 result = value;
9369 }
9370 }
9371 return result;
9372 }
9373
9374 /**
9375 * A specialized version of `_.filter` for arrays without support for callback
9376 * shorthands and `this` binding.
9377 *
9378 * @private
9379 * @param {Array} array The array to iterate over.
9380 * @param {Function} predicate The function invoked per iteration.
9381 * @returns {Array} Returns the new filtered array.
9382 */
9383 function arrayFilter(array, predicate) {
9384 var index = -1,
9385 length = array.length,
9386 resIndex = -1,
9387 result = [];
9388
9389 while (++index < length) {
9390 var value = array[index];
9391 if (predicate(value, index, array)) {
9392 result[++resIndex] = value;
9393 }
9394 }
9395 return result;
9396 }
9397
9398 /**
9399 * A specialized version of `_.map` for arrays without support for callback
9400 * shorthands and `this` binding.
9401 *
9402 * @private
9403 * @param {Array} array The array to iterate over.
9404 * @param {Function} iteratee The function invoked per iteration.
9405 * @returns {Array} Returns the new mapped array.
9406 */
9407 function arrayMap(array, iteratee) {
9408 var index = -1,
9409 length = array.length,
9410 result = Array(length);
9411
9412 while (++index < length) {
9413 result[index] = iteratee(array[index], index, array);
9414 }
9415 return result;
9416 }
9417
9418 /**
9419 * Appends the elements of `values` to `array`.
9420 *
9421 * @private
9422 * @param {Array} array The array to modify.
9423 * @param {Array} values The values to append.
9424 * @returns {Array} Returns `array`.
9425 */
9426 function arrayPush(array, values) {
9427 var index = -1,
9428 length = values.length,
9429 offset = array.length;
9430
9431 while (++index < length) {
9432 array[offset + index] = values[index];
9433 }
9434 return array;
9435 }
9436
9437 /**
9438 * A specialized version of `_.reduce` for arrays without support for callback
9439 * shorthands and `this` binding.
9440 *
9441 * @private
9442 * @param {Array} array The array to iterate over.
9443 * @param {Function} iteratee The function invoked per iteration.
9444 * @param {*} [accumulator] The initial value.
9445 * @param {boolean} [initFromArray] Specify using the first element of `array`
9446 * as the initial value.
9447 * @returns {*} Returns the accumulated value.
9448 */
9449 function arrayReduce(array, iteratee, accumulator, initFromArray) {
9450 var index = -1,
9451 length = array.length;
9452
9453 if (initFromArray && length) {
9454 accumulator = array[++index];
9455 }
9456 while (++index < length) {
9457 accumulator = iteratee(accumulator, array[index], index, array);
9458 }
9459 return accumulator;
9460 }
9461
9462 /**
9463 * A specialized version of `_.reduceRight` for arrays without support for
9464 * callback shorthands and `this` binding.
9465 *
9466 * @private
9467 * @param {Array} array The array to iterate over.
9468 * @param {Function} iteratee The function invoked per iteration.
9469 * @param {*} [accumulator] The initial value.
9470 * @param {boolean} [initFromArray] Specify using the last element of `array`
9471 * as the initial value.
9472 * @returns {*} Returns the accumulated value.
9473 */
9474 function arrayReduceRight(array, iteratee, accumulator, initFromArray) {
9475 var length = array.length;
9476 if (initFromArray && length) {
9477 accumulator = array[--length];
9478 }
9479 while (length--) {
9480 accumulator = iteratee(accumulator, array[length], length, array);
9481 }
9482 return accumulator;
9483 }
9484
9485 /**
9486 * A specialized version of `_.some` for arrays without support for callback
9487 * shorthands and `this` binding.
9488 *
9489 * @private
9490 * @param {Array} array The array to iterate over.
9491 * @param {Function} predicate The function invoked per iteration.
9492 * @returns {boolean} Returns `true` if any element passes the predicate check,
9493 * else `false`.
9494 */
9495 function arraySome(array, predicate) {
9496 var index = -1,
9497 length = array.length;
9498
9499 while (++index < length) {
9500 if (predicate(array[index], index, array)) {
9501 return true;
9502 }
9503 }
9504 return false;
9505 }
9506
9507 /**
9508 * A specialized version of `_.sum` for arrays without support for callback
9509 * shorthands and `this` binding..
9510 *
9511 * @private
9512 * @param {Array} array The array to iterate over.
9513 * @param {Function} iteratee The function invoked per iteration.
9514 * @returns {number} Returns the sum.
9515 */
9516 function arraySum(array, iteratee) {
9517 var length = array.length,
9518 result = 0;
9519
9520 while (length--) {
9521 result += +iteratee(array[length]) || 0;
9522 }
9523 return result;
9524 }
9525
9526 /**
9527 * Used by `_.defaults` to customize its `_.assign` use.
9528 *
9529 * @private
9530 * @param {*} objectValue The destination object property value.
9531 * @param {*} sourceValue The source object property value.
9532 * @returns {*} Returns the value to assign to the destination object.
9533 */
9534 function assignDefaults(objectValue, sourceValue) {
9535 return objectValue === undefined ? sourceValue : objectValue;
9536 }
9537
9538 /**
9539 * Used by `_.template` to customize its `_.assign` use.
9540 *
9541 * **Note:** This function is like `assignDefaults` except that it ignores
9542 * inherited property values when checking if a property is `undefined`.
9543 *
9544 * @private
9545 * @param {*} objectValue The destination object property value.
9546 * @param {*} sourceValue The source object property value.
9547 * @param {string} key The key associated with the object and source values.
9548 * @param {Object} object The destination object.
9549 * @returns {*} Returns the value to assign to the destination object.
9550 */
9551 function assignOwnDefaults(objectValue, sourceValue, key, object) {
9552 return (objectValue === undefined || !hasOwnProperty.call(object, key))
9553 ? sourceValue
9554 : objectValue;
9555 }
9556
9557 /**
9558 * A specialized version of `_.assign` for customizing assigned values without
9559 * support for argument juggling, multiple sources, and `this` binding `customizer`
9560 * functions.
9561 *
9562 * @private
9563 * @param {Object} object The destination object.
9564 * @param {Object} source The source object.
9565 * @param {Function} customizer The function to customize assigned values.
9566 * @returns {Object} Returns `object`.
9567 */
9568 function assignWith(object, source, customizer) {
9569 var index = -1,
9570 props = keys(source),
9571 length = props.length;
9572
9573 while (++index < length) {
9574 var key = props[index],
9575 value = object[key],
9576 result = customizer(value, source[key], key, object, source);
9577
9578 if ((result === result ? (result !== value) : (value === value)) ||
9579 (value === undefined && !(key in object))) {
9580 object[key] = result;
9581 }
9582 }
9583 return object;
9584 }
9585
9586 /**
9587 * The base implementation of `_.assign` without support for argument juggling,
9588 * multiple sources, and `customizer` functions.
9589 *
9590 * @private
9591 * @param {Object} object The destination object.
9592 * @param {Object} source The source object.
9593 * @returns {Object} Returns `object`.
9594 */
9595 function baseAssign(object, source) {
9596 return source == null
9597 ? object
9598 : baseCopy(source, keys(source), object);
9599 }
9600
9601 /**
9602 * The base implementation of `_.at` without support for string collections
9603 * and individual key arguments.
9604 *
9605 * @private
9606 * @param {Array|Object} collection The collection to iterate over.
9607 * @param {number[]|string[]} props The property names or indexes of elements to pick.
9608 * @returns {Array} Returns the new array of picked elements.
9609 */
9610 function baseAt(collection, props) {
9611 var index = -1,
9612 isNil = collection == null,
9613 isArr = !isNil && isArrayLike(collection),
9614 length = isArr ? collection.length : 0,
9615 propsLength = props.length,
9616 result = Array(propsLength);
9617
9618 while(++index < propsLength) {
9619 var key = props[index];
9620 if (isArr) {
9621 result[index] = isIndex(key, length) ? collection[key] : undefined;
9622 } else {
9623 result[index] = isNil ? undefined : collection[key];
9624 }
9625 }
9626 return result;
9627 }
9628
9629 /**
9630 * Copies properties of `source` to `object`.
9631 *
9632 * @private
9633 * @param {Object} source The object to copy properties from.
9634 * @param {Array} props The property names to copy.
9635 * @param {Object} [object={}] The object to copy properties to.
9636 * @returns {Object} Returns `object`.
9637 */
9638 function baseCopy(source, props, object) {
9639 object || (object = {});
9640
9641 var index = -1,
9642 length = props.length;
9643
9644 while (++index < length) {
9645 var key = props[index];
9646 object[key] = source[key];
9647 }
9648 return object;
9649 }
9650
9651 /**
9652 * The base implementation of `_.callback` which supports specifying the
9653 * number of arguments to provide to `func`.
9654 *
9655 * @private
9656 * @param {*} [func=_.identity] The value to convert to a callback.
9657 * @param {*} [thisArg] The `this` binding of `func`.
9658 * @param {number} [argCount] The number of arguments to provide to `func`.
9659 * @returns {Function} Returns the callback.
9660 */
9661 function baseCallback(func, thisArg, argCount) {
9662 var type = typeof func;
9663 if (type == 'function') {
9664 return thisArg === undefined
9665 ? func
9666 : bindCallback(func, thisArg, argCount);
9667 }
9668 if (func == null) {
9669 return identity;
9670 }
9671 if (type == 'object') {
9672 return baseMatches(func);
9673 }
9674 return thisArg === undefined
9675 ? property(func)
9676 : baseMatchesProperty(func, thisArg);
9677 }
9678
9679 /**
9680 * The base implementation of `_.clone` without support for argument juggling
9681 * and `this` binding `customizer` functions.
9682 *
9683 * @private
9684 * @param {*} value The value to clone.
9685 * @param {boolean} [isDeep] Specify a deep clone.
9686 * @param {Function} [customizer] The function to customize cloning values.
9687 * @param {string} [key] The key of `value`.
9688 * @param {Object} [object] The object `value` belongs to.
9689 * @param {Array} [stackA=[]] Tracks traversed source objects.
9690 * @param {Array} [stackB=[]] Associates clones with source counterparts.
9691 * @returns {*} Returns the cloned value.
9692 */
9693 function baseClone(value, isDeep, customizer, key, object, stackA, stackB) {
9694 var result;
9695 if (customizer) {
9696 result = object ? customizer(value, key, object) : customizer(value);
9697 }
9698 if (result !== undefined) {
9699 return result;
9700 }
9701 if (!isObject(value)) {
9702 return value;
9703 }
9704 var isArr = isArray(value);
9705 if (isArr) {
9706 result = initCloneArray(value);
9707 if (!isDeep) {
9708 return arrayCopy(value, result);
9709 }
9710 } else {
9711 var tag = objToString.call(value),
9712 isFunc = tag == funcTag;
9713
9714 if (tag == objectTag || tag == argsTag || (isFunc && !object)) {
9715 result = initCloneObject(isFunc ? {} : value);
9716 if (!isDeep) {
9717 return baseAssign(result, value);
9718 }
9719 } else {
9720 return cloneableTags[tag]
9721 ? initCloneByTag(value, tag, isDeep)
9722 : (object ? value : {});
9723 }
9724 }
9725 // Check for circular references and return its corresponding clone.
9726 stackA || (stackA = []);
9727 stackB || (stackB = []);
9728
9729 var length = stackA.length;
9730 while (length--) {
9731 if (stackA[length] == value) {
9732 return stackB[length];
9733 }
9734 }
9735 // Add the source value to the stack of traversed objects and associate it with its clone.
9736 stackA.push(value);
9737 stackB.push(result);
9738
9739 // Recursively populate clone (susceptible to call stack limits).
9740 (isArr ? arrayEach : baseForOwn)(value, function(subValue, key) {
9741 result[key] = baseClone(subValue, isDeep, customizer, key, value, stackA, stackB);
9742 });
9743 return result;
9744 }
9745
9746 /**
9747 * The base implementation of `_.create` without support for assigning
9748 * properties to the created object.
9749 *
9750 * @private
9751 * @param {Object} prototype The object to inherit from.
9752 * @returns {Object} Returns the new object.
9753 */
9754 var baseCreate = (function() {
9755 function object() {}
9756 return function(prototype) {
9757 if (isObject(prototype)) {
9758 object.prototype = prototype;
9759 var result = new object;
9760 object.prototype = undefined;
9761 }
9762 return result || {};
9763 };
9764 }());
9765
9766 /**
9767 * The base implementation of `_.delay` and `_.defer` which accepts an index
9768 * of where to slice the arguments to provide to `func`.
9769 *
9770 * @private
9771 * @param {Function} func The function to delay.
9772 * @param {number} wait The number of milliseconds to delay invocation.
9773 * @param {Object} args The arguments provide to `func`.
9774 * @returns {number} Returns the timer id.
9775 */
9776 function baseDelay(func, wait, args) {
9777 if (typeof func != 'function') {
9778 throw new TypeError(FUNC_ERROR_TEXT);
9779 }
9780 return setTimeout(function() { func.apply(undefined, args); }, wait);
9781 }
9782
9783 /**
9784 * The base implementation of `_.difference` which accepts a single array
9785 * of values to exclude.
9786 *
9787 * @private
9788 * @param {Array} array The array to inspect.
9789 * @param {Array} values The values to exclude.
9790 * @returns {Array} Returns the new array of filtered values.
9791 */
9792 function baseDifference(array, values) {
9793 var length = array ? array.length : 0,
9794 result = [];
9795
9796 if (!length) {
9797 return result;
9798 }
9799 var index = -1,
9800 indexOf = getIndexOf(),
9801 isCommon = indexOf == baseIndexOf,
9802 cache = (isCommon && values.length >= LARGE_ARRAY_SIZE) ? createCache(values) : null,
9803 valuesLength = values.length;
9804
9805 if (cache) {
9806 indexOf = cacheIndexOf;
9807 isCommon = false;
9808 values = cache;
9809 }
9810 outer:
9811 while (++index < length) {
9812 var value = array[index];
9813
9814 if (isCommon && value === value) {
9815 var valuesIndex = valuesLength;
9816 while (valuesIndex--) {
9817 if (values[valuesIndex] === value) {
9818 continue outer;
9819 }
9820 }
9821 result.push(value);
9822 }
9823 else if (indexOf(values, value, 0) < 0) {
9824 result.push(value);
9825 }
9826 }
9827 return result;
9828 }
9829
9830 /**
9831 * The base implementation of `_.forEach` without support for callback
9832 * shorthands and `this` binding.
9833 *
9834 * @private
9835 * @param {Array|Object|string} collection The collection to iterate over.
9836 * @param {Function} iteratee The function invoked per iteration.
9837 * @returns {Array|Object|string} Returns `collection`.
9838 */
9839 var baseEach = createBaseEach(baseForOwn);
9840
9841 /**
9842 * The base implementation of `_.forEachRight` without support for callback
9843 * shorthands and `this` binding.
9844 *
9845 * @private
9846 * @param {Array|Object|string} collection The collection to iterate over.
9847 * @param {Function} iteratee The function invoked per iteration.
9848 * @returns {Array|Object|string} Returns `collection`.
9849 */
9850 var baseEachRight = createBaseEach(baseForOwnRight, true);
9851
9852 /**
9853 * The base implementation of `_.every` without support for callback
9854 * shorthands and `this` binding.
9855 *
9856 * @private
9857 * @param {Array|Object|string} collection The collection to iterate over.
9858 * @param {Function} predicate The function invoked per iteration.
9859 * @returns {boolean} Returns `true` if all elements pass the predicate check,
9860 * else `false`
9861 */
9862 function baseEvery(collection, predicate) {
9863 var result = true;
9864 baseEach(collection, function(value, index, collection) {
9865 result = !!predicate(value, index, collection);
9866 return result;
9867 });
9868 return result;
9869 }
9870
9871 /**
9872 * Gets the extremum value of `collection` invoking `iteratee` for each value
9873 * in `collection` to generate the criterion by which the value is ranked.
9874 * The `iteratee` is invoked with three arguments: (value, index|key, collection).
9875 *
9876 * @private
9877 * @param {Array|Object|string} collection The collection to iterate over.
9878 * @param {Function} iteratee The function invoked per iteration.
9879 * @param {Function} comparator The function used to compare values.
9880 * @param {*} exValue The initial extremum value.
9881 * @returns {*} Returns the extremum value.
9882 */
9883 function baseExtremum(collection, iteratee, comparator, exValue) {
9884 var computed = exValue,
9885 result = computed;
9886
9887 baseEach(collection, function(value, index, collection) {
9888 var current = +iteratee(value, index, collection);
9889 if (comparator(current, computed) || (current === exValue && current === result)) {
9890 computed = current;
9891 result = value;
9892 }
9893 });
9894 return result;
9895 }
9896
9897 /**
9898 * The base implementation of `_.fill` without an iteratee call guard.
9899 *
9900 * @private
9901 * @param {Array} array The array to fill.
9902 * @param {*} value The value to fill `array` with.
9903 * @param {number} [start=0] The start position.
9904 * @param {number} [end=array.length] The end position.
9905 * @returns {Array} Returns `array`.
9906 */
9907 function baseFill(array, value, start, end) {
9908 var length = array.length;
9909
9910 start = start == null ? 0 : (+start || 0);
9911 if (start < 0) {
9912 start = -start > length ? 0 : (length + start);
9913 }
9914 end = (end === undefined || end > length) ? length : (+end || 0);
9915 if (end < 0) {
9916 end += length;
9917 }
9918 length = start > end ? 0 : (end >>> 0);
9919 start >>>= 0;
9920
9921 while (start < length) {
9922 array[start++] = value;
9923 }
9924 return array;
9925 }
9926
9927 /**
9928 * The base implementation of `_.filter` without support for callback
9929 * shorthands and `this` binding.
9930 *
9931 * @private
9932 * @param {Array|Object|string} collection The collection to iterate over.
9933 * @param {Function} predicate The function invoked per iteration.
9934 * @returns {Array} Returns the new filtered array.
9935 */
9936 function baseFilter(collection, predicate) {
9937 var result = [];
9938 baseEach(collection, function(value, index, collection) {
9939 if (predicate(value, index, collection)) {
9940 result.push(value);
9941 }
9942 });
9943 return result;
9944 }
9945
9946 /**
9947 * The base implementation of `_.find`, `_.findLast`, `_.findKey`, and `_.findLastKey`,
9948 * without support for callback shorthands and `this` binding, which iterates
9949 * over `collection` using the provided `eachFunc`.
9950 *
9951 * @private
9952 * @param {Array|Object|string} collection The collection to search.
9953 * @param {Function} predicate The function invoked per iteration.
9954 * @param {Function} eachFunc The function to iterate over `collection`.
9955 * @param {boolean} [retKey] Specify returning the key of the found element
9956 * instead of the element itself.
9957 * @returns {*} Returns the found element or its key, else `undefined`.
9958 */
9959 function baseFind(collection, predicate, eachFunc, retKey) {
9960 var result;
9961 eachFunc(collection, function(value, key, collection) {
9962 if (predicate(value, key, collection)) {
9963 result = retKey ? key : value;
9964 return false;
9965 }
9966 });
9967 return result;
9968 }
9969
9970 /**
9971 * The base implementation of `_.flatten` with added support for restricting
9972 * flattening and specifying the start index.
9973 *
9974 * @private
9975 * @param {Array} array The array to flatten.
9976 * @param {boolean} [isDeep] Specify a deep flatten.
9977 * @param {boolean} [isStrict] Restrict flattening to arrays-like objects.
9978 * @param {Array} [result=[]] The initial result value.
9979 * @returns {Array} Returns the new flattened array.
9980 */
9981 function baseFlatten(array, isDeep, isStrict, result) {
9982 result || (result = []);
9983
9984 var index = -1,
9985 length = array.length;
9986
9987 while (++index < length) {
9988 var value = array[index];
9989 if (isObjectLike(value) && isArrayLike(value) &&
9990 (isStrict || isArray(value) || isArguments(value))) {
9991 if (isDeep) {
9992 // Recursively flatten arrays (susceptible to call stack limits).
9993 baseFlatten(value, isDeep, isStrict, result);
9994 } else {
9995 arrayPush(result, value);
9996 }
9997 } else if (!isStrict) {
9998 result[result.length] = value;
9999 }
10000 }
10001 return result;
10002 }
10003
10004 /**
10005 * The base implementation of `baseForIn` and `baseForOwn` which iterates
10006 * over `object` properties returned by `keysFunc` invoking `iteratee` for
10007 * each property. Iteratee functions may exit iteration early by explicitly
10008 * returning `false`.
10009 *
10010 * @private
10011 * @param {Object} object The object to iterate over.
10012 * @param {Function} iteratee The function invoked per iteration.
10013 * @param {Function} keysFunc The function to get the keys of `object`.
10014 * @returns {Object} Returns `object`.
10015 */
10016 var baseFor = createBaseFor();
10017
10018 /**
10019 * This function is like `baseFor` except that it iterates over properties
10020 * in the opposite order.
10021 *
10022 * @private
10023 * @param {Object} object The object to iterate over.
10024 * @param {Function} iteratee The function invoked per iteration.
10025 * @param {Function} keysFunc The function to get the keys of `object`.
10026 * @returns {Object} Returns `object`.
10027 */
10028 var baseForRight = createBaseFor(true);
10029
10030 /**
10031 * The base implementation of `_.forIn` without support for callback
10032 * shorthands and `this` binding.
10033 *
10034 * @private
10035 * @param {Object} object The object to iterate over.
10036 * @param {Function} iteratee The function invoked per iteration.
10037 * @returns {Object} Returns `object`.
10038 */
10039 function baseForIn(object, iteratee) {
10040 return baseFor(object, iteratee, keysIn);
10041 }
10042
10043 /**
10044 * The base implementation of `_.forOwn` without support for callback
10045 * shorthands and `this` binding.
10046 *
10047 * @private
10048 * @param {Object} object The object to iterate over.
10049 * @param {Function} iteratee The function invoked per iteration.
10050 * @returns {Object} Returns `object`.
10051 */
10052 function baseForOwn(object, iteratee) {
10053 return baseFor(object, iteratee, keys);
10054 }
10055
10056 /**
10057 * The base implementation of `_.forOwnRight` without support for callback
10058 * shorthands and `this` binding.
10059 *
10060 * @private
10061 * @param {Object} object The object to iterate over.
10062 * @param {Function} iteratee The function invoked per iteration.
10063 * @returns {Object} Returns `object`.
10064 */
10065 function baseForOwnRight(object, iteratee) {
10066 return baseForRight(object, iteratee, keys);
10067 }
10068
10069 /**
10070 * The base implementation of `_.functions` which creates an array of
10071 * `object` function property names filtered from those provided.
10072 *
10073 * @private
10074 * @param {Object} object The object to inspect.
10075 * @param {Array} props The property names to filter.
10076 * @returns {Array} Returns the new array of filtered property names.
10077 */
10078 function baseFunctions(object, props) {
10079 var index = -1,
10080 length = props.length,
10081 resIndex = -1,
10082 result = [];
10083
10084 while (++index < length) {
10085 var key = props[index];
10086 if (isFunction(object[key])) {
10087 result[++resIndex] = key;
10088 }
10089 }
10090 return result;
10091 }
10092
10093 /**
10094 * The base implementation of `get` without support for string paths
10095 * and default values.
10096 *
10097 * @private
10098 * @param {Object} object The object to query.
10099 * @param {Array} path The path of the property to get.
10100 * @param {string} [pathKey] The key representation of path.
10101 * @returns {*} Returns the resolved value.
10102 */
10103 function baseGet(object, path, pathKey) {
10104 if (object == null) {
10105 return;
10106 }
10107 if (pathKey !== undefined && pathKey in toObject(object)) {
10108 path = [pathKey];
10109 }
10110 var index = 0,
10111 length = path.length;
10112
10113 while (object != null && index < length) {
10114 object = object[path[index++]];
10115 }
10116 return (index && index == length) ? object : undefined;
10117 }
10118
10119 /**
10120 * The base implementation of `_.isEqual` without support for `this` binding
10121 * `customizer` functions.
10122 *
10123 * @private
10124 * @param {*} value The value to compare.
10125 * @param {*} other The other value to compare.
10126 * @param {Function} [customizer] The function to customize comparing values.
10127 * @param {boolean} [isLoose] Specify performing partial comparisons.
10128 * @param {Array} [stackA] Tracks traversed `value` objects.
10129 * @param {Array} [stackB] Tracks traversed `other` objects.
10130 * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
10131 */
10132 function baseIsEqual(value, other, customizer, isLoose, stackA, stackB) {
10133 if (value === other) {
10134 return true;
10135 }
10136 if (value == null || other == null || (!isObject(value) && !isObjectLike(other))) {
10137 return value !== value && other !== other;
10138 }
10139 return baseIsEqualDeep(value, other, baseIsEqual, customizer, isLoose, stackA, stackB);
10140 }
10141
10142 /**
10143 * A specialized version of `baseIsEqual` for arrays and objects which performs
10144 * deep comparisons and tracks traversed objects enabling objects with circular
10145 * references to be compared.
10146 *
10147 * @private
10148 * @param {Object} object The object to compare.
10149 * @param {Object} other The other object to compare.
10150 * @param {Function} equalFunc The function to determine equivalents of values.
10151 * @param {Function} [customizer] The function to customize comparing objects.
10152 * @param {boolean} [isLoose] Specify performing partial comparisons.
10153 * @param {Array} [stackA=[]] Tracks traversed `value` objects.
10154 * @param {Array} [stackB=[]] Tracks traversed `other` objects.
10155 * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
10156 */
10157 function baseIsEqualDeep(object, other, equalFunc, customizer, isLoose, stackA, stackB) {
10158 var objIsArr = isArray(object),
10159 othIsArr = isArray(other),
10160 objTag = arrayTag,
10161 othTag = arrayTag;
10162
10163 if (!objIsArr) {
10164 objTag = objToString.call(object);
10165 if (objTag == argsTag) {
10166 objTag = objectTag;
10167 } else if (objTag != objectTag) {
10168 objIsArr = isTypedArray(object);
10169 }
10170 }
10171 if (!othIsArr) {
10172 othTag = objToString.call(other);
10173 if (othTag == argsTag) {
10174 othTag = objectTag;
10175 } else if (othTag != objectTag) {
10176 othIsArr = isTypedArray(other);
10177 }
10178 }
10179 var objIsObj = objTag == objectTag,
10180 othIsObj = othTag == objectTag,
10181 isSameTag = objTag == othTag;
10182
10183 if (isSameTag && !(objIsArr || objIsObj)) {
10184 return equalByTag(object, other, objTag);
10185 }
10186 if (!isLoose) {
10187 var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),
10188 othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');
10189
10190 if (objIsWrapped || othIsWrapped) {
10191 return equalFunc(objIsWrapped ? object.value() : object, othIsWrapped ? other.value() : other, customizer, isLoose, stackA, stackB);
10192 }
10193 }
10194 if (!isSameTag) {
10195 return false;
10196 }
10197 // Assume cyclic values are equal.
10198 // For more information on detecting circular references see https://es5.github.io/#JO.
10199 stackA || (stackA = []);
10200 stackB || (stackB = []);
10201
10202 var length = stackA.length;
10203 while (length--) {
10204 if (stackA[length] == object) {
10205 return stackB[length] == other;
10206 }
10207 }
10208 // Add `object` and `other` to the stack of traversed objects.
10209 stackA.push(object);
10210 stackB.push(other);
10211
10212 var result = (objIsArr ? equalArrays : equalObjects)(object, other, equalFunc, customizer, isLoose, stackA, stackB);
10213
10214 stackA.pop();
10215 stackB.pop();
10216
10217 return result;
10218 }
10219
10220 /**
10221 * The base implementation of `_.isMatch` without support for callback
10222 * shorthands and `this` binding.
10223 *
10224 * @private
10225 * @param {Object} object The object to inspect.
10226 * @param {Array} matchData The propery names, values, and compare flags to match.
10227 * @param {Function} [customizer] The function to customize comparing objects.
10228 * @returns {boolean} Returns `true` if `object` is a match, else `false`.
10229 */
10230 function baseIsMatch(object, matchData, customizer) {
10231 var index = matchData.length,
10232 length = index,
10233 noCustomizer = !customizer;
10234
10235 if (object == null) {
10236 return !length;
10237 }
10238 object = toObject(object);
10239 while (index--) {
10240 var data = matchData[index];
10241 if ((noCustomizer && data[2])
10242 ? data[1] !== object[data[0]]
10243 : !(data[0] in object)
10244 ) {
10245 return false;
10246 }
10247 }
10248 while (++index < length) {
10249 data = matchData[index];
10250 var key = data[0],
10251 objValue = object[key],
10252 srcValue = data[1];
10253
10254 if (noCustomizer && data[2]) {
10255 if (objValue === undefined && !(key in object)) {
10256 return false;
10257 }
10258 } else {
10259 var result = customizer ? customizer(objValue, srcValue, key) : undefined;
10260 if (!(result === undefined ? baseIsEqual(srcValue, objValue, customizer, true) : result)) {
10261 return false;
10262 }
10263 }
10264 }
10265 return true;
10266 }
10267
10268 /**
10269 * The base implementation of `_.map` without support for callback shorthands
10270 * and `this` binding.
10271 *
10272 * @private
10273 * @param {Array|Object|string} collection The collection to iterate over.
10274 * @param {Function} iteratee The function invoked per iteration.
10275 * @returns {Array} Returns the new mapped array.
10276 */
10277 function baseMap(collection, iteratee) {
10278 var index = -1,
10279 result = isArrayLike(collection) ? Array(collection.length) : [];
10280
10281 baseEach(collection, function(value, key, collection) {
10282 result[++index] = iteratee(value, key, collection);
10283 });
10284 return result;
10285 }
10286
10287 /**
10288 * The base implementation of `_.matches` which does not clone `source`.
10289 *
10290 * @private
10291 * @param {Object} source The object of property values to match.
10292 * @returns {Function} Returns the new function.
10293 */
10294 function baseMatches(source) {
10295 var matchData = getMatchData(source);
10296 if (matchData.length == 1 && matchData[0][2]) {
10297 var key = matchData[0][0],
10298 value = matchData[0][1];
10299
10300 return function(object) {
10301 if (object == null) {
10302 return false;
10303 }
10304 return object[key] === value && (value !== undefined || (key in toObject(object)));
10305 };
10306 }
10307 return function(object) {
10308 return baseIsMatch(object, matchData);
10309 };
10310 }
10311
10312 /**
10313 * The base implementation of `_.matchesProperty` which does not clone `srcValue`.
10314 *
10315 * @private
10316 * @param {string} path The path of the property to get.
10317 * @param {*} srcValue The value to compare.
10318 * @returns {Function} Returns the new function.
10319 */
10320 function baseMatchesProperty(path, srcValue) {
10321 var isArr = isArray(path),
10322 isCommon = isKey(path) && isStrictComparable(srcValue),
10323 pathKey = (path + '');
10324
10325 path = toPath(path);
10326 return function(object) {
10327 if (object == null) {
10328 return false;
10329 }
10330 var key = pathKey;
10331 object = toObject(object);
10332 if ((isArr || !isCommon) && !(key in object)) {
10333 object = path.length == 1 ? object : baseGet(object, baseSlice(path, 0, -1));
10334 if (object == null) {
10335 return false;
10336 }
10337 key = last(path);
10338 object = toObject(object);
10339 }
10340 return object[key] === srcValue
10341 ? (srcValue !== undefined || (key in object))
10342 : baseIsEqual(srcValue, object[key], undefined, true);
10343 };
10344 }
10345
10346 /**
10347 * The base implementation of `_.merge` without support for argument juggling,
10348 * multiple sources, and `this` binding `customizer` functions.
10349 *
10350 * @private
10351 * @param {Object} object The destination object.
10352 * @param {Object} source The source object.
10353 * @param {Function} [customizer] The function to customize merged values.
10354 * @param {Array} [stackA=[]] Tracks traversed source objects.
10355 * @param {Array} [stackB=[]] Associates values with source counterparts.
10356 * @returns {Object} Returns `object`.
10357 */
10358 function baseMerge(object, source, customizer, stackA, stackB) {
10359 if (!isObject(object)) {
10360 return object;
10361 }
10362 var isSrcArr = isArrayLike(source) && (isArray(source) || isTypedArray(source)),
10363 props = isSrcArr ? undefined : keys(source);
10364
10365 arrayEach(props || source, function(srcValue, key) {
10366 if (props) {
10367 key = srcValue;
10368 srcValue = source[key];
10369 }
10370 if (isObjectLike(srcValue)) {
10371 stackA || (stackA = []);
10372 stackB || (stackB = []);
10373 baseMergeDeep(object, source, key, baseMerge, customizer, stackA, stackB);
10374 }
10375 else {
10376 var value = object[key],
10377 result = customizer ? customizer(value, srcValue, key, object, source) : undefined,
10378 isCommon = result === undefined;
10379
10380 if (isCommon) {
10381 result = srcValue;
10382 }
10383 if ((result !== undefined || (isSrcArr && !(key in object))) &&
10384 (isCommon || (result === result ? (result !== value) : (value === value)))) {
10385 object[key] = result;
10386 }
10387 }
10388 });
10389 return object;
10390 }
10391
10392 /**
10393 * A specialized version of `baseMerge` for arrays and objects which performs
10394 * deep merges and tracks traversed objects enabling objects with circular
10395 * references to be merged.
10396 *
10397 * @private
10398 * @param {Object} object The destination object.
10399 * @param {Object} source The source object.
10400 * @param {string} key The key of the value to merge.
10401 * @param {Function} mergeFunc The function to merge values.
10402 * @param {Function} [customizer] The function to customize merged values.
10403 * @param {Array} [stackA=[]] Tracks traversed source objects.
10404 * @param {Array} [stackB=[]] Associates values with source counterparts.
10405 * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
10406 */
10407 function baseMergeDeep(object, source, key, mergeFunc, customizer, stackA, stackB) {
10408 var length = stackA.length,
10409 srcValue = source[key];
10410
10411 while (length--) {
10412 if (stackA[length] == srcValue) {
10413 object[key] = stackB[length];
10414 return;
10415 }
10416 }
10417 var value = object[key],
10418 result = customizer ? customizer(value, srcValue, key, object, source) : undefined,
10419 isCommon = result === undefined;
10420
10421 if (isCommon) {
10422 result = srcValue;
10423 if (isArrayLike(srcValue) && (isArray(srcValue) || isTypedArray(srcValue))) {
10424 result = isArray(value)
10425 ? value
10426 : (isArrayLike(value) ? arrayCopy(value) : []);
10427 }
10428 else if (isPlainObject(srcValue) || isArguments(srcValue)) {
10429 result = isArguments(value)
10430 ? toPlainObject(value)
10431 : (isPlainObject(value) ? value : {});
10432 }
10433 else {
10434 isCommon = false;
10435 }
10436 }
10437 // Add the source value to the stack of traversed objects and associate
10438 // it with its merged value.
10439 stackA.push(srcValue);
10440 stackB.push(result);
10441
10442 if (isCommon) {
10443 // Recursively merge objects and arrays (susceptible to call stack limits).
10444 object[key] = mergeFunc(result, srcValue, customizer, stackA, stackB);
10445 } else if (result === result ? (result !== value) : (value === value)) {
10446 object[key] = result;
10447 }
10448 }
10449
10450 /**
10451 * The base implementation of `_.property` without support for deep paths.
10452 *
10453 * @private
10454 * @param {string} key The key of the property to get.
10455 * @returns {Function} Returns the new function.
10456 */
10457 function baseProperty(key) {
10458 return function(object) {
10459 return object == null ? undefined : object[key];
10460 };
10461 }
10462
10463 /**
10464 * A specialized version of `baseProperty` which supports deep paths.
10465 *
10466 * @private
10467 * @param {Array|string} path The path of the property to get.
10468 * @returns {Function} Returns the new function.
10469 */
10470 function basePropertyDeep(path) {
10471 var pathKey = (path + '');
10472 path = toPath(path);
10473 return function(object) {
10474 return baseGet(object, path, pathKey);
10475 };
10476 }
10477
10478 /**
10479 * The base implementation of `_.pullAt` without support for individual
10480 * index arguments and capturing the removed elements.
10481 *
10482 * @private
10483 * @param {Array} array The array to modify.
10484 * @param {number[]} indexes The indexes of elements to remove.
10485 * @returns {Array} Returns `array`.
10486 */
10487 function basePullAt(array, indexes) {
10488 var length = array ? indexes.length : 0;
10489 while (length--) {
10490 var index = indexes[length];
10491 if (index != previous && isIndex(index)) {
10492 var previous = index;
10493 splice.call(array, index, 1);
10494 }
10495 }
10496 return array;
10497 }
10498
10499 /**
10500 * The base implementation of `_.random` without support for argument juggling
10501 * and returning floating-point numbers.
10502 *
10503 * @private
10504 * @param {number} min The minimum possible value.
10505 * @param {number} max The maximum possible value.
10506 * @returns {number} Returns the random number.
10507 */
10508 function baseRandom(min, max) {
10509 return min + nativeFloor(nativeRandom() * (max - min + 1));
10510 }
10511
10512 /**
10513 * The base implementation of `_.reduce` and `_.reduceRight` without support
10514 * for callback shorthands and `this` binding, which iterates over `collection`
10515 * using the provided `eachFunc`.
10516 *
10517 * @private
10518 * @param {Array|Object|string} collection The collection to iterate over.
10519 * @param {Function} iteratee The function invoked per iteration.
10520 * @param {*} accumulator The initial value.
10521 * @param {boolean} initFromCollection Specify using the first or last element
10522 * of `collection` as the initial value.
10523 * @param {Function} eachFunc The function to iterate over `collection`.
10524 * @returns {*} Returns the accumulated value.
10525 */
10526 function baseReduce(collection, iteratee, accumulator, initFromCollection, eachFunc) {
10527 eachFunc(collection, function(value, index, collection) {
10528 accumulator = initFromCollection
10529 ? (initFromCollection = false, value)
10530 : iteratee(accumulator, value, index, collection);
10531 });
10532 return accumulator;
10533 }
10534
10535 /**
10536 * The base implementation of `setData` without support for hot loop detection.
10537 *
10538 * @private
10539 * @param {Function} func The function to associate metadata with.
10540 * @param {*} data The metadata.
10541 * @returns {Function} Returns `func`.
10542 */
10543 var baseSetData = !metaMap ? identity : function(func, data) {
10544 metaMap.set(func, data);
10545 return func;
10546 };
10547
10548 /**
10549 * The base implementation of `_.slice` without an iteratee call guard.
10550 *
10551 * @private
10552 * @param {Array} array The array to slice.
10553 * @param {number} [start=0] The start position.
10554 * @param {number} [end=array.length] The end position.
10555 * @returns {Array} Returns the slice of `array`.
10556 */
10557 function baseSlice(array, start, end) {
10558 var index = -1,
10559 length = array.length;
10560
10561 start = start == null ? 0 : (+start || 0);
10562 if (start < 0) {
10563 start = -start > length ? 0 : (length + start);
10564 }
10565 end = (end === undefined || end > length) ? length : (+end || 0);
10566 if (end < 0) {
10567 end += length;
10568 }
10569 length = start > end ? 0 : ((end - start) >>> 0);
10570 start >>>= 0;
10571
10572 var result = Array(length);
10573 while (++index < length) {
10574 result[index] = array[index + start];
10575 }
10576 return result;
10577 }
10578
10579 /**
10580 * The base implementation of `_.some` without support for callback shorthands
10581 * and `this` binding.
10582 *
10583 * @private
10584 * @param {Array|Object|string} collection The collection to iterate over.
10585 * @param {Function} predicate The function invoked per iteration.
10586 * @returns {boolean} Returns `true` if any element passes the predicate check,
10587 * else `false`.
10588 */
10589 function baseSome(collection, predicate) {
10590 var result;
10591
10592 baseEach(collection, function(value, index, collection) {
10593 result = predicate(value, index, collection);
10594 return !result;
10595 });
10596 return !!result;
10597 }
10598
10599 /**
10600 * The base implementation of `_.sortBy` which uses `comparer` to define
10601 * the sort order of `array` and replaces criteria objects with their
10602 * corresponding values.
10603 *
10604 * @private
10605 * @param {Array} array The array to sort.
10606 * @param {Function} comparer The function to define sort order.
10607 * @returns {Array} Returns `array`.
10608 */
10609 function baseSortBy(array, comparer) {
10610 var length = array.length;
10611
10612 array.sort(comparer);
10613 while (length--) {
10614 array[length] = array[length].value;
10615 }
10616 return array;
10617 }
10618
10619 /**
10620 * The base implementation of `_.sortByOrder` without param guards.
10621 *
10622 * @private
10623 * @param {Array|Object|string} collection The collection to iterate over.
10624 * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by.
10625 * @param {boolean[]} orders The sort orders of `iteratees`.
10626 * @returns {Array} Returns the new sorted array.
10627 */
10628 function baseSortByOrder(collection, iteratees, orders) {
10629 var callback = getCallback(),
10630 index = -1;
10631
10632 iteratees = arrayMap(iteratees, function(iteratee) { return callback(iteratee); });
10633
10634 var result = baseMap(collection, function(value) {
10635 var criteria = arrayMap(iteratees, function(iteratee) { return iteratee(value); });
10636 return { 'criteria': criteria, 'index': ++index, 'value': value };
10637 });
10638
10639 return baseSortBy(result, function(object, other) {
10640 return compareMultiple(object, other, orders);
10641 });
10642 }
10643
10644 /**
10645 * The base implementation of `_.sum` without support for callback shorthands
10646 * and `this` binding.
10647 *
10648 * @private
10649 * @param {Array|Object|string} collection The collection to iterate over.
10650 * @param {Function} iteratee The function invoked per iteration.
10651 * @returns {number} Returns the sum.
10652 */
10653 function baseSum(collection, iteratee) {
10654 var result = 0;
10655 baseEach(collection, function(value, index, collection) {
10656 result += +iteratee(value, index, collection) || 0;
10657 });
10658 return result;
10659 }
10660
10661 /**
10662 * The base implementation of `_.uniq` without support for callback shorthands
10663 * and `this` binding.
10664 *
10665 * @private
10666 * @param {Array} array The array to inspect.
10667 * @param {Function} [iteratee] The function invoked per iteration.
10668 * @returns {Array} Returns the new duplicate-value-free array.
10669 */
10670 function baseUniq(array, iteratee) {
10671 var index = -1,
10672 indexOf = getIndexOf(),
10673 length = array.length,
10674 isCommon = indexOf == baseIndexOf,
10675 isLarge = isCommon && length >= LARGE_ARRAY_SIZE,
10676 seen = isLarge ? createCache() : null,
10677 result = [];
10678
10679 if (seen) {
10680 indexOf = cacheIndexOf;
10681 isCommon = false;
10682 } else {
10683 isLarge = false;
10684 seen = iteratee ? [] : result;
10685 }
10686 outer:
10687 while (++index < length) {
10688 var value = array[index],
10689 computed = iteratee ? iteratee(value, index, array) : value;
10690
10691 if (isCommon && value === value) {
10692 var seenIndex = seen.length;
10693 while (seenIndex--) {
10694 if (seen[seenIndex] === computed) {
10695 continue outer;
10696 }
10697 }
10698 if (iteratee) {
10699 seen.push(computed);
10700 }
10701 result.push(value);
10702 }
10703 else if (indexOf(seen, computed, 0) < 0) {
10704 if (iteratee || isLarge) {
10705 seen.push(computed);
10706 }
10707 result.push(value);
10708 }
10709 }
10710 return result;
10711 }
10712
10713 /**
10714 * The base implementation of `_.values` and `_.valuesIn` which creates an
10715 * array of `object` property values corresponding to the property names
10716 * of `props`.
10717 *
10718 * @private
10719 * @param {Object} object The object to query.
10720 * @param {Array} props The property names to get values for.
10721 * @returns {Object} Returns the array of property values.
10722 */
10723 function baseValues(object, props) {
10724 var index = -1,
10725 length = props.length,
10726 result = Array(length);
10727
10728 while (++index < length) {
10729 result[index] = object[props[index]];
10730 }
10731 return result;
10732 }
10733
10734 /**
10735 * The base implementation of `_.dropRightWhile`, `_.dropWhile`, `_.takeRightWhile`,
10736 * and `_.takeWhile` without support for callback shorthands and `this` binding.
10737 *
10738 * @private
10739 * @param {Array} array The array to query.
10740 * @param {Function} predicate The function invoked per iteration.
10741 * @param {boolean} [isDrop] Specify dropping elements instead of taking them.
10742 * @param {boolean} [fromRight] Specify iterating from right to left.
10743 * @returns {Array} Returns the slice of `array`.
10744 */
10745 function baseWhile(array, predicate, isDrop, fromRight) {
10746 var length = array.length,
10747 index = fromRight ? length : -1;
10748
10749 while ((fromRight ? index-- : ++index < length) && predicate(array[index], index, array)) {}
10750 return isDrop
10751 ? baseSlice(array, (fromRight ? 0 : index), (fromRight ? index + 1 : length))
10752 : baseSlice(array, (fromRight ? index + 1 : 0), (fromRight ? length : index));
10753 }
10754
10755 /**
10756 * The base implementation of `wrapperValue` which returns the result of
10757 * performing a sequence of actions on the unwrapped `value`, where each
10758 * successive action is supplied the return value of the previous.
10759 *
10760 * @private
10761 * @param {*} value The unwrapped value.
10762 * @param {Array} actions Actions to peform to resolve the unwrapped value.
10763 * @returns {*} Returns the resolved value.
10764 */
10765 function baseWrapperValue(value, actions) {
10766 var result = value;
10767 if (result instanceof LazyWrapper) {
10768 result = result.value();
10769 }
10770 var index = -1,
10771 length = actions.length;
10772
10773 while (++index < length) {
10774 var action = actions[index];
10775 result = action.func.apply(action.thisArg, arrayPush([result], action.args));
10776 }
10777 return result;
10778 }
10779
10780 /**
10781 * Performs a binary search of `array` to determine the index at which `value`
10782 * should be inserted into `array` in order to maintain its sort order.
10783 *
10784 * @private
10785 * @param {Array} array The sorted array to inspect.
10786 * @param {*} value The value to evaluate.
10787 * @param {boolean} [retHighest] Specify returning the highest qualified index.
10788 * @returns {number} Returns the index at which `value` should be inserted
10789 * into `array`.
10790 */
10791 function binaryIndex(array, value, retHighest) {
10792 var low = 0,
10793 high = array ? array.length : low;
10794
10795 if (typeof value == 'number' && value === value && high <= HALF_MAX_ARRAY_LENGTH) {
10796 while (low < high) {
10797 var mid = (low + high) >>> 1,
10798 computed = array[mid];
10799
10800 if ((retHighest ? (computed <= value) : (computed < value)) && computed !== null) {
10801 low = mid + 1;
10802 } else {
10803 high = mid;
10804 }
10805 }
10806 return high;
10807 }
10808 return binaryIndexBy(array, value, identity, retHighest);
10809 }
10810
10811 /**
10812 * This function is like `binaryIndex` except that it invokes `iteratee` for
10813 * `value` and each element of `array` to compute their sort ranking. The
10814 * iteratee is invoked with one argument; (value).
10815 *
10816 * @private
10817 * @param {Array} array The sorted array to inspect.
10818 * @param {*} value The value to evaluate.
10819 * @param {Function} iteratee The function invoked per iteration.
10820 * @param {boolean} [retHighest] Specify returning the highest qualified index.
10821 * @returns {number} Returns the index at which `value` should be inserted
10822 * into `array`.
10823 */
10824 function binaryIndexBy(array, value, iteratee, retHighest) {
10825 value = iteratee(value);
10826
10827 var low = 0,
10828 high = array ? array.length : 0,
10829 valIsNaN = value !== value,
10830 valIsNull = value === null,
10831 valIsUndef = value === undefined;
10832
10833 while (low < high) {
10834 var mid = nativeFloor((low + high) / 2),
10835 computed = iteratee(array[mid]),
10836 isDef = computed !== undefined,
10837 isReflexive = computed === computed;
10838
10839 if (valIsNaN) {
10840 var setLow = isReflexive || retHighest;
10841 } else if (valIsNull) {
10842 setLow = isReflexive && isDef && (retHighest || computed != null);
10843 } else if (valIsUndef) {
10844 setLow = isReflexive && (retHighest || isDef);
10845 } else if (computed == null) {
10846 setLow = false;
10847 } else {
10848 setLow = retHighest ? (computed <= value) : (computed < value);
10849 }
10850 if (setLow) {
10851 low = mid + 1;
10852 } else {
10853 high = mid;
10854 }
10855 }
10856 return nativeMin(high, MAX_ARRAY_INDEX);
10857 }
10858
10859 /**
10860 * A specialized version of `baseCallback` which only supports `this` binding
10861 * and specifying the number of arguments to provide to `func`.
10862 *
10863 * @private
10864 * @param {Function} func The function to bind.
10865 * @param {*} thisArg The `this` binding of `func`.
10866 * @param {number} [argCount] The number of arguments to provide to `func`.
10867 * @returns {Function} Returns the callback.
10868 */
10869 function bindCallback(func, thisArg, argCount) {
10870 if (typeof func != 'function') {
10871 return identity;
10872 }
10873 if (thisArg === undefined) {
10874 return func;
10875 }
10876 switch (argCount) {
10877 case 1: return function(value) {
10878 return func.call(thisArg, value);
10879 };
10880 case 3: return function(value, index, collection) {
10881 return func.call(thisArg, value, index, collection);
10882 };
10883 case 4: return function(accumulator, value, index, collection) {
10884 return func.call(thisArg, accumulator, value, index, collection);
10885 };
10886 case 5: return function(value, other, key, object, source) {
10887 return func.call(thisArg, value, other, key, object, source);
10888 };
10889 }
10890 return function() {
10891 return func.apply(thisArg, arguments);
10892 };
10893 }
10894
10895 /**
10896 * Creates a clone of the given array buffer.
10897 *
10898 * @private
10899 * @param {ArrayBuffer} buffer The array buffer to clone.
10900 * @returns {ArrayBuffer} Returns the cloned array buffer.
10901 */
10902 function bufferClone(buffer) {
10903 var result = new ArrayBuffer(buffer.byteLength),
10904 view = new Uint8Array(result);
10905
10906 view.set(new Uint8Array(buffer));
10907 return result;
10908 }
10909
10910 /**
10911 * Creates an array that is the composition of partially applied arguments,
10912 * placeholders, and provided arguments into a single array of arguments.
10913 *
10914 * @private
10915 * @param {Array|Object} args The provided arguments.
10916 * @param {Array} partials The arguments to prepend to those provided.
10917 * @param {Array} holders The `partials` placeholder indexes.
10918 * @returns {Array} Returns the new array of composed arguments.
10919 */
10920 function composeArgs(args, partials, holders) {
10921 var holdersLength = holders.length,
10922 argsIndex = -1,
10923 argsLength = nativeMax(args.length - holdersLength, 0),
10924 leftIndex = -1,
10925 leftLength = partials.length,
10926 result = Array(leftLength + argsLength);
10927
10928 while (++leftIndex < leftLength) {
10929 result[leftIndex] = partials[leftIndex];
10930 }
10931 while (++argsIndex < holdersLength) {
10932 result[holders[argsIndex]] = args[argsIndex];
10933 }
10934 while (argsLength--) {
10935 result[leftIndex++] = args[argsIndex++];
10936 }
10937 return result;
10938 }
10939
10940 /**
10941 * This function is like `composeArgs` except that the arguments composition
10942 * is tailored for `_.partialRight`.
10943 *
10944 * @private
10945 * @param {Array|Object} args The provided arguments.
10946 * @param {Array} partials The arguments to append to those provided.
10947 * @param {Array} holders The `partials` placeholder indexes.
10948 * @returns {Array} Returns the new array of composed arguments.
10949 */
10950 function composeArgsRight(args, partials, holders) {
10951 var holdersIndex = -1,
10952 holdersLength = holders.length,
10953 argsIndex = -1,
10954 argsLength = nativeMax(args.length - holdersLength, 0),
10955 rightIndex = -1,
10956 rightLength = partials.length,
10957 result = Array(argsLength + rightLength);
10958
10959 while (++argsIndex < argsLength) {
10960 result[argsIndex] = args[argsIndex];
10961 }
10962 var offset = argsIndex;
10963 while (++rightIndex < rightLength) {
10964 result[offset + rightIndex] = partials[rightIndex];
10965 }
10966 while (++holdersIndex < holdersLength) {
10967 result[offset + holders[holdersIndex]] = args[argsIndex++];
10968 }
10969 return result;
10970 }
10971
10972 /**
10973 * Creates a `_.countBy`, `_.groupBy`, `_.indexBy`, or `_.partition` function.
10974 *
10975 * @private
10976 * @param {Function} setter The function to set keys and values of the accumulator object.
10977 * @param {Function} [initializer] The function to initialize the accumulator object.
10978 * @returns {Function} Returns the new aggregator function.
10979 */
10980 function createAggregator(setter, initializer) {
10981 return function(collection, iteratee, thisArg) {
10982 var result = initializer ? initializer() : {};
10983 iteratee = getCallback(iteratee, thisArg, 3);
10984
10985 if (isArray(collection)) {
10986 var index = -1,
10987 length = collection.length;
10988
10989 while (++index < length) {
10990 var value = collection[index];
10991 setter(result, value, iteratee(value, index, collection), collection);
10992 }
10993 } else {
10994 baseEach(collection, function(value, key, collection) {
10995 setter(result, value, iteratee(value, key, collection), collection);
10996 });
10997 }
10998 return result;
10999 };
11000 }
11001
11002 /**
11003 * Creates a `_.assign`, `_.defaults`, or `_.merge` function.
11004 *
11005 * @private
11006 * @param {Function} assigner The function to assign values.
11007 * @returns {Function} Returns the new assigner function.
11008 */
11009 function createAssigner(assigner) {
11010 return restParam(function(object, sources) {
11011 var index = -1,
11012 length = object == null ? 0 : sources.length,
11013 customizer = length > 2 ? sources[length - 2] : undefined,
11014 guard = length > 2 ? sources[2] : undefined,
11015 thisArg = length > 1 ? sources[length - 1] : undefined;
11016
11017 if (typeof customizer == 'function') {
11018 customizer = bindCallback(customizer, thisArg, 5);
11019 length -= 2;
11020 } else {
11021 customizer = typeof thisArg == 'function' ? thisArg : undefined;
11022 length -= (customizer ? 1 : 0);
11023 }
11024 if (guard && isIterateeCall(sources[0], sources[1], guard)) {
11025 customizer = length < 3 ? undefined : customizer;
11026 length = 1;
11027 }
11028 while (++index < length) {
11029 var source = sources[index];
11030 if (source) {
11031 assigner(object, source, customizer);
11032 }
11033 }
11034 return object;
11035 });
11036 }
11037
11038 /**
11039 * Creates a `baseEach` or `baseEachRight` function.
11040 *
11041 * @private
11042 * @param {Function} eachFunc The function to iterate over a collection.
11043 * @param {boolean} [fromRight] Specify iterating from right to left.
11044 * @returns {Function} Returns the new base function.
11045 */
11046 function createBaseEach(eachFunc, fromRight) {
11047 return function(collection, iteratee) {
11048 var length = collection ? getLength(collection) : 0;
11049 if (!isLength(length)) {
11050 return eachFunc(collection, iteratee);
11051 }
11052 var index = fromRight ? length : -1,
11053 iterable = toObject(collection);
11054
11055 while ((fromRight ? index-- : ++index < length)) {
11056 if (iteratee(iterable[index], index, iterable) === false) {
11057 break;
11058 }
11059 }
11060 return collection;
11061 };
11062 }
11063
11064 /**
11065 * Creates a base function for `_.forIn` or `_.forInRight`.
11066 *
11067 * @private
11068 * @param {boolean} [fromRight] Specify iterating from right to left.
11069 * @returns {Function} Returns the new base function.
11070 */
11071 function createBaseFor(fromRight) {
11072 return function(object, iteratee, keysFunc) {
11073 var iterable = toObject(object),
11074 props = keysFunc(object),
11075 length = props.length,
11076 index = fromRight ? length : -1;
11077
11078 while ((fromRight ? index-- : ++index < length)) {
11079 var key = props[index];
11080 if (iteratee(iterable[key], key, iterable) === false) {
11081 break;
11082 }
11083 }
11084 return object;
11085 };
11086 }
11087
11088 /**
11089 * Creates a function that wraps `func` and invokes it with the `this`
11090 * binding of `thisArg`.
11091 *
11092 * @private
11093 * @param {Function} func The function to bind.
11094 * @param {*} [thisArg] The `this` binding of `func`.
11095 * @returns {Function} Returns the new bound function.
11096 */
11097 function createBindWrapper(func, thisArg) {
11098 var Ctor = createCtorWrapper(func);
11099
11100 function wrapper() {
11101 var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;
11102 return fn.apply(thisArg, arguments);
11103 }
11104 return wrapper;
11105 }
11106
11107 /**
11108 * Creates a `Set` cache object to optimize linear searches of large arrays.
11109 *
11110 * @private
11111 * @param {Array} [values] The values to cache.
11112 * @returns {null|Object} Returns the new cache object if `Set` is supported, else `null`.
11113 */
11114 function createCache(values) {
11115 return (nativeCreate && Set) ? new SetCache(values) : null;
11116 }
11117
11118 /**
11119 * Creates a function that produces compound words out of the words in a
11120 * given string.
11121 *
11122 * @private
11123 * @param {Function} callback The function to combine each word.
11124 * @returns {Function} Returns the new compounder function.
11125 */
11126 function createCompounder(callback) {
11127 return function(string) {
11128 var index = -1,
11129 array = words(deburr(string)),
11130 length = array.length,
11131 result = '';
11132
11133 while (++index < length) {
11134 result = callback(result, array[index], index);
11135 }
11136 return result;
11137 };
11138 }
11139
11140 /**
11141 * Creates a function that produces an instance of `Ctor` regardless of
11142 * whether it was invoked as part of a `new` expression or by `call` or `apply`.
11143 *
11144 * @private
11145 * @param {Function} Ctor The constructor to wrap.
11146 * @returns {Function} Returns the new wrapped function.
11147 */
11148 function createCtorWrapper(Ctor) {
11149 return function() {
11150 // Use a `switch` statement to work with class constructors.
11151 // See http://ecma-international.org/ecma-262/6.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist
11152 // for more details.
11153 var args = arguments;
11154 switch (args.length) {
11155 case 0: return new Ctor;
11156 case 1: return new Ctor(args[0]);
11157 case 2: return new Ctor(args[0], args[1]);
11158 case 3: return new Ctor(args[0], args[1], args[2]);
11159 case 4: return new Ctor(args[0], args[1], args[2], args[3]);
11160 case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]);
11161 case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]);
11162 case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]);
11163 }
11164 var thisBinding = baseCreate(Ctor.prototype),
11165 result = Ctor.apply(thisBinding, args);
11166
11167 // Mimic the constructor's `return` behavior.
11168 // See https://es5.github.io/#x13.2.2 for more details.
11169 return isObject(result) ? result : thisBinding;
11170 };
11171 }
11172
11173 /**
11174 * Creates a `_.curry` or `_.curryRight` function.
11175 *
11176 * @private
11177 * @param {boolean} flag The curry bit flag.
11178 * @returns {Function} Returns the new curry function.
11179 */
11180 function createCurry(flag) {
11181 function curryFunc(func, arity, guard) {
11182 if (guard && isIterateeCall(func, arity, guard)) {
11183 arity = undefined;
11184 }
11185 var result = createWrapper(func, flag, undefined, undefined, undefined, undefined, undefined, arity);
11186 result.placeholder = curryFunc.placeholder;
11187 return result;
11188 }
11189 return curryFunc;
11190 }
11191
11192 /**
11193 * Creates a `_.defaults` or `_.defaultsDeep` function.
11194 *
11195 * @private
11196 * @param {Function} assigner The function to assign values.
11197 * @param {Function} customizer The function to customize assigned values.
11198 * @returns {Function} Returns the new defaults function.
11199 */
11200 function createDefaults(assigner, customizer) {
11201 return restParam(function(args) {
11202 var object = args[0];
11203 if (object == null) {
11204 return object;
11205 }
11206 args.push(customizer);
11207 return assigner.apply(undefined, args);
11208 });
11209 }
11210
11211 /**
11212 * Creates a `_.max` or `_.min` function.
11213 *
11214 * @private
11215 * @param {Function} comparator The function used to compare values.
11216 * @param {*} exValue The initial extremum value.
11217 * @returns {Function} Returns the new extremum function.
11218 */
11219 function createExtremum(comparator, exValue) {
11220 return function(collection, iteratee, thisArg) {
11221 if (thisArg && isIterateeCall(collection, iteratee, thisArg)) {
11222 iteratee = undefined;
11223 }
11224 iteratee = getCallback(iteratee, thisArg, 3);
11225 if (iteratee.length == 1) {
11226 collection = isArray(collection) ? collection : toIterable(collection);
11227 var result = arrayExtremum(collection, iteratee, comparator, exValue);
11228 if (!(collection.length && result === exValue)) {
11229 return result;
11230 }
11231 }
11232 return baseExtremum(collection, iteratee, comparator, exValue);
11233 };
11234 }
11235
11236 /**
11237 * Creates a `_.find` or `_.findLast` function.
11238 *
11239 * @private
11240 * @param {Function} eachFunc The function to iterate over a collection.
11241 * @param {boolean} [fromRight] Specify iterating from right to left.
11242 * @returns {Function} Returns the new find function.
11243 */
11244 function createFind(eachFunc, fromRight) {
11245 return function(collection, predicate, thisArg) {
11246 predicate = getCallback(predicate, thisArg, 3);
11247 if (isArray(collection)) {
11248 var index = baseFindIndex(collection, predicate, fromRight);
11249 return index > -1 ? collection[index] : undefined;
11250 }
11251 return baseFind(collection, predicate, eachFunc);
11252 };
11253 }
11254
11255 /**
11256 * Creates a `_.findIndex` or `_.findLastIndex` function.
11257 *
11258 * @private
11259 * @param {boolean} [fromRight] Specify iterating from right to left.
11260 * @returns {Function} Returns the new find function.
11261 */
11262 function createFindIndex(fromRight) {
11263 return function(array, predicate, thisArg) {
11264 if (!(array && array.length)) {
11265 return -1;
11266 }
11267 predicate = getCallback(predicate, thisArg, 3);
11268 return baseFindIndex(array, predicate, fromRight);
11269 };
11270 }
11271
11272 /**
11273 * Creates a `_.findKey` or `_.findLastKey` function.
11274 *
11275 * @private
11276 * @param {Function} objectFunc The function to iterate over an object.
11277 * @returns {Function} Returns the new find function.
11278 */
11279 function createFindKey(objectFunc) {
11280 return function(object, predicate, thisArg) {
11281 predicate = getCallback(predicate, thisArg, 3);
11282 return baseFind(object, predicate, objectFunc, true);
11283 };
11284 }
11285
11286 /**
11287 * Creates a `_.flow` or `_.flowRight` function.
11288 *
11289 * @private
11290 * @param {boolean} [fromRight] Specify iterating from right to left.
11291 * @returns {Function} Returns the new flow function.
11292 */
11293 function createFlow(fromRight) {
11294 return function() {
11295 var wrapper,
11296 length = arguments.length,
11297 index = fromRight ? length : -1,
11298 leftIndex = 0,
11299 funcs = Array(length);
11300
11301 while ((fromRight ? index-- : ++index < length)) {
11302 var func = funcs[leftIndex++] = arguments[index];
11303 if (typeof func != 'function') {
11304 throw new TypeError(FUNC_ERROR_TEXT);
11305 }
11306 if (!wrapper && LodashWrapper.prototype.thru && getFuncName(func) == 'wrapper') {
11307 wrapper = new LodashWrapper([], true);
11308 }
11309 }
11310 index = wrapper ? -1 : length;
11311 while (++index < length) {
11312 func = funcs[index];
11313
11314 var funcName = getFuncName(func),
11315 data = funcName == 'wrapper' ? getData(func) : undefined;
11316
11317 if (data && isLaziable(data[0]) && data[1] == (ARY_FLAG | CURRY_FLAG | PARTIAL_FLAG | REARG_FLAG) && !data[4].length && data[9] == 1) {
11318 wrapper = wrapper[getFuncName(data[0])].apply(wrapper, data[3]);
11319 } else {
11320 wrapper = (func.length == 1 && isLaziable(func)) ? wrapper[funcName]() : wrapper.thru(func);
11321 }
11322 }
11323 return function() {
11324 var args = arguments,
11325 value = args[0];
11326
11327 if (wrapper && args.length == 1 && isArray(value) && value.length >= LARGE_ARRAY_SIZE) {
11328 return wrapper.plant(value).value();
11329 }
11330 var index = 0,
11331 result = length ? funcs[index].apply(this, args) : value;
11332
11333 while (++index < length) {
11334 result = funcs[index].call(this, result);
11335 }
11336 return result;
11337 };
11338 };
11339 }
11340
11341 /**
11342 * Creates a function for `_.forEach` or `_.forEachRight`.
11343 *
11344 * @private
11345 * @param {Function} arrayFunc The function to iterate over an array.
11346 * @param {Function} eachFunc The function to iterate over a collection.
11347 * @returns {Function} Returns the new each function.
11348 */
11349 function createForEach(arrayFunc, eachFunc) {
11350 return function(collection, iteratee, thisArg) {
11351 return (typeof iteratee == 'function' && thisArg === undefined && isArray(collection))
11352 ? arrayFunc(collection, iteratee)
11353 : eachFunc(collection, bindCallback(iteratee, thisArg, 3));
11354 };
11355 }
11356
11357 /**
11358 * Creates a function for `_.forIn` or `_.forInRight`.
11359 *
11360 * @private
11361 * @param {Function} objectFunc The function to iterate over an object.
11362 * @returns {Function} Returns the new each function.
11363 */
11364 function createForIn(objectFunc) {
11365 return function(object, iteratee, thisArg) {
11366 if (typeof iteratee != 'function' || thisArg !== undefined) {
11367 iteratee = bindCallback(iteratee, thisArg, 3);
11368 }
11369 return objectFunc(object, iteratee, keysIn);
11370 };
11371 }
11372
11373 /**
11374 * Creates a function for `_.forOwn` or `_.forOwnRight`.
11375 *
11376 * @private
11377 * @param {Function} objectFunc The function to iterate over an object.
11378 * @returns {Function} Returns the new each function.
11379 */
11380 function createForOwn(objectFunc) {
11381 return function(object, iteratee, thisArg) {
11382 if (typeof iteratee != 'function' || thisArg !== undefined) {
11383 iteratee = bindCallback(iteratee, thisArg, 3);
11384 }
11385 return objectFunc(object, iteratee);
11386 };
11387 }
11388
11389 /**
11390 * Creates a function for `_.mapKeys` or `_.mapValues`.
11391 *
11392 * @private
11393 * @param {boolean} [isMapKeys] Specify mapping keys instead of values.
11394 * @returns {Function} Returns the new map function.
11395 */
11396 function createObjectMapper(isMapKeys) {
11397 return function(object, iteratee, thisArg) {
11398 var result = {};
11399 iteratee = getCallback(iteratee, thisArg, 3);
11400
11401 baseForOwn(object, function(value, key, object) {
11402 var mapped = iteratee(value, key, object);
11403 key = isMapKeys ? mapped : key;
11404 value = isMapKeys ? value : mapped;
11405 result[key] = value;
11406 });
11407 return result;
11408 };
11409 }
11410
11411 /**
11412 * Creates a function for `_.padLeft` or `_.padRight`.
11413 *
11414 * @private
11415 * @param {boolean} [fromRight] Specify padding from the right.
11416 * @returns {Function} Returns the new pad function.
11417 */
11418 function createPadDir(fromRight) {
11419 return function(string, length, chars) {
11420 string = baseToString(string);
11421 return (fromRight ? string : '') + createPadding(string, length, chars) + (fromRight ? '' : string);
11422 };
11423 }
11424
11425 /**
11426 * Creates a `_.partial` or `_.partialRight` function.
11427 *
11428 * @private
11429 * @param {boolean} flag The partial bit flag.
11430 * @returns {Function} Returns the new partial function.
11431 */
11432 function createPartial(flag) {
11433 var partialFunc = restParam(function(func, partials) {
11434 var holders = replaceHolders(partials, partialFunc.placeholder);
11435 return createWrapper(func, flag, undefined, partials, holders);
11436 });
11437 return partialFunc;
11438 }
11439
11440 /**
11441 * Creates a function for `_.reduce` or `_.reduceRight`.
11442 *
11443 * @private
11444 * @param {Function} arrayFunc The function to iterate over an array.
11445 * @param {Function} eachFunc The function to iterate over a collection.
11446 * @returns {Function} Returns the new each function.
11447 */
11448 function createReduce(arrayFunc, eachFunc) {
11449 return function(collection, iteratee, accumulator, thisArg) {
11450 var initFromArray = arguments.length < 3;
11451 return (typeof iteratee == 'function' && thisArg === undefined && isArray(collection))
11452 ? arrayFunc(collection, iteratee, accumulator, initFromArray)
11453 : baseReduce(collection, getCallback(iteratee, thisArg, 4), accumulator, initFromArray, eachFunc);
11454 };
11455 }
11456
11457 /**
11458 * Creates a function that wraps `func` and invokes it with optional `this`
11459 * binding of, partial application, and currying.
11460 *
11461 * @private
11462 * @param {Function|string} func The function or method name to reference.
11463 * @param {number} bitmask The bitmask of flags. See `createWrapper` for more details.
11464 * @param {*} [thisArg] The `this` binding of `func`.
11465 * @param {Array} [partials] The arguments to prepend to those provided to the new function.
11466 * @param {Array} [holders] The `partials` placeholder indexes.
11467 * @param {Array} [partialsRight] The arguments to append to those provided to the new function.
11468 * @param {Array} [holdersRight] The `partialsRight` placeholder indexes.
11469 * @param {Array} [argPos] The argument positions of the new function.
11470 * @param {number} [ary] The arity cap of `func`.
11471 * @param {number} [arity] The arity of `func`.
11472 * @returns {Function} Returns the new wrapped function.
11473 */
11474 function createHybridWrapper(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) {
11475 var isAry = bitmask & ARY_FLAG,
11476 isBind = bitmask & BIND_FLAG,
11477 isBindKey = bitmask & BIND_KEY_FLAG,
11478 isCurry = bitmask & CURRY_FLAG,
11479 isCurryBound = bitmask & CURRY_BOUND_FLAG,
11480 isCurryRight = bitmask & CURRY_RIGHT_FLAG,
11481 Ctor = isBindKey ? undefined : createCtorWrapper(func);
11482
11483 function wrapper() {
11484 // Avoid `arguments` object use disqualifying optimizations by
11485 // converting it to an array before providing it to other functions.
11486 var length = arguments.length,
11487 index = length,
11488 args = Array(length);
11489
11490 while (index--) {
11491 args[index] = arguments[index];
11492 }
11493 if (partials) {
11494 args = composeArgs(args, partials, holders);
11495 }
11496 if (partialsRight) {
11497 args = composeArgsRight(args, partialsRight, holdersRight);
11498 }
11499 if (isCurry || isCurryRight) {
11500 var placeholder = wrapper.placeholder,
11501 argsHolders = replaceHolders(args, placeholder);
11502
11503 length -= argsHolders.length;
11504 if (length < arity) {
11505 var newArgPos = argPos ? arrayCopy(argPos) : undefined,
11506 newArity = nativeMax(arity - length, 0),
11507 newsHolders = isCurry ? argsHolders : undefined,
11508 newHoldersRight = isCurry ? undefined : argsHolders,
11509 newPartials = isCurry ? args : undefined,
11510 newPartialsRight = isCurry ? undefined : args;
11511
11512 bitmask |= (isCurry ? PARTIAL_FLAG : PARTIAL_RIGHT_FLAG);
11513 bitmask &= ~(isCurry ? PARTIAL_RIGHT_FLAG : PARTIAL_FLAG);
11514
11515 if (!isCurryBound) {
11516 bitmask &= ~(BIND_FLAG | BIND_KEY_FLAG);
11517 }
11518 var newData = [func, bitmask, thisArg, newPartials, newsHolders, newPartialsRight, newHoldersRight, newArgPos, ary, newArity],
11519 result = createHybridWrapper.apply(undefined, newData);
11520
11521 if (isLaziable(func)) {
11522 setData(result, newData);
11523 }
11524 result.placeholder = placeholder;
11525 return result;
11526 }
11527 }
11528 var thisBinding = isBind ? thisArg : this,
11529 fn = isBindKey ? thisBinding[func] : func;
11530
11531 if (argPos) {
11532 args = reorder(args, argPos);
11533 }
11534 if (isAry && ary < args.length) {
11535 args.length = ary;
11536 }
11537 if (this && this !== root && this instanceof wrapper) {
11538 fn = Ctor || createCtorWrapper(func);
11539 }
11540 return fn.apply(thisBinding, args);
11541 }
11542 return wrapper;
11543 }
11544
11545 /**
11546 * Creates the padding required for `string` based on the given `length`.
11547 * The `chars` string is truncated if the number of characters exceeds `length`.
11548 *
11549 * @private
11550 * @param {string} string The string to create padding for.
11551 * @param {number} [length=0] The padding length.
11552 * @param {string} [chars=' '] The string used as padding.
11553 * @returns {string} Returns the pad for `string`.
11554 */
11555 function createPadding(string, length, chars) {
11556 var strLength = string.length;
11557 length = +length;
11558
11559 if (strLength >= length || !nativeIsFinite(length)) {
11560 return '';
11561 }
11562 var padLength = length - strLength;
11563 chars = chars == null ? ' ' : (chars + '');
11564 return repeat(chars, nativeCeil(padLength / chars.length)).slice(0, padLength);
11565 }
11566
11567 /**
11568 * Creates a function that wraps `func` and invokes it with the optional `this`
11569 * binding of `thisArg` and the `partials` prepended to those provided to
11570 * the wrapper.
11571 *
11572 * @private
11573 * @param {Function} func The function to partially apply arguments to.
11574 * @param {number} bitmask The bitmask of flags. See `createWrapper` for more details.
11575 * @param {*} thisArg The `this` binding of `func`.
11576 * @param {Array} partials The arguments to prepend to those provided to the new function.
11577 * @returns {Function} Returns the new bound function.
11578 */
11579 function createPartialWrapper(func, bitmask, thisArg, partials) {
11580 var isBind = bitmask & BIND_FLAG,
11581 Ctor = createCtorWrapper(func);
11582
11583 function wrapper() {
11584 // Avoid `arguments` object use disqualifying optimizations by
11585 // converting it to an array before providing it `func`.
11586 var argsIndex = -1,
11587 argsLength = arguments.length,
11588 leftIndex = -1,
11589 leftLength = partials.length,
11590 args = Array(leftLength + argsLength);
11591
11592 while (++leftIndex < leftLength) {
11593 args[leftIndex] = partials[leftIndex];
11594 }
11595 while (argsLength--) {
11596 args[leftIndex++] = arguments[++argsIndex];
11597 }
11598 var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;
11599 return fn.apply(isBind ? thisArg : this, args);
11600 }
11601 return wrapper;
11602 }
11603
11604 /**
11605 * Creates a `_.ceil`, `_.floor`, or `_.round` function.
11606 *
11607 * @private
11608 * @param {string} methodName The name of the `Math` method to use when rounding.
11609 * @returns {Function} Returns the new round function.
11610 */
11611 function createRound(methodName) {
11612 var func = Math[methodName];
11613 return function(number, precision) {
11614 precision = precision === undefined ? 0 : (+precision || 0);
11615 if (precision) {
11616 precision = pow(10, precision);
11617 return func(number * precision) / precision;
11618 }
11619 return func(number);
11620 };
11621 }
11622
11623 /**
11624 * Creates a `_.sortedIndex` or `_.sortedLastIndex` function.
11625 *
11626 * @private
11627 * @param {boolean} [retHighest] Specify returning the highest qualified index.
11628 * @returns {Function} Returns the new index function.
11629 */
11630 function createSortedIndex(retHighest) {
11631 return function(array, value, iteratee, thisArg) {
11632 var callback = getCallback(iteratee);
11633 return (iteratee == null && callback === baseCallback)
11634 ? binaryIndex(array, value, retHighest)
11635 : binaryIndexBy(array, value, callback(iteratee, thisArg, 1), retHighest);
11636 };
11637 }
11638
11639 /**
11640 * Creates a function that either curries or invokes `func` with optional
11641 * `this` binding and partially applied arguments.
11642 *
11643 * @private
11644 * @param {Function|string} func The function or method name to reference.
11645 * @param {number} bitmask The bitmask of flags.
11646 * The bitmask may be composed of the following flags:
11647 * 1 - `_.bind`
11648 * 2 - `_.bindKey`
11649 * 4 - `_.curry` or `_.curryRight` of a bound function
11650 * 8 - `_.curry`
11651 * 16 - `_.curryRight`
11652 * 32 - `_.partial`
11653 * 64 - `_.partialRight`
11654 * 128 - `_.rearg`
11655 * 256 - `_.ary`
11656 * @param {*} [thisArg] The `this` binding of `func`.
11657 * @param {Array} [partials] The arguments to be partially applied.
11658 * @param {Array} [holders] The `partials` placeholder indexes.
11659 * @param {Array} [argPos] The argument positions of the new function.
11660 * @param {number} [ary] The arity cap of `func`.
11661 * @param {number} [arity] The arity of `func`.
11662 * @returns {Function} Returns the new wrapped function.
11663 */
11664 function createWrapper(func, bitmask, thisArg, partials, holders, argPos, ary, arity) {
11665 var isBindKey = bitmask & BIND_KEY_FLAG;
11666 if (!isBindKey && typeof func != 'function') {
11667 throw new TypeError(FUNC_ERROR_TEXT);
11668 }
11669 var length = partials ? partials.length : 0;
11670 if (!length) {
11671 bitmask &= ~(PARTIAL_FLAG | PARTIAL_RIGHT_FLAG);
11672 partials = holders = undefined;
11673 }
11674 length -= (holders ? holders.length : 0);
11675 if (bitmask & PARTIAL_RIGHT_FLAG) {
11676 var partialsRight = partials,
11677 holdersRight = holders;
11678
11679 partials = holders = undefined;
11680 }
11681 var data = isBindKey ? undefined : getData(func),
11682 newData = [func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity];
11683
11684 if (data) {
11685 mergeData(newData, data);
11686 bitmask = newData[1];
11687 arity = newData[9];
11688 }
11689 newData[9] = arity == null
11690 ? (isBindKey ? 0 : func.length)
11691 : (nativeMax(arity - length, 0) || 0);
11692
11693 if (bitmask == BIND_FLAG) {
11694 var result = createBindWrapper(newData[0], newData[2]);
11695 } else if ((bitmask == PARTIAL_FLAG || bitmask == (BIND_FLAG | PARTIAL_FLAG)) && !newData[4].length) {
11696 result = createPartialWrapper.apply(undefined, newData);
11697 } else {
11698 result = createHybridWrapper.apply(undefined, newData);
11699 }
11700 var setter = data ? baseSetData : setData;
11701 return setter(result, newData);
11702 }
11703
11704 /**
11705 * A specialized version of `baseIsEqualDeep` for arrays with support for
11706 * partial deep comparisons.
11707 *
11708 * @private
11709 * @param {Array} array The array to compare.
11710 * @param {Array} other The other array to compare.
11711 * @param {Function} equalFunc The function to determine equivalents of values.
11712 * @param {Function} [customizer] The function to customize comparing arrays.
11713 * @param {boolean} [isLoose] Specify performing partial comparisons.
11714 * @param {Array} [stackA] Tracks traversed `value` objects.
11715 * @param {Array} [stackB] Tracks traversed `other` objects.
11716 * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.
11717 */
11718 function equalArrays(array, other, equalFunc, customizer, isLoose, stackA, stackB) {
11719 var index = -1,
11720 arrLength = array.length,
11721 othLength = other.length;
11722
11723 if (arrLength != othLength && !(isLoose && othLength > arrLength)) {
11724 return false;
11725 }
11726 // Ignore non-index properties.
11727 while (++index < arrLength) {
11728 var arrValue = array[index],
11729 othValue = other[index],
11730 result = customizer ? customizer(isLoose ? othValue : arrValue, isLoose ? arrValue : othValue, index) : undefined;
11731
11732 if (result !== undefined) {
11733 if (result) {
11734 continue;
11735 }
11736 return false;
11737 }
11738 // Recursively compare arrays (susceptible to call stack limits).
11739 if (isLoose) {
11740 if (!arraySome(other, function(othValue) {
11741 return arrValue === othValue || equalFunc(arrValue, othValue, customizer, isLoose, stackA, stackB);
11742 })) {
11743 return false;
11744 }
11745 } else if (!(arrValue === othValue || equalFunc(arrValue, othValue, customizer, isLoose, stackA, stackB))) {
11746 return false;
11747 }
11748 }
11749 return true;
11750 }
11751
11752 /**
11753 * A specialized version of `baseIsEqualDeep` for comparing objects of
11754 * the same `toStringTag`.
11755 *
11756 * **Note:** This function only supports comparing values with tags of
11757 * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
11758 *
11759 * @private
11760 * @param {Object} object The object to compare.
11761 * @param {Object} other The other object to compare.
11762 * @param {string} tag The `toStringTag` of the objects to compare.
11763 * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
11764 */
11765 function equalByTag(object, other, tag) {
11766 switch (tag) {
11767 case boolTag:
11768 case dateTag:
11769 // Coerce dates and booleans to numbers, dates to milliseconds and booleans
11770 // to `1` or `0` treating invalid dates coerced to `NaN` as not equal.
11771 return +object == +other;
11772
11773 case errorTag:
11774 return object.name == other.name && object.message == other.message;
11775
11776 case numberTag:
11777 // Treat `NaN` vs. `NaN` as equal.
11778 return (object != +object)
11779 ? other != +other
11780 : object == +other;
11781
11782 case regexpTag:
11783 case stringTag:
11784 // Coerce regexes to strings and treat strings primitives and string
11785 // objects as equal. See https://es5.github.io/#x15.10.6.4 for more details.
11786 return object == (other + '');
11787 }
11788 return false;
11789 }
11790
11791 /**
11792 * A specialized version of `baseIsEqualDeep` for objects with support for
11793 * partial deep comparisons.
11794 *
11795 * @private
11796 * @param {Object} object The object to compare.
11797 * @param {Object} other The other object to compare.
11798 * @param {Function} equalFunc The function to determine equivalents of values.
11799 * @param {Function} [customizer] The function to customize comparing values.
11800 * @param {boolean} [isLoose] Specify performing partial comparisons.
11801 * @param {Array} [stackA] Tracks traversed `value` objects.
11802 * @param {Array} [stackB] Tracks traversed `other` objects.
11803 * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
11804 */
11805 function equalObjects(object, other, equalFunc, customizer, isLoose, stackA, stackB) {
11806 var objProps = keys(object),
11807 objLength = objProps.length,
11808 othProps = keys(other),
11809 othLength = othProps.length;
11810
11811 if (objLength != othLength && !isLoose) {
11812 return false;
11813 }
11814 var index = objLength;
11815 while (index--) {
11816 var key = objProps[index];
11817 if (!(isLoose ? key in other : hasOwnProperty.call(other, key))) {
11818 return false;
11819 }
11820 }
11821 var skipCtor = isLoose;
11822 while (++index < objLength) {
11823 key = objProps[index];
11824 var objValue = object[key],
11825 othValue = other[key],
11826 result = customizer ? customizer(isLoose ? othValue : objValue, isLoose? objValue : othValue, key) : undefined;
11827
11828 // Recursively compare objects (susceptible to call stack limits).
11829 if (!(result === undefined ? equalFunc(objValue, othValue, customizer, isLoose, stackA, stackB) : result)) {
11830 return false;
11831 }
11832 skipCtor || (skipCtor = key == 'constructor');
11833 }
11834 if (!skipCtor) {
11835 var objCtor = object.constructor,
11836 othCtor = other.constructor;
11837
11838 // Non `Object` object instances with different constructors are not equal.
11839 if (objCtor != othCtor &&
11840 ('constructor' in object && 'constructor' in other) &&
11841 !(typeof objCtor == 'function' && objCtor instanceof objCtor &&
11842 typeof othCtor == 'function' && othCtor instanceof othCtor)) {
11843 return false;
11844 }
11845 }
11846 return true;
11847 }
11848
11849 /**
11850 * Gets the appropriate "callback" function. If the `_.callback` method is
11851 * customized this function returns the custom method, otherwise it returns
11852 * the `baseCallback` function. If arguments are provided the chosen function
11853 * is invoked with them and its result is returned.
11854 *
11855 * @private
11856 * @returns {Function} Returns the chosen function or its result.
11857 */
11858 function getCallback(func, thisArg, argCount) {
11859 var result = lodash.callback || callback;
11860 result = result === callback ? baseCallback : result;
11861 return argCount ? result(func, thisArg, argCount) : result;
11862 }
11863
11864 /**
11865 * Gets metadata for `func`.
11866 *
11867 * @private
11868 * @param {Function} func The function to query.
11869 * @returns {*} Returns the metadata for `func`.
11870 */
11871 var getData = !metaMap ? noop : function(func) {
11872 return metaMap.get(func);
11873 };
11874
11875 /**
11876 * Gets the name of `func`.
11877 *
11878 * @private
11879 * @param {Function} func The function to query.
11880 * @returns {string} Returns the function name.
11881 */
11882 function getFuncName(func) {
11883 var result = func.name,
11884 array = realNames[result],
11885 length = array ? array.length : 0;
11886
11887 while (length--) {
11888 var data = array[length],
11889 otherFunc = data.func;
11890 if (otherFunc == null || otherFunc == func) {
11891 return data.name;
11892 }
11893 }
11894 return result;
11895 }
11896
11897 /**
11898 * Gets the appropriate "indexOf" function. If the `_.indexOf` method is
11899 * customized this function returns the custom method, otherwise it returns
11900 * the `baseIndexOf` function. If arguments are provided the chosen function
11901 * is invoked with them and its result is returned.
11902 *
11903 * @private
11904 * @returns {Function|number} Returns the chosen function or its result.
11905 */
11906 function getIndexOf(collection, target, fromIndex) {
11907 var result = lodash.indexOf || indexOf;
11908 result = result === indexOf ? baseIndexOf : result;
11909 return collection ? result(collection, target, fromIndex) : result;
11910 }
11911
11912 /**
11913 * Gets the "length" property value of `object`.
11914 *
11915 * **Note:** This function is used to avoid a [JIT bug](https://bugs.webkit.org/show_bug.cgi?id=142792)
11916 * that affects Safari on at least iOS 8.1-8.3 ARM64.
11917 *
11918 * @private
11919 * @param {Object} object The object to query.
11920 * @returns {*} Returns the "length" value.
11921 */
11922 var getLength = baseProperty('length');
11923
11924 /**
11925 * Gets the propery names, values, and compare flags of `object`.
11926 *
11927 * @private
11928 * @param {Object} object The object to query.
11929 * @returns {Array} Returns the match data of `object`.
11930 */
11931 function getMatchData(object) {
11932 var result = pairs(object),
11933 length = result.length;
11934
11935 while (length--) {
11936 result[length][2] = isStrictComparable(result[length][1]);
11937 }
11938 return result;
11939 }
11940
11941 /**
11942 * Gets the native function at `key` of `object`.
11943 *
11944 * @private
11945 * @param {Object} object The object to query.
11946 * @param {string} key The key of the method to get.
11947 * @returns {*} Returns the function if it's native, else `undefined`.
11948 */
11949 function getNative(object, key) {
11950 var value = object == null ? undefined : object[key];
11951 return isNative(value) ? value : undefined;
11952 }
11953
11954 /**
11955 * Gets the view, applying any `transforms` to the `start` and `end` positions.
11956 *
11957 * @private
11958 * @param {number} start The start of the view.
11959 * @param {number} end The end of the view.
11960 * @param {Array} transforms The transformations to apply to the view.
11961 * @returns {Object} Returns an object containing the `start` and `end`
11962 * positions of the view.
11963 */
11964 function getView(start, end, transforms) {
11965 var index = -1,
11966 length = transforms.length;
11967
11968 while (++index < length) {
11969 var data = transforms[index],
11970 size = data.size;
11971
11972 switch (data.type) {
11973 case 'drop': start += size; break;
11974 case 'dropRight': end -= size; break;
11975 case 'take': end = nativeMin(end, start + size); break;
11976 case 'takeRight': start = nativeMax(start, end - size); break;
11977 }
11978 }
11979 return { 'start': start, 'end': end };
11980 }
11981
11982 /**
11983 * Initializes an array clone.
11984 *
11985 * @private
11986 * @param {Array} array The array to clone.
11987 * @returns {Array} Returns the initialized clone.
11988 */
11989 function initCloneArray(array) {
11990 var length = array.length,
11991 result = new array.constructor(length);
11992
11993 // Add array properties assigned by `RegExp#exec`.
11994 if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) {
11995 result.index = array.index;
11996 result.input = array.input;
11997 }
11998 return result;
11999 }
12000
12001 /**
12002 * Initializes an object clone.
12003 *
12004 * @private
12005 * @param {Object} object The object to clone.
12006 * @returns {Object} Returns the initialized clone.
12007 */
12008 function initCloneObject(object) {
12009 var Ctor = object.constructor;
12010 if (!(typeof Ctor == 'function' && Ctor instanceof Ctor)) {
12011 Ctor = Object;
12012 }
12013 return new Ctor;
12014 }
12015
12016 /**
12017 * Initializes an object clone based on its `toStringTag`.
12018 *
12019 * **Note:** This function only supports cloning values with tags of
12020 * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
12021 *
12022 * @private
12023 * @param {Object} object The object to clone.
12024 * @param {string} tag The `toStringTag` of the object to clone.
12025 * @param {boolean} [isDeep] Specify a deep clone.
12026 * @returns {Object} Returns the initialized clone.
12027 */
12028 function initCloneByTag(object, tag, isDeep) {
12029 var Ctor = object.constructor;
12030 switch (tag) {
12031 case arrayBufferTag:
12032 return bufferClone(object);
12033
12034 case boolTag:
12035 case dateTag:
12036 return new Ctor(+object);
12037
12038 case float32Tag: case float64Tag:
12039 case int8Tag: case int16Tag: case int32Tag:
12040 case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag:
12041 var buffer = object.buffer;
12042 return new Ctor(isDeep ? bufferClone(buffer) : buffer, object.byteOffset, object.length);
12043
12044 case numberTag:
12045 case stringTag:
12046 return new Ctor(object);
12047
12048 case regexpTag:
12049 var result = new Ctor(object.source, reFlags.exec(object));
12050 result.lastIndex = object.lastIndex;
12051 }
12052 return result;
12053 }
12054
12055 /**
12056 * Invokes the method at `path` on `object`.
12057 *
12058 * @private
12059 * @param {Object} object The object to query.
12060 * @param {Array|string} path The path of the method to invoke.
12061 * @param {Array} args The arguments to invoke the method with.
12062 * @returns {*} Returns the result of the invoked method.
12063 */
12064 function invokePath(object, path, args) {
12065 if (object != null && !isKey(path, object)) {
12066 path = toPath(path);
12067 object = path.length == 1 ? object : baseGet(object, baseSlice(path, 0, -1));
12068 path = last(path);
12069 }
12070 var func = object == null ? object : object[path];
12071 return func == null ? undefined : func.apply(object, args);
12072 }
12073
12074 /**
12075 * Checks if `value` is array-like.
12076 *
12077 * @private
12078 * @param {*} value The value to check.
12079 * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
12080 */
12081 function isArrayLike(value) {
12082 return value != null && isLength(getLength(value));
12083 }
12084
12085 /**
12086 * Checks if `value` is a valid array-like index.
12087 *
12088 * @private
12089 * @param {*} value The value to check.
12090 * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
12091 * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
12092 */
12093 function isIndex(value, length) {
12094 value = (typeof value == 'number' || reIsUint.test(value)) ? +value : -1;
12095 length = length == null ? MAX_SAFE_INTEGER : length;
12096 return value > -1 && value % 1 == 0 && value < length;
12097 }
12098
12099 /**
12100 * Checks if the provided arguments are from an iteratee call.
12101 *
12102 * @private
12103 * @param {*} value The potential iteratee value argument.
12104 * @param {*} index The potential iteratee index or key argument.
12105 * @param {*} object The potential iteratee object argument.
12106 * @returns {boolean} Returns `true` if the arguments are from an iteratee call, else `false`.
12107 */
12108 function isIterateeCall(value, index, object) {
12109 if (!isObject(object)) {
12110 return false;
12111 }
12112 var type = typeof index;
12113 if (type == 'number'
12114 ? (isArrayLike(object) && isIndex(index, object.length))
12115 : (type == 'string' && index in object)) {
12116 var other = object[index];
12117 return value === value ? (value === other) : (other !== other);
12118 }
12119 return false;
12120 }
12121
12122 /**
12123 * Checks if `value` is a property name and not a property path.
12124 *
12125 * @private
12126 * @param {*} value The value to check.
12127 * @param {Object} [object] The object to query keys on.
12128 * @returns {boolean} Returns `true` if `value` is a property name, else `false`.
12129 */
12130 function isKey(value, object) {
12131 var type = typeof value;
12132 if ((type == 'string' && reIsPlainProp.test(value)) || type == 'number') {
12133 return true;
12134 }
12135 if (isArray(value)) {
12136 return false;
12137 }
12138 var result = !reIsDeepProp.test(value);
12139 return result || (object != null && value in toObject(object));
12140 }
12141
12142 /**
12143 * Checks if `func` has a lazy counterpart.
12144 *
12145 * @private
12146 * @param {Function} func The function to check.
12147 * @returns {boolean} Returns `true` if `func` has a lazy counterpart, else `false`.
12148 */
12149 function isLaziable(func) {
12150 var funcName = getFuncName(func);
12151 if (!(funcName in LazyWrapper.prototype)) {
12152 return false;
12153 }
12154 var other = lodash[funcName];
12155 if (func === other) {
12156 return true;
12157 }
12158 var data = getData(other);
12159 return !!data && func === data[0];
12160 }
12161
12162 /**
12163 * Checks if `value` is a valid array-like length.
12164 *
12165 * **Note:** This function is based on [`ToLength`](http://ecma-international.org/ecma-262/6.0/#sec-tolength).
12166 *
12167 * @private
12168 * @param {*} value The value to check.
12169 * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
12170 */
12171 function isLength(value) {
12172 return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
12173 }
12174
12175 /**
12176 * Checks if `value` is suitable for strict equality comparisons, i.e. `===`.
12177 *
12178 * @private
12179 * @param {*} value The value to check.
12180 * @returns {boolean} Returns `true` if `value` if suitable for strict
12181 * equality comparisons, else `false`.
12182 */
12183 function isStrictComparable(value) {
12184 return value === value && !isObject(value);
12185 }
12186
12187 /**
12188 * Merges the function metadata of `source` into `data`.
12189 *
12190 * Merging metadata reduces the number of wrappers required to invoke a function.
12191 * This is possible because methods like `_.bind`, `_.curry`, and `_.partial`
12192 * may be applied regardless of execution order. Methods like `_.ary` and `_.rearg`
12193 * augment function arguments, making the order in which they are executed important,
12194 * preventing the merging of metadata. However, we make an exception for a safe
12195 * common case where curried functions have `_.ary` and or `_.rearg` applied.
12196 *
12197 * @private
12198 * @param {Array} data The destination metadata.
12199 * @param {Array} source The source metadata.
12200 * @returns {Array} Returns `data`.
12201 */
12202 function mergeData(data, source) {
12203 var bitmask = data[1],
12204 srcBitmask = source[1],
12205 newBitmask = bitmask | srcBitmask,
12206 isCommon = newBitmask < ARY_FLAG;
12207
12208 var isCombo =
12209 (srcBitmask == ARY_FLAG && bitmask == CURRY_FLAG) ||
12210 (srcBitmask == ARY_FLAG && bitmask == REARG_FLAG && data[7].length <= source[8]) ||
12211 (srcBitmask == (ARY_FLAG | REARG_FLAG) && bitmask == CURRY_FLAG);
12212
12213 // Exit early if metadata can't be merged.
12214 if (!(isCommon || isCombo)) {
12215 return data;
12216 }
12217 // Use source `thisArg` if available.
12218 if (srcBitmask & BIND_FLAG) {
12219 data[2] = source[2];
12220 // Set when currying a bound function.
12221 newBitmask |= (bitmask & BIND_FLAG) ? 0 : CURRY_BOUND_FLAG;
12222 }
12223 // Compose partial arguments.
12224 var value = source[3];
12225 if (value) {
12226 var partials = data[3];
12227 data[3] = partials ? composeArgs(partials, value, source[4]) : arrayCopy(value);
12228 data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : arrayCopy(source[4]);
12229 }
12230 // Compose partial right arguments.
12231 value = source[5];
12232 if (value) {
12233 partials = data[5];
12234 data[5] = partials ? composeArgsRight(partials, value, source[6]) : arrayCopy(value);
12235 data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : arrayCopy(source[6]);
12236 }
12237 // Use source `argPos` if available.
12238 value = source[7];
12239 if (value) {
12240 data[7] = arrayCopy(value);
12241 }
12242 // Use source `ary` if it's smaller.
12243 if (srcBitmask & ARY_FLAG) {
12244 data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]);
12245 }
12246 // Use source `arity` if one is not provided.
12247 if (data[9] == null) {
12248 data[9] = source[9];
12249 }
12250 // Use source `func` and merge bitmasks.
12251 data[0] = source[0];
12252 data[1] = newBitmask;
12253
12254 return data;
12255 }
12256
12257 /**
12258 * Used by `_.defaultsDeep` to customize its `_.merge` use.
12259 *
12260 * @private
12261 * @param {*} objectValue The destination object property value.
12262 * @param {*} sourceValue The source object property value.
12263 * @returns {*} Returns the value to assign to the destination object.
12264 */
12265 function mergeDefaults(objectValue, sourceValue) {
12266 return objectValue === undefined ? sourceValue : merge(objectValue, sourceValue, mergeDefaults);
12267 }
12268
12269 /**
12270 * A specialized version of `_.pick` which picks `object` properties specified
12271 * by `props`.
12272 *
12273 * @private
12274 * @param {Object} object The source object.
12275 * @param {string[]} props The property names to pick.
12276 * @returns {Object} Returns the new object.
12277 */
12278 function pickByArray(object, props) {
12279 object = toObject(object);
12280
12281 var index = -1,
12282 length = props.length,
12283 result = {};
12284
12285 while (++index < length) {
12286 var key = props[index];
12287 if (key in object) {
12288 result[key] = object[key];
12289 }
12290 }
12291 return result;
12292 }
12293
12294 /**
12295 * A specialized version of `_.pick` which picks `object` properties `predicate`
12296 * returns truthy for.
12297 *
12298 * @private
12299 * @param {Object} object The source object.
12300 * @param {Function} predicate The function invoked per iteration.
12301 * @returns {Object} Returns the new object.
12302 */
12303 function pickByCallback(object, predicate) {
12304 var result = {};
12305 baseForIn(object, function(value, key, object) {
12306 if (predicate(value, key, object)) {
12307 result[key] = value;
12308 }
12309 });
12310 return result;
12311 }
12312
12313 /**
12314 * Reorder `array` according to the specified indexes where the element at
12315 * the first index is assigned as the first element, the element at
12316 * the second index is assigned as the second element, and so on.
12317 *
12318 * @private
12319 * @param {Array} array The array to reorder.
12320 * @param {Array} indexes The arranged array indexes.
12321 * @returns {Array} Returns `array`.
12322 */
12323 function reorder(array, indexes) {
12324 var arrLength = array.length,
12325 length = nativeMin(indexes.length, arrLength),
12326 oldArray = arrayCopy(array);
12327
12328 while (length--) {
12329 var index = indexes[length];
12330 array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined;
12331 }
12332 return array;
12333 }
12334
12335 /**
12336 * Sets metadata for `func`.
12337 *
12338 * **Note:** If this function becomes hot, i.e. is invoked a lot in a short
12339 * period of time, it will trip its breaker and transition to an identity function
12340 * to avoid garbage collection pauses in V8. See [V8 issue 2070](https://code.google.com/p/v8/issues/detail?id=2070)
12341 * for more details.
12342 *
12343 * @private
12344 * @param {Function} func The function to associate metadata with.
12345 * @param {*} data The metadata.
12346 * @returns {Function} Returns `func`.
12347 */
12348 var setData = (function() {
12349 var count = 0,
12350 lastCalled = 0;
12351
12352 return function(key, value) {
12353 var stamp = now(),
12354 remaining = HOT_SPAN - (stamp - lastCalled);
12355
12356 lastCalled = stamp;
12357 if (remaining > 0) {
12358 if (++count >= HOT_COUNT) {
12359 return key;
12360 }
12361 } else {
12362 count = 0;
12363 }
12364 return baseSetData(key, value);
12365 };
12366 }());
12367
12368 /**
12369 * A fallback implementation of `Object.keys` which creates an array of the
12370 * own enumerable property names of `object`.
12371 *
12372 * @private
12373 * @param {Object} object The object to query.
12374 * @returns {Array} Returns the array of property names.
12375 */
12376 function shimKeys(object) {
12377 var props = keysIn(object),
12378 propsLength = props.length,
12379 length = propsLength && object.length;
12380
12381 var allowIndexes = !!length && isLength(length) &&
12382 (isArray(object) || isArguments(object));
12383
12384 var index = -1,
12385 result = [];
12386
12387 while (++index < propsLength) {
12388 var key = props[index];
12389 if ((allowIndexes && isIndex(key, length)) || hasOwnProperty.call(object, key)) {
12390 result.push(key);
12391 }
12392 }
12393 return result;
12394 }
12395
12396 /**
12397 * Converts `value` to an array-like object if it's not one.
12398 *
12399 * @private
12400 * @param {*} value The value to process.
12401 * @returns {Array|Object} Returns the array-like object.
12402 */
12403 function toIterable(value) {
12404 if (value == null) {
12405 return [];
12406 }
12407 if (!isArrayLike(value)) {
12408 return values(value);
12409 }
12410 return isObject(value) ? value : Object(value);
12411 }
12412
12413 /**
12414 * Converts `value` to an object if it's not one.
12415 *
12416 * @private
12417 * @param {*} value The value to process.
12418 * @returns {Object} Returns the object.
12419 */
12420 function toObject(value) {
12421 return isObject(value) ? value : Object(value);
12422 }
12423
12424 /**
12425 * Converts `value` to property path array if it's not one.
12426 *
12427 * @private
12428 * @param {*} value The value to process.
12429 * @returns {Array} Returns the property path array.
12430 */
12431 function toPath(value) {
12432 if (isArray(value)) {
12433 return value;
12434 }
12435 var result = [];
12436 baseToString(value).replace(rePropName, function(match, number, quote, string) {
12437 result.push(quote ? string.replace(reEscapeChar, '$1') : (number || match));
12438 });
12439 return result;
12440 }
12441
12442 /**
12443 * Creates a clone of `wrapper`.
12444 *
12445 * @private
12446 * @param {Object} wrapper The wrapper to clone.
12447 * @returns {Object} Returns the cloned wrapper.
12448 */
12449 function wrapperClone(wrapper) {
12450 return wrapper instanceof LazyWrapper
12451 ? wrapper.clone()
12452 : new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__, arrayCopy(wrapper.__actions__));
12453 }
12454
12455 /*------------------------------------------------------------------------*/
12456
12457 /**
12458 * Creates an array of elements split into groups the length of `size`.
12459 * If `collection` can't be split evenly, the final chunk will be the remaining
12460 * elements.
12461 *
12462 * @static
12463 * @memberOf _
12464 * @category Array
12465 * @param {Array} array The array to process.
12466 * @param {number} [size=1] The length of each chunk.
12467 * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
12468 * @returns {Array} Returns the new array containing chunks.
12469 * @example
12470 *
12471 * _.chunk(['a', 'b', 'c', 'd'], 2);
12472 * // => [['a', 'b'], ['c', 'd']]
12473 *
12474 * _.chunk(['a', 'b', 'c', 'd'], 3);
12475 * // => [['a', 'b', 'c'], ['d']]
12476 */
12477 function chunk(array, size, guard) {
12478 if (guard ? isIterateeCall(array, size, guard) : size == null) {
12479 size = 1;
12480 } else {
12481 size = nativeMax(nativeFloor(size) || 1, 1);
12482 }
12483 var index = 0,
12484 length = array ? array.length : 0,
12485 resIndex = -1,
12486 result = Array(nativeCeil(length / size));
12487
12488 while (index < length) {
12489 result[++resIndex] = baseSlice(array, index, (index += size));
12490 }
12491 return result;
12492 }
12493
12494 /**
12495 * Creates an array with all falsey values removed. The values `false`, `null`,
12496 * `0`, `""`, `undefined`, and `NaN` are falsey.
12497 *
12498 * @static
12499 * @memberOf _
12500 * @category Array
12501 * @param {Array} array The array to compact.
12502 * @returns {Array} Returns the new array of filtered values.
12503 * @example
12504 *
12505 * _.compact([0, 1, false, 2, '', 3]);
12506 * // => [1, 2, 3]
12507 */
12508 function compact(array) {
12509 var index = -1,
12510 length = array ? array.length : 0,
12511 resIndex = -1,
12512 result = [];
12513
12514 while (++index < length) {
12515 var value = array[index];
12516 if (value) {
12517 result[++resIndex] = value;
12518 }
12519 }
12520 return result;
12521 }
12522
12523 /**
12524 * Creates an array of unique `array` values not included in the other
12525 * provided arrays using [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
12526 * for equality comparisons.
12527 *
12528 * @static
12529 * @memberOf _
12530 * @category Array
12531 * @param {Array} array The array to inspect.
12532 * @param {...Array} [values] The arrays of values to exclude.
12533 * @returns {Array} Returns the new array of filtered values.
12534 * @example
12535 *
12536 * _.difference([1, 2, 3], [4, 2]);
12537 * // => [1, 3]
12538 */
12539 var difference = restParam(function(array, values) {
12540 return (isObjectLike(array) && isArrayLike(array))
12541 ? baseDifference(array, baseFlatten(values, false, true))
12542 : [];
12543 });
12544
12545 /**
12546 * Creates a slice of `array` with `n` elements dropped from the beginning.
12547 *
12548 * @static
12549 * @memberOf _
12550 * @category Array
12551 * @param {Array} array The array to query.
12552 * @param {number} [n=1] The number of elements to drop.
12553 * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
12554 * @returns {Array} Returns the slice of `array`.
12555 * @example
12556 *
12557 * _.drop([1, 2, 3]);
12558 * // => [2, 3]
12559 *
12560 * _.drop([1, 2, 3], 2);
12561 * // => [3]
12562 *
12563 * _.drop([1, 2, 3], 5);
12564 * // => []
12565 *
12566 * _.drop([1, 2, 3], 0);
12567 * // => [1, 2, 3]
12568 */
12569 function drop(array, n, guard) {
12570 var length = array ? array.length : 0;
12571 if (!length) {
12572 return [];
12573 }
12574 if (guard ? isIterateeCall(array, n, guard) : n == null) {
12575 n = 1;
12576 }
12577 return baseSlice(array, n < 0 ? 0 : n);
12578 }
12579
12580 /**
12581 * Creates a slice of `array` with `n` elements dropped from the end.
12582 *
12583 * @static
12584 * @memberOf _
12585 * @category Array
12586 * @param {Array} array The array to query.
12587 * @param {number} [n=1] The number of elements to drop.
12588 * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
12589 * @returns {Array} Returns the slice of `array`.
12590 * @example
12591 *
12592 * _.dropRight([1, 2, 3]);
12593 * // => [1, 2]
12594 *
12595 * _.dropRight([1, 2, 3], 2);
12596 * // => [1]
12597 *
12598 * _.dropRight([1, 2, 3], 5);
12599 * // => []
12600 *
12601 * _.dropRight([1, 2, 3], 0);
12602 * // => [1, 2, 3]
12603 */
12604 function dropRight(array, n, guard) {
12605 var length = array ? array.length : 0;
12606 if (!length) {
12607 return [];
12608 }
12609 if (guard ? isIterateeCall(array, n, guard) : n == null) {
12610 n = 1;
12611 }
12612 n = length - (+n || 0);
12613 return baseSlice(array, 0, n < 0 ? 0 : n);
12614 }
12615
12616 /**
12617 * Creates a slice of `array` excluding elements dropped from the end.
12618 * Elements are dropped until `predicate` returns falsey. The predicate is
12619 * bound to `thisArg` and invoked with three arguments: (value, index, array).
12620 *
12621 * If a property name is provided for `predicate` the created `_.property`
12622 * style callback returns the property value of the given element.
12623 *
12624 * If a value is also provided for `thisArg` the created `_.matchesProperty`
12625 * style callback returns `true` for elements that have a matching property
12626 * value, else `false`.
12627 *
12628 * If an object is provided for `predicate` the created `_.matches` style
12629 * callback returns `true` for elements that match the properties of the given
12630 * object, else `false`.
12631 *
12632 * @static
12633 * @memberOf _
12634 * @category Array
12635 * @param {Array} array The array to query.
12636 * @param {Function|Object|string} [predicate=_.identity] The function invoked
12637 * per iteration.
12638 * @param {*} [thisArg] The `this` binding of `predicate`.
12639 * @returns {Array} Returns the slice of `array`.
12640 * @example
12641 *
12642 * _.dropRightWhile([1, 2, 3], function(n) {
12643 * return n > 1;
12644 * });
12645 * // => [1]
12646 *
12647 * var users = [
12648 * { 'user': 'barney', 'active': true },
12649 * { 'user': 'fred', 'active': false },
12650 * { 'user': 'pebbles', 'active': false }
12651 * ];
12652 *
12653 * // using the `_.matches` callback shorthand
12654 * _.pluck(_.dropRightWhile(users, { 'user': 'pebbles', 'active': false }), 'user');
12655 * // => ['barney', 'fred']
12656 *
12657 * // using the `_.matchesProperty` callback shorthand
12658 * _.pluck(_.dropRightWhile(users, 'active', false), 'user');
12659 * // => ['barney']
12660 *
12661 * // using the `_.property` callback shorthand
12662 * _.pluck(_.dropRightWhile(users, 'active'), 'user');
12663 * // => ['barney', 'fred', 'pebbles']
12664 */
12665 function dropRightWhile(array, predicate, thisArg) {
12666 return (array && array.length)
12667 ? baseWhile(array, getCallback(predicate, thisArg, 3), true, true)
12668 : [];
12669 }
12670
12671 /**
12672 * Creates a slice of `array` excluding elements dropped from the beginning.
12673 * Elements are dropped until `predicate` returns falsey. The predicate is
12674 * bound to `thisArg` and invoked with three arguments: (value, index, array).
12675 *
12676 * If a property name is provided for `predicate` the created `_.property`
12677 * style callback returns the property value of the given element.
12678 *
12679 * If a value is also provided for `thisArg` the created `_.matchesProperty`
12680 * style callback returns `true` for elements that have a matching property
12681 * value, else `false`.
12682 *
12683 * If an object is provided for `predicate` the created `_.matches` style
12684 * callback returns `true` for elements that have the properties of the given
12685 * object, else `false`.
12686 *
12687 * @static
12688 * @memberOf _
12689 * @category Array
12690 * @param {Array} array The array to query.
12691 * @param {Function|Object|string} [predicate=_.identity] The function invoked
12692 * per iteration.
12693 * @param {*} [thisArg] The `this` binding of `predicate`.
12694 * @returns {Array} Returns the slice of `array`.
12695 * @example
12696 *
12697 * _.dropWhile([1, 2, 3], function(n) {
12698 * return n < 3;
12699 * });
12700 * // => [3]
12701 *
12702 * var users = [
12703 * { 'user': 'barney', 'active': false },
12704 * { 'user': 'fred', 'active': false },
12705 * { 'user': 'pebbles', 'active': true }
12706 * ];
12707 *
12708 * // using the `_.matches` callback shorthand
12709 * _.pluck(_.dropWhile(users, { 'user': 'barney', 'active': false }), 'user');
12710 * // => ['fred', 'pebbles']
12711 *
12712 * // using the `_.matchesProperty` callback shorthand
12713 * _.pluck(_.dropWhile(users, 'active', false), 'user');
12714 * // => ['pebbles']
12715 *
12716 * // using the `_.property` callback shorthand
12717 * _.pluck(_.dropWhile(users, 'active'), 'user');
12718 * // => ['barney', 'fred', 'pebbles']
12719 */
12720 function dropWhile(array, predicate, thisArg) {
12721 return (array && array.length)
12722 ? baseWhile(array, getCallback(predicate, thisArg, 3), true)
12723 : [];
12724 }
12725
12726 /**
12727 * Fills elements of `array` with `value` from `start` up to, but not
12728 * including, `end`.
12729 *
12730 * **Note:** This method mutates `array`.
12731 *
12732 * @static
12733 * @memberOf _
12734 * @category Array
12735 * @param {Array} array The array to fill.
12736 * @param {*} value The value to fill `array` with.
12737 * @param {number} [start=0] The start position.
12738 * @param {number} [end=array.length] The end position.
12739 * @returns {Array} Returns `array`.
12740 * @example
12741 *
12742 * var array = [1, 2, 3];
12743 *
12744 * _.fill(array, 'a');
12745 * console.log(array);
12746 * // => ['a', 'a', 'a']
12747 *
12748 * _.fill(Array(3), 2);
12749 * // => [2, 2, 2]
12750 *
12751 * _.fill([4, 6, 8], '*', 1, 2);
12752 * // => [4, '*', 8]
12753 */
12754 function fill(array, value, start, end) {
12755 var length = array ? array.length : 0;
12756 if (!length) {
12757 return [];
12758 }
12759 if (start && typeof start != 'number' && isIterateeCall(array, value, start)) {
12760 start = 0;
12761 end = length;
12762 }
12763 return baseFill(array, value, start, end);
12764 }
12765
12766 /**
12767 * This method is like `_.find` except that it returns the index of the first
12768 * element `predicate` returns truthy for instead of the element itself.
12769 *
12770 * If a property name is provided for `predicate` the created `_.property`
12771 * style callback returns the property value of the given element.
12772 *
12773 * If a value is also provided for `thisArg` the created `_.matchesProperty`
12774 * style callback returns `true` for elements that have a matching property
12775 * value, else `false`.
12776 *
12777 * If an object is provided for `predicate` the created `_.matches` style
12778 * callback returns `true` for elements that have the properties of the given
12779 * object, else `false`.
12780 *
12781 * @static
12782 * @memberOf _
12783 * @category Array
12784 * @param {Array} array The array to search.
12785 * @param {Function|Object|string} [predicate=_.identity] The function invoked
12786 * per iteration.
12787 * @param {*} [thisArg] The `this` binding of `predicate`.
12788 * @returns {number} Returns the index of the found element, else `-1`.
12789 * @example
12790 *
12791 * var users = [
12792 * { 'user': 'barney', 'active': false },
12793 * { 'user': 'fred', 'active': false },
12794 * { 'user': 'pebbles', 'active': true }
12795 * ];
12796 *
12797 * _.findIndex(users, function(chr) {
12798 * return chr.user == 'barney';
12799 * });
12800 * // => 0
12801 *
12802 * // using the `_.matches` callback shorthand
12803 * _.findIndex(users, { 'user': 'fred', 'active': false });
12804 * // => 1
12805 *
12806 * // using the `_.matchesProperty` callback shorthand
12807 * _.findIndex(users, 'active', false);
12808 * // => 0
12809 *
12810 * // using the `_.property` callback shorthand
12811 * _.findIndex(users, 'active');
12812 * // => 2
12813 */
12814 var findIndex = createFindIndex();
12815
12816 /**
12817 * This method is like `_.findIndex` except that it iterates over elements
12818 * of `collection` from right to left.
12819 *
12820 * If a property name is provided for `predicate` the created `_.property`
12821 * style callback returns the property value of the given element.
12822 *
12823 * If a value is also provided for `thisArg` the created `_.matchesProperty`
12824 * style callback returns `true` for elements that have a matching property
12825 * value, else `false`.
12826 *
12827 * If an object is provided for `predicate` the created `_.matches` style
12828 * callback returns `true` for elements that have the properties of the given
12829 * object, else `false`.
12830 *
12831 * @static
12832 * @memberOf _
12833 * @category Array
12834 * @param {Array} array The array to search.
12835 * @param {Function|Object|string} [predicate=_.identity] The function invoked
12836 * per iteration.
12837 * @param {*} [thisArg] The `this` binding of `predicate`.
12838 * @returns {number} Returns the index of the found element, else `-1`.
12839 * @example
12840 *
12841 * var users = [
12842 * { 'user': 'barney', 'active': true },
12843 * { 'user': 'fred', 'active': false },
12844 * { 'user': 'pebbles', 'active': false }
12845 * ];
12846 *
12847 * _.findLastIndex(users, function(chr) {
12848 * return chr.user == 'pebbles';
12849 * });
12850 * // => 2
12851 *
12852 * // using the `_.matches` callback shorthand
12853 * _.findLastIndex(users, { 'user': 'barney', 'active': true });
12854 * // => 0
12855 *
12856 * // using the `_.matchesProperty` callback shorthand
12857 * _.findLastIndex(users, 'active', false);
12858 * // => 2
12859 *
12860 * // using the `_.property` callback shorthand
12861 * _.findLastIndex(users, 'active');
12862 * // => 0
12863 */
12864 var findLastIndex = createFindIndex(true);
12865
12866 /**
12867 * Gets the first element of `array`.
12868 *
12869 * @static
12870 * @memberOf _
12871 * @alias head
12872 * @category Array
12873 * @param {Array} array The array to query.
12874 * @returns {*} Returns the first element of `array`.
12875 * @example
12876 *
12877 * _.first([1, 2, 3]);
12878 * // => 1
12879 *
12880 * _.first([]);
12881 * // => undefined
12882 */
12883 function first(array) {
12884 return array ? array[0] : undefined;
12885 }
12886
12887 /**
12888 * Flattens a nested array. If `isDeep` is `true` the array is recursively
12889 * flattened, otherwise it is only flattened a single level.
12890 *
12891 * @static
12892 * @memberOf _
12893 * @category Array
12894 * @param {Array} array The array to flatten.
12895 * @param {boolean} [isDeep] Specify a deep flatten.
12896 * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
12897 * @returns {Array} Returns the new flattened array.
12898 * @example
12899 *
12900 * _.flatten([1, [2, 3, [4]]]);
12901 * // => [1, 2, 3, [4]]
12902 *
12903 * // using `isDeep`
12904 * _.flatten([1, [2, 3, [4]]], true);
12905 * // => [1, 2, 3, 4]
12906 */
12907 function flatten(array, isDeep, guard) {
12908 var length = array ? array.length : 0;
12909 if (guard && isIterateeCall(array, isDeep, guard)) {
12910 isDeep = false;
12911 }
12912 return length ? baseFlatten(array, isDeep) : [];
12913 }
12914
12915 /**
12916 * Recursively flattens a nested array.
12917 *
12918 * @static
12919 * @memberOf _
12920 * @category Array
12921 * @param {Array} array The array to recursively flatten.
12922 * @returns {Array} Returns the new flattened array.
12923 * @example
12924 *
12925 * _.flattenDeep([1, [2, 3, [4]]]);
12926 * // => [1, 2, 3, 4]
12927 */
12928 function flattenDeep(array) {
12929 var length = array ? array.length : 0;
12930 return length ? baseFlatten(array, true) : [];
12931 }
12932
12933 /**
12934 * Gets the index at which the first occurrence of `value` is found in `array`
12935 * using [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
12936 * for equality comparisons. If `fromIndex` is negative, it is used as the offset
12937 * from the end of `array`. If `array` is sorted providing `true` for `fromIndex`
12938 * performs a faster binary search.
12939 *
12940 * @static
12941 * @memberOf _
12942 * @category Array
12943 * @param {Array} array The array to search.
12944 * @param {*} value The value to search for.
12945 * @param {boolean|number} [fromIndex=0] The index to search from or `true`
12946 * to perform a binary search on a sorted array.
12947 * @returns {number} Returns the index of the matched value, else `-1`.
12948 * @example
12949 *
12950 * _.indexOf([1, 2, 1, 2], 2);
12951 * // => 1
12952 *
12953 * // using `fromIndex`
12954 * _.indexOf([1, 2, 1, 2], 2, 2);
12955 * // => 3
12956 *
12957 * // performing a binary search
12958 * _.indexOf([1, 1, 2, 2], 2, true);
12959 * // => 2
12960 */
12961 function indexOf(array, value, fromIndex) {
12962 var length = array ? array.length : 0;
12963 if (!length) {
12964 return -1;
12965 }
12966 if (typeof fromIndex == 'number') {
12967 fromIndex = fromIndex < 0 ? nativeMax(length + fromIndex, 0) : fromIndex;
12968 } else if (fromIndex) {
12969 var index = binaryIndex(array, value);
12970 if (index < length &&
12971 (value === value ? (value === array[index]) : (array[index] !== array[index]))) {
12972 return index;
12973 }
12974 return -1;
12975 }
12976 return baseIndexOf(array, value, fromIndex || 0);
12977 }
12978
12979 /**
12980 * Gets all but the last element of `array`.
12981 *
12982 * @static
12983 * @memberOf _
12984 * @category Array
12985 * @param {Array} array The array to query.
12986 * @returns {Array} Returns the slice of `array`.
12987 * @example
12988 *
12989 * _.initial([1, 2, 3]);
12990 * // => [1, 2]
12991 */
12992 function initial(array) {
12993 return dropRight(array, 1);
12994 }
12995
12996 /**
12997 * Creates an array of unique values that are included in all of the provided
12998 * arrays using [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
12999 * for equality comparisons.
13000 *
13001 * @static
13002 * @memberOf _
13003 * @category Array
13004 * @param {...Array} [arrays] The arrays to inspect.
13005 * @returns {Array} Returns the new array of shared values.
13006 * @example
13007 * _.intersection([1, 2], [4, 2], [2, 1]);
13008 * // => [2]
13009 */
13010 var intersection = restParam(function(arrays) {
13011 var othLength = arrays.length,
13012 othIndex = othLength,
13013 caches = Array(length),
13014 indexOf = getIndexOf(),
13015 isCommon = indexOf == baseIndexOf,
13016 result = [];
13017
13018 while (othIndex--) {
13019 var value = arrays[othIndex] = isArrayLike(value = arrays[othIndex]) ? value : [];
13020 caches[othIndex] = (isCommon && value.length >= 120) ? createCache(othIndex && value) : null;
13021 }
13022 var array = arrays[0],
13023 index = -1,
13024 length = array ? array.length : 0,
13025 seen = caches[0];
13026
13027 outer:
13028 while (++index < length) {
13029 value = array[index];
13030 if ((seen ? cacheIndexOf(seen, value) : indexOf(result, value, 0)) < 0) {
13031 var othIndex = othLength;
13032 while (--othIndex) {
13033 var cache = caches[othIndex];
13034 if ((cache ? cacheIndexOf(cache, value) : indexOf(arrays[othIndex], value, 0)) < 0) {
13035 continue outer;
13036 }
13037 }
13038 if (seen) {
13039 seen.push(value);
13040 }
13041 result.push(value);
13042 }
13043 }
13044 return result;
13045 });
13046
13047 /**
13048 * Gets the last element of `array`.
13049 *
13050 * @static
13051 * @memberOf _
13052 * @category Array
13053 * @param {Array} array The array to query.
13054 * @returns {*} Returns the last element of `array`.
13055 * @example
13056 *
13057 * _.last([1, 2, 3]);
13058 * // => 3
13059 */
13060 function last(array) {
13061 var length = array ? array.length : 0;
13062 return length ? array[length - 1] : undefined;
13063 }
13064
13065 /**
13066 * This method is like `_.indexOf` except that it iterates over elements of
13067 * `array` from right to left.
13068 *
13069 * @static
13070 * @memberOf _
13071 * @category Array
13072 * @param {Array} array The array to search.
13073 * @param {*} value The value to search for.
13074 * @param {boolean|number} [fromIndex=array.length-1] The index to search from
13075 * or `true` to perform a binary search on a sorted array.
13076 * @returns {number} Returns the index of the matched value, else `-1`.
13077 * @example
13078 *
13079 * _.lastIndexOf([1, 2, 1, 2], 2);
13080 * // => 3
13081 *
13082 * // using `fromIndex`
13083 * _.lastIndexOf([1, 2, 1, 2], 2, 2);
13084 * // => 1
13085 *
13086 * // performing a binary search
13087 * _.lastIndexOf([1, 1, 2, 2], 2, true);
13088 * // => 3
13089 */
13090 function lastIndexOf(array, value, fromIndex) {
13091 var length = array ? array.length : 0;
13092 if (!length) {
13093 return -1;
13094 }
13095 var index = length;
13096 if (typeof fromIndex == 'number') {
13097 index = (fromIndex < 0 ? nativeMax(length + fromIndex, 0) : nativeMin(fromIndex || 0, length - 1)) + 1;
13098 } else if (fromIndex) {
13099 index = binaryIndex(array, value, true) - 1;
13100 var other = array[index];
13101 if (value === value ? (value === other) : (other !== other)) {
13102 return index;
13103 }
13104 return -1;
13105 }
13106 if (value !== value) {
13107 return indexOfNaN(array, index, true);
13108 }
13109 while (index--) {
13110 if (array[index] === value) {
13111 return index;
13112 }
13113 }
13114 return -1;
13115 }
13116
13117 /**
13118 * Removes all provided values from `array` using
13119 * [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
13120 * for equality comparisons.
13121 *
13122 * **Note:** Unlike `_.without`, this method mutates `array`.
13123 *
13124 * @static
13125 * @memberOf _
13126 * @category Array
13127 * @param {Array} array The array to modify.
13128 * @param {...*} [values] The values to remove.
13129 * @returns {Array} Returns `array`.
13130 * @example
13131 *
13132 * var array = [1, 2, 3, 1, 2, 3];
13133 *
13134 * _.pull(array, 2, 3);
13135 * console.log(array);
13136 * // => [1, 1]
13137 */
13138 function pull() {
13139 var args = arguments,
13140 array = args[0];
13141
13142 if (!(array && array.length)) {
13143 return array;
13144 }
13145 var index = 0,
13146 indexOf = getIndexOf(),
13147 length = args.length;
13148
13149 while (++index < length) {
13150 var fromIndex = 0,
13151 value = args[index];
13152
13153 while ((fromIndex = indexOf(array, value, fromIndex)) > -1) {
13154 splice.call(array, fromIndex, 1);
13155 }
13156 }
13157 return array;
13158 }
13159
13160 /**
13161 * Removes elements from `array` corresponding to the given indexes and returns
13162 * an array of the removed elements. Indexes may be specified as an array of
13163 * indexes or as individual arguments.
13164 *
13165 * **Note:** Unlike `_.at`, this method mutates `array`.
13166 *
13167 * @static
13168 * @memberOf _
13169 * @category Array
13170 * @param {Array} array The array to modify.
13171 * @param {...(number|number[])} [indexes] The indexes of elements to remove,
13172 * specified as individual indexes or arrays of indexes.
13173 * @returns {Array} Returns the new array of removed elements.
13174 * @example
13175 *
13176 * var array = [5, 10, 15, 20];
13177 * var evens = _.pullAt(array, 1, 3);
13178 *
13179 * console.log(array);
13180 * // => [5, 15]
13181 *
13182 * console.log(evens);
13183 * // => [10, 20]
13184 */
13185 var pullAt = restParam(function(array, indexes) {
13186 indexes = baseFlatten(indexes);
13187
13188 var result = baseAt(array, indexes);
13189 basePullAt(array, indexes.sort(baseCompareAscending));
13190 return result;
13191 });
13192
13193 /**
13194 * Removes all elements from `array` that `predicate` returns truthy for
13195 * and returns an array of the removed elements. The predicate is bound to
13196 * `thisArg` and invoked with three arguments: (value, index, array).
13197 *
13198 * If a property name is provided for `predicate` the created `_.property`
13199 * style callback returns the property value of the given element.
13200 *
13201 * If a value is also provided for `thisArg` the created `_.matchesProperty`
13202 * style callback returns `true` for elements that have a matching property
13203 * value, else `false`.
13204 *
13205 * If an object is provided for `predicate` the created `_.matches` style
13206 * callback returns `true` for elements that have the properties of the given
13207 * object, else `false`.
13208 *
13209 * **Note:** Unlike `_.filter`, this method mutates `array`.
13210 *
13211 * @static
13212 * @memberOf _
13213 * @category Array
13214 * @param {Array} array The array to modify.
13215 * @param {Function|Object|string} [predicate=_.identity] The function invoked
13216 * per iteration.
13217 * @param {*} [thisArg] The `this` binding of `predicate`.
13218 * @returns {Array} Returns the new array of removed elements.
13219 * @example
13220 *
13221 * var array = [1, 2, 3, 4];
13222 * var evens = _.remove(array, function(n) {
13223 * return n % 2 == 0;
13224 * });
13225 *
13226 * console.log(array);
13227 * // => [1, 3]
13228 *
13229 * console.log(evens);
13230 * // => [2, 4]
13231 */
13232 function remove(array, predicate, thisArg) {
13233 var result = [];
13234 if (!(array && array.length)) {
13235 return result;
13236 }
13237 var index = -1,
13238 indexes = [],
13239 length = array.length;
13240
13241 predicate = getCallback(predicate, thisArg, 3);
13242 while (++index < length) {
13243 var value = array[index];
13244 if (predicate(value, index, array)) {
13245 result.push(value);
13246 indexes.push(index);
13247 }
13248 }
13249 basePullAt(array, indexes);
13250 return result;
13251 }
13252
13253 /**
13254 * Gets all but the first element of `array`.
13255 *
13256 * @static
13257 * @memberOf _
13258 * @alias tail
13259 * @category Array
13260 * @param {Array} array The array to query.
13261 * @returns {Array} Returns the slice of `array`.
13262 * @example
13263 *
13264 * _.rest([1, 2, 3]);
13265 * // => [2, 3]
13266 */
13267 function rest(array) {
13268 return drop(array, 1);
13269 }
13270
13271 /**
13272 * Creates a slice of `array` from `start` up to, but not including, `end`.
13273 *
13274 * **Note:** This method is used instead of `Array#slice` to support node
13275 * lists in IE < 9 and to ensure dense arrays are returned.
13276 *
13277 * @static
13278 * @memberOf _
13279 * @category Array
13280 * @param {Array} array The array to slice.
13281 * @param {number} [start=0] The start position.
13282 * @param {number} [end=array.length] The end position.
13283 * @returns {Array} Returns the slice of `array`.
13284 */
13285 function slice(array, start, end) {
13286 var length = array ? array.length : 0;
13287 if (!length) {
13288 return [];
13289 }
13290 if (end && typeof end != 'number' && isIterateeCall(array, start, end)) {
13291 start = 0;
13292 end = length;
13293 }
13294 return baseSlice(array, start, end);
13295 }
13296
13297 /**
13298 * Uses a binary search to determine the lowest index at which `value` should
13299 * be inserted into `array` in order to maintain its sort order. If an iteratee
13300 * function is provided it is invoked for `value` and each element of `array`
13301 * to compute their sort ranking. The iteratee is bound to `thisArg` and
13302 * invoked with one argument; (value).
13303 *
13304 * If a property name is provided for `iteratee` the created `_.property`
13305 * style callback returns the property value of the given element.
13306 *
13307 * If a value is also provided for `thisArg` the created `_.matchesProperty`
13308 * style callback returns `true` for elements that have a matching property
13309 * value, else `false`.
13310 *
13311 * If an object is provided for `iteratee` the created `_.matches` style
13312 * callback returns `true` for elements that have the properties of the given
13313 * object, else `false`.
13314 *
13315 * @static
13316 * @memberOf _
13317 * @category Array
13318 * @param {Array} array The sorted array to inspect.
13319 * @param {*} value The value to evaluate.
13320 * @param {Function|Object|string} [iteratee=_.identity] The function invoked
13321 * per iteration.
13322 * @param {*} [thisArg] The `this` binding of `iteratee`.
13323 * @returns {number} Returns the index at which `value` should be inserted
13324 * into `array`.
13325 * @example
13326 *
13327 * _.sortedIndex([30, 50], 40);
13328 * // => 1
13329 *
13330 * _.sortedIndex([4, 4, 5, 5], 5);
13331 * // => 2
13332 *
13333 * var dict = { 'data': { 'thirty': 30, 'forty': 40, 'fifty': 50 } };
13334 *
13335 * // using an iteratee function
13336 * _.sortedIndex(['thirty', 'fifty'], 'forty', function(word) {
13337 * return this.data[word];
13338 * }, dict);
13339 * // => 1
13340 *
13341 * // using the `_.property` callback shorthand
13342 * _.sortedIndex([{ 'x': 30 }, { 'x': 50 }], { 'x': 40 }, 'x');
13343 * // => 1
13344 */
13345 var sortedIndex = createSortedIndex();
13346
13347 /**
13348 * This method is like `_.sortedIndex` except that it returns the highest
13349 * index at which `value` should be inserted into `array` in order to
13350 * maintain its sort order.
13351 *
13352 * @static
13353 * @memberOf _
13354 * @category Array
13355 * @param {Array} array The sorted array to inspect.
13356 * @param {*} value The value to evaluate.
13357 * @param {Function|Object|string} [iteratee=_.identity] The function invoked
13358 * per iteration.
13359 * @param {*} [thisArg] The `this` binding of `iteratee`.
13360 * @returns {number} Returns the index at which `value` should be inserted
13361 * into `array`.
13362 * @example
13363 *
13364 * _.sortedLastIndex([4, 4, 5, 5], 5);
13365 * // => 4
13366 */
13367 var sortedLastIndex = createSortedIndex(true);
13368
13369 /**
13370 * Creates a slice of `array` with `n` elements taken from the beginning.
13371 *
13372 * @static
13373 * @memberOf _
13374 * @category Array
13375 * @param {Array} array The array to query.
13376 * @param {number} [n=1] The number of elements to take.
13377 * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
13378 * @returns {Array} Returns the slice of `array`.
13379 * @example
13380 *
13381 * _.take([1, 2, 3]);
13382 * // => [1]
13383 *
13384 * _.take([1, 2, 3], 2);
13385 * // => [1, 2]
13386 *
13387 * _.take([1, 2, 3], 5);
13388 * // => [1, 2, 3]
13389 *
13390 * _.take([1, 2, 3], 0);
13391 * // => []
13392 */
13393 function take(array, n, guard) {
13394 var length = array ? array.length : 0;
13395 if (!length) {
13396 return [];
13397 }
13398 if (guard ? isIterateeCall(array, n, guard) : n == null) {
13399 n = 1;
13400 }
13401 return baseSlice(array, 0, n < 0 ? 0 : n);
13402 }
13403
13404 /**
13405 * Creates a slice of `array` with `n` elements taken from the end.
13406 *
13407 * @static
13408 * @memberOf _
13409 * @category Array
13410 * @param {Array} array The array to query.
13411 * @param {number} [n=1] The number of elements to take.
13412 * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
13413 * @returns {Array} Returns the slice of `array`.
13414 * @example
13415 *
13416 * _.takeRight([1, 2, 3]);
13417 * // => [3]
13418 *
13419 * _.takeRight([1, 2, 3], 2);
13420 * // => [2, 3]
13421 *
13422 * _.takeRight([1, 2, 3], 5);
13423 * // => [1, 2, 3]
13424 *
13425 * _.takeRight([1, 2, 3], 0);
13426 * // => []
13427 */
13428 function takeRight(array, n, guard) {
13429 var length = array ? array.length : 0;
13430 if (!length) {
13431 return [];
13432 }
13433 if (guard ? isIterateeCall(array, n, guard) : n == null) {
13434 n = 1;
13435 }
13436 n = length - (+n || 0);
13437 return baseSlice(array, n < 0 ? 0 : n);
13438 }
13439
13440 /**
13441 * Creates a slice of `array` with elements taken from the end. Elements are
13442 * taken until `predicate` returns falsey. The predicate is bound to `thisArg`
13443 * and invoked with three arguments: (value, index, array).
13444 *
13445 * If a property name is provided for `predicate` the created `_.property`
13446 * style callback returns the property value of the given element.
13447 *
13448 * If a value is also provided for `thisArg` the created `_.matchesProperty`
13449 * style callback returns `true` for elements that have a matching property
13450 * value, else `false`.
13451 *
13452 * If an object is provided for `predicate` the created `_.matches` style
13453 * callback returns `true` for elements that have the properties of the given
13454 * object, else `false`.
13455 *
13456 * @static
13457 * @memberOf _
13458 * @category Array
13459 * @param {Array} array The array to query.
13460 * @param {Function|Object|string} [predicate=_.identity] The function invoked
13461 * per iteration.
13462 * @param {*} [thisArg] The `this` binding of `predicate`.
13463 * @returns {Array} Returns the slice of `array`.
13464 * @example
13465 *
13466 * _.takeRightWhile([1, 2, 3], function(n) {
13467 * return n > 1;
13468 * });
13469 * // => [2, 3]
13470 *
13471 * var users = [
13472 * { 'user': 'barney', 'active': true },
13473 * { 'user': 'fred', 'active': false },
13474 * { 'user': 'pebbles', 'active': false }
13475 * ];
13476 *
13477 * // using the `_.matches` callback shorthand
13478 * _.pluck(_.takeRightWhile(users, { 'user': 'pebbles', 'active': false }), 'user');
13479 * // => ['pebbles']
13480 *
13481 * // using the `_.matchesProperty` callback shorthand
13482 * _.pluck(_.takeRightWhile(users, 'active', false), 'user');
13483 * // => ['fred', 'pebbles']
13484 *
13485 * // using the `_.property` callback shorthand
13486 * _.pluck(_.takeRightWhile(users, 'active'), 'user');
13487 * // => []
13488 */
13489 function takeRightWhile(array, predicate, thisArg) {
13490 return (array && array.length)
13491 ? baseWhile(array, getCallback(predicate, thisArg, 3), false, true)
13492 : [];
13493 }
13494
13495 /**
13496 * Creates a slice of `array` with elements taken from the beginning. Elements
13497 * are taken until `predicate` returns falsey. The predicate is bound to
13498 * `thisArg` and invoked with three arguments: (value, index, array).
13499 *
13500 * If a property name is provided for `predicate` the created `_.property`
13501 * style callback returns the property value of the given element.
13502 *
13503 * If a value is also provided for `thisArg` the created `_.matchesProperty`
13504 * style callback returns `true` for elements that have a matching property
13505 * value, else `false`.
13506 *
13507 * If an object is provided for `predicate` the created `_.matches` style
13508 * callback returns `true` for elements that have the properties of the given
13509 * object, else `false`.
13510 *
13511 * @static
13512 * @memberOf _
13513 * @category Array
13514 * @param {Array} array The array to query.
13515 * @param {Function|Object|string} [predicate=_.identity] The function invoked
13516 * per iteration.
13517 * @param {*} [thisArg] The `this` binding of `predicate`.
13518 * @returns {Array} Returns the slice of `array`.
13519 * @example
13520 *
13521 * _.takeWhile([1, 2, 3], function(n) {
13522 * return n < 3;
13523 * });
13524 * // => [1, 2]
13525 *
13526 * var users = [
13527 * { 'user': 'barney', 'active': false },
13528 * { 'user': 'fred', 'active': false},
13529 * { 'user': 'pebbles', 'active': true }
13530 * ];
13531 *
13532 * // using the `_.matches` callback shorthand
13533 * _.pluck(_.takeWhile(users, { 'user': 'barney', 'active': false }), 'user');
13534 * // => ['barney']
13535 *
13536 * // using the `_.matchesProperty` callback shorthand
13537 * _.pluck(_.takeWhile(users, 'active', false), 'user');
13538 * // => ['barney', 'fred']
13539 *
13540 * // using the `_.property` callback shorthand
13541 * _.pluck(_.takeWhile(users, 'active'), 'user');
13542 * // => []
13543 */
13544 function takeWhile(array, predicate, thisArg) {
13545 return (array && array.length)
13546 ? baseWhile(array, getCallback(predicate, thisArg, 3))
13547 : [];
13548 }
13549
13550 /**
13551 * Creates an array of unique values, in order, from all of the provided arrays
13552 * using [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
13553 * for equality comparisons.
13554 *
13555 * @static
13556 * @memberOf _
13557 * @category Array
13558 * @param {...Array} [arrays] The arrays to inspect.
13559 * @returns {Array} Returns the new array of combined values.
13560 * @example
13561 *
13562 * _.union([1, 2], [4, 2], [2, 1]);
13563 * // => [1, 2, 4]
13564 */
13565 var union = restParam(function(arrays) {
13566 return baseUniq(baseFlatten(arrays, false, true));
13567 });
13568
13569 /**
13570 * Creates a duplicate-free version of an array, using
13571 * [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
13572 * for equality comparisons, in which only the first occurence of each element
13573 * is kept. Providing `true` for `isSorted` performs a faster search algorithm
13574 * for sorted arrays. If an iteratee function is provided it is invoked for
13575 * each element in the array to generate the criterion by which uniqueness
13576 * is computed. The `iteratee` is bound to `thisArg` and invoked with three
13577 * arguments: (value, index, array).
13578 *
13579 * If a property name is provided for `iteratee` the created `_.property`
13580 * style callback returns the property value of the given element.
13581 *
13582 * If a value is also provided for `thisArg` the created `_.matchesProperty`
13583 * style callback returns `true` for elements that have a matching property
13584 * value, else `false`.
13585 *
13586 * If an object is provided for `iteratee` the created `_.matches` style
13587 * callback returns `true` for elements that have the properties of the given
13588 * object, else `false`.
13589 *
13590 * @static
13591 * @memberOf _
13592 * @alias unique
13593 * @category Array
13594 * @param {Array} array The array to inspect.
13595 * @param {boolean} [isSorted] Specify the array is sorted.
13596 * @param {Function|Object|string} [iteratee] The function invoked per iteration.
13597 * @param {*} [thisArg] The `this` binding of `iteratee`.
13598 * @returns {Array} Returns the new duplicate-value-free array.
13599 * @example
13600 *
13601 * _.uniq([2, 1, 2]);
13602 * // => [2, 1]
13603 *
13604 * // using `isSorted`
13605 * _.uniq([1, 1, 2], true);
13606 * // => [1, 2]
13607 *
13608 * // using an iteratee function
13609 * _.uniq([1, 2.5, 1.5, 2], function(n) {
13610 * return this.floor(n);
13611 * }, Math);
13612 * // => [1, 2.5]
13613 *
13614 * // using the `_.property` callback shorthand
13615 * _.uniq([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x');
13616 * // => [{ 'x': 1 }, { 'x': 2 }]
13617 */
13618 function uniq(array, isSorted, iteratee, thisArg) {
13619 var length = array ? array.length : 0;
13620 if (!length) {
13621 return [];
13622 }
13623 if (isSorted != null && typeof isSorted != 'boolean') {
13624 thisArg = iteratee;
13625 iteratee = isIterateeCall(array, isSorted, thisArg) ? undefined : isSorted;
13626 isSorted = false;
13627 }
13628 var callback = getCallback();
13629 if (!(iteratee == null && callback === baseCallback)) {
13630 iteratee = callback(iteratee, thisArg, 3);
13631 }
13632 return (isSorted && getIndexOf() == baseIndexOf)
13633 ? sortedUniq(array, iteratee)
13634 : baseUniq(array, iteratee);
13635 }
13636
13637 /**
13638 * This method is like `_.zip` except that it accepts an array of grouped
13639 * elements and creates an array regrouping the elements to their pre-zip
13640 * configuration.
13641 *
13642 * @static
13643 * @memberOf _
13644 * @category Array
13645 * @param {Array} array The array of grouped elements to process.
13646 * @returns {Array} Returns the new array of regrouped elements.
13647 * @example
13648 *
13649 * var zipped = _.zip(['fred', 'barney'], [30, 40], [true, false]);
13650 * // => [['fred', 30, true], ['barney', 40, false]]
13651 *
13652 * _.unzip(zipped);
13653 * // => [['fred', 'barney'], [30, 40], [true, false]]
13654 */
13655 function unzip(array) {
13656 if (!(array && array.length)) {
13657 return [];
13658 }
13659 var index = -1,
13660 length = 0;
13661
13662 array = arrayFilter(array, function(group) {
13663 if (isArrayLike(group)) {
13664 length = nativeMax(group.length, length);
13665 return true;
13666 }
13667 });
13668 var result = Array(length);
13669 while (++index < length) {
13670 result[index] = arrayMap(array, baseProperty(index));
13671 }
13672 return result;
13673 }
13674
13675 /**
13676 * This method is like `_.unzip` except that it accepts an iteratee to specify
13677 * how regrouped values should be combined. The `iteratee` is bound to `thisArg`
13678 * and invoked with four arguments: (accumulator, value, index, group).
13679 *
13680 * @static
13681 * @memberOf _
13682 * @category Array
13683 * @param {Array} array The array of grouped elements to process.
13684 * @param {Function} [iteratee] The function to combine regrouped values.
13685 * @param {*} [thisArg] The `this` binding of `iteratee`.
13686 * @returns {Array} Returns the new array of regrouped elements.
13687 * @example
13688 *
13689 * var zipped = _.zip([1, 2], [10, 20], [100, 200]);
13690 * // => [[1, 10, 100], [2, 20, 200]]
13691 *
13692 * _.unzipWith(zipped, _.add);
13693 * // => [3, 30, 300]
13694 */
13695 function unzipWith(array, iteratee, thisArg) {
13696 var length = array ? array.length : 0;
13697 if (!length) {
13698 return [];
13699 }
13700 var result = unzip(array);
13701 if (iteratee == null) {
13702 return result;
13703 }
13704 iteratee = bindCallback(iteratee, thisArg, 4);
13705 return arrayMap(result, function(group) {
13706 return arrayReduce(group, iteratee, undefined, true);
13707 });
13708 }
13709
13710 /**
13711 * Creates an array excluding all provided values using
13712 * [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
13713 * for equality comparisons.
13714 *
13715 * @static
13716 * @memberOf _
13717 * @category Array
13718 * @param {Array} array The array to filter.
13719 * @param {...*} [values] The values to exclude.
13720 * @returns {Array} Returns the new array of filtered values.
13721 * @example
13722 *
13723 * _.without([1, 2, 1, 3], 1, 2);
13724 * // => [3]
13725 */
13726 var without = restParam(function(array, values) {
13727 return isArrayLike(array)
13728 ? baseDifference(array, values)
13729 : [];
13730 });
13731
13732 /**
13733 * Creates an array of unique values that is the [symmetric difference](https://en.wikipedia.org/wiki/Symmetric_difference)
13734 * of the provided arrays.
13735 *
13736 * @static
13737 * @memberOf _
13738 * @category Array
13739 * @param {...Array} [arrays] The arrays to inspect.
13740 * @returns {Array} Returns the new array of values.
13741 * @example
13742 *
13743 * _.xor([1, 2], [4, 2]);
13744 * // => [1, 4]
13745 */
13746 function xor() {
13747 var index = -1,
13748 length = arguments.length;
13749
13750 while (++index < length) {
13751 var array = arguments[index];
13752 if (isArrayLike(array)) {
13753 var result = result
13754 ? arrayPush(baseDifference(result, array), baseDifference(array, result))
13755 : array;
13756 }
13757 }
13758 return result ? baseUniq(result) : [];
13759 }
13760
13761 /**
13762 * Creates an array of grouped elements, the first of which contains the first
13763 * elements of the given arrays, the second of which contains the second elements
13764 * of the given arrays, and so on.
13765 *
13766 * @static
13767 * @memberOf _
13768 * @category Array
13769 * @param {...Array} [arrays] The arrays to process.
13770 * @returns {Array} Returns the new array of grouped elements.
13771 * @example
13772 *
13773 * _.zip(['fred', 'barney'], [30, 40], [true, false]);
13774 * // => [['fred', 30, true], ['barney', 40, false]]
13775 */
13776 var zip = restParam(unzip);
13777
13778 /**
13779 * The inverse of `_.pairs`; this method returns an object composed from arrays
13780 * of property names and values. Provide either a single two dimensional array,
13781 * e.g. `[[key1, value1], [key2, value2]]` or two arrays, one of property names
13782 * and one of corresponding values.
13783 *
13784 * @static
13785 * @memberOf _
13786 * @alias object
13787 * @category Array
13788 * @param {Array} props The property names.
13789 * @param {Array} [values=[]] The property values.
13790 * @returns {Object} Returns the new object.
13791 * @example
13792 *
13793 * _.zipObject([['fred', 30], ['barney', 40]]);
13794 * // => { 'fred': 30, 'barney': 40 }
13795 *
13796 * _.zipObject(['fred', 'barney'], [30, 40]);
13797 * // => { 'fred': 30, 'barney': 40 }
13798 */
13799 function zipObject(props, values) {
13800 var index = -1,
13801 length = props ? props.length : 0,
13802 result = {};
13803
13804 if (length && !values && !isArray(props[0])) {
13805 values = [];
13806 }
13807 while (++index < length) {
13808 var key = props[index];
13809 if (values) {
13810 result[key] = values[index];
13811 } else if (key) {
13812 result[key[0]] = key[1];
13813 }
13814 }
13815 return result;
13816 }
13817
13818 /**
13819 * This method is like `_.zip` except that it accepts an iteratee to specify
13820 * how grouped values should be combined. The `iteratee` is bound to `thisArg`
13821 * and invoked with four arguments: (accumulator, value, index, group).
13822 *
13823 * @static
13824 * @memberOf _
13825 * @category Array
13826 * @param {...Array} [arrays] The arrays to process.
13827 * @param {Function} [iteratee] The function to combine grouped values.
13828 * @param {*} [thisArg] The `this` binding of `iteratee`.
13829 * @returns {Array} Returns the new array of grouped elements.
13830 * @example
13831 *
13832 * _.zipWith([1, 2], [10, 20], [100, 200], _.add);
13833 * // => [111, 222]
13834 */
13835 var zipWith = restParam(function(arrays) {
13836 var length = arrays.length,
13837 iteratee = length > 2 ? arrays[length - 2] : undefined,
13838 thisArg = length > 1 ? arrays[length - 1] : undefined;
13839
13840 if (length > 2 && typeof iteratee == 'function') {
13841 length -= 2;
13842 } else {
13843 iteratee = (length > 1 && typeof thisArg == 'function') ? (--length, thisArg) : undefined;
13844 thisArg = undefined;
13845 }
13846 arrays.length = length;
13847 return unzipWith(arrays, iteratee, thisArg);
13848 });
13849
13850 /*------------------------------------------------------------------------*/
13851
13852 /**
13853 * Creates a `lodash` object that wraps `value` with explicit method
13854 * chaining enabled.
13855 *
13856 * @static
13857 * @memberOf _
13858 * @category Chain
13859 * @param {*} value The value to wrap.
13860 * @returns {Object} Returns the new `lodash` wrapper instance.
13861 * @example
13862 *
13863 * var users = [
13864 * { 'user': 'barney', 'age': 36 },
13865 * { 'user': 'fred', 'age': 40 },
13866 * { 'user': 'pebbles', 'age': 1 }
13867 * ];
13868 *
13869 * var youngest = _.chain(users)
13870 * .sortBy('age')
13871 * .map(function(chr) {
13872 * return chr.user + ' is ' + chr.age;
13873 * })
13874 * .first()
13875 * .value();
13876 * // => 'pebbles is 1'
13877 */
13878 function chain(value) {
13879 var result = lodash(value);
13880 result.__chain__ = true;
13881 return result;
13882 }
13883
13884 /**
13885 * This method invokes `interceptor` and returns `value`. The interceptor is
13886 * bound to `thisArg` and invoked with one argument; (value). The purpose of
13887 * this method is to "tap into" a method chain in order to perform operations
13888 * on intermediate results within the chain.
13889 *
13890 * @static
13891 * @memberOf _
13892 * @category Chain
13893 * @param {*} value The value to provide to `interceptor`.
13894 * @param {Function} interceptor The function to invoke.
13895 * @param {*} [thisArg] The `this` binding of `interceptor`.
13896 * @returns {*} Returns `value`.
13897 * @example
13898 *
13899 * _([1, 2, 3])
13900 * .tap(function(array) {
13901 * array.pop();
13902 * })
13903 * .reverse()
13904 * .value();
13905 * // => [2, 1]
13906 */
13907 function tap(value, interceptor, thisArg) {
13908 interceptor.call(thisArg, value);
13909 return value;
13910 }
13911
13912 /**
13913 * This method is like `_.tap` except that it returns the result of `interceptor`.
13914 *
13915 * @static
13916 * @memberOf _
13917 * @category Chain
13918 * @param {*} value The value to provide to `interceptor`.
13919 * @param {Function} interceptor The function to invoke.
13920 * @param {*} [thisArg] The `this` binding of `interceptor`.
13921 * @returns {*} Returns the result of `interceptor`.
13922 * @example
13923 *
13924 * _(' abc ')
13925 * .chain()
13926 * .trim()
13927 * .thru(function(value) {
13928 * return [value];
13929 * })
13930 * .value();
13931 * // => ['abc']
13932 */
13933 function thru(value, interceptor, thisArg) {
13934 return interceptor.call(thisArg, value);
13935 }
13936
13937 /**
13938 * Enables explicit method chaining on the wrapper object.
13939 *
13940 * @name chain
13941 * @memberOf _
13942 * @category Chain
13943 * @returns {Object} Returns the new `lodash` wrapper instance.
13944 * @example
13945 *
13946 * var users = [
13947 * { 'user': 'barney', 'age': 36 },
13948 * { 'user': 'fred', 'age': 40 }
13949 * ];
13950 *
13951 * // without explicit chaining
13952 * _(users).first();
13953 * // => { 'user': 'barney', 'age': 36 }
13954 *
13955 * // with explicit chaining
13956 * _(users).chain()
13957 * .first()
13958 * .pick('user')
13959 * .value();
13960 * // => { 'user': 'barney' }
13961 */
13962 function wrapperChain() {
13963 return chain(this);
13964 }
13965
13966 /**
13967 * Executes the chained sequence and returns the wrapped result.
13968 *
13969 * @name commit
13970 * @memberOf _
13971 * @category Chain
13972 * @returns {Object} Returns the new `lodash` wrapper instance.
13973 * @example
13974 *
13975 * var array = [1, 2];
13976 * var wrapped = _(array).push(3);
13977 *
13978 * console.log(array);
13979 * // => [1, 2]
13980 *
13981 * wrapped = wrapped.commit();
13982 * console.log(array);
13983 * // => [1, 2, 3]
13984 *
13985 * wrapped.last();
13986 * // => 3
13987 *
13988 * console.log(array);
13989 * // => [1, 2, 3]
13990 */
13991 function wrapperCommit() {
13992 return new LodashWrapper(this.value(), this.__chain__);
13993 }
13994
13995 /**
13996 * Creates a new array joining a wrapped array with any additional arrays
13997 * and/or values.
13998 *
13999 * @name concat
14000 * @memberOf _
14001 * @category Chain
14002 * @param {...*} [values] The values to concatenate.
14003 * @returns {Array} Returns the new concatenated array.
14004 * @example
14005 *
14006 * var array = [1];
14007 * var wrapped = _(array).concat(2, [3], [[4]]);
14008 *
14009 * console.log(wrapped.value());
14010 * // => [1, 2, 3, [4]]
14011 *
14012 * console.log(array);
14013 * // => [1]
14014 */
14015 var wrapperConcat = restParam(function(values) {
14016 values = baseFlatten(values);
14017 return this.thru(function(array) {
14018 return arrayConcat(isArray(array) ? array : [toObject(array)], values);
14019 });
14020 });
14021
14022 /**
14023 * Creates a clone of the chained sequence planting `value` as the wrapped value.
14024 *
14025 * @name plant
14026 * @memberOf _
14027 * @category Chain
14028 * @returns {Object} Returns the new `lodash` wrapper instance.
14029 * @example
14030 *
14031 * var array = [1, 2];
14032 * var wrapped = _(array).map(function(value) {
14033 * return Math.pow(value, 2);
14034 * });
14035 *
14036 * var other = [3, 4];
14037 * var otherWrapped = wrapped.plant(other);
14038 *
14039 * otherWrapped.value();
14040 * // => [9, 16]
14041 *
14042 * wrapped.value();
14043 * // => [1, 4]
14044 */
14045 function wrapperPlant(value) {
14046 var result,
14047 parent = this;
14048
14049 while (parent instanceof baseLodash) {
14050 var clone = wrapperClone(parent);
14051 if (result) {
14052 previous.__wrapped__ = clone;
14053 } else {
14054 result = clone;
14055 }
14056 var previous = clone;
14057 parent = parent.__wrapped__;
14058 }
14059 previous.__wrapped__ = value;
14060 return result;
14061 }
14062
14063 /**
14064 * Reverses the wrapped array so the first element becomes the last, the
14065 * second element becomes the second to last, and so on.
14066 *
14067 * **Note:** This method mutates the wrapped array.
14068 *
14069 * @name reverse
14070 * @memberOf _
14071 * @category Chain
14072 * @returns {Object} Returns the new reversed `lodash` wrapper instance.
14073 * @example
14074 *
14075 * var array = [1, 2, 3];
14076 *
14077 * _(array).reverse().value()
14078 * // => [3, 2, 1]
14079 *
14080 * console.log(array);
14081 * // => [3, 2, 1]
14082 */
14083 function wrapperReverse() {
14084 var value = this.__wrapped__;
14085
14086 var interceptor = function(value) {
14087 return (wrapped && wrapped.__dir__ < 0) ? value : value.reverse();
14088 };
14089 if (value instanceof LazyWrapper) {
14090 var wrapped = value;
14091 if (this.__actions__.length) {
14092 wrapped = new LazyWrapper(this);
14093 }
14094 wrapped = wrapped.reverse();
14095 wrapped.__actions__.push({ 'func': thru, 'args': [interceptor], 'thisArg': undefined });
14096 return new LodashWrapper(wrapped, this.__chain__);
14097 }
14098 return this.thru(interceptor);
14099 }
14100
14101 /**
14102 * Produces the result of coercing the unwrapped value to a string.
14103 *
14104 * @name toString
14105 * @memberOf _
14106 * @category Chain
14107 * @returns {string} Returns the coerced string value.
14108 * @example
14109 *
14110 * _([1, 2, 3]).toString();
14111 * // => '1,2,3'
14112 */
14113 function wrapperToString() {
14114 return (this.value() + '');
14115 }
14116
14117 /**
14118 * Executes the chained sequence to extract the unwrapped value.
14119 *
14120 * @name value
14121 * @memberOf _
14122 * @alias run, toJSON, valueOf
14123 * @category Chain
14124 * @returns {*} Returns the resolved unwrapped value.
14125 * @example
14126 *
14127 * _([1, 2, 3]).value();
14128 * // => [1, 2, 3]
14129 */
14130 function wrapperValue() {
14131 return baseWrapperValue(this.__wrapped__, this.__actions__);
14132 }
14133
14134 /*------------------------------------------------------------------------*/
14135
14136 /**
14137 * Creates an array of elements corresponding to the given keys, or indexes,
14138 * of `collection`. Keys may be specified as individual arguments or as arrays
14139 * of keys.
14140 *
14141 * @static
14142 * @memberOf _
14143 * @category Collection
14144 * @param {Array|Object|string} collection The collection to iterate over.
14145 * @param {...(number|number[]|string|string[])} [props] The property names
14146 * or indexes of elements to pick, specified individually or in arrays.
14147 * @returns {Array} Returns the new array of picked elements.
14148 * @example
14149 *
14150 * _.at(['a', 'b', 'c'], [0, 2]);
14151 * // => ['a', 'c']
14152 *
14153 * _.at(['barney', 'fred', 'pebbles'], 0, 2);
14154 * // => ['barney', 'pebbles']
14155 */
14156 var at = restParam(function(collection, props) {
14157 return baseAt(collection, baseFlatten(props));
14158 });
14159
14160 /**
14161 * Creates an object composed of keys generated from the results of running
14162 * each element of `collection` through `iteratee`. The corresponding value
14163 * of each key is the number of times the key was returned by `iteratee`.
14164 * The `iteratee` is bound to `thisArg` and invoked with three arguments:
14165 * (value, index|key, collection).
14166 *
14167 * If a property name is provided for `iteratee` the created `_.property`
14168 * style callback returns the property value of the given element.
14169 *
14170 * If a value is also provided for `thisArg` the created `_.matchesProperty`
14171 * style callback returns `true` for elements that have a matching property
14172 * value, else `false`.
14173 *
14174 * If an object is provided for `iteratee` the created `_.matches` style
14175 * callback returns `true` for elements that have the properties of the given
14176 * object, else `false`.
14177 *
14178 * @static
14179 * @memberOf _
14180 * @category Collection
14181 * @param {Array|Object|string} collection The collection to iterate over.
14182 * @param {Function|Object|string} [iteratee=_.identity] The function invoked
14183 * per iteration.
14184 * @param {*} [thisArg] The `this` binding of `iteratee`.
14185 * @returns {Object} Returns the composed aggregate object.
14186 * @example
14187 *
14188 * _.countBy([4.3, 6.1, 6.4], function(n) {
14189 * return Math.floor(n);
14190 * });
14191 * // => { '4': 1, '6': 2 }
14192 *
14193 * _.countBy([4.3, 6.1, 6.4], function(n) {
14194 * return this.floor(n);
14195 * }, Math);
14196 * // => { '4': 1, '6': 2 }
14197 *
14198 * _.countBy(['one', 'two', 'three'], 'length');
14199 * // => { '3': 2, '5': 1 }
14200 */
14201 var countBy = createAggregator(function(result, value, key) {
14202 hasOwnProperty.call(result, key) ? ++result[key] : (result[key] = 1);
14203 });
14204
14205 /**
14206 * Checks if `predicate` returns truthy for **all** elements of `collection`.
14207 * The predicate is bound to `thisArg` and invoked with three arguments:
14208 * (value, index|key, collection).
14209 *
14210 * If a property name is provided for `predicate` the created `_.property`
14211 * style callback returns the property value of the given element.
14212 *
14213 * If a value is also provided for `thisArg` the created `_.matchesProperty`
14214 * style callback returns `true` for elements that have a matching property
14215 * value, else `false`.
14216 *
14217 * If an object is provided for `predicate` the created `_.matches` style
14218 * callback returns `true` for elements that have the properties of the given
14219 * object, else `false`.
14220 *
14221 * @static
14222 * @memberOf _
14223 * @alias all
14224 * @category Collection
14225 * @param {Array|Object|string} collection The collection to iterate over.
14226 * @param {Function|Object|string} [predicate=_.identity] The function invoked
14227 * per iteration.
14228 * @param {*} [thisArg] The `this` binding of `predicate`.
14229 * @returns {boolean} Returns `true` if all elements pass the predicate check,
14230 * else `false`.
14231 * @example
14232 *
14233 * _.every([true, 1, null, 'yes'], Boolean);
14234 * // => false
14235 *
14236 * var users = [
14237 * { 'user': 'barney', 'active': false },
14238 * { 'user': 'fred', 'active': false }
14239 * ];
14240 *
14241 * // using the `_.matches` callback shorthand
14242 * _.every(users, { 'user': 'barney', 'active': false });
14243 * // => false
14244 *
14245 * // using the `_.matchesProperty` callback shorthand
14246 * _.every(users, 'active', false);
14247 * // => true
14248 *
14249 * // using the `_.property` callback shorthand
14250 * _.every(users, 'active');
14251 * // => false
14252 */
14253 function every(collection, predicate, thisArg) {
14254 var func = isArray(collection) ? arrayEvery : baseEvery;
14255 if (thisArg && isIterateeCall(collection, predicate, thisArg)) {
14256 predicate = undefined;
14257 }
14258 if (typeof predicate != 'function' || thisArg !== undefined) {
14259 predicate = getCallback(predicate, thisArg, 3);
14260 }
14261 return func(collection, predicate);
14262 }
14263
14264 /**
14265 * Iterates over elements of `collection`, returning an array of all elements
14266 * `predicate` returns truthy for. The predicate is bound to `thisArg` and
14267 * invoked with three arguments: (value, index|key, collection).
14268 *
14269 * If a property name is provided for `predicate` the created `_.property`
14270 * style callback returns the property value of the given element.
14271 *
14272 * If a value is also provided for `thisArg` the created `_.matchesProperty`
14273 * style callback returns `true` for elements that have a matching property
14274 * value, else `false`.
14275 *
14276 * If an object is provided for `predicate` the created `_.matches` style
14277 * callback returns `true` for elements that have the properties of the given
14278 * object, else `false`.
14279 *
14280 * @static
14281 * @memberOf _
14282 * @alias select
14283 * @category Collection
14284 * @param {Array|Object|string} collection The collection to iterate over.
14285 * @param {Function|Object|string} [predicate=_.identity] The function invoked
14286 * per iteration.
14287 * @param {*} [thisArg] The `this` binding of `predicate`.
14288 * @returns {Array} Returns the new filtered array.
14289 * @example
14290 *
14291 * _.filter([4, 5, 6], function(n) {
14292 * return n % 2 == 0;
14293 * });
14294 * // => [4, 6]
14295 *
14296 * var users = [
14297 * { 'user': 'barney', 'age': 36, 'active': true },
14298 * { 'user': 'fred', 'age': 40, 'active': false }
14299 * ];
14300 *
14301 * // using the `_.matches` callback shorthand
14302 * _.pluck(_.filter(users, { 'age': 36, 'active': true }), 'user');
14303 * // => ['barney']
14304 *
14305 * // using the `_.matchesProperty` callback shorthand
14306 * _.pluck(_.filter(users, 'active', false), 'user');
14307 * // => ['fred']
14308 *
14309 * // using the `_.property` callback shorthand
14310 * _.pluck(_.filter(users, 'active'), 'user');
14311 * // => ['barney']
14312 */
14313 function filter(collection, predicate, thisArg) {
14314 var func = isArray(collection) ? arrayFilter : baseFilter;
14315 predicate = getCallback(predicate, thisArg, 3);
14316 return func(collection, predicate);
14317 }
14318
14319 /**
14320 * Iterates over elements of `collection`, returning the first element
14321 * `predicate` returns truthy for. The predicate is bound to `thisArg` and
14322 * invoked with three arguments: (value, index|key, collection).
14323 *
14324 * If a property name is provided for `predicate` the created `_.property`
14325 * style callback returns the property value of the given element.
14326 *
14327 * If a value is also provided for `thisArg` the created `_.matchesProperty`
14328 * style callback returns `true` for elements that have a matching property
14329 * value, else `false`.
14330 *
14331 * If an object is provided for `predicate` the created `_.matches` style
14332 * callback returns `true` for elements that have the properties of the given
14333 * object, else `false`.
14334 *
14335 * @static
14336 * @memberOf _
14337 * @alias detect
14338 * @category Collection
14339 * @param {Array|Object|string} collection The collection to search.
14340 * @param {Function|Object|string} [predicate=_.identity] The function invoked
14341 * per iteration.
14342 * @param {*} [thisArg] The `this` binding of `predicate`.
14343 * @returns {*} Returns the matched element, else `undefined`.
14344 * @example
14345 *
14346 * var users = [
14347 * { 'user': 'barney', 'age': 36, 'active': true },
14348 * { 'user': 'fred', 'age': 40, 'active': false },
14349 * { 'user': 'pebbles', 'age': 1, 'active': true }
14350 * ];
14351 *
14352 * _.result(_.find(users, function(chr) {
14353 * return chr.age < 40;
14354 * }), 'user');
14355 * // => 'barney'
14356 *
14357 * // using the `_.matches` callback shorthand
14358 * _.result(_.find(users, { 'age': 1, 'active': true }), 'user');
14359 * // => 'pebbles'
14360 *
14361 * // using the `_.matchesProperty` callback shorthand
14362 * _.result(_.find(users, 'active', false), 'user');
14363 * // => 'fred'
14364 *
14365 * // using the `_.property` callback shorthand
14366 * _.result(_.find(users, 'active'), 'user');
14367 * // => 'barney'
14368 */
14369 var find = createFind(baseEach);
14370
14371 /**
14372 * This method is like `_.find` except that it iterates over elements of
14373 * `collection` from right to left.
14374 *
14375 * @static
14376 * @memberOf _
14377 * @category Collection
14378 * @param {Array|Object|string} collection The collection to search.
14379 * @param {Function|Object|string} [predicate=_.identity] The function invoked
14380 * per iteration.
14381 * @param {*} [thisArg] The `this` binding of `predicate`.
14382 * @returns {*} Returns the matched element, else `undefined`.
14383 * @example
14384 *
14385 * _.findLast([1, 2, 3, 4], function(n) {
14386 * return n % 2 == 1;
14387 * });
14388 * // => 3
14389 */
14390 var findLast = createFind(baseEachRight, true);
14391
14392 /**
14393 * Performs a deep comparison between each element in `collection` and the
14394 * source object, returning the first element that has equivalent property
14395 * values.
14396 *
14397 * **Note:** This method supports comparing arrays, booleans, `Date` objects,
14398 * numbers, `Object` objects, regexes, and strings. Objects are compared by
14399 * their own, not inherited, enumerable properties. For comparing a single
14400 * own or inherited property value see `_.matchesProperty`.
14401 *
14402 * @static
14403 * @memberOf _
14404 * @category Collection
14405 * @param {Array|Object|string} collection The collection to search.
14406 * @param {Object} source The object of property values to match.
14407 * @returns {*} Returns the matched element, else `undefined`.
14408 * @example
14409 *
14410 * var users = [
14411 * { 'user': 'barney', 'age': 36, 'active': true },
14412 * { 'user': 'fred', 'age': 40, 'active': false }
14413 * ];
14414 *
14415 * _.result(_.findWhere(users, { 'age': 36, 'active': true }), 'user');
14416 * // => 'barney'
14417 *
14418 * _.result(_.findWhere(users, { 'age': 40, 'active': false }), 'user');
14419 * // => 'fred'
14420 */
14421 function findWhere(collection, source) {
14422 return find(collection, baseMatches(source));
14423 }
14424
14425 /**
14426 * Iterates over elements of `collection` invoking `iteratee` for each element.
14427 * The `iteratee` is bound to `thisArg` and invoked with three arguments:
14428 * (value, index|key, collection). Iteratee functions may exit iteration early
14429 * by explicitly returning `false`.
14430 *
14431 * **Note:** As with other "Collections" methods, objects with a "length" property
14432 * are iterated like arrays. To avoid this behavior `_.forIn` or `_.forOwn`
14433 * may be used for object iteration.
14434 *
14435 * @static
14436 * @memberOf _
14437 * @alias each
14438 * @category Collection
14439 * @param {Array|Object|string} collection The collection to iterate over.
14440 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
14441 * @param {*} [thisArg] The `this` binding of `iteratee`.
14442 * @returns {Array|Object|string} Returns `collection`.
14443 * @example
14444 *
14445 * _([1, 2]).forEach(function(n) {
14446 * console.log(n);
14447 * }).value();
14448 * // => logs each value from left to right and returns the array
14449 *
14450 * _.forEach({ 'a': 1, 'b': 2 }, function(n, key) {
14451 * console.log(n, key);
14452 * });
14453 * // => logs each value-key pair and returns the object (iteration order is not guaranteed)
14454 */
14455 var forEach = createForEach(arrayEach, baseEach);
14456
14457 /**
14458 * This method is like `_.forEach` except that it iterates over elements of
14459 * `collection` from right to left.
14460 *
14461 * @static
14462 * @memberOf _
14463 * @alias eachRight
14464 * @category Collection
14465 * @param {Array|Object|string} collection The collection to iterate over.
14466 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
14467 * @param {*} [thisArg] The `this` binding of `iteratee`.
14468 * @returns {Array|Object|string} Returns `collection`.
14469 * @example
14470 *
14471 * _([1, 2]).forEachRight(function(n) {
14472 * console.log(n);
14473 * }).value();
14474 * // => logs each value from right to left and returns the array
14475 */
14476 var forEachRight = createForEach(arrayEachRight, baseEachRight);
14477
14478 /**
14479 * Creates an object composed of keys generated from the results of running
14480 * each element of `collection` through `iteratee`. The corresponding value
14481 * of each key is an array of the elements responsible for generating the key.
14482 * The `iteratee` is bound to `thisArg` and invoked with three arguments:
14483 * (value, index|key, collection).
14484 *
14485 * If a property name is provided for `iteratee` the created `_.property`
14486 * style callback returns the property value of the given element.
14487 *
14488 * If a value is also provided for `thisArg` the created `_.matchesProperty`
14489 * style callback returns `true` for elements that have a matching property
14490 * value, else `false`.
14491 *
14492 * If an object is provided for `iteratee` the created `_.matches` style
14493 * callback returns `true` for elements that have the properties of the given
14494 * object, else `false`.
14495 *
14496 * @static
14497 * @memberOf _
14498 * @category Collection
14499 * @param {Array|Object|string} collection The collection to iterate over.
14500 * @param {Function|Object|string} [iteratee=_.identity] The function invoked
14501 * per iteration.
14502 * @param {*} [thisArg] The `this` binding of `iteratee`.
14503 * @returns {Object} Returns the composed aggregate object.
14504 * @example
14505 *
14506 * _.groupBy([4.2, 6.1, 6.4], function(n) {
14507 * return Math.floor(n);
14508 * });
14509 * // => { '4': [4.2], '6': [6.1, 6.4] }
14510 *
14511 * _.groupBy([4.2, 6.1, 6.4], function(n) {
14512 * return this.floor(n);
14513 * }, Math);
14514 * // => { '4': [4.2], '6': [6.1, 6.4] }
14515 *
14516 * // using the `_.property` callback shorthand
14517 * _.groupBy(['one', 'two', 'three'], 'length');
14518 * // => { '3': ['one', 'two'], '5': ['three'] }
14519 */
14520 var groupBy = createAggregator(function(result, value, key) {
14521 if (hasOwnProperty.call(result, key)) {
14522 result[key].push(value);
14523 } else {
14524 result[key] = [value];
14525 }
14526 });
14527
14528 /**
14529 * Checks if `value` is in `collection` using
14530 * [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
14531 * for equality comparisons. If `fromIndex` is negative, it is used as the offset
14532 * from the end of `collection`.
14533 *
14534 * @static
14535 * @memberOf _
14536 * @alias contains, include
14537 * @category Collection
14538 * @param {Array|Object|string} collection The collection to search.
14539 * @param {*} target The value to search for.
14540 * @param {number} [fromIndex=0] The index to search from.
14541 * @param- {Object} [guard] Enables use as a callback for functions like `_.reduce`.
14542 * @returns {boolean} Returns `true` if a matching element is found, else `false`.
14543 * @example
14544 *
14545 * _.includes([1, 2, 3], 1);
14546 * // => true
14547 *
14548 * _.includes([1, 2, 3], 1, 2);
14549 * // => false
14550 *
14551 * _.includes({ 'user': 'fred', 'age': 40 }, 'fred');
14552 * // => true
14553 *
14554 * _.includes('pebbles', 'eb');
14555 * // => true
14556 */
14557 function includes(collection, target, fromIndex, guard) {
14558 var length = collection ? getLength(collection) : 0;
14559 if (!isLength(length)) {
14560 collection = values(collection);
14561 length = collection.length;
14562 }
14563 if (typeof fromIndex != 'number' || (guard && isIterateeCall(target, fromIndex, guard))) {
14564 fromIndex = 0;
14565 } else {
14566 fromIndex = fromIndex < 0 ? nativeMax(length + fromIndex, 0) : (fromIndex || 0);
14567 }
14568 return (typeof collection == 'string' || !isArray(collection) && isString(collection))
14569 ? (fromIndex <= length && collection.indexOf(target, fromIndex) > -1)
14570 : (!!length && getIndexOf(collection, target, fromIndex) > -1);
14571 }
14572
14573 /**
14574 * Creates an object composed of keys generated from the results of running
14575 * each element of `collection` through `iteratee`. The corresponding value
14576 * of each key is the last element responsible for generating the key. The
14577 * iteratee function is bound to `thisArg` and invoked with three arguments:
14578 * (value, index|key, collection).
14579 *
14580 * If a property name is provided for `iteratee` the created `_.property`
14581 * style callback returns the property value of the given element.
14582 *
14583 * If a value is also provided for `thisArg` the created `_.matchesProperty`
14584 * style callback returns `true` for elements that have a matching property
14585 * value, else `false`.
14586 *
14587 * If an object is provided for `iteratee` the created `_.matches` style
14588 * callback returns `true` for elements that have the properties of the given
14589 * object, else `false`.
14590 *
14591 * @static
14592 * @memberOf _
14593 * @category Collection
14594 * @param {Array|Object|string} collection The collection to iterate over.
14595 * @param {Function|Object|string} [iteratee=_.identity] The function invoked
14596 * per iteration.
14597 * @param {*} [thisArg] The `this` binding of `iteratee`.
14598 * @returns {Object} Returns the composed aggregate object.
14599 * @example
14600 *
14601 * var keyData = [
14602 * { 'dir': 'left', 'code': 97 },
14603 * { 'dir': 'right', 'code': 100 }
14604 * ];
14605 *
14606 * _.indexBy(keyData, 'dir');
14607 * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } }
14608 *
14609 * _.indexBy(keyData, function(object) {
14610 * return String.fromCharCode(object.code);
14611 * });
14612 * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } }
14613 *
14614 * _.indexBy(keyData, function(object) {
14615 * return this.fromCharCode(object.code);
14616 * }, String);
14617 * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } }
14618 */
14619 var indexBy = createAggregator(function(result, value, key) {
14620 result[key] = value;
14621 });
14622
14623 /**
14624 * Invokes the method at `path` of each element in `collection`, returning
14625 * an array of the results of each invoked method. Any additional arguments
14626 * are provided to each invoked method. If `methodName` is a function it is
14627 * invoked for, and `this` bound to, each element in `collection`.
14628 *
14629 * @static
14630 * @memberOf _
14631 * @category Collection
14632 * @param {Array|Object|string} collection The collection to iterate over.
14633 * @param {Array|Function|string} path The path of the method to invoke or
14634 * the function invoked per iteration.
14635 * @param {...*} [args] The arguments to invoke the method with.
14636 * @returns {Array} Returns the array of results.
14637 * @example
14638 *
14639 * _.invoke([[5, 1, 7], [3, 2, 1]], 'sort');
14640 * // => [[1, 5, 7], [1, 2, 3]]
14641 *
14642 * _.invoke([123, 456], String.prototype.split, '');
14643 * // => [['1', '2', '3'], ['4', '5', '6']]
14644 */
14645 var invoke = restParam(function(collection, path, args) {
14646 var index = -1,
14647 isFunc = typeof path == 'function',
14648 isProp = isKey(path),
14649 result = isArrayLike(collection) ? Array(collection.length) : [];
14650
14651 baseEach(collection, function(value) {
14652 var func = isFunc ? path : ((isProp && value != null) ? value[path] : undefined);
14653 result[++index] = func ? func.apply(value, args) : invokePath(value, path, args);
14654 });
14655 return result;
14656 });
14657
14658 /**
14659 * Creates an array of values by running each element in `collection` through
14660 * `iteratee`. The `iteratee` is bound to `thisArg` and invoked with three
14661 * arguments: (value, index|key, collection).
14662 *
14663 * If a property name is provided for `iteratee` the created `_.property`
14664 * style callback returns the property value of the given element.
14665 *
14666 * If a value is also provided for `thisArg` the created `_.matchesProperty`
14667 * style callback returns `true` for elements that have a matching property
14668 * value, else `false`.
14669 *
14670 * If an object is provided for `iteratee` the created `_.matches` style
14671 * callback returns `true` for elements that have the properties of the given
14672 * object, else `false`.
14673 *
14674 * Many lodash methods are guarded to work as iteratees for methods like
14675 * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`.
14676 *
14677 * The guarded methods are:
14678 * `ary`, `callback`, `chunk`, `clone`, `create`, `curry`, `curryRight`,
14679 * `drop`, `dropRight`, `every`, `fill`, `flatten`, `invert`, `max`, `min`,
14680 * `parseInt`, `slice`, `sortBy`, `take`, `takeRight`, `template`, `trim`,
14681 * `trimLeft`, `trimRight`, `trunc`, `random`, `range`, `sample`, `some`,
14682 * `sum`, `uniq`, and `words`
14683 *
14684 * @static
14685 * @memberOf _
14686 * @alias collect
14687 * @category Collection
14688 * @param {Array|Object|string} collection The collection to iterate over.
14689 * @param {Function|Object|string} [iteratee=_.identity] The function invoked
14690 * per iteration.
14691 * @param {*} [thisArg] The `this` binding of `iteratee`.
14692 * @returns {Array} Returns the new mapped array.
14693 * @example
14694 *
14695 * function timesThree(n) {
14696 * return n * 3;
14697 * }
14698 *
14699 * _.map([1, 2], timesThree);
14700 * // => [3, 6]
14701 *
14702 * _.map({ 'a': 1, 'b': 2 }, timesThree);
14703 * // => [3, 6] (iteration order is not guaranteed)
14704 *
14705 * var users = [
14706 * { 'user': 'barney' },
14707 * { 'user': 'fred' }
14708 * ];
14709 *
14710 * // using the `_.property` callback shorthand
14711 * _.map(users, 'user');
14712 * // => ['barney', 'fred']
14713 */
14714 function map(collection, iteratee, thisArg) {
14715 var func = isArray(collection) ? arrayMap : baseMap;
14716 iteratee = getCallback(iteratee, thisArg, 3);
14717 return func(collection, iteratee);
14718 }
14719
14720 /**
14721 * Creates an array of elements split into two groups, the first of which
14722 * contains elements `predicate` returns truthy for, while the second of which
14723 * contains elements `predicate` returns falsey for. The predicate is bound
14724 * to `thisArg` and invoked with three arguments: (value, index|key, collection).
14725 *
14726 * If a property name is provided for `predicate` the created `_.property`
14727 * style callback returns the property value of the given element.
14728 *
14729 * If a value is also provided for `thisArg` the created `_.matchesProperty`
14730 * style callback returns `true` for elements that have a matching property
14731 * value, else `false`.
14732 *
14733 * If an object is provided for `predicate` the created `_.matches` style
14734 * callback returns `true` for elements that have the properties of the given
14735 * object, else `false`.
14736 *
14737 * @static
14738 * @memberOf _
14739 * @category Collection
14740 * @param {Array|Object|string} collection The collection to iterate over.
14741 * @param {Function|Object|string} [predicate=_.identity] The function invoked
14742 * per iteration.
14743 * @param {*} [thisArg] The `this` binding of `predicate`.
14744 * @returns {Array} Returns the array of grouped elements.
14745 * @example
14746 *
14747 * _.partition([1, 2, 3], function(n) {
14748 * return n % 2;
14749 * });
14750 * // => [[1, 3], [2]]
14751 *
14752 * _.partition([1.2, 2.3, 3.4], function(n) {
14753 * return this.floor(n) % 2;
14754 * }, Math);
14755 * // => [[1.2, 3.4], [2.3]]
14756 *
14757 * var users = [
14758 * { 'user': 'barney', 'age': 36, 'active': false },
14759 * { 'user': 'fred', 'age': 40, 'active': true },
14760 * { 'user': 'pebbles', 'age': 1, 'active': false }
14761 * ];
14762 *
14763 * var mapper = function(array) {
14764 * return _.pluck(array, 'user');
14765 * };
14766 *
14767 * // using the `_.matches` callback shorthand
14768 * _.map(_.partition(users, { 'age': 1, 'active': false }), mapper);
14769 * // => [['pebbles'], ['barney', 'fred']]
14770 *
14771 * // using the `_.matchesProperty` callback shorthand
14772 * _.map(_.partition(users, 'active', false), mapper);
14773 * // => [['barney', 'pebbles'], ['fred']]
14774 *
14775 * // using the `_.property` callback shorthand
14776 * _.map(_.partition(users, 'active'), mapper);
14777 * // => [['fred'], ['barney', 'pebbles']]
14778 */
14779 var partition = createAggregator(function(result, value, key) {
14780 result[key ? 0 : 1].push(value);
14781 }, function() { return [[], []]; });
14782
14783 /**
14784 * Gets the property value of `path` from all elements in `collection`.
14785 *
14786 * @static
14787 * @memberOf _
14788 * @category Collection
14789 * @param {Array|Object|string} collection The collection to iterate over.
14790 * @param {Array|string} path The path of the property to pluck.
14791 * @returns {Array} Returns the property values.
14792 * @example
14793 *
14794 * var users = [
14795 * { 'user': 'barney', 'age': 36 },
14796 * { 'user': 'fred', 'age': 40 }
14797 * ];
14798 *
14799 * _.pluck(users, 'user');
14800 * // => ['barney', 'fred']
14801 *
14802 * var userIndex = _.indexBy(users, 'user');
14803 * _.pluck(userIndex, 'age');
14804 * // => [36, 40] (iteration order is not guaranteed)
14805 */
14806 function pluck(collection, path) {
14807 return map(collection, property(path));
14808 }
14809
14810 /**
14811 * Reduces `collection` to a value which is the accumulated result of running
14812 * each element in `collection` through `iteratee`, where each successive
14813 * invocation is supplied the return value of the previous. If `accumulator`
14814 * is not provided the first element of `collection` is used as the initial
14815 * value. The `iteratee` is bound to `thisArg` and invoked with four arguments:
14816 * (accumulator, value, index|key, collection).
14817 *
14818 * Many lodash methods are guarded to work as iteratees for methods like
14819 * `_.reduce`, `_.reduceRight`, and `_.transform`.
14820 *
14821 * The guarded methods are:
14822 * `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `sortByAll`,
14823 * and `sortByOrder`
14824 *
14825 * @static
14826 * @memberOf _
14827 * @alias foldl, inject
14828 * @category Collection
14829 * @param {Array|Object|string} collection The collection to iterate over.
14830 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
14831 * @param {*} [accumulator] The initial value.
14832 * @param {*} [thisArg] The `this` binding of `iteratee`.
14833 * @returns {*} Returns the accumulated value.
14834 * @example
14835 *
14836 * _.reduce([1, 2], function(total, n) {
14837 * return total + n;
14838 * });
14839 * // => 3
14840 *
14841 * _.reduce({ 'a': 1, 'b': 2 }, function(result, n, key) {
14842 * result[key] = n * 3;
14843 * return result;
14844 * }, {});
14845 * // => { 'a': 3, 'b': 6 } (iteration order is not guaranteed)
14846 */
14847 var reduce = createReduce(arrayReduce, baseEach);
14848
14849 /**
14850 * This method is like `_.reduce` except that it iterates over elements of
14851 * `collection` from right to left.
14852 *
14853 * @static
14854 * @memberOf _
14855 * @alias foldr
14856 * @category Collection
14857 * @param {Array|Object|string} collection The collection to iterate over.
14858 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
14859 * @param {*} [accumulator] The initial value.
14860 * @param {*} [thisArg] The `this` binding of `iteratee`.
14861 * @returns {*} Returns the accumulated value.
14862 * @example
14863 *
14864 * var array = [[0, 1], [2, 3], [4, 5]];
14865 *
14866 * _.reduceRight(array, function(flattened, other) {
14867 * return flattened.concat(other);
14868 * }, []);
14869 * // => [4, 5, 2, 3, 0, 1]
14870 */
14871 var reduceRight = createReduce(arrayReduceRight, baseEachRight);
14872
14873 /**
14874 * The opposite of `_.filter`; this method returns the elements of `collection`
14875 * that `predicate` does **not** return truthy for.
14876 *
14877 * @static
14878 * @memberOf _
14879 * @category Collection
14880 * @param {Array|Object|string} collection The collection to iterate over.
14881 * @param {Function|Object|string} [predicate=_.identity] The function invoked
14882 * per iteration.
14883 * @param {*} [thisArg] The `this` binding of `predicate`.
14884 * @returns {Array} Returns the new filtered array.
14885 * @example
14886 *
14887 * _.reject([1, 2, 3, 4], function(n) {
14888 * return n % 2 == 0;
14889 * });
14890 * // => [1, 3]
14891 *
14892 * var users = [
14893 * { 'user': 'barney', 'age': 36, 'active': false },
14894 * { 'user': 'fred', 'age': 40, 'active': true }
14895 * ];
14896 *
14897 * // using the `_.matches` callback shorthand
14898 * _.pluck(_.reject(users, { 'age': 40, 'active': true }), 'user');
14899 * // => ['barney']
14900 *
14901 * // using the `_.matchesProperty` callback shorthand
14902 * _.pluck(_.reject(users, 'active', false), 'user');
14903 * // => ['fred']
14904 *
14905 * // using the `_.property` callback shorthand
14906 * _.pluck(_.reject(users, 'active'), 'user');
14907 * // => ['barney']
14908 */
14909 function reject(collection, predicate, thisArg) {
14910 var func = isArray(collection) ? arrayFilter : baseFilter;
14911 predicate = getCallback(predicate, thisArg, 3);
14912 return func(collection, function(value, index, collection) {
14913 return !predicate(value, index, collection);
14914 });
14915 }
14916
14917 /**
14918 * Gets a random element or `n` random elements from a collection.
14919 *
14920 * @static
14921 * @memberOf _
14922 * @category Collection
14923 * @param {Array|Object|string} collection The collection to sample.
14924 * @param {number} [n] The number of elements to sample.
14925 * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
14926 * @returns {*} Returns the random sample(s).
14927 * @example
14928 *
14929 * _.sample([1, 2, 3, 4]);
14930 * // => 2
14931 *
14932 * _.sample([1, 2, 3, 4], 2);
14933 * // => [3, 1]
14934 */
14935 function sample(collection, n, guard) {
14936 if (guard ? isIterateeCall(collection, n, guard) : n == null) {
14937 collection = toIterable(collection);
14938 var length = collection.length;
14939 return length > 0 ? collection[baseRandom(0, length - 1)] : undefined;
14940 }
14941 var index = -1,
14942 result = toArray(collection),
14943 length = result.length,
14944 lastIndex = length - 1;
14945
14946 n = nativeMin(n < 0 ? 0 : (+n || 0), length);
14947 while (++index < n) {
14948 var rand = baseRandom(index, lastIndex),
14949 value = result[rand];
14950
14951 result[rand] = result[index];
14952 result[index] = value;
14953 }
14954 result.length = n;
14955 return result;
14956 }
14957
14958 /**
14959 * Creates an array of shuffled values, using a version of the
14960 * [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle).
14961 *
14962 * @static
14963 * @memberOf _
14964 * @category Collection
14965 * @param {Array|Object|string} collection The collection to shuffle.
14966 * @returns {Array} Returns the new shuffled array.
14967 * @example
14968 *
14969 * _.shuffle([1, 2, 3, 4]);
14970 * // => [4, 1, 3, 2]
14971 */
14972 function shuffle(collection) {
14973 return sample(collection, POSITIVE_INFINITY);
14974 }
14975
14976 /**
14977 * Gets the size of `collection` by returning its length for array-like
14978 * values or the number of own enumerable properties for objects.
14979 *
14980 * @static
14981 * @memberOf _
14982 * @category Collection
14983 * @param {Array|Object|string} collection The collection to inspect.
14984 * @returns {number} Returns the size of `collection`.
14985 * @example
14986 *
14987 * _.size([1, 2, 3]);
14988 * // => 3
14989 *
14990 * _.size({ 'a': 1, 'b': 2 });
14991 * // => 2
14992 *
14993 * _.size('pebbles');
14994 * // => 7
14995 */
14996 function size(collection) {
14997 var length = collection ? getLength(collection) : 0;
14998 return isLength(length) ? length : keys(collection).length;
14999 }
15000
15001 /**
15002 * Checks if `predicate` returns truthy for **any** element of `collection`.
15003 * The function returns as soon as it finds a passing value and does not iterate
15004 * over the entire collection. The predicate is bound to `thisArg` and invoked
15005 * with three arguments: (value, index|key, collection).
15006 *
15007 * If a property name is provided for `predicate` the created `_.property`
15008 * style callback returns the property value of the given element.
15009 *
15010 * If a value is also provided for `thisArg` the created `_.matchesProperty`
15011 * style callback returns `true` for elements that have a matching property
15012 * value, else `false`.
15013 *
15014 * If an object is provided for `predicate` the created `_.matches` style
15015 * callback returns `true` for elements that have the properties of the given
15016 * object, else `false`.
15017 *
15018 * @static
15019 * @memberOf _
15020 * @alias any
15021 * @category Collection
15022 * @param {Array|Object|string} collection The collection to iterate over.
15023 * @param {Function|Object|string} [predicate=_.identity] The function invoked
15024 * per iteration.
15025 * @param {*} [thisArg] The `this` binding of `predicate`.
15026 * @returns {boolean} Returns `true` if any element passes the predicate check,
15027 * else `false`.
15028 * @example
15029 *
15030 * _.some([null, 0, 'yes', false], Boolean);
15031 * // => true
15032 *
15033 * var users = [
15034 * { 'user': 'barney', 'active': true },
15035 * { 'user': 'fred', 'active': false }
15036 * ];
15037 *
15038 * // using the `_.matches` callback shorthand
15039 * _.some(users, { 'user': 'barney', 'active': false });
15040 * // => false
15041 *
15042 * // using the `_.matchesProperty` callback shorthand
15043 * _.some(users, 'active', false);
15044 * // => true
15045 *
15046 * // using the `_.property` callback shorthand
15047 * _.some(users, 'active');
15048 * // => true
15049 */
15050 function some(collection, predicate, thisArg) {
15051 var func = isArray(collection) ? arraySome : baseSome;
15052 if (thisArg && isIterateeCall(collection, predicate, thisArg)) {
15053 predicate = undefined;
15054 }
15055 if (typeof predicate != 'function' || thisArg !== undefined) {
15056 predicate = getCallback(predicate, thisArg, 3);
15057 }
15058 return func(collection, predicate);
15059 }
15060
15061 /**
15062 * Creates an array of elements, sorted in ascending order by the results of
15063 * running each element in a collection through `iteratee`. This method performs
15064 * a stable sort, that is, it preserves the original sort order of equal elements.
15065 * The `iteratee` is bound to `thisArg` and invoked with three arguments:
15066 * (value, index|key, collection).
15067 *
15068 * If a property name is provided for `iteratee` the created `_.property`
15069 * style callback returns the property value of the given element.
15070 *
15071 * If a value is also provided for `thisArg` the created `_.matchesProperty`
15072 * style callback returns `true` for elements that have a matching property
15073 * value, else `false`.
15074 *
15075 * If an object is provided for `iteratee` the created `_.matches` style
15076 * callback returns `true` for elements that have the properties of the given
15077 * object, else `false`.
15078 *
15079 * @static
15080 * @memberOf _
15081 * @category Collection
15082 * @param {Array|Object|string} collection The collection to iterate over.
15083 * @param {Function|Object|string} [iteratee=_.identity] The function invoked
15084 * per iteration.
15085 * @param {*} [thisArg] The `this` binding of `iteratee`.
15086 * @returns {Array} Returns the new sorted array.
15087 * @example
15088 *
15089 * _.sortBy([1, 2, 3], function(n) {
15090 * return Math.sin(n);
15091 * });
15092 * // => [3, 1, 2]
15093 *
15094 * _.sortBy([1, 2, 3], function(n) {
15095 * return this.sin(n);
15096 * }, Math);
15097 * // => [3, 1, 2]
15098 *
15099 * var users = [
15100 * { 'user': 'fred' },
15101 * { 'user': 'pebbles' },
15102 * { 'user': 'barney' }
15103 * ];
15104 *
15105 * // using the `_.property` callback shorthand
15106 * _.pluck(_.sortBy(users, 'user'), 'user');
15107 * // => ['barney', 'fred', 'pebbles']
15108 */
15109 function sortBy(collection, iteratee, thisArg) {
15110 if (collection == null) {
15111 return [];
15112 }
15113 if (thisArg && isIterateeCall(collection, iteratee, thisArg)) {
15114 iteratee = undefined;
15115 }
15116 var index = -1;
15117 iteratee = getCallback(iteratee, thisArg, 3);
15118
15119 var result = baseMap(collection, function(value, key, collection) {
15120 return { 'criteria': iteratee(value, key, collection), 'index': ++index, 'value': value };
15121 });
15122 return baseSortBy(result, compareAscending);
15123 }
15124
15125 /**
15126 * This method is like `_.sortBy` except that it can sort by multiple iteratees
15127 * or property names.
15128 *
15129 * If a property name is provided for an iteratee the created `_.property`
15130 * style callback returns the property value of the given element.
15131 *
15132 * If an object is provided for an iteratee the created `_.matches` style
15133 * callback returns `true` for elements that have the properties of the given
15134 * object, else `false`.
15135 *
15136 * @static
15137 * @memberOf _
15138 * @category Collection
15139 * @param {Array|Object|string} collection The collection to iterate over.
15140 * @param {...(Function|Function[]|Object|Object[]|string|string[])} iteratees
15141 * The iteratees to sort by, specified as individual values or arrays of values.
15142 * @returns {Array} Returns the new sorted array.
15143 * @example
15144 *
15145 * var users = [
15146 * { 'user': 'fred', 'age': 48 },
15147 * { 'user': 'barney', 'age': 36 },
15148 * { 'user': 'fred', 'age': 42 },
15149 * { 'user': 'barney', 'age': 34 }
15150 * ];
15151 *
15152 * _.map(_.sortByAll(users, ['user', 'age']), _.values);
15153 * // => [['barney', 34], ['barney', 36], ['fred', 42], ['fred', 48]]
15154 *
15155 * _.map(_.sortByAll(users, 'user', function(chr) {
15156 * return Math.floor(chr.age / 10);
15157 * }), _.values);
15158 * // => [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 42]]
15159 */
15160 var sortByAll = restParam(function(collection, iteratees) {
15161 if (collection == null) {
15162 return [];
15163 }
15164 var guard = iteratees[2];
15165 if (guard && isIterateeCall(iteratees[0], iteratees[1], guard)) {
15166 iteratees.length = 1;
15167 }
15168 return baseSortByOrder(collection, baseFlatten(iteratees), []);
15169 });
15170
15171 /**
15172 * This method is like `_.sortByAll` except that it allows specifying the
15173 * sort orders of the iteratees to sort by. If `orders` is unspecified, all
15174 * values are sorted in ascending order. Otherwise, a value is sorted in
15175 * ascending order if its corresponding order is "asc", and descending if "desc".
15176 *
15177 * If a property name is provided for an iteratee the created `_.property`
15178 * style callback returns the property value of the given element.
15179 *
15180 * If an object is provided for an iteratee the created `_.matches` style
15181 * callback returns `true` for elements that have the properties of the given
15182 * object, else `false`.
15183 *
15184 * @static
15185 * @memberOf _
15186 * @category Collection
15187 * @param {Array|Object|string} collection The collection to iterate over.
15188 * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by.
15189 * @param {boolean[]} [orders] The sort orders of `iteratees`.
15190 * @param- {Object} [guard] Enables use as a callback for functions like `_.reduce`.
15191 * @returns {Array} Returns the new sorted array.
15192 * @example
15193 *
15194 * var users = [
15195 * { 'user': 'fred', 'age': 48 },
15196 * { 'user': 'barney', 'age': 34 },
15197 * { 'user': 'fred', 'age': 42 },
15198 * { 'user': 'barney', 'age': 36 }
15199 * ];
15200 *
15201 * // sort by `user` in ascending order and by `age` in descending order
15202 * _.map(_.sortByOrder(users, ['user', 'age'], ['asc', 'desc']), _.values);
15203 * // => [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 42]]
15204 */
15205 function sortByOrder(collection, iteratees, orders, guard) {
15206 if (collection == null) {
15207 return [];
15208 }
15209 if (guard && isIterateeCall(iteratees, orders, guard)) {
15210 orders = undefined;
15211 }
15212 if (!isArray(iteratees)) {
15213 iteratees = iteratees == null ? [] : [iteratees];
15214 }
15215 if (!isArray(orders)) {
15216 orders = orders == null ? [] : [orders];
15217 }
15218 return baseSortByOrder(collection, iteratees, orders);
15219 }
15220
15221 /**
15222 * Performs a deep comparison between each element in `collection` and the
15223 * source object, returning an array of all elements that have equivalent
15224 * property values.
15225 *
15226 * **Note:** This method supports comparing arrays, booleans, `Date` objects,
15227 * numbers, `Object` objects, regexes, and strings. Objects are compared by
15228 * their own, not inherited, enumerable properties. For comparing a single
15229 * own or inherited property value see `_.matchesProperty`.
15230 *
15231 * @static
15232 * @memberOf _
15233 * @category Collection
15234 * @param {Array|Object|string} collection The collection to search.
15235 * @param {Object} source The object of property values to match.
15236 * @returns {Array} Returns the new filtered array.
15237 * @example
15238 *
15239 * var users = [
15240 * { 'user': 'barney', 'age': 36, 'active': false, 'pets': ['hoppy'] },
15241 * { 'user': 'fred', 'age': 40, 'active': true, 'pets': ['baby puss', 'dino'] }
15242 * ];
15243 *
15244 * _.pluck(_.where(users, { 'age': 36, 'active': false }), 'user');
15245 * // => ['barney']
15246 *
15247 * _.pluck(_.where(users, { 'pets': ['dino'] }), 'user');
15248 * // => ['fred']
15249 */
15250 function where(collection, source) {
15251 return filter(collection, baseMatches(source));
15252 }
15253
15254 /*------------------------------------------------------------------------*/
15255
15256 /**
15257 * Gets the number of milliseconds that have elapsed since the Unix epoch
15258 * (1 January 1970 00:00:00 UTC).
15259 *
15260 * @static
15261 * @memberOf _
15262 * @category Date
15263 * @example
15264 *
15265 * _.defer(function(stamp) {
15266 * console.log(_.now() - stamp);
15267 * }, _.now());
15268 * // => logs the number of milliseconds it took for the deferred function to be invoked
15269 */
15270 var now = nativeNow || function() {
15271 return new Date().getTime();
15272 };
15273
15274 /*------------------------------------------------------------------------*/
15275
15276 /**
15277 * The opposite of `_.before`; this method creates a function that invokes
15278 * `func` once it is called `n` or more times.
15279 *
15280 * @static
15281 * @memberOf _
15282 * @category Function
15283 * @param {number} n The number of calls before `func` is invoked.
15284 * @param {Function} func The function to restrict.
15285 * @returns {Function} Returns the new restricted function.
15286 * @example
15287 *
15288 * var saves = ['profile', 'settings'];
15289 *
15290 * var done = _.after(saves.length, function() {
15291 * console.log('done saving!');
15292 * });
15293 *
15294 * _.forEach(saves, function(type) {
15295 * asyncSave({ 'type': type, 'complete': done });
15296 * });
15297 * // => logs 'done saving!' after the two async saves have completed
15298 */
15299 function after(n, func) {
15300 if (typeof func != 'function') {
15301 if (typeof n == 'function') {
15302 var temp = n;
15303 n = func;
15304 func = temp;
15305 } else {
15306 throw new TypeError(FUNC_ERROR_TEXT);
15307 }
15308 }
15309 n = nativeIsFinite(n = +n) ? n : 0;
15310 return function() {
15311 if (--n < 1) {
15312 return func.apply(this, arguments);
15313 }
15314 };
15315 }
15316
15317 /**
15318 * Creates a function that accepts up to `n` arguments ignoring any
15319 * additional arguments.
15320 *
15321 * @static
15322 * @memberOf _
15323 * @category Function
15324 * @param {Function} func The function to cap arguments for.
15325 * @param {number} [n=func.length] The arity cap.
15326 * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
15327 * @returns {Function} Returns the new function.
15328 * @example
15329 *
15330 * _.map(['6', '8', '10'], _.ary(parseInt, 1));
15331 * // => [6, 8, 10]
15332 */
15333 function ary(func, n, guard) {
15334 if (guard && isIterateeCall(func, n, guard)) {
15335 n = undefined;
15336 }
15337 n = (func && n == null) ? func.length : nativeMax(+n || 0, 0);
15338 return createWrapper(func, ARY_FLAG, undefined, undefined, undefined, undefined, n);
15339 }
15340
15341 /**
15342 * Creates a function that invokes `func`, with the `this` binding and arguments
15343 * of the created function, while it is called less than `n` times. Subsequent
15344 * calls to the created function return the result of the last `func` invocation.
15345 *
15346 * @static
15347 * @memberOf _
15348 * @category Function
15349 * @param {number} n The number of calls at which `func` is no longer invoked.
15350 * @param {Function} func The function to restrict.
15351 * @returns {Function} Returns the new restricted function.
15352 * @example
15353 *
15354 * jQuery('#add').on('click', _.before(5, addContactToList));
15355 * // => allows adding up to 4 contacts to the list
15356 */
15357 function before(n, func) {
15358 var result;
15359 if (typeof func != 'function') {
15360 if (typeof n == 'function') {
15361 var temp = n;
15362 n = func;
15363 func = temp;
15364 } else {
15365 throw new TypeError(FUNC_ERROR_TEXT);
15366 }
15367 }
15368 return function() {
15369 if (--n > 0) {
15370 result = func.apply(this, arguments);
15371 }
15372 if (n <= 1) {
15373 func = undefined;
15374 }
15375 return result;
15376 };
15377 }
15378
15379 /**
15380 * Creates a function that invokes `func` with the `this` binding of `thisArg`
15381 * and prepends any additional `_.bind` arguments to those provided to the
15382 * bound function.
15383 *
15384 * The `_.bind.placeholder` value, which defaults to `_` in monolithic builds,
15385 * may be used as a placeholder for partially applied arguments.
15386 *
15387 * **Note:** Unlike native `Function#bind` this method does not set the "length"
15388 * property of bound functions.
15389 *
15390 * @static
15391 * @memberOf _
15392 * @category Function
15393 * @param {Function} func The function to bind.
15394 * @param {*} thisArg The `this` binding of `func`.
15395 * @param {...*} [partials] The arguments to be partially applied.
15396 * @returns {Function} Returns the new bound function.
15397 * @example
15398 *
15399 * var greet = function(greeting, punctuation) {
15400 * return greeting + ' ' + this.user + punctuation;
15401 * };
15402 *
15403 * var object = { 'user': 'fred' };
15404 *
15405 * var bound = _.bind(greet, object, 'hi');
15406 * bound('!');
15407 * // => 'hi fred!'
15408 *
15409 * // using placeholders
15410 * var bound = _.bind(greet, object, _, '!');
15411 * bound('hi');
15412 * // => 'hi fred!'
15413 */
15414 var bind = restParam(function(func, thisArg, partials) {
15415 var bitmask = BIND_FLAG;
15416 if (partials.length) {
15417 var holders = replaceHolders(partials, bind.placeholder);
15418 bitmask |= PARTIAL_FLAG;
15419 }
15420 return createWrapper(func, bitmask, thisArg, partials, holders);
15421 });
15422
15423 /**
15424 * Binds methods of an object to the object itself, overwriting the existing
15425 * method. Method names may be specified as individual arguments or as arrays
15426 * of method names. If no method names are provided all enumerable function
15427 * properties, own and inherited, of `object` are bound.
15428 *
15429 * **Note:** This method does not set the "length" property of bound functions.
15430 *
15431 * @static
15432 * @memberOf _
15433 * @category Function
15434 * @param {Object} object The object to bind and assign the bound methods to.
15435 * @param {...(string|string[])} [methodNames] The object method names to bind,
15436 * specified as individual method names or arrays of method names.
15437 * @returns {Object} Returns `object`.
15438 * @example
15439 *
15440 * var view = {
15441 * 'label': 'docs',
15442 * 'onClick': function() {
15443 * console.log('clicked ' + this.label);
15444 * }
15445 * };
15446 *
15447 * _.bindAll(view);
15448 * jQuery('#docs').on('click', view.onClick);
15449 * // => logs 'clicked docs' when the element is clicked
15450 */
15451 var bindAll = restParam(function(object, methodNames) {
15452 methodNames = methodNames.length ? baseFlatten(methodNames) : functions(object);
15453
15454 var index = -1,
15455 length = methodNames.length;
15456
15457 while (++index < length) {
15458 var key = methodNames[index];
15459 object[key] = createWrapper(object[key], BIND_FLAG, object);
15460 }
15461 return object;
15462 });
15463
15464 /**
15465 * Creates a function that invokes the method at `object[key]` and prepends
15466 * any additional `_.bindKey` arguments to those provided to the bound function.
15467 *
15468 * This method differs from `_.bind` by allowing bound functions to reference
15469 * methods that may be redefined or don't yet exist.
15470 * See [Peter Michaux's article](http://peter.michaux.ca/articles/lazy-function-definition-pattern)
15471 * for more details.
15472 *
15473 * The `_.bindKey.placeholder` value, which defaults to `_` in monolithic
15474 * builds, may be used as a placeholder for partially applied arguments.
15475 *
15476 * @static
15477 * @memberOf _
15478 * @category Function
15479 * @param {Object} object The object the method belongs to.
15480 * @param {string} key The key of the method.
15481 * @param {...*} [partials] The arguments to be partially applied.
15482 * @returns {Function} Returns the new bound function.
15483 * @example
15484 *
15485 * var object = {
15486 * 'user': 'fred',
15487 * 'greet': function(greeting, punctuation) {
15488 * return greeting + ' ' + this.user + punctuation;
15489 * }
15490 * };
15491 *
15492 * var bound = _.bindKey(object, 'greet', 'hi');
15493 * bound('!');
15494 * // => 'hi fred!'
15495 *
15496 * object.greet = function(greeting, punctuation) {
15497 * return greeting + 'ya ' + this.user + punctuation;
15498 * };
15499 *
15500 * bound('!');
15501 * // => 'hiya fred!'
15502 *
15503 * // using placeholders
15504 * var bound = _.bindKey(object, 'greet', _, '!');
15505 * bound('hi');
15506 * // => 'hiya fred!'
15507 */
15508 var bindKey = restParam(function(object, key, partials) {
15509 var bitmask = BIND_FLAG | BIND_KEY_FLAG;
15510 if (partials.length) {
15511 var holders = replaceHolders(partials, bindKey.placeholder);
15512 bitmask |= PARTIAL_FLAG;
15513 }
15514 return createWrapper(key, bitmask, object, partials, holders);
15515 });
15516
15517 /**
15518 * Creates a function that accepts one or more arguments of `func` that when
15519 * called either invokes `func` returning its result, if all `func` arguments
15520 * have been provided, or returns a function that accepts one or more of the
15521 * remaining `func` arguments, and so on. The arity of `func` may be specified
15522 * if `func.length` is not sufficient.
15523 *
15524 * The `_.curry.placeholder` value, which defaults to `_` in monolithic builds,
15525 * may be used as a placeholder for provided arguments.
15526 *
15527 * **Note:** This method does not set the "length" property of curried functions.
15528 *
15529 * @static
15530 * @memberOf _
15531 * @category Function
15532 * @param {Function} func The function to curry.
15533 * @param {number} [arity=func.length] The arity of `func`.
15534 * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
15535 * @returns {Function} Returns the new curried function.
15536 * @example
15537 *
15538 * var abc = function(a, b, c) {
15539 * return [a, b, c];
15540 * };
15541 *
15542 * var curried = _.curry(abc);
15543 *
15544 * curried(1)(2)(3);
15545 * // => [1, 2, 3]
15546 *
15547 * curried(1, 2)(3);
15548 * // => [1, 2, 3]
15549 *
15550 * curried(1, 2, 3);
15551 * // => [1, 2, 3]
15552 *
15553 * // using placeholders
15554 * curried(1)(_, 3)(2);
15555 * // => [1, 2, 3]
15556 */
15557 var curry = createCurry(CURRY_FLAG);
15558
15559 /**
15560 * This method is like `_.curry` except that arguments are applied to `func`
15561 * in the manner of `_.partialRight` instead of `_.partial`.
15562 *
15563 * The `_.curryRight.placeholder` value, which defaults to `_` in monolithic
15564 * builds, may be used as a placeholder for provided arguments.
15565 *
15566 * **Note:** This method does not set the "length" property of curried functions.
15567 *
15568 * @static
15569 * @memberOf _
15570 * @category Function
15571 * @param {Function} func The function to curry.
15572 * @param {number} [arity=func.length] The arity of `func`.
15573 * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
15574 * @returns {Function} Returns the new curried function.
15575 * @example
15576 *
15577 * var abc = function(a, b, c) {
15578 * return [a, b, c];
15579 * };
15580 *
15581 * var curried = _.curryRight(abc);
15582 *
15583 * curried(3)(2)(1);
15584 * // => [1, 2, 3]
15585 *
15586 * curried(2, 3)(1);
15587 * // => [1, 2, 3]
15588 *
15589 * curried(1, 2, 3);
15590 * // => [1, 2, 3]
15591 *
15592 * // using placeholders
15593 * curried(3)(1, _)(2);
15594 * // => [1, 2, 3]
15595 */
15596 var curryRight = createCurry(CURRY_RIGHT_FLAG);
15597
15598 /**
15599 * Creates a debounced function that delays invoking `func` until after `wait`
15600 * milliseconds have elapsed since the last time the debounced function was
15601 * invoked. The debounced function comes with a `cancel` method to cancel
15602 * delayed invocations. Provide an options object to indicate that `func`
15603 * should be invoked on the leading and/or trailing edge of the `wait` timeout.
15604 * Subsequent calls to the debounced function return the result of the last
15605 * `func` invocation.
15606 *
15607 * **Note:** If `leading` and `trailing` options are `true`, `func` is invoked
15608 * on the trailing edge of the timeout only if the the debounced function is
15609 * invoked more than once during the `wait` timeout.
15610 *
15611 * See [David Corbacho's article](http://drupalmotion.com/article/debounce-and-throttle-visual-explanation)
15612 * for details over the differences between `_.debounce` and `_.throttle`.
15613 *
15614 * @static
15615 * @memberOf _
15616 * @category Function
15617 * @param {Function} func The function to debounce.
15618 * @param {number} [wait=0] The number of milliseconds to delay.
15619 * @param {Object} [options] The options object.
15620 * @param {boolean} [options.leading=false] Specify invoking on the leading
15621 * edge of the timeout.
15622 * @param {number} [options.maxWait] The maximum time `func` is allowed to be
15623 * delayed before it is invoked.
15624 * @param {boolean} [options.trailing=true] Specify invoking on the trailing
15625 * edge of the timeout.
15626 * @returns {Function} Returns the new debounced function.
15627 * @example
15628 *
15629 * // avoid costly calculations while the window size is in flux
15630 * jQuery(window).on('resize', _.debounce(calculateLayout, 150));
15631 *
15632 * // invoke `sendMail` when the click event is fired, debouncing subsequent calls
15633 * jQuery('#postbox').on('click', _.debounce(sendMail, 300, {
15634 * 'leading': true,
15635 * 'trailing': false
15636 * }));
15637 *
15638 * // ensure `batchLog` is invoked once after 1 second of debounced calls
15639 * var source = new EventSource('/stream');
15640 * jQuery(source).on('message', _.debounce(batchLog, 250, {
15641 * 'maxWait': 1000
15642 * }));
15643 *
15644 * // cancel a debounced call
15645 * var todoChanges = _.debounce(batchLog, 1000);
15646 * Object.observe(models.todo, todoChanges);
15647 *
15648 * Object.observe(models, function(changes) {
15649 * if (_.find(changes, { 'user': 'todo', 'type': 'delete'})) {
15650 * todoChanges.cancel();
15651 * }
15652 * }, ['delete']);
15653 *
15654 * // ...at some point `models.todo` is changed
15655 * models.todo.completed = true;
15656 *
15657 * // ...before 1 second has passed `models.todo` is deleted
15658 * // which cancels the debounced `todoChanges` call
15659 * delete models.todo;
15660 */
15661 function debounce(func, wait, options) {
15662 var args,
15663 maxTimeoutId,
15664 result,
15665 stamp,
15666 thisArg,
15667 timeoutId,
15668 trailingCall,
15669 lastCalled = 0,
15670 maxWait = false,
15671 trailing = true;
15672
15673 if (typeof func != 'function') {
15674 throw new TypeError(FUNC_ERROR_TEXT);
15675 }
15676 wait = wait < 0 ? 0 : (+wait || 0);
15677 if (options === true) {
15678 var leading = true;
15679 trailing = false;
15680 } else if (isObject(options)) {
15681 leading = !!options.leading;
15682 maxWait = 'maxWait' in options && nativeMax(+options.maxWait || 0, wait);
15683 trailing = 'trailing' in options ? !!options.trailing : trailing;
15684 }
15685
15686 function cancel() {
15687 if (timeoutId) {
15688 clearTimeout(timeoutId);
15689 }
15690 if (maxTimeoutId) {
15691 clearTimeout(maxTimeoutId);
15692 }
15693 lastCalled = 0;
15694 maxTimeoutId = timeoutId = trailingCall = undefined;
15695 }
15696
15697 function complete(isCalled, id) {
15698 if (id) {
15699 clearTimeout(id);
15700 }
15701 maxTimeoutId = timeoutId = trailingCall = undefined;
15702 if (isCalled) {
15703 lastCalled = now();
15704 result = func.apply(thisArg, args);
15705 if (!timeoutId && !maxTimeoutId) {
15706 args = thisArg = undefined;
15707 }
15708 }
15709 }
15710
15711 function delayed() {
15712 var remaining = wait - (now() - stamp);
15713 if (remaining <= 0 || remaining > wait) {
15714 complete(trailingCall, maxTimeoutId);
15715 } else {
15716 timeoutId = setTimeout(delayed, remaining);
15717 }
15718 }
15719
15720 function maxDelayed() {
15721 complete(trailing, timeoutId);
15722 }
15723
15724 function debounced() {
15725 args = arguments;
15726 stamp = now();
15727 thisArg = this;
15728 trailingCall = trailing && (timeoutId || !leading);
15729
15730 if (maxWait === false) {
15731 var leadingCall = leading && !timeoutId;
15732 } else {
15733 if (!maxTimeoutId && !leading) {
15734 lastCalled = stamp;
15735 }
15736 var remaining = maxWait - (stamp - lastCalled),
15737 isCalled = remaining <= 0 || remaining > maxWait;
15738
15739 if (isCalled) {
15740 if (maxTimeoutId) {
15741 maxTimeoutId = clearTimeout(maxTimeoutId);
15742 }
15743 lastCalled = stamp;
15744 result = func.apply(thisArg, args);
15745 }
15746 else if (!maxTimeoutId) {
15747 maxTimeoutId = setTimeout(maxDelayed, remaining);
15748 }
15749 }
15750 if (isCalled && timeoutId) {
15751 timeoutId = clearTimeout(timeoutId);
15752 }
15753 else if (!timeoutId && wait !== maxWait) {
15754 timeoutId = setTimeout(delayed, wait);
15755 }
15756 if (leadingCall) {
15757 isCalled = true;
15758 result = func.apply(thisArg, args);
15759 }
15760 if (isCalled && !timeoutId && !maxTimeoutId) {
15761 args = thisArg = undefined;
15762 }
15763 return result;
15764 }
15765 debounced.cancel = cancel;
15766 return debounced;
15767 }
15768
15769 /**
15770 * Defers invoking the `func` until the current call stack has cleared. Any
15771 * additional arguments are provided to `func` when it is invoked.
15772 *
15773 * @static
15774 * @memberOf _
15775 * @category Function
15776 * @param {Function} func The function to defer.
15777 * @param {...*} [args] The arguments to invoke the function with.
15778 * @returns {number} Returns the timer id.
15779 * @example
15780 *
15781 * _.defer(function(text) {
15782 * console.log(text);
15783 * }, 'deferred');
15784 * // logs 'deferred' after one or more milliseconds
15785 */
15786 var defer = restParam(function(func, args) {
15787 return baseDelay(func, 1, args);
15788 });
15789
15790 /**
15791 * Invokes `func` after `wait` milliseconds. Any additional arguments are
15792 * provided to `func` when it is invoked.
15793 *
15794 * @static
15795 * @memberOf _
15796 * @category Function
15797 * @param {Function} func The function to delay.
15798 * @param {number} wait The number of milliseconds to delay invocation.
15799 * @param {...*} [args] The arguments to invoke the function with.
15800 * @returns {number} Returns the timer id.
15801 * @example
15802 *
15803 * _.delay(function(text) {
15804 * console.log(text);
15805 * }, 1000, 'later');
15806 * // => logs 'later' after one second
15807 */
15808 var delay = restParam(function(func, wait, args) {
15809 return baseDelay(func, wait, args);
15810 });
15811
15812 /**
15813 * Creates a function that returns the result of invoking the provided
15814 * functions with the `this` binding of the created function, where each
15815 * successive invocation is supplied the return value of the previous.
15816 *
15817 * @static
15818 * @memberOf _
15819 * @category Function
15820 * @param {...Function} [funcs] Functions to invoke.
15821 * @returns {Function} Returns the new function.
15822 * @example
15823 *
15824 * function square(n) {
15825 * return n * n;
15826 * }
15827 *
15828 * var addSquare = _.flow(_.add, square);
15829 * addSquare(1, 2);
15830 * // => 9
15831 */
15832 var flow = createFlow();
15833
15834 /**
15835 * This method is like `_.flow` except that it creates a function that
15836 * invokes the provided functions from right to left.
15837 *
15838 * @static
15839 * @memberOf _
15840 * @alias backflow, compose
15841 * @category Function
15842 * @param {...Function} [funcs] Functions to invoke.
15843 * @returns {Function} Returns the new function.
15844 * @example
15845 *
15846 * function square(n) {
15847 * return n * n;
15848 * }
15849 *
15850 * var addSquare = _.flowRight(square, _.add);
15851 * addSquare(1, 2);
15852 * // => 9
15853 */
15854 var flowRight = createFlow(true);
15855
15856 /**
15857 * Creates a function that memoizes the result of `func`. If `resolver` is
15858 * provided it determines the cache key for storing the result based on the
15859 * arguments provided to the memoized function. By default, the first argument
15860 * provided to the memoized function is coerced to a string and used as the
15861 * cache key. The `func` is invoked with the `this` binding of the memoized
15862 * function.
15863 *
15864 * **Note:** The cache is exposed as the `cache` property on the memoized
15865 * function. Its creation may be customized by replacing the `_.memoize.Cache`
15866 * constructor with one whose instances implement the [`Map`](http://ecma-international.org/ecma-262/6.0/#sec-properties-of-the-map-prototype-object)
15867 * method interface of `get`, `has`, and `set`.
15868 *
15869 * @static
15870 * @memberOf _
15871 * @category Function
15872 * @param {Function} func The function to have its output memoized.
15873 * @param {Function} [resolver] The function to resolve the cache key.
15874 * @returns {Function} Returns the new memoizing function.
15875 * @example
15876 *
15877 * var upperCase = _.memoize(function(string) {
15878 * return string.toUpperCase();
15879 * });
15880 *
15881 * upperCase('fred');
15882 * // => 'FRED'
15883 *
15884 * // modifying the result cache
15885 * upperCase.cache.set('fred', 'BARNEY');
15886 * upperCase('fred');
15887 * // => 'BARNEY'
15888 *
15889 * // replacing `_.memoize.Cache`
15890 * var object = { 'user': 'fred' };
15891 * var other = { 'user': 'barney' };
15892 * var identity = _.memoize(_.identity);
15893 *
15894 * identity(object);
15895 * // => { 'user': 'fred' }
15896 * identity(other);
15897 * // => { 'user': 'fred' }
15898 *
15899 * _.memoize.Cache = WeakMap;
15900 * var identity = _.memoize(_.identity);
15901 *
15902 * identity(object);
15903 * // => { 'user': 'fred' }
15904 * identity(other);
15905 * // => { 'user': 'barney' }
15906 */
15907 function memoize(func, resolver) {
15908 if (typeof func != 'function' || (resolver && typeof resolver != 'function')) {
15909 throw new TypeError(FUNC_ERROR_TEXT);
15910 }
15911 var memoized = function() {
15912 var args = arguments,
15913 key = resolver ? resolver.apply(this, args) : args[0],
15914 cache = memoized.cache;
15915
15916 if (cache.has(key)) {
15917 return cache.get(key);
15918 }
15919 var result = func.apply(this, args);
15920 memoized.cache = cache.set(key, result);
15921 return result;
15922 };
15923 memoized.cache = new memoize.Cache;
15924 return memoized;
15925 }
15926
15927 /**
15928 * Creates a function that runs each argument through a corresponding
15929 * transform function.
15930 *
15931 * @static
15932 * @memberOf _
15933 * @category Function
15934 * @param {Function} func The function to wrap.
15935 * @param {...(Function|Function[])} [transforms] The functions to transform
15936 * arguments, specified as individual functions or arrays of functions.
15937 * @returns {Function} Returns the new function.
15938 * @example
15939 *
15940 * function doubled(n) {
15941 * return n * 2;
15942 * }
15943 *
15944 * function square(n) {
15945 * return n * n;
15946 * }
15947 *
15948 * var modded = _.modArgs(function(x, y) {
15949 * return [x, y];
15950 * }, square, doubled);
15951 *
15952 * modded(1, 2);
15953 * // => [1, 4]
15954 *
15955 * modded(5, 10);
15956 * // => [25, 20]
15957 */
15958 var modArgs = restParam(function(func, transforms) {
15959 transforms = baseFlatten(transforms);
15960 if (typeof func != 'function' || !arrayEvery(transforms, baseIsFunction)) {
15961 throw new TypeError(FUNC_ERROR_TEXT);
15962 }
15963 var length = transforms.length;
15964 return restParam(function(args) {
15965 var index = nativeMin(args.length, length);
15966 while (index--) {
15967 args[index] = transforms[index](args[index]);
15968 }
15969 return func.apply(this, args);
15970 });
15971 });
15972
15973 /**
15974 * Creates a function that negates the result of the predicate `func`. The
15975 * `func` predicate is invoked with the `this` binding and arguments of the
15976 * created function.
15977 *
15978 * @static
15979 * @memberOf _
15980 * @category Function
15981 * @param {Function} predicate The predicate to negate.
15982 * @returns {Function} Returns the new function.
15983 * @example
15984 *
15985 * function isEven(n) {
15986 * return n % 2 == 0;
15987 * }
15988 *
15989 * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven));
15990 * // => [1, 3, 5]
15991 */
15992 function negate(predicate) {
15993 if (typeof predicate != 'function') {
15994 throw new TypeError(FUNC_ERROR_TEXT);
15995 }
15996 return function() {
15997 return !predicate.apply(this, arguments);
15998 };
15999 }
16000
16001 /**
16002 * Creates a function that is restricted to invoking `func` once. Repeat calls
16003 * to the function return the value of the first call. The `func` is invoked
16004 * with the `this` binding and arguments of the created function.
16005 *
16006 * @static
16007 * @memberOf _
16008 * @category Function
16009 * @param {Function} func The function to restrict.
16010 * @returns {Function} Returns the new restricted function.
16011 * @example
16012 *
16013 * var initialize = _.once(createApplication);
16014 * initialize();
16015 * initialize();
16016 * // `initialize` invokes `createApplication` once
16017 */
16018 function once(func) {
16019 return before(2, func);
16020 }
16021
16022 /**
16023 * Creates a function that invokes `func` with `partial` arguments prepended
16024 * to those provided to the new function. This method is like `_.bind` except
16025 * it does **not** alter the `this` binding.
16026 *
16027 * The `_.partial.placeholder` value, which defaults to `_` in monolithic
16028 * builds, may be used as a placeholder for partially applied arguments.
16029 *
16030 * **Note:** This method does not set the "length" property of partially
16031 * applied functions.
16032 *
16033 * @static
16034 * @memberOf _
16035 * @category Function
16036 * @param {Function} func The function to partially apply arguments to.
16037 * @param {...*} [partials] The arguments to be partially applied.
16038 * @returns {Function} Returns the new partially applied function.
16039 * @example
16040 *
16041 * var greet = function(greeting, name) {
16042 * return greeting + ' ' + name;
16043 * };
16044 *
16045 * var sayHelloTo = _.partial(greet, 'hello');
16046 * sayHelloTo('fred');
16047 * // => 'hello fred'
16048 *
16049 * // using placeholders
16050 * var greetFred = _.partial(greet, _, 'fred');
16051 * greetFred('hi');
16052 * // => 'hi fred'
16053 */
16054 var partial = createPartial(PARTIAL_FLAG);
16055
16056 /**
16057 * This method is like `_.partial` except that partially applied arguments
16058 * are appended to those provided to the new function.
16059 *
16060 * The `_.partialRight.placeholder` value, which defaults to `_` in monolithic
16061 * builds, may be used as a placeholder for partially applied arguments.
16062 *
16063 * **Note:** This method does not set the "length" property of partially
16064 * applied functions.
16065 *
16066 * @static
16067 * @memberOf _
16068 * @category Function
16069 * @param {Function} func The function to partially apply arguments to.
16070 * @param {...*} [partials] The arguments to be partially applied.
16071 * @returns {Function} Returns the new partially applied function.
16072 * @example
16073 *
16074 * var greet = function(greeting, name) {
16075 * return greeting + ' ' + name;
16076 * };
16077 *
16078 * var greetFred = _.partialRight(greet, 'fred');
16079 * greetFred('hi');
16080 * // => 'hi fred'
16081 *
16082 * // using placeholders
16083 * var sayHelloTo = _.partialRight(greet, 'hello', _);
16084 * sayHelloTo('fred');
16085 * // => 'hello fred'
16086 */
16087 var partialRight = createPartial(PARTIAL_RIGHT_FLAG);
16088
16089 /**
16090 * Creates a function that invokes `func` with arguments arranged according
16091 * to the specified indexes where the argument value at the first index is
16092 * provided as the first argument, the argument value at the second index is
16093 * provided as the second argument, and so on.
16094 *
16095 * @static
16096 * @memberOf _
16097 * @category Function
16098 * @param {Function} func The function to rearrange arguments for.
16099 * @param {...(number|number[])} indexes The arranged argument indexes,
16100 * specified as individual indexes or arrays of indexes.
16101 * @returns {Function} Returns the new function.
16102 * @example
16103 *
16104 * var rearged = _.rearg(function(a, b, c) {
16105 * return [a, b, c];
16106 * }, 2, 0, 1);
16107 *
16108 * rearged('b', 'c', 'a')
16109 * // => ['a', 'b', 'c']
16110 *
16111 * var map = _.rearg(_.map, [1, 0]);
16112 * map(function(n) {
16113 * return n * 3;
16114 * }, [1, 2, 3]);
16115 * // => [3, 6, 9]
16116 */
16117 var rearg = restParam(function(func, indexes) {
16118 return createWrapper(func, REARG_FLAG, undefined, undefined, undefined, baseFlatten(indexes));
16119 });
16120
16121 /**
16122 * Creates a function that invokes `func` with the `this` binding of the
16123 * created function and arguments from `start` and beyond provided as an array.
16124 *
16125 * **Note:** This method is based on the [rest parameter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters).
16126 *
16127 * @static
16128 * @memberOf _
16129 * @category Function
16130 * @param {Function} func The function to apply a rest parameter to.
16131 * @param {number} [start=func.length-1] The start position of the rest parameter.
16132 * @returns {Function} Returns the new function.
16133 * @example
16134 *
16135 * var say = _.restParam(function(what, names) {
16136 * return what + ' ' + _.initial(names).join(', ') +
16137 * (_.size(names) > 1 ? ', & ' : '') + _.last(names);
16138 * });
16139 *
16140 * say('hello', 'fred', 'barney', 'pebbles');
16141 * // => 'hello fred, barney, & pebbles'
16142 */
16143 function restParam(func, start) {
16144 if (typeof func != 'function') {
16145 throw new TypeError(FUNC_ERROR_TEXT);
16146 }
16147 start = nativeMax(start === undefined ? (func.length - 1) : (+start || 0), 0);
16148 return function() {
16149 var args = arguments,
16150 index = -1,
16151 length = nativeMax(args.length - start, 0),
16152 rest = Array(length);
16153
16154 while (++index < length) {
16155 rest[index] = args[start + index];
16156 }
16157 switch (start) {
16158 case 0: return func.call(this, rest);
16159 case 1: return func.call(this, args[0], rest);
16160 case 2: return func.call(this, args[0], args[1], rest);
16161 }
16162 var otherArgs = Array(start + 1);
16163 index = -1;
16164 while (++index < start) {
16165 otherArgs[index] = args[index];
16166 }
16167 otherArgs[start] = rest;
16168 return func.apply(this, otherArgs);
16169 };
16170 }
16171
16172 /**
16173 * Creates a function that invokes `func` with the `this` binding of the created
16174 * function and an array of arguments much like [`Function#apply`](https://es5.github.io/#x15.3.4.3).
16175 *
16176 * **Note:** This method is based on the [spread operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator).
16177 *
16178 * @static
16179 * @memberOf _
16180 * @category Function
16181 * @param {Function} func The function to spread arguments over.
16182 * @returns {Function} Returns the new function.
16183 * @example
16184 *
16185 * var say = _.spread(function(who, what) {
16186 * return who + ' says ' + what;
16187 * });
16188 *
16189 * say(['fred', 'hello']);
16190 * // => 'fred says hello'
16191 *
16192 * // with a Promise
16193 * var numbers = Promise.all([
16194 * Promise.resolve(40),
16195 * Promise.resolve(36)
16196 * ]);
16197 *
16198 * numbers.then(_.spread(function(x, y) {
16199 * return x + y;
16200 * }));
16201 * // => a Promise of 76
16202 */
16203 function spread(func) {
16204 if (typeof func != 'function') {
16205 throw new TypeError(FUNC_ERROR_TEXT);
16206 }
16207 return function(array) {
16208 return func.apply(this, array);
16209 };
16210 }
16211
16212 /**
16213 * Creates a throttled function that only invokes `func` at most once per
16214 * every `wait` milliseconds. The throttled function comes with a `cancel`
16215 * method to cancel delayed invocations. Provide an options object to indicate
16216 * that `func` should be invoked on the leading and/or trailing edge of the
16217 * `wait` timeout. Subsequent calls to the throttled function return the
16218 * result of the last `func` call.
16219 *
16220 * **Note:** If `leading` and `trailing` options are `true`, `func` is invoked
16221 * on the trailing edge of the timeout only if the the throttled function is
16222 * invoked more than once during the `wait` timeout.
16223 *
16224 * See [David Corbacho's article](http://drupalmotion.com/article/debounce-and-throttle-visual-explanation)
16225 * for details over the differences between `_.throttle` and `_.debounce`.
16226 *
16227 * @static
16228 * @memberOf _
16229 * @category Function
16230 * @param {Function} func The function to throttle.
16231 * @param {number} [wait=0] The number of milliseconds to throttle invocations to.
16232 * @param {Object} [options] The options object.
16233 * @param {boolean} [options.leading=true] Specify invoking on the leading
16234 * edge of the timeout.
16235 * @param {boolean} [options.trailing=true] Specify invoking on the trailing
16236 * edge of the timeout.
16237 * @returns {Function} Returns the new throttled function.
16238 * @example
16239 *
16240 * // avoid excessively updating the position while scrolling
16241 * jQuery(window).on('scroll', _.throttle(updatePosition, 100));
16242 *
16243 * // invoke `renewToken` when the click event is fired, but not more than once every 5 minutes
16244 * jQuery('.interactive').on('click', _.throttle(renewToken, 300000, {
16245 * 'trailing': false
16246 * }));
16247 *
16248 * // cancel a trailing throttled call
16249 * jQuery(window).on('popstate', throttled.cancel);
16250 */
16251 function throttle(func, wait, options) {
16252 var leading = true,
16253 trailing = true;
16254
16255 if (typeof func != 'function') {
16256 throw new TypeError(FUNC_ERROR_TEXT);
16257 }
16258 if (options === false) {
16259 leading = false;
16260 } else if (isObject(options)) {
16261 leading = 'leading' in options ? !!options.leading : leading;
16262 trailing = 'trailing' in options ? !!options.trailing : trailing;
16263 }
16264 return debounce(func, wait, { 'leading': leading, 'maxWait': +wait, 'trailing': trailing });
16265 }
16266
16267 /**
16268 * Creates a function that provides `value` to the wrapper function as its
16269 * first argument. Any additional arguments provided to the function are
16270 * appended to those provided to the wrapper function. The wrapper is invoked
16271 * with the `this` binding of the created function.
16272 *
16273 * @static
16274 * @memberOf _
16275 * @category Function
16276 * @param {*} value The value to wrap.
16277 * @param {Function} wrapper The wrapper function.
16278 * @returns {Function} Returns the new function.
16279 * @example
16280 *
16281 * var p = _.wrap(_.escape, function(func, text) {
16282 * return '<p>' + func(text) + '</p>';
16283 * });
16284 *
16285 * p('fred, barney, & pebbles');
16286 * // => '<p>fred, barney, &amp; pebbles</p>'
16287 */
16288 function wrap(value, wrapper) {
16289 wrapper = wrapper == null ? identity : wrapper;
16290 return createWrapper(wrapper, PARTIAL_FLAG, undefined, [value], []);
16291 }
16292
16293 /*------------------------------------------------------------------------*/
16294
16295 /**
16296 * Creates a clone of `value`. If `isDeep` is `true` nested objects are cloned,
16297 * otherwise they are assigned by reference. If `customizer` is provided it is
16298 * invoked to produce the cloned values. If `customizer` returns `undefined`
16299 * cloning is handled by the method instead. The `customizer` is bound to
16300 * `thisArg` and invoked with two argument; (value [, index|key, object]).
16301 *
16302 * **Note:** This method is loosely based on the
16303 * [structured clone algorithm](http://www.w3.org/TR/html5/infrastructure.html#internal-structured-cloning-algorithm).
16304 * The enumerable properties of `arguments` objects and objects created by
16305 * constructors other than `Object` are cloned to plain `Object` objects. An
16306 * empty object is returned for uncloneable values such as functions, DOM nodes,
16307 * Maps, Sets, and WeakMaps.
16308 *
16309 * @static
16310 * @memberOf _
16311 * @category Lang
16312 * @param {*} value The value to clone.
16313 * @param {boolean} [isDeep] Specify a deep clone.
16314 * @param {Function} [customizer] The function to customize cloning values.
16315 * @param {*} [thisArg] The `this` binding of `customizer`.
16316 * @returns {*} Returns the cloned value.
16317 * @example
16318 *
16319 * var users = [
16320 * { 'user': 'barney' },
16321 * { 'user': 'fred' }
16322 * ];
16323 *
16324 * var shallow = _.clone(users);
16325 * shallow[0] === users[0];
16326 * // => true
16327 *
16328 * var deep = _.clone(users, true);
16329 * deep[0] === users[0];
16330 * // => false
16331 *
16332 * // using a customizer callback
16333 * var el = _.clone(document.body, function(value) {
16334 * if (_.isElement(value)) {
16335 * return value.cloneNode(false);
16336 * }
16337 * });
16338 *
16339 * el === document.body
16340 * // => false
16341 * el.nodeName
16342 * // => BODY
16343 * el.childNodes.length;
16344 * // => 0
16345 */
16346 function clone(value, isDeep, customizer, thisArg) {
16347 if (isDeep && typeof isDeep != 'boolean' && isIterateeCall(value, isDeep, customizer)) {
16348 isDeep = false;
16349 }
16350 else if (typeof isDeep == 'function') {
16351 thisArg = customizer;
16352 customizer = isDeep;
16353 isDeep = false;
16354 }
16355 return typeof customizer == 'function'
16356 ? baseClone(value, isDeep, bindCallback(customizer, thisArg, 1))
16357 : baseClone(value, isDeep);
16358 }
16359
16360 /**
16361 * Creates a deep clone of `value`. If `customizer` is provided it is invoked
16362 * to produce the cloned values. If `customizer` returns `undefined` cloning
16363 * is handled by the method instead. The `customizer` is bound to `thisArg`
16364 * and invoked with two argument; (value [, index|key, object]).
16365 *
16366 * **Note:** This method is loosely based on the
16367 * [structured clone algorithm](http://www.w3.org/TR/html5/infrastructure.html#internal-structured-cloning-algorithm).
16368 * The enumerable properties of `arguments` objects and objects created by
16369 * constructors other than `Object` are cloned to plain `Object` objects. An
16370 * empty object is returned for uncloneable values such as functions, DOM nodes,
16371 * Maps, Sets, and WeakMaps.
16372 *
16373 * @static
16374 * @memberOf _
16375 * @category Lang
16376 * @param {*} value The value to deep clone.
16377 * @param {Function} [customizer] The function to customize cloning values.
16378 * @param {*} [thisArg] The `this` binding of `customizer`.
16379 * @returns {*} Returns the deep cloned value.
16380 * @example
16381 *
16382 * var users = [
16383 * { 'user': 'barney' },
16384 * { 'user': 'fred' }
16385 * ];
16386 *
16387 * var deep = _.cloneDeep(users);
16388 * deep[0] === users[0];
16389 * // => false
16390 *
16391 * // using a customizer callback
16392 * var el = _.cloneDeep(document.body, function(value) {
16393 * if (_.isElement(value)) {
16394 * return value.cloneNode(true);
16395 * }
16396 * });
16397 *
16398 * el === document.body
16399 * // => false
16400 * el.nodeName
16401 * // => BODY
16402 * el.childNodes.length;
16403 * // => 20
16404 */
16405 function cloneDeep(value, customizer, thisArg) {
16406 return typeof customizer == 'function'
16407 ? baseClone(value, true, bindCallback(customizer, thisArg, 1))
16408 : baseClone(value, true);
16409 }
16410
16411 /**
16412 * Checks if `value` is greater than `other`.
16413 *
16414 * @static
16415 * @memberOf _
16416 * @category Lang
16417 * @param {*} value The value to compare.
16418 * @param {*} other The other value to compare.
16419 * @returns {boolean} Returns `true` if `value` is greater than `other`, else `false`.
16420 * @example
16421 *
16422 * _.gt(3, 1);
16423 * // => true
16424 *
16425 * _.gt(3, 3);
16426 * // => false
16427 *
16428 * _.gt(1, 3);
16429 * // => false
16430 */
16431 function gt(value, other) {
16432 return value > other;
16433 }
16434
16435 /**
16436 * Checks if `value` is greater than or equal to `other`.
16437 *
16438 * @static
16439 * @memberOf _
16440 * @category Lang
16441 * @param {*} value The value to compare.
16442 * @param {*} other The other value to compare.
16443 * @returns {boolean} Returns `true` if `value` is greater than or equal to `other`, else `false`.
16444 * @example
16445 *
16446 * _.gte(3, 1);
16447 * // => true
16448 *
16449 * _.gte(3, 3);
16450 * // => true
16451 *
16452 * _.gte(1, 3);
16453 * // => false
16454 */
16455 function gte(value, other) {
16456 return value >= other;
16457 }
16458
16459 /**
16460 * Checks if `value` is classified as an `arguments` object.
16461 *
16462 * @static
16463 * @memberOf _
16464 * @category Lang
16465 * @param {*} value The value to check.
16466 * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
16467 * @example
16468 *
16469 * _.isArguments(function() { return arguments; }());
16470 * // => true
16471 *
16472 * _.isArguments([1, 2, 3]);
16473 * // => false
16474 */
16475 function isArguments(value) {
16476 return isObjectLike(value) && isArrayLike(value) &&
16477 hasOwnProperty.call(value, 'callee') && !propertyIsEnumerable.call(value, 'callee');
16478 }
16479
16480 /**
16481 * Checks if `value` is classified as an `Array` object.
16482 *
16483 * @static
16484 * @memberOf _
16485 * @category Lang
16486 * @param {*} value The value to check.
16487 * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
16488 * @example
16489 *
16490 * _.isArray([1, 2, 3]);
16491 * // => true
16492 *
16493 * _.isArray(function() { return arguments; }());
16494 * // => false
16495 */
16496 var isArray = nativeIsArray || function(value) {
16497 return isObjectLike(value) && isLength(value.length) && objToString.call(value) == arrayTag;
16498 };
16499
16500 /**
16501 * Checks if `value` is classified as a boolean primitive or object.
16502 *
16503 * @static
16504 * @memberOf _
16505 * @category Lang
16506 * @param {*} value The value to check.
16507 * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
16508 * @example
16509 *
16510 * _.isBoolean(false);
16511 * // => true
16512 *
16513 * _.isBoolean(null);
16514 * // => false
16515 */
16516 function isBoolean(value) {
16517 return value === true || value === false || (isObjectLike(value) && objToString.call(value) == boolTag);
16518 }
16519
16520 /**
16521 * Checks if `value` is classified as a `Date` object.
16522 *
16523 * @static
16524 * @memberOf _
16525 * @category Lang
16526 * @param {*} value The value to check.
16527 * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
16528 * @example
16529 *
16530 * _.isDate(new Date);
16531 * // => true
16532 *
16533 * _.isDate('Mon April 23 2012');
16534 * // => false
16535 */
16536 function isDate(value) {
16537 return isObjectLike(value) && objToString.call(value) == dateTag;
16538 }
16539
16540 /**
16541 * Checks if `value` is a DOM element.
16542 *
16543 * @static
16544 * @memberOf _
16545 * @category Lang
16546 * @param {*} value The value to check.
16547 * @returns {boolean} Returns `true` if `value` is a DOM element, else `false`.
16548 * @example
16549 *
16550 * _.isElement(document.body);
16551 * // => true
16552 *
16553 * _.isElement('<body>');
16554 * // => false
16555 */
16556 function isElement(value) {
16557 return !!value && value.nodeType === 1 && isObjectLike(value) && !isPlainObject(value);
16558 }
16559
16560 /**
16561 * Checks if `value` is empty. A value is considered empty unless it is an
16562 * `arguments` object, array, string, or jQuery-like collection with a length
16563 * greater than `0` or an object with own enumerable properties.
16564 *
16565 * @static
16566 * @memberOf _
16567 * @category Lang
16568 * @param {Array|Object|string} value The value to inspect.
16569 * @returns {boolean} Returns `true` if `value` is empty, else `false`.
16570 * @example
16571 *
16572 * _.isEmpty(null);
16573 * // => true
16574 *
16575 * _.isEmpty(true);
16576 * // => true
16577 *
16578 * _.isEmpty(1);
16579 * // => true
16580 *
16581 * _.isEmpty([1, 2, 3]);
16582 * // => false
16583 *
16584 * _.isEmpty({ 'a': 1 });
16585 * // => false
16586 */
16587 function isEmpty(value) {
16588 if (value == null) {
16589 return true;
16590 }
16591 if (isArrayLike(value) && (isArray(value) || isString(value) || isArguments(value) ||
16592 (isObjectLike(value) && isFunction(value.splice)))) {
16593 return !value.length;
16594 }
16595 return !keys(value).length;
16596 }
16597
16598 /**
16599 * Performs a deep comparison between two values to determine if they are
16600 * equivalent. If `customizer` is provided it is invoked to compare values.
16601 * If `customizer` returns `undefined` comparisons are handled by the method
16602 * instead. The `customizer` is bound to `thisArg` and invoked with three
16603 * arguments: (value, other [, index|key]).
16604 *
16605 * **Note:** This method supports comparing arrays, booleans, `Date` objects,
16606 * numbers, `Object` objects, regexes, and strings. Objects are compared by
16607 * their own, not inherited, enumerable properties. Functions and DOM nodes
16608 * are **not** supported. Provide a customizer function to extend support
16609 * for comparing other values.
16610 *
16611 * @static
16612 * @memberOf _
16613 * @alias eq
16614 * @category Lang
16615 * @param {*} value The value to compare.
16616 * @param {*} other The other value to compare.
16617 * @param {Function} [customizer] The function to customize value comparisons.
16618 * @param {*} [thisArg] The `this` binding of `customizer`.
16619 * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
16620 * @example
16621 *
16622 * var object = { 'user': 'fred' };
16623 * var other = { 'user': 'fred' };
16624 *
16625 * object == other;
16626 * // => false
16627 *
16628 * _.isEqual(object, other);
16629 * // => true
16630 *
16631 * // using a customizer callback
16632 * var array = ['hello', 'goodbye'];
16633 * var other = ['hi', 'goodbye'];
16634 *
16635 * _.isEqual(array, other, function(value, other) {
16636 * if (_.every([value, other], RegExp.prototype.test, /^h(?:i|ello)$/)) {
16637 * return true;
16638 * }
16639 * });
16640 * // => true
16641 */
16642 function isEqual(value, other, customizer, thisArg) {
16643 customizer = typeof customizer == 'function' ? bindCallback(customizer, thisArg, 3) : undefined;
16644 var result = customizer ? customizer(value, other) : undefined;
16645 return result === undefined ? baseIsEqual(value, other, customizer) : !!result;
16646 }
16647
16648 /**
16649 * Checks if `value` is an `Error`, `EvalError`, `RangeError`, `ReferenceError`,
16650 * `SyntaxError`, `TypeError`, or `URIError` object.
16651 *
16652 * @static
16653 * @memberOf _
16654 * @category Lang
16655 * @param {*} value The value to check.
16656 * @returns {boolean} Returns `true` if `value` is an error object, else `false`.
16657 * @example
16658 *
16659 * _.isError(new Error);
16660 * // => true
16661 *
16662 * _.isError(Error);
16663 * // => false
16664 */
16665 function isError(value) {
16666 return isObjectLike(value) && typeof value.message == 'string' && objToString.call(value) == errorTag;
16667 }
16668
16669 /**
16670 * Checks if `value` is a finite primitive number.
16671 *
16672 * **Note:** This method is based on [`Number.isFinite`](http://ecma-international.org/ecma-262/6.0/#sec-number.isfinite).
16673 *
16674 * @static
16675 * @memberOf _
16676 * @category Lang
16677 * @param {*} value The value to check.
16678 * @returns {boolean} Returns `true` if `value` is a finite number, else `false`.
16679 * @example
16680 *
16681 * _.isFinite(10);
16682 * // => true
16683 *
16684 * _.isFinite('10');
16685 * // => false
16686 *
16687 * _.isFinite(true);
16688 * // => false
16689 *
16690 * _.isFinite(Object(10));
16691 * // => false
16692 *
16693 * _.isFinite(Infinity);
16694 * // => false
16695 */
16696 function isFinite(value) {
16697 return typeof value == 'number' && nativeIsFinite(value);
16698 }
16699
16700 /**
16701 * Checks if `value` is classified as a `Function` object.
16702 *
16703 * @static
16704 * @memberOf _
16705 * @category Lang
16706 * @param {*} value The value to check.
16707 * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
16708 * @example
16709 *
16710 * _.isFunction(_);
16711 * // => true
16712 *
16713 * _.isFunction(/abc/);
16714 * // => false
16715 */
16716 function isFunction(value) {
16717 // The use of `Object#toString` avoids issues with the `typeof` operator
16718 // in older versions of Chrome and Safari which return 'function' for regexes
16719 // and Safari 8 equivalents which return 'object' for typed array constructors.
16720 return isObject(value) && objToString.call(value) == funcTag;
16721 }
16722
16723 /**
16724 * Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`.
16725 * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
16726 *
16727 * @static
16728 * @memberOf _
16729 * @category Lang
16730 * @param {*} value The value to check.
16731 * @returns {boolean} Returns `true` if `value` is an object, else `false`.
16732 * @example
16733 *
16734 * _.isObject({});
16735 * // => true
16736 *
16737 * _.isObject([1, 2, 3]);
16738 * // => true
16739 *
16740 * _.isObject(1);
16741 * // => false
16742 */
16743 function isObject(value) {
16744 // Avoid a V8 JIT bug in Chrome 19-20.
16745 // See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
16746 var type = typeof value;
16747 return !!value && (type == 'object' || type == 'function');
16748 }
16749
16750 /**
16751 * Performs a deep comparison between `object` and `source` to determine if
16752 * `object` contains equivalent property values. If `customizer` is provided
16753 * it is invoked to compare values. If `customizer` returns `undefined`
16754 * comparisons are handled by the method instead. The `customizer` is bound
16755 * to `thisArg` and invoked with three arguments: (value, other, index|key).
16756 *
16757 * **Note:** This method supports comparing properties of arrays, booleans,
16758 * `Date` objects, numbers, `Object` objects, regexes, and strings. Functions
16759 * and DOM nodes are **not** supported. Provide a customizer function to extend
16760 * support for comparing other values.
16761 *
16762 * @static
16763 * @memberOf _
16764 * @category Lang
16765 * @param {Object} object The object to inspect.
16766 * @param {Object} source The object of property values to match.
16767 * @param {Function} [customizer] The function to customize value comparisons.
16768 * @param {*} [thisArg] The `this` binding of `customizer`.
16769 * @returns {boolean} Returns `true` if `object` is a match, else `false`.
16770 * @example
16771 *
16772 * var object = { 'user': 'fred', 'age': 40 };
16773 *
16774 * _.isMatch(object, { 'age': 40 });
16775 * // => true
16776 *
16777 * _.isMatch(object, { 'age': 36 });
16778 * // => false
16779 *
16780 * // using a customizer callback
16781 * var object = { 'greeting': 'hello' };
16782 * var source = { 'greeting': 'hi' };
16783 *
16784 * _.isMatch(object, source, function(value, other) {
16785 * return _.every([value, other], RegExp.prototype.test, /^h(?:i|ello)$/) || undefined;
16786 * });
16787 * // => true
16788 */
16789 function isMatch(object, source, customizer, thisArg) {
16790 customizer = typeof customizer == 'function' ? bindCallback(customizer, thisArg, 3) : undefined;
16791 return baseIsMatch(object, getMatchData(source), customizer);
16792 }
16793
16794 /**
16795 * Checks if `value` is `NaN`.
16796 *
16797 * **Note:** This method is not the same as [`isNaN`](https://es5.github.io/#x15.1.2.4)
16798 * which returns `true` for `undefined` and other non-numeric values.
16799 *
16800 * @static
16801 * @memberOf _
16802 * @category Lang
16803 * @param {*} value The value to check.
16804 * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.
16805 * @example
16806 *
16807 * _.isNaN(NaN);
16808 * // => true
16809 *
16810 * _.isNaN(new Number(NaN));
16811 * // => true
16812 *
16813 * isNaN(undefined);
16814 * // => true
16815 *
16816 * _.isNaN(undefined);
16817 * // => false
16818 */
16819 function isNaN(value) {
16820 // An `NaN` primitive is the only value that is not equal to itself.
16821 // Perform the `toStringTag` check first to avoid errors with some host objects in IE.
16822 return isNumber(value) && value != +value;
16823 }
16824
16825 /**
16826 * Checks if `value` is a native function.
16827 *
16828 * @static
16829 * @memberOf _
16830 * @category Lang
16831 * @param {*} value The value to check.
16832 * @returns {boolean} Returns `true` if `value` is a native function, else `false`.
16833 * @example
16834 *
16835 * _.isNative(Array.prototype.push);
16836 * // => true
16837 *
16838 * _.isNative(_);
16839 * // => false
16840 */
16841 function isNative(value) {
16842 if (value == null) {
16843 return false;
16844 }
16845 if (isFunction(value)) {
16846 return reIsNative.test(fnToString.call(value));
16847 }
16848 return isObjectLike(value) && reIsHostCtor.test(value);
16849 }
16850
16851 /**
16852 * Checks if `value` is `null`.
16853 *
16854 * @static
16855 * @memberOf _
16856 * @category Lang
16857 * @param {*} value The value to check.
16858 * @returns {boolean} Returns `true` if `value` is `null`, else `false`.
16859 * @example
16860 *
16861 * _.isNull(null);
16862 * // => true
16863 *
16864 * _.isNull(void 0);
16865 * // => false
16866 */
16867 function isNull(value) {
16868 return value === null;
16869 }
16870
16871 /**
16872 * Checks if `value` is classified as a `Number` primitive or object.
16873 *
16874 * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are classified
16875 * as numbers, use the `_.isFinite` method.
16876 *
16877 * @static
16878 * @memberOf _
16879 * @category Lang
16880 * @param {*} value The value to check.
16881 * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
16882 * @example
16883 *
16884 * _.isNumber(8.4);
16885 * // => true
16886 *
16887 * _.isNumber(NaN);
16888 * // => true
16889 *
16890 * _.isNumber('8.4');
16891 * // => false
16892 */
16893 function isNumber(value) {
16894 return typeof value == 'number' || (isObjectLike(value) && objToString.call(value) == numberTag);
16895 }
16896
16897 /**
16898 * Checks if `value` is a plain object, that is, an object created by the
16899 * `Object` constructor or one with a `[[Prototype]]` of `null`.
16900 *
16901 * **Note:** This method assumes objects created by the `Object` constructor
16902 * have no inherited enumerable properties.
16903 *
16904 * @static
16905 * @memberOf _
16906 * @category Lang
16907 * @param {*} value The value to check.
16908 * @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
16909 * @example
16910 *
16911 * function Foo() {
16912 * this.a = 1;
16913 * }
16914 *
16915 * _.isPlainObject(new Foo);
16916 * // => false
16917 *
16918 * _.isPlainObject([1, 2, 3]);
16919 * // => false
16920 *
16921 * _.isPlainObject({ 'x': 0, 'y': 0 });
16922 * // => true
16923 *
16924 * _.isPlainObject(Object.create(null));
16925 * // => true
16926 */
16927 function isPlainObject(value) {
16928 var Ctor;
16929
16930 // Exit early for non `Object` objects.
16931 if (!(isObjectLike(value) && objToString.call(value) == objectTag && !isArguments(value)) ||
16932 (!hasOwnProperty.call(value, 'constructor') && (Ctor = value.constructor, typeof Ctor == 'function' && !(Ctor instanceof Ctor)))) {
16933 return false;
16934 }
16935 // IE < 9 iterates inherited properties before own properties. If the first
16936 // iterated property is an object's own property then there are no inherited
16937 // enumerable properties.
16938 var result;
16939 // In most environments an object's own properties are iterated before
16940 // its inherited properties. If the last iterated property is an object's
16941 // own property then there are no inherited enumerable properties.
16942 baseForIn(value, function(subValue, key) {
16943 result = key;
16944 });
16945 return result === undefined || hasOwnProperty.call(value, result);
16946 }
16947
16948 /**
16949 * Checks if `value` is classified as a `RegExp` object.
16950 *
16951 * @static
16952 * @memberOf _
16953 * @category Lang
16954 * @param {*} value The value to check.
16955 * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
16956 * @example
16957 *
16958 * _.isRegExp(/abc/);
16959 * // => true
16960 *
16961 * _.isRegExp('/abc/');
16962 * // => false
16963 */
16964 function isRegExp(value) {
16965 return isObject(value) && objToString.call(value) == regexpTag;
16966 }
16967
16968 /**
16969 * Checks if `value` is classified as a `String` primitive or object.
16970 *
16971 * @static
16972 * @memberOf _
16973 * @category Lang
16974 * @param {*} value The value to check.
16975 * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
16976 * @example
16977 *
16978 * _.isString('abc');
16979 * // => true
16980 *
16981 * _.isString(1);
16982 * // => false
16983 */
16984 function isString(value) {
16985 return typeof value == 'string' || (isObjectLike(value) && objToString.call(value) == stringTag);
16986 }
16987
16988 /**
16989 * Checks if `value` is classified as a typed array.
16990 *
16991 * @static
16992 * @memberOf _
16993 * @category Lang
16994 * @param {*} value The value to check.
16995 * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
16996 * @example
16997 *
16998 * _.isTypedArray(new Uint8Array);
16999 * // => true
17000 *
17001 * _.isTypedArray([]);
17002 * // => false
17003 */
17004 function isTypedArray(value) {
17005 return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[objToString.call(value)];
17006 }
17007
17008 /**
17009 * Checks if `value` is `undefined`.
17010 *
17011 * @static
17012 * @memberOf _
17013 * @category Lang
17014 * @param {*} value The value to check.
17015 * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`.
17016 * @example
17017 *
17018 * _.isUndefined(void 0);
17019 * // => true
17020 *
17021 * _.isUndefined(null);
17022 * // => false
17023 */
17024 function isUndefined(value) {
17025 return value === undefined;
17026 }
17027
17028 /**
17029 * Checks if `value` is less than `other`.
17030 *
17031 * @static
17032 * @memberOf _
17033 * @category Lang
17034 * @param {*} value The value to compare.
17035 * @param {*} other The other value to compare.
17036 * @returns {boolean} Returns `true` if `value` is less than `other`, else `false`.
17037 * @example
17038 *
17039 * _.lt(1, 3);
17040 * // => true
17041 *
17042 * _.lt(3, 3);
17043 * // => false
17044 *
17045 * _.lt(3, 1);
17046 * // => false
17047 */
17048 function lt(value, other) {
17049 return value < other;
17050 }
17051
17052 /**
17053 * Checks if `value` is less than or equal to `other`.
17054 *
17055 * @static
17056 * @memberOf _
17057 * @category Lang
17058 * @param {*} value The value to compare.
17059 * @param {*} other The other value to compare.
17060 * @returns {boolean} Returns `true` if `value` is less than or equal to `other`, else `false`.
17061 * @example
17062 *
17063 * _.lte(1, 3);
17064 * // => true
17065 *
17066 * _.lte(3, 3);
17067 * // => true
17068 *
17069 * _.lte(3, 1);
17070 * // => false
17071 */
17072 function lte(value, other) {
17073 return value <= other;
17074 }
17075
17076 /**
17077 * Converts `value` to an array.
17078 *
17079 * @static
17080 * @memberOf _
17081 * @category Lang
17082 * @param {*} value The value to convert.
17083 * @returns {Array} Returns the converted array.
17084 * @example
17085 *
17086 * (function() {
17087 * return _.toArray(arguments).slice(1);
17088 * }(1, 2, 3));
17089 * // => [2, 3]
17090 */
17091 function toArray(value) {
17092 var length = value ? getLength(value) : 0;
17093 if (!isLength(length)) {
17094 return values(value);
17095 }
17096 if (!length) {
17097 return [];
17098 }
17099 return arrayCopy(value);
17100 }
17101
17102 /**
17103 * Converts `value` to a plain object flattening inherited enumerable
17104 * properties of `value` to own properties of the plain object.
17105 *
17106 * @static
17107 * @memberOf _
17108 * @category Lang
17109 * @param {*} value The value to convert.
17110 * @returns {Object} Returns the converted plain object.
17111 * @example
17112 *
17113 * function Foo() {
17114 * this.b = 2;
17115 * }
17116 *
17117 * Foo.prototype.c = 3;
17118 *
17119 * _.assign({ 'a': 1 }, new Foo);
17120 * // => { 'a': 1, 'b': 2 }
17121 *
17122 * _.assign({ 'a': 1 }, _.toPlainObject(new Foo));
17123 * // => { 'a': 1, 'b': 2, 'c': 3 }
17124 */
17125 function toPlainObject(value) {
17126 return baseCopy(value, keysIn(value));
17127 }
17128
17129 /*------------------------------------------------------------------------*/
17130
17131 /**
17132 * Recursively merges own enumerable properties of the source object(s), that
17133 * don't resolve to `undefined` into the destination object. Subsequent sources
17134 * overwrite property assignments of previous sources. If `customizer` is
17135 * provided it is invoked to produce the merged values of the destination and
17136 * source properties. If `customizer` returns `undefined` merging is handled
17137 * by the method instead. The `customizer` is bound to `thisArg` and invoked
17138 * with five arguments: (objectValue, sourceValue, key, object, source).
17139 *
17140 * @static
17141 * @memberOf _
17142 * @category Object
17143 * @param {Object} object The destination object.
17144 * @param {...Object} [sources] The source objects.
17145 * @param {Function} [customizer] The function to customize assigned values.
17146 * @param {*} [thisArg] The `this` binding of `customizer`.
17147 * @returns {Object} Returns `object`.
17148 * @example
17149 *
17150 * var users = {
17151 * 'data': [{ 'user': 'barney' }, { 'user': 'fred' }]
17152 * };
17153 *
17154 * var ages = {
17155 * 'data': [{ 'age': 36 }, { 'age': 40 }]
17156 * };
17157 *
17158 * _.merge(users, ages);
17159 * // => { 'data': [{ 'user': 'barney', 'age': 36 }, { 'user': 'fred', 'age': 40 }] }
17160 *
17161 * // using a customizer callback
17162 * var object = {
17163 * 'fruits': ['apple'],
17164 * 'vegetables': ['beet']
17165 * };
17166 *
17167 * var other = {
17168 * 'fruits': ['banana'],
17169 * 'vegetables': ['carrot']
17170 * };
17171 *
17172 * _.merge(object, other, function(a, b) {
17173 * if (_.isArray(a)) {
17174 * return a.concat(b);
17175 * }
17176 * });
17177 * // => { 'fruits': ['apple', 'banana'], 'vegetables': ['beet', 'carrot'] }
17178 */
17179 var merge = createAssigner(baseMerge);
17180
17181 /**
17182 * Assigns own enumerable properties of source object(s) to the destination
17183 * object. Subsequent sources overwrite property assignments of previous sources.
17184 * If `customizer` is provided it is invoked to produce the assigned values.
17185 * The `customizer` is bound to `thisArg` and invoked with five arguments:
17186 * (objectValue, sourceValue, key, object, source).
17187 *
17188 * **Note:** This method mutates `object` and is based on
17189 * [`Object.assign`](http://ecma-international.org/ecma-262/6.0/#sec-object.assign).
17190 *
17191 * @static
17192 * @memberOf _
17193 * @alias extend
17194 * @category Object
17195 * @param {Object} object The destination object.
17196 * @param {...Object} [sources] The source objects.
17197 * @param {Function} [customizer] The function to customize assigned values.
17198 * @param {*} [thisArg] The `this` binding of `customizer`.
17199 * @returns {Object} Returns `object`.
17200 * @example
17201 *
17202 * _.assign({ 'user': 'barney' }, { 'age': 40 }, { 'user': 'fred' });
17203 * // => { 'user': 'fred', 'age': 40 }
17204 *
17205 * // using a customizer callback
17206 * var defaults = _.partialRight(_.assign, function(value, other) {
17207 * return _.isUndefined(value) ? other : value;
17208 * });
17209 *
17210 * defaults({ 'user': 'barney' }, { 'age': 36 }, { 'user': 'fred' });
17211 * // => { 'user': 'barney', 'age': 36 }
17212 */
17213 var assign = createAssigner(function(object, source, customizer) {
17214 return customizer
17215 ? assignWith(object, source, customizer)
17216 : baseAssign(object, source);
17217 });
17218
17219 /**
17220 * Creates an object that inherits from the given `prototype` object. If a
17221 * `properties` object is provided its own enumerable properties are assigned
17222 * to the created object.
17223 *
17224 * @static
17225 * @memberOf _
17226 * @category Object
17227 * @param {Object} prototype The object to inherit from.
17228 * @param {Object} [properties] The properties to assign to the object.
17229 * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
17230 * @returns {Object} Returns the new object.
17231 * @example
17232 *
17233 * function Shape() {
17234 * this.x = 0;
17235 * this.y = 0;
17236 * }
17237 *
17238 * function Circle() {
17239 * Shape.call(this);
17240 * }
17241 *
17242 * Circle.prototype = _.create(Shape.prototype, {
17243 * 'constructor': Circle
17244 * });
17245 *
17246 * var circle = new Circle;
17247 * circle instanceof Circle;
17248 * // => true
17249 *
17250 * circle instanceof Shape;
17251 * // => true
17252 */
17253 function create(prototype, properties, guard) {
17254 var result = baseCreate(prototype);
17255 if (guard && isIterateeCall(prototype, properties, guard)) {
17256 properties = undefined;
17257 }
17258 return properties ? baseAssign(result, properties) : result;
17259 }
17260
17261 /**
17262 * Assigns own enumerable properties of source object(s) to the destination
17263 * object for all destination properties that resolve to `undefined`. Once a
17264 * property is set, additional values of the same property are ignored.
17265 *
17266 * **Note:** This method mutates `object`.
17267 *
17268 * @static
17269 * @memberOf _
17270 * @category Object
17271 * @param {Object} object The destination object.
17272 * @param {...Object} [sources] The source objects.
17273 * @returns {Object} Returns `object`.
17274 * @example
17275 *
17276 * _.defaults({ 'user': 'barney' }, { 'age': 36 }, { 'user': 'fred' });
17277 * // => { 'user': 'barney', 'age': 36 }
17278 */
17279 var defaults = createDefaults(assign, assignDefaults);
17280
17281 /**
17282 * This method is like `_.defaults` except that it recursively assigns
17283 * default properties.
17284 *
17285 * **Note:** This method mutates `object`.
17286 *
17287 * @static
17288 * @memberOf _
17289 * @category Object
17290 * @param {Object} object The destination object.
17291 * @param {...Object} [sources] The source objects.
17292 * @returns {Object} Returns `object`.
17293 * @example
17294 *
17295 * _.defaultsDeep({ 'user': { 'name': 'barney' } }, { 'user': { 'name': 'fred', 'age': 36 } });
17296 * // => { 'user': { 'name': 'barney', 'age': 36 } }
17297 *
17298 */
17299 var defaultsDeep = createDefaults(merge, mergeDefaults);
17300
17301 /**
17302 * This method is like `_.find` except that it returns the key of the first
17303 * element `predicate` returns truthy for instead of the element itself.
17304 *
17305 * If a property name is provided for `predicate` the created `_.property`
17306 * style callback returns the property value of the given element.
17307 *
17308 * If a value is also provided for `thisArg` the created `_.matchesProperty`
17309 * style callback returns `true` for elements that have a matching property
17310 * value, else `false`.
17311 *
17312 * If an object is provided for `predicate` the created `_.matches` style
17313 * callback returns `true` for elements that have the properties of the given
17314 * object, else `false`.
17315 *
17316 * @static
17317 * @memberOf _
17318 * @category Object
17319 * @param {Object} object The object to search.
17320 * @param {Function|Object|string} [predicate=_.identity] The function invoked
17321 * per iteration.
17322 * @param {*} [thisArg] The `this` binding of `predicate`.
17323 * @returns {string|undefined} Returns the key of the matched element, else `undefined`.
17324 * @example
17325 *
17326 * var users = {
17327 * 'barney': { 'age': 36, 'active': true },
17328 * 'fred': { 'age': 40, 'active': false },
17329 * 'pebbles': { 'age': 1, 'active': true }
17330 * };
17331 *
17332 * _.findKey(users, function(chr) {
17333 * return chr.age < 40;
17334 * });
17335 * // => 'barney' (iteration order is not guaranteed)
17336 *
17337 * // using the `_.matches` callback shorthand
17338 * _.findKey(users, { 'age': 1, 'active': true });
17339 * // => 'pebbles'
17340 *
17341 * // using the `_.matchesProperty` callback shorthand
17342 * _.findKey(users, 'active', false);
17343 * // => 'fred'
17344 *
17345 * // using the `_.property` callback shorthand
17346 * _.findKey(users, 'active');
17347 * // => 'barney'
17348 */
17349 var findKey = createFindKey(baseForOwn);
17350
17351 /**
17352 * This method is like `_.findKey` except that it iterates over elements of
17353 * a collection in the opposite order.
17354 *
17355 * If a property name is provided for `predicate` the created `_.property`
17356 * style callback returns the property value of the given element.
17357 *
17358 * If a value is also provided for `thisArg` the created `_.matchesProperty`
17359 * style callback returns `true` for elements that have a matching property
17360 * value, else `false`.
17361 *
17362 * If an object is provided for `predicate` the created `_.matches` style
17363 * callback returns `true` for elements that have the properties of the given
17364 * object, else `false`.
17365 *
17366 * @static
17367 * @memberOf _
17368 * @category Object
17369 * @param {Object} object The object to search.
17370 * @param {Function|Object|string} [predicate=_.identity] The function invoked
17371 * per iteration.
17372 * @param {*} [thisArg] The `this` binding of `predicate`.
17373 * @returns {string|undefined} Returns the key of the matched element, else `undefined`.
17374 * @example
17375 *
17376 * var users = {
17377 * 'barney': { 'age': 36, 'active': true },
17378 * 'fred': { 'age': 40, 'active': false },
17379 * 'pebbles': { 'age': 1, 'active': true }
17380 * };
17381 *
17382 * _.findLastKey(users, function(chr) {
17383 * return chr.age < 40;
17384 * });
17385 * // => returns `pebbles` assuming `_.findKey` returns `barney`
17386 *
17387 * // using the `_.matches` callback shorthand
17388 * _.findLastKey(users, { 'age': 36, 'active': true });
17389 * // => 'barney'
17390 *
17391 * // using the `_.matchesProperty` callback shorthand
17392 * _.findLastKey(users, 'active', false);
17393 * // => 'fred'
17394 *
17395 * // using the `_.property` callback shorthand
17396 * _.findLastKey(users, 'active');
17397 * // => 'pebbles'
17398 */
17399 var findLastKey = createFindKey(baseForOwnRight);
17400
17401 /**
17402 * Iterates over own and inherited enumerable properties of an object invoking
17403 * `iteratee` for each property. The `iteratee` is bound to `thisArg` and invoked
17404 * with three arguments: (value, key, object). Iteratee functions may exit
17405 * iteration early by explicitly returning `false`.
17406 *
17407 * @static
17408 * @memberOf _
17409 * @category Object
17410 * @param {Object} object The object to iterate over.
17411 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
17412 * @param {*} [thisArg] The `this` binding of `iteratee`.
17413 * @returns {Object} Returns `object`.
17414 * @example
17415 *
17416 * function Foo() {
17417 * this.a = 1;
17418 * this.b = 2;
17419 * }
17420 *
17421 * Foo.prototype.c = 3;
17422 *
17423 * _.forIn(new Foo, function(value, key) {
17424 * console.log(key);
17425 * });
17426 * // => logs 'a', 'b', and 'c' (iteration order is not guaranteed)
17427 */
17428 var forIn = createForIn(baseFor);
17429
17430 /**
17431 * This method is like `_.forIn` except that it iterates over properties of
17432 * `object` in the opposite order.
17433 *
17434 * @static
17435 * @memberOf _
17436 * @category Object
17437 * @param {Object} object The object to iterate over.
17438 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
17439 * @param {*} [thisArg] The `this` binding of `iteratee`.
17440 * @returns {Object} Returns `object`.
17441 * @example
17442 *
17443 * function Foo() {
17444 * this.a = 1;
17445 * this.b = 2;
17446 * }
17447 *
17448 * Foo.prototype.c = 3;
17449 *
17450 * _.forInRight(new Foo, function(value, key) {
17451 * console.log(key);
17452 * });
17453 * // => logs 'c', 'b', and 'a' assuming `_.forIn ` logs 'a', 'b', and 'c'
17454 */
17455 var forInRight = createForIn(baseForRight);
17456
17457 /**
17458 * Iterates over own enumerable properties of an object invoking `iteratee`
17459 * for each property. The `iteratee` is bound to `thisArg` and invoked with
17460 * three arguments: (value, key, object). Iteratee functions may exit iteration
17461 * early by explicitly returning `false`.
17462 *
17463 * @static
17464 * @memberOf _
17465 * @category Object
17466 * @param {Object} object The object to iterate over.
17467 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
17468 * @param {*} [thisArg] The `this` binding of `iteratee`.
17469 * @returns {Object} Returns `object`.
17470 * @example
17471 *
17472 * function Foo() {
17473 * this.a = 1;
17474 * this.b = 2;
17475 * }
17476 *
17477 * Foo.prototype.c = 3;
17478 *
17479 * _.forOwn(new Foo, function(value, key) {
17480 * console.log(key);
17481 * });
17482 * // => logs 'a' and 'b' (iteration order is not guaranteed)
17483 */
17484 var forOwn = createForOwn(baseForOwn);
17485
17486 /**
17487 * This method is like `_.forOwn` except that it iterates over properties of
17488 * `object` in the opposite order.
17489 *
17490 * @static
17491 * @memberOf _
17492 * @category Object
17493 * @param {Object} object The object to iterate over.
17494 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
17495 * @param {*} [thisArg] The `this` binding of `iteratee`.
17496 * @returns {Object} Returns `object`.
17497 * @example
17498 *
17499 * function Foo() {
17500 * this.a = 1;
17501 * this.b = 2;
17502 * }
17503 *
17504 * Foo.prototype.c = 3;
17505 *
17506 * _.forOwnRight(new Foo, function(value, key) {
17507 * console.log(key);
17508 * });
17509 * // => logs 'b' and 'a' assuming `_.forOwn` logs 'a' and 'b'
17510 */
17511 var forOwnRight = createForOwn(baseForOwnRight);
17512
17513 /**
17514 * Creates an array of function property names from all enumerable properties,
17515 * own and inherited, of `object`.
17516 *
17517 * @static
17518 * @memberOf _
17519 * @alias methods
17520 * @category Object
17521 * @param {Object} object The object to inspect.
17522 * @returns {Array} Returns the new array of property names.
17523 * @example
17524 *
17525 * _.functions(_);
17526 * // => ['after', 'ary', 'assign', ...]
17527 */
17528 function functions(object) {
17529 return baseFunctions(object, keysIn(object));
17530 }
17531
17532 /**
17533 * Gets the property value at `path` of `object`. If the resolved value is
17534 * `undefined` the `defaultValue` is used in its place.
17535 *
17536 * @static
17537 * @memberOf _
17538 * @category Object
17539 * @param {Object} object The object to query.
17540 * @param {Array|string} path The path of the property to get.
17541 * @param {*} [defaultValue] The value returned if the resolved value is `undefined`.
17542 * @returns {*} Returns the resolved value.
17543 * @example
17544 *
17545 * var object = { 'a': [{ 'b': { 'c': 3 } }] };
17546 *
17547 * _.get(object, 'a[0].b.c');
17548 * // => 3
17549 *
17550 * _.get(object, ['a', '0', 'b', 'c']);
17551 * // => 3
17552 *
17553 * _.get(object, 'a.b.c', 'default');
17554 * // => 'default'
17555 */
17556 function get(object, path, defaultValue) {
17557 var result = object == null ? undefined : baseGet(object, toPath(path), path + '');
17558 return result === undefined ? defaultValue : result;
17559 }
17560
17561 /**
17562 * Checks if `path` is a direct property.
17563 *
17564 * @static
17565 * @memberOf _
17566 * @category Object
17567 * @param {Object} object The object to query.
17568 * @param {Array|string} path The path to check.
17569 * @returns {boolean} Returns `true` if `path` is a direct property, else `false`.
17570 * @example
17571 *
17572 * var object = { 'a': { 'b': { 'c': 3 } } };
17573 *
17574 * _.has(object, 'a');
17575 * // => true
17576 *
17577 * _.has(object, 'a.b.c');
17578 * // => true
17579 *
17580 * _.has(object, ['a', 'b', 'c']);
17581 * // => true
17582 */
17583 function has(object, path) {
17584 if (object == null) {
17585 return false;
17586 }
17587 var result = hasOwnProperty.call(object, path);
17588 if (!result && !isKey(path)) {
17589 path = toPath(path);
17590 object = path.length == 1 ? object : baseGet(object, baseSlice(path, 0, -1));
17591 if (object == null) {
17592 return false;
17593 }
17594 path = last(path);
17595 result = hasOwnProperty.call(object, path);
17596 }
17597 return result || (isLength(object.length) && isIndex(path, object.length) &&
17598 (isArray(object) || isArguments(object)));
17599 }
17600
17601 /**
17602 * Creates an object composed of the inverted keys and values of `object`.
17603 * If `object` contains duplicate values, subsequent values overwrite property
17604 * assignments of previous values unless `multiValue` is `true`.
17605 *
17606 * @static
17607 * @memberOf _
17608 * @category Object
17609 * @param {Object} object The object to invert.
17610 * @param {boolean} [multiValue] Allow multiple values per key.
17611 * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
17612 * @returns {Object} Returns the new inverted object.
17613 * @example
17614 *
17615 * var object = { 'a': 1, 'b': 2, 'c': 1 };
17616 *
17617 * _.invert(object);
17618 * // => { '1': 'c', '2': 'b' }
17619 *
17620 * // with `multiValue`
17621 * _.invert(object, true);
17622 * // => { '1': ['a', 'c'], '2': ['b'] }
17623 */
17624 function invert(object, multiValue, guard) {
17625 if (guard && isIterateeCall(object, multiValue, guard)) {
17626 multiValue = undefined;
17627 }
17628 var index = -1,
17629 props = keys(object),
17630 length = props.length,
17631 result = {};
17632
17633 while (++index < length) {
17634 var key = props[index],
17635 value = object[key];
17636
17637 if (multiValue) {
17638 if (hasOwnProperty.call(result, value)) {
17639 result[value].push(key);
17640 } else {
17641 result[value] = [key];
17642 }
17643 }
17644 else {
17645 result[value] = key;
17646 }
17647 }
17648 return result;
17649 }
17650
17651 /**
17652 * Creates an array of the own enumerable property names of `object`.
17653 *
17654 * **Note:** Non-object values are coerced to objects. See the
17655 * [ES spec](http://ecma-international.org/ecma-262/6.0/#sec-object.keys)
17656 * for more details.
17657 *
17658 * @static
17659 * @memberOf _
17660 * @category Object
17661 * @param {Object} object The object to query.
17662 * @returns {Array} Returns the array of property names.
17663 * @example
17664 *
17665 * function Foo() {
17666 * this.a = 1;
17667 * this.b = 2;
17668 * }
17669 *
17670 * Foo.prototype.c = 3;
17671 *
17672 * _.keys(new Foo);
17673 * // => ['a', 'b'] (iteration order is not guaranteed)
17674 *
17675 * _.keys('hi');
17676 * // => ['0', '1']
17677 */
17678 var keys = !nativeKeys ? shimKeys : function(object) {
17679 var Ctor = object == null ? undefined : object.constructor;
17680 if ((typeof Ctor == 'function' && Ctor.prototype === object) ||
17681 (typeof object != 'function' && isArrayLike(object))) {
17682 return shimKeys(object);
17683 }
17684 return isObject(object) ? nativeKeys(object) : [];
17685 };
17686
17687 /**
17688 * Creates an array of the own and inherited enumerable property names of `object`.
17689 *
17690 * **Note:** Non-object values are coerced to objects.
17691 *
17692 * @static
17693 * @memberOf _
17694 * @category Object
17695 * @param {Object} object The object to query.
17696 * @returns {Array} Returns the array of property names.
17697 * @example
17698 *
17699 * function Foo() {
17700 * this.a = 1;
17701 * this.b = 2;
17702 * }
17703 *
17704 * Foo.prototype.c = 3;
17705 *
17706 * _.keysIn(new Foo);
17707 * // => ['a', 'b', 'c'] (iteration order is not guaranteed)
17708 */
17709 function keysIn(object) {
17710 if (object == null) {
17711 return [];
17712 }
17713 if (!isObject(object)) {
17714 object = Object(object);
17715 }
17716 var length = object.length;
17717 length = (length && isLength(length) &&
17718 (isArray(object) || isArguments(object)) && length) || 0;
17719
17720 var Ctor = object.constructor,
17721 index = -1,
17722 isProto = typeof Ctor == 'function' && Ctor.prototype === object,
17723 result = Array(length),
17724 skipIndexes = length > 0;
17725
17726 while (++index < length) {
17727 result[index] = (index + '');
17728 }
17729 for (var key in object) {
17730 if (!(skipIndexes && isIndex(key, length)) &&
17731 !(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) {
17732 result.push(key);
17733 }
17734 }
17735 return result;
17736 }
17737
17738 /**
17739 * The opposite of `_.mapValues`; this method creates an object with the
17740 * same values as `object` and keys generated by running each own enumerable
17741 * property of `object` through `iteratee`.
17742 *
17743 * @static
17744 * @memberOf _
17745 * @category Object
17746 * @param {Object} object The object to iterate over.
17747 * @param {Function|Object|string} [iteratee=_.identity] The function invoked
17748 * per iteration.
17749 * @param {*} [thisArg] The `this` binding of `iteratee`.
17750 * @returns {Object} Returns the new mapped object.
17751 * @example
17752 *
17753 * _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) {
17754 * return key + value;
17755 * });
17756 * // => { 'a1': 1, 'b2': 2 }
17757 */
17758 var mapKeys = createObjectMapper(true);
17759
17760 /**
17761 * Creates an object with the same keys as `object` and values generated by
17762 * running each own enumerable property of `object` through `iteratee`. The
17763 * iteratee function is bound to `thisArg` and invoked with three arguments:
17764 * (value, key, object).
17765 *
17766 * If a property name is provided for `iteratee` the created `_.property`
17767 * style callback returns the property value of the given element.
17768 *
17769 * If a value is also provided for `thisArg` the created `_.matchesProperty`
17770 * style callback returns `true` for elements that have a matching property
17771 * value, else `false`.
17772 *
17773 * If an object is provided for `iteratee` the created `_.matches` style
17774 * callback returns `true` for elements that have the properties of the given
17775 * object, else `false`.
17776 *
17777 * @static
17778 * @memberOf _
17779 * @category Object
17780 * @param {Object} object The object to iterate over.
17781 * @param {Function|Object|string} [iteratee=_.identity] The function invoked
17782 * per iteration.
17783 * @param {*} [thisArg] The `this` binding of `iteratee`.
17784 * @returns {Object} Returns the new mapped object.
17785 * @example
17786 *
17787 * _.mapValues({ 'a': 1, 'b': 2 }, function(n) {
17788 * return n * 3;
17789 * });
17790 * // => { 'a': 3, 'b': 6 }
17791 *
17792 * var users = {
17793 * 'fred': { 'user': 'fred', 'age': 40 },
17794 * 'pebbles': { 'user': 'pebbles', 'age': 1 }
17795 * };
17796 *
17797 * // using the `_.property` callback shorthand
17798 * _.mapValues(users, 'age');
17799 * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)
17800 */
17801 var mapValues = createObjectMapper();
17802
17803 /**
17804 * The opposite of `_.pick`; this method creates an object composed of the
17805 * own and inherited enumerable properties of `object` that are not omitted.
17806 *
17807 * @static
17808 * @memberOf _
17809 * @category Object
17810 * @param {Object} object The source object.
17811 * @param {Function|...(string|string[])} [predicate] The function invoked per
17812 * iteration or property names to omit, specified as individual property
17813 * names or arrays of property names.
17814 * @param {*} [thisArg] The `this` binding of `predicate`.
17815 * @returns {Object} Returns the new object.
17816 * @example
17817 *
17818 * var object = { 'user': 'fred', 'age': 40 };
17819 *
17820 * _.omit(object, 'age');
17821 * // => { 'user': 'fred' }
17822 *
17823 * _.omit(object, _.isNumber);
17824 * // => { 'user': 'fred' }
17825 */
17826 var omit = restParam(function(object, props) {
17827 if (object == null) {
17828 return {};
17829 }
17830 if (typeof props[0] != 'function') {
17831 var props = arrayMap(baseFlatten(props), String);
17832 return pickByArray(object, baseDifference(keysIn(object), props));
17833 }
17834 var predicate = bindCallback(props[0], props[1], 3);
17835 return pickByCallback(object, function(value, key, object) {
17836 return !predicate(value, key, object);
17837 });
17838 });
17839
17840 /**
17841 * Creates a two dimensional array of the key-value pairs for `object`,
17842 * e.g. `[[key1, value1], [key2, value2]]`.
17843 *
17844 * @static
17845 * @memberOf _
17846 * @category Object
17847 * @param {Object} object The object to query.
17848 * @returns {Array} Returns the new array of key-value pairs.
17849 * @example
17850 *
17851 * _.pairs({ 'barney': 36, 'fred': 40 });
17852 * // => [['barney', 36], ['fred', 40]] (iteration order is not guaranteed)
17853 */
17854 function pairs(object) {
17855 object = toObject(object);
17856
17857 var index = -1,
17858 props = keys(object),
17859 length = props.length,
17860 result = Array(length);
17861
17862 while (++index < length) {
17863 var key = props[index];
17864 result[index] = [key, object[key]];
17865 }
17866 return result;
17867 }
17868
17869 /**
17870 * Creates an object composed of the picked `object` properties. Property
17871 * names may be specified as individual arguments or as arrays of property
17872 * names. If `predicate` is provided it is invoked for each property of `object`
17873 * picking the properties `predicate` returns truthy for. The predicate is
17874 * bound to `thisArg` and invoked with three arguments: (value, key, object).
17875 *
17876 * @static
17877 * @memberOf _
17878 * @category Object
17879 * @param {Object} object The source object.
17880 * @param {Function|...(string|string[])} [predicate] The function invoked per
17881 * iteration or property names to pick, specified as individual property
17882 * names or arrays of property names.
17883 * @param {*} [thisArg] The `this` binding of `predicate`.
17884 * @returns {Object} Returns the new object.
17885 * @example
17886 *
17887 * var object = { 'user': 'fred', 'age': 40 };
17888 *
17889 * _.pick(object, 'user');
17890 * // => { 'user': 'fred' }
17891 *
17892 * _.pick(object, _.isString);
17893 * // => { 'user': 'fred' }
17894 */
17895 var pick = restParam(function(object, props) {
17896 if (object == null) {
17897 return {};
17898 }
17899 return typeof props[0] == 'function'
17900 ? pickByCallback(object, bindCallback(props[0], props[1], 3))
17901 : pickByArray(object, baseFlatten(props));
17902 });
17903
17904 /**
17905 * This method is like `_.get` except that if the resolved value is a function
17906 * it is invoked with the `this` binding of its parent object and its result
17907 * is returned.
17908 *
17909 * @static
17910 * @memberOf _
17911 * @category Object
17912 * @param {Object} object The object to query.
17913 * @param {Array|string} path The path of the property to resolve.
17914 * @param {*} [defaultValue] The value returned if the resolved value is `undefined`.
17915 * @returns {*} Returns the resolved value.
17916 * @example
17917 *
17918 * var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] };
17919 *
17920 * _.result(object, 'a[0].b.c1');
17921 * // => 3
17922 *
17923 * _.result(object, 'a[0].b.c2');
17924 * // => 4
17925 *
17926 * _.result(object, 'a.b.c', 'default');
17927 * // => 'default'
17928 *
17929 * _.result(object, 'a.b.c', _.constant('default'));
17930 * // => 'default'
17931 */
17932 function result(object, path, defaultValue) {
17933 var result = object == null ? undefined : object[path];
17934 if (result === undefined) {
17935 if (object != null && !isKey(path, object)) {
17936 path = toPath(path);
17937 object = path.length == 1 ? object : baseGet(object, baseSlice(path, 0, -1));
17938 result = object == null ? undefined : object[last(path)];
17939 }
17940 result = result === undefined ? defaultValue : result;
17941 }
17942 return isFunction(result) ? result.call(object) : result;
17943 }
17944
17945 /**
17946 * Sets the property value of `path` on `object`. If a portion of `path`
17947 * does not exist it is created.
17948 *
17949 * @static
17950 * @memberOf _
17951 * @category Object
17952 * @param {Object} object The object to augment.
17953 * @param {Array|string} path The path of the property to set.
17954 * @param {*} value The value to set.
17955 * @returns {Object} Returns `object`.
17956 * @example
17957 *
17958 * var object = { 'a': [{ 'b': { 'c': 3 } }] };
17959 *
17960 * _.set(object, 'a[0].b.c', 4);
17961 * console.log(object.a[0].b.c);
17962 * // => 4
17963 *
17964 * _.set(object, 'x[0].y.z', 5);
17965 * console.log(object.x[0].y.z);
17966 * // => 5
17967 */
17968 function set(object, path, value) {
17969 if (object == null) {
17970 return object;
17971 }
17972 var pathKey = (path + '');
17973 path = (object[pathKey] != null || isKey(path, object)) ? [pathKey] : toPath(path);
17974
17975 var index = -1,
17976 length = path.length,
17977 lastIndex = length - 1,
17978 nested = object;
17979
17980 while (nested != null && ++index < length) {
17981 var key = path[index];
17982 if (isObject(nested)) {
17983 if (index == lastIndex) {
17984 nested[key] = value;
17985 } else if (nested[key] == null) {
17986 nested[key] = isIndex(path[index + 1]) ? [] : {};
17987 }
17988 }
17989 nested = nested[key];
17990 }
17991 return object;
17992 }
17993
17994 /**
17995 * An alternative to `_.reduce`; this method transforms `object` to a new
17996 * `accumulator` object which is the result of running each of its own enumerable
17997 * properties through `iteratee`, with each invocation potentially mutating
17998 * the `accumulator` object. The `iteratee` is bound to `thisArg` and invoked
17999 * with four arguments: (accumulator, value, key, object). Iteratee functions
18000 * may exit iteration early by explicitly returning `false`.
18001 *
18002 * @static
18003 * @memberOf _
18004 * @category Object
18005 * @param {Array|Object} object The object to iterate over.
18006 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
18007 * @param {*} [accumulator] The custom accumulator value.
18008 * @param {*} [thisArg] The `this` binding of `iteratee`.
18009 * @returns {*} Returns the accumulated value.
18010 * @example
18011 *
18012 * _.transform([2, 3, 4], function(result, n) {
18013 * result.push(n *= n);
18014 * return n % 2 == 0;
18015 * });
18016 * // => [4, 9]
18017 *
18018 * _.transform({ 'a': 1, 'b': 2 }, function(result, n, key) {
18019 * result[key] = n * 3;
18020 * });
18021 * // => { 'a': 3, 'b': 6 }
18022 */
18023 function transform(object, iteratee, accumulator, thisArg) {
18024 var isArr = isArray(object) || isTypedArray(object);
18025 iteratee = getCallback(iteratee, thisArg, 4);
18026
18027 if (accumulator == null) {
18028 if (isArr || isObject(object)) {
18029 var Ctor = object.constructor;
18030 if (isArr) {
18031 accumulator = isArray(object) ? new Ctor : [];
18032 } else {
18033 accumulator = baseCreate(isFunction(Ctor) ? Ctor.prototype : undefined);
18034 }
18035 } else {
18036 accumulator = {};
18037 }
18038 }
18039 (isArr ? arrayEach : baseForOwn)(object, function(value, index, object) {
18040 return iteratee(accumulator, value, index, object);
18041 });
18042 return accumulator;
18043 }
18044
18045 /**
18046 * Creates an array of the own enumerable property values of `object`.
18047 *
18048 * **Note:** Non-object values are coerced to objects.
18049 *
18050 * @static
18051 * @memberOf _
18052 * @category Object
18053 * @param {Object} object The object to query.
18054 * @returns {Array} Returns the array of property values.
18055 * @example
18056 *
18057 * function Foo() {
18058 * this.a = 1;
18059 * this.b = 2;
18060 * }
18061 *
18062 * Foo.prototype.c = 3;
18063 *
18064 * _.values(new Foo);
18065 * // => [1, 2] (iteration order is not guaranteed)
18066 *
18067 * _.values('hi');
18068 * // => ['h', 'i']
18069 */
18070 function values(object) {
18071 return baseValues(object, keys(object));
18072 }
18073
18074 /**
18075 * Creates an array of the own and inherited enumerable property values
18076 * of `object`.
18077 *
18078 * **Note:** Non-object values are coerced to objects.
18079 *
18080 * @static
18081 * @memberOf _
18082 * @category Object
18083 * @param {Object} object The object to query.
18084 * @returns {Array} Returns the array of property values.
18085 * @example
18086 *
18087 * function Foo() {
18088 * this.a = 1;
18089 * this.b = 2;
18090 * }
18091 *
18092 * Foo.prototype.c = 3;
18093 *
18094 * _.valuesIn(new Foo);
18095 * // => [1, 2, 3] (iteration order is not guaranteed)
18096 */
18097 function valuesIn(object) {
18098 return baseValues(object, keysIn(object));
18099 }
18100
18101 /*------------------------------------------------------------------------*/
18102
18103 /**
18104 * Checks if `n` is between `start` and up to but not including, `end`. If
18105 * `end` is not specified it is set to `start` with `start` then set to `0`.
18106 *
18107 * @static
18108 * @memberOf _
18109 * @category Number
18110 * @param {number} n The number to check.
18111 * @param {number} [start=0] The start of the range.
18112 * @param {number} end The end of the range.
18113 * @returns {boolean} Returns `true` if `n` is in the range, else `false`.
18114 * @example
18115 *
18116 * _.inRange(3, 2, 4);
18117 * // => true
18118 *
18119 * _.inRange(4, 8);
18120 * // => true
18121 *
18122 * _.inRange(4, 2);
18123 * // => false
18124 *
18125 * _.inRange(2, 2);
18126 * // => false
18127 *
18128 * _.inRange(1.2, 2);
18129 * // => true
18130 *
18131 * _.inRange(5.2, 4);
18132 * // => false
18133 */
18134 function inRange(value, start, end) {
18135 start = +start || 0;
18136 if (end === undefined) {
18137 end = start;
18138 start = 0;
18139 } else {
18140 end = +end || 0;
18141 }
18142 return value >= nativeMin(start, end) && value < nativeMax(start, end);
18143 }
18144
18145 /**
18146 * Produces a random number between `min` and `max` (inclusive). If only one
18147 * argument is provided a number between `0` and the given number is returned.
18148 * If `floating` is `true`, or either `min` or `max` are floats, a floating-point
18149 * number is returned instead of an integer.
18150 *
18151 * @static
18152 * @memberOf _
18153 * @category Number
18154 * @param {number} [min=0] The minimum possible value.
18155 * @param {number} [max=1] The maximum possible value.
18156 * @param {boolean} [floating] Specify returning a floating-point number.
18157 * @returns {number} Returns the random number.
18158 * @example
18159 *
18160 * _.random(0, 5);
18161 * // => an integer between 0 and 5
18162 *
18163 * _.random(5);
18164 * // => also an integer between 0 and 5
18165 *
18166 * _.random(5, true);
18167 * // => a floating-point number between 0 and 5
18168 *
18169 * _.random(1.2, 5.2);
18170 * // => a floating-point number between 1.2 and 5.2
18171 */
18172 function random(min, max, floating) {
18173 if (floating && isIterateeCall(min, max, floating)) {
18174 max = floating = undefined;
18175 }
18176 var noMin = min == null,
18177 noMax = max == null;
18178
18179 if (floating == null) {
18180 if (noMax && typeof min == 'boolean') {
18181 floating = min;
18182 min = 1;
18183 }
18184 else if (typeof max == 'boolean') {
18185 floating = max;
18186 noMax = true;
18187 }
18188 }
18189 if (noMin && noMax) {
18190 max = 1;
18191 noMax = false;
18192 }
18193 min = +min || 0;
18194 if (noMax) {
18195 max = min;
18196 min = 0;
18197 } else {
18198 max = +max || 0;
18199 }
18200 if (floating || min % 1 || max % 1) {
18201 var rand = nativeRandom();
18202 return nativeMin(min + (rand * (max - min + parseFloat('1e-' + ((rand + '').length - 1)))), max);
18203 }
18204 return baseRandom(min, max);
18205 }
18206
18207 /*------------------------------------------------------------------------*/
18208
18209 /**
18210 * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase).
18211 *
18212 * @static
18213 * @memberOf _
18214 * @category String
18215 * @param {string} [string=''] The string to convert.
18216 * @returns {string} Returns the camel cased string.
18217 * @example
18218 *
18219 * _.camelCase('Foo Bar');
18220 * // => 'fooBar'
18221 *
18222 * _.camelCase('--foo-bar');
18223 * // => 'fooBar'
18224 *
18225 * _.camelCase('__foo_bar__');
18226 * // => 'fooBar'
18227 */
18228 var camelCase = createCompounder(function(result, word, index) {
18229 word = word.toLowerCase();
18230 return result + (index ? (word.charAt(0).toUpperCase() + word.slice(1)) : word);
18231 });
18232
18233 /**
18234 * Capitalizes the first character of `string`.
18235 *
18236 * @static
18237 * @memberOf _
18238 * @category String
18239 * @param {string} [string=''] The string to capitalize.
18240 * @returns {string} Returns the capitalized string.
18241 * @example
18242 *
18243 * _.capitalize('fred');
18244 * // => 'Fred'
18245 */
18246 function capitalize(string) {
18247 string = baseToString(string);
18248 return string && (string.charAt(0).toUpperCase() + string.slice(1));
18249 }
18250
18251 /**
18252 * Deburrs `string` by converting [latin-1 supplementary letters](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table)
18253 * to basic latin letters and removing [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks).
18254 *
18255 * @static
18256 * @memberOf _
18257 * @category String
18258 * @param {string} [string=''] The string to deburr.
18259 * @returns {string} Returns the deburred string.
18260 * @example
18261 *
18262 * _.deburr('déjà vu');
18263 * // => 'deja vu'
18264 */
18265 function deburr(string) {
18266 string = baseToString(string);
18267 return string && string.replace(reLatin1, deburrLetter).replace(reComboMark, '');
18268 }
18269
18270 /**
18271 * Checks if `string` ends with the given target string.
18272 *
18273 * @static
18274 * @memberOf _
18275 * @category String
18276 * @param {string} [string=''] The string to search.
18277 * @param {string} [target] The string to search for.
18278 * @param {number} [position=string.length] The position to search from.
18279 * @returns {boolean} Returns `true` if `string` ends with `target`, else `false`.
18280 * @example
18281 *
18282 * _.endsWith('abc', 'c');
18283 * // => true
18284 *
18285 * _.endsWith('abc', 'b');
18286 * // => false
18287 *
18288 * _.endsWith('abc', 'b', 2);
18289 * // => true
18290 */
18291 function endsWith(string, target, position) {
18292 string = baseToString(string);
18293 target = (target + '');
18294
18295 var length = string.length;
18296 position = position === undefined
18297 ? length
18298 : nativeMin(position < 0 ? 0 : (+position || 0), length);
18299
18300 position -= target.length;
18301 return position >= 0 && string.indexOf(target, position) == position;
18302 }
18303
18304 /**
18305 * Converts the characters "&", "<", ">", '"', "'", and "\`", in `string` to
18306 * their corresponding HTML entities.
18307 *
18308 * **Note:** No other characters are escaped. To escape additional characters
18309 * use a third-party library like [_he_](https://mths.be/he).
18310 *
18311 * Though the ">" character is escaped for symmetry, characters like
18312 * ">" and "/" don't need escaping in HTML and have no special meaning
18313 * unless they're part of a tag or unquoted attribute value.
18314 * See [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands)
18315 * (under "semi-related fun fact") for more details.
18316 *
18317 * Backticks are escaped because in Internet Explorer < 9, they can break out
18318 * of attribute values or HTML comments. See [#59](https://html5sec.org/#59),
18319 * [#102](https://html5sec.org/#102), [#108](https://html5sec.org/#108), and
18320 * [#133](https://html5sec.org/#133) of the [HTML5 Security Cheatsheet](https://html5sec.org/)
18321 * for more details.
18322 *
18323 * When working with HTML you should always [quote attribute values](http://wonko.com/post/html-escaping)
18324 * to reduce XSS vectors.
18325 *
18326 * @static
18327 * @memberOf _
18328 * @category String
18329 * @param {string} [string=''] The string to escape.
18330 * @returns {string} Returns the escaped string.
18331 * @example
18332 *
18333 * _.escape('fred, barney, & pebbles');
18334 * // => 'fred, barney, &amp; pebbles'
18335 */
18336 function escape(string) {
18337 // Reset `lastIndex` because in IE < 9 `String#replace` does not.
18338 string = baseToString(string);
18339 return (string && reHasUnescapedHtml.test(string))
18340 ? string.replace(reUnescapedHtml, escapeHtmlChar)
18341 : string;
18342 }
18343
18344 /**
18345 * Escapes the `RegExp` special characters "\", "/", "^", "$", ".", "|", "?",
18346 * "*", "+", "(", ")", "[", "]", "{" and "}" in `string`.
18347 *
18348 * @static
18349 * @memberOf _
18350 * @category String
18351 * @param {string} [string=''] The string to escape.
18352 * @returns {string} Returns the escaped string.
18353 * @example
18354 *
18355 * _.escapeRegExp('[lodash](https://lodash.com/)');
18356 * // => '\[lodash\]\(https:\/\/lodash\.com\/\)'
18357 */
18358 function escapeRegExp(string) {
18359 string = baseToString(string);
18360 return (string && reHasRegExpChars.test(string))
18361 ? string.replace(reRegExpChars, escapeRegExpChar)
18362 : (string || '(?:)');
18363 }
18364
18365 /**
18366 * Converts `string` to [kebab case](https://en.wikipedia.org/wiki/Letter_case#Special_case_styles).
18367 *
18368 * @static
18369 * @memberOf _
18370 * @category String
18371 * @param {string} [string=''] The string to convert.
18372 * @returns {string} Returns the kebab cased string.
18373 * @example
18374 *
18375 * _.kebabCase('Foo Bar');
18376 * // => 'foo-bar'
18377 *
18378 * _.kebabCase('fooBar');
18379 * // => 'foo-bar'
18380 *
18381 * _.kebabCase('__foo_bar__');
18382 * // => 'foo-bar'
18383 */
18384 var kebabCase = createCompounder(function(result, word, index) {
18385 return result + (index ? '-' : '') + word.toLowerCase();
18386 });
18387
18388 /**
18389 * Pads `string` on the left and right sides if it's shorter than `length`.
18390 * Padding characters are truncated if they can't be evenly divided by `length`.
18391 *
18392 * @static
18393 * @memberOf _
18394 * @category String
18395 * @param {string} [string=''] The string to pad.
18396 * @param {number} [length=0] The padding length.
18397 * @param {string} [chars=' '] The string used as padding.
18398 * @returns {string} Returns the padded string.
18399 * @example
18400 *
18401 * _.pad('abc', 8);
18402 * // => ' abc '
18403 *
18404 * _.pad('abc', 8, '_-');
18405 * // => '_-abc_-_'
18406 *
18407 * _.pad('abc', 3);
18408 * // => 'abc'
18409 */
18410 function pad(string, length, chars) {
18411 string = baseToString(string);
18412 length = +length;
18413
18414 var strLength = string.length;
18415 if (strLength >= length || !nativeIsFinite(length)) {
18416 return string;
18417 }
18418 var mid = (length - strLength) / 2,
18419 leftLength = nativeFloor(mid),
18420 rightLength = nativeCeil(mid);
18421
18422 chars = createPadding('', rightLength, chars);
18423 return chars.slice(0, leftLength) + string + chars;
18424 }
18425
18426 /**
18427 * Pads `string` on the left side if it's shorter than `length`. Padding
18428 * characters are truncated if they exceed `length`.
18429 *
18430 * @static
18431 * @memberOf _
18432 * @category String
18433 * @param {string} [string=''] The string to pad.
18434 * @param {number} [length=0] The padding length.
18435 * @param {string} [chars=' '] The string used as padding.
18436 * @returns {string} Returns the padded string.
18437 * @example
18438 *
18439 * _.padLeft('abc', 6);
18440 * // => ' abc'
18441 *
18442 * _.padLeft('abc', 6, '_-');
18443 * // => '_-_abc'
18444 *
18445 * _.padLeft('abc', 3);
18446 * // => 'abc'
18447 */
18448 var padLeft = createPadDir();
18449
18450 /**
18451 * Pads `string` on the right side if it's shorter than `length`. Padding
18452 * characters are truncated if they exceed `length`.
18453 *
18454 * @static
18455 * @memberOf _
18456 * @category String
18457 * @param {string} [string=''] The string to pad.
18458 * @param {number} [length=0] The padding length.
18459 * @param {string} [chars=' '] The string used as padding.
18460 * @returns {string} Returns the padded string.
18461 * @example
18462 *
18463 * _.padRight('abc', 6);
18464 * // => 'abc '
18465 *
18466 * _.padRight('abc', 6, '_-');
18467 * // => 'abc_-_'
18468 *
18469 * _.padRight('abc', 3);
18470 * // => 'abc'
18471 */
18472 var padRight = createPadDir(true);
18473
18474 /**
18475 * Converts `string` to an integer of the specified radix. If `radix` is
18476 * `undefined` or `0`, a `radix` of `10` is used unless `value` is a hexadecimal,
18477 * in which case a `radix` of `16` is used.
18478 *
18479 * **Note:** This method aligns with the [ES5 implementation](https://es5.github.io/#E)
18480 * of `parseInt`.
18481 *
18482 * @static
18483 * @memberOf _
18484 * @category String
18485 * @param {string} string The string to convert.
18486 * @param {number} [radix] The radix to interpret `value` by.
18487 * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
18488 * @returns {number} Returns the converted integer.
18489 * @example
18490 *
18491 * _.parseInt('08');
18492 * // => 8
18493 *
18494 * _.map(['6', '08', '10'], _.parseInt);
18495 * // => [6, 8, 10]
18496 */
18497 function parseInt(string, radix, guard) {
18498 // Firefox < 21 and Opera < 15 follow ES3 for `parseInt`.
18499 // Chrome fails to trim leading <BOM> whitespace characters.
18500 // See https://code.google.com/p/v8/issues/detail?id=3109 for more details.
18501 if (guard ? isIterateeCall(string, radix, guard) : radix == null) {
18502 radix = 0;
18503 } else if (radix) {
18504 radix = +radix;
18505 }
18506 string = trim(string);
18507 return nativeParseInt(string, radix || (reHasHexPrefix.test(string) ? 16 : 10));
18508 }
18509
18510 /**
18511 * Repeats the given string `n` times.
18512 *
18513 * @static
18514 * @memberOf _
18515 * @category String
18516 * @param {string} [string=''] The string to repeat.
18517 * @param {number} [n=0] The number of times to repeat the string.
18518 * @returns {string} Returns the repeated string.
18519 * @example
18520 *
18521 * _.repeat('*', 3);
18522 * // => '***'
18523 *
18524 * _.repeat('abc', 2);
18525 * // => 'abcabc'
18526 *
18527 * _.repeat('abc', 0);
18528 * // => ''
18529 */
18530 function repeat(string, n) {
18531 var result = '';
18532 string = baseToString(string);
18533 n = +n;
18534 if (n < 1 || !string || !nativeIsFinite(n)) {
18535 return result;
18536 }
18537 // Leverage the exponentiation by squaring algorithm for a faster repeat.
18538 // See https://en.wikipedia.org/wiki/Exponentiation_by_squaring for more details.
18539 do {
18540 if (n % 2) {
18541 result += string;
18542 }
18543 n = nativeFloor(n / 2);
18544 string += string;
18545 } while (n);
18546
18547 return result;
18548 }
18549
18550 /**
18551 * Converts `string` to [snake case](https://en.wikipedia.org/wiki/Snake_case).
18552 *
18553 * @static
18554 * @memberOf _
18555 * @category String
18556 * @param {string} [string=''] The string to convert.
18557 * @returns {string} Returns the snake cased string.
18558 * @example
18559 *
18560 * _.snakeCase('Foo Bar');
18561 * // => 'foo_bar'
18562 *
18563 * _.snakeCase('fooBar');
18564 * // => 'foo_bar'
18565 *
18566 * _.snakeCase('--foo-bar');
18567 * // => 'foo_bar'
18568 */
18569 var snakeCase = createCompounder(function(result, word, index) {
18570 return result + (index ? '_' : '') + word.toLowerCase();
18571 });
18572
18573 /**
18574 * Converts `string` to [start case](https://en.wikipedia.org/wiki/Letter_case#Stylistic_or_specialised_usage).
18575 *
18576 * @static
18577 * @memberOf _
18578 * @category String
18579 * @param {string} [string=''] The string to convert.
18580 * @returns {string} Returns the start cased string.
18581 * @example
18582 *
18583 * _.startCase('--foo-bar');
18584 * // => 'Foo Bar'
18585 *
18586 * _.startCase('fooBar');
18587 * // => 'Foo Bar'
18588 *
18589 * _.startCase('__foo_bar__');
18590 * // => 'Foo Bar'
18591 */
18592 var startCase = createCompounder(function(result, word, index) {
18593 return result + (index ? ' ' : '') + (word.charAt(0).toUpperCase() + word.slice(1));
18594 });
18595
18596 /**
18597 * Checks if `string` starts with the given target string.
18598 *
18599 * @static
18600 * @memberOf _
18601 * @category String
18602 * @param {string} [string=''] The string to search.
18603 * @param {string} [target] The string to search for.
18604 * @param {number} [position=0] The position to search from.
18605 * @returns {boolean} Returns `true` if `string` starts with `target`, else `false`.
18606 * @example
18607 *
18608 * _.startsWith('abc', 'a');
18609 * // => true
18610 *
18611 * _.startsWith('abc', 'b');
18612 * // => false
18613 *
18614 * _.startsWith('abc', 'b', 1);
18615 * // => true
18616 */
18617 function startsWith(string, target, position) {
18618 string = baseToString(string);
18619 position = position == null
18620 ? 0
18621 : nativeMin(position < 0 ? 0 : (+position || 0), string.length);
18622
18623 return string.lastIndexOf(target, position) == position;
18624 }
18625
18626 /**
18627 * Creates a compiled template function that can interpolate data properties
18628 * in "interpolate" delimiters, HTML-escape interpolated data properties in
18629 * "escape" delimiters, and execute JavaScript in "evaluate" delimiters. Data
18630 * properties may be accessed as free variables in the template. If a setting
18631 * object is provided it takes precedence over `_.templateSettings` values.
18632 *
18633 * **Note:** In the development build `_.template` utilizes
18634 * [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl)
18635 * for easier debugging.
18636 *
18637 * For more information on precompiling templates see
18638 * [lodash's custom builds documentation](https://lodash.com/custom-builds).
18639 *
18640 * For more information on Chrome extension sandboxes see
18641 * [Chrome's extensions documentation](https://developer.chrome.com/extensions/sandboxingEval).
18642 *
18643 * @static
18644 * @memberOf _
18645 * @category String
18646 * @param {string} [string=''] The template string.
18647 * @param {Object} [options] The options object.
18648 * @param {RegExp} [options.escape] The HTML "escape" delimiter.
18649 * @param {RegExp} [options.evaluate] The "evaluate" delimiter.
18650 * @param {Object} [options.imports] An object to import into the template as free variables.
18651 * @param {RegExp} [options.interpolate] The "interpolate" delimiter.
18652 * @param {string} [options.sourceURL] The sourceURL of the template's compiled source.
18653 * @param {string} [options.variable] The data object variable name.
18654 * @param- {Object} [otherOptions] Enables the legacy `options` param signature.
18655 * @returns {Function} Returns the compiled template function.
18656 * @example
18657 *
18658 * // using the "interpolate" delimiter to create a compiled template
18659 * var compiled = _.template('hello <%= user %>!');
18660 * compiled({ 'user': 'fred' });
18661 * // => 'hello fred!'
18662 *
18663 * // using the HTML "escape" delimiter to escape data property values
18664 * var compiled = _.template('<b><%- value %></b>');
18665 * compiled({ 'value': '<script>' });
18666 * // => '<b>&lt;script&gt;</b>'
18667 *
18668 * // using the "evaluate" delimiter to execute JavaScript and generate HTML
18669 * var compiled = _.template('<% _.forEach(users, function(user) { %><li><%- user %></li><% }); %>');
18670 * compiled({ 'users': ['fred', 'barney'] });
18671 * // => '<li>fred</li><li>barney</li>'
18672 *
18673 * // using the internal `print` function in "evaluate" delimiters
18674 * var compiled = _.template('<% print("hello " + user); %>!');
18675 * compiled({ 'user': 'barney' });
18676 * // => 'hello barney!'
18677 *
18678 * // using the ES delimiter as an alternative to the default "interpolate" delimiter
18679 * var compiled = _.template('hello ${ user }!');
18680 * compiled({ 'user': 'pebbles' });
18681 * // => 'hello pebbles!'
18682 *
18683 * // using custom template delimiters
18684 * _.templateSettings.interpolate = /{{([\s\S]+?)}}/g;
18685 * var compiled = _.template('hello {{ user }}!');
18686 * compiled({ 'user': 'mustache' });
18687 * // => 'hello mustache!'
18688 *
18689 * // using backslashes to treat delimiters as plain text
18690 * var compiled = _.template('<%= "\\<%- value %\\>" %>');
18691 * compiled({ 'value': 'ignored' });
18692 * // => '<%- value %>'
18693 *
18694 * // using the `imports` option to import `jQuery` as `jq`
18695 * var text = '<% jq.each(users, function(user) { %><li><%- user %></li><% }); %>';
18696 * var compiled = _.template(text, { 'imports': { 'jq': jQuery } });
18697 * compiled({ 'users': ['fred', 'barney'] });
18698 * // => '<li>fred</li><li>barney</li>'
18699 *
18700 * // using the `sourceURL` option to specify a custom sourceURL for the template
18701 * var compiled = _.template('hello <%= user %>!', { 'sourceURL': '/basic/greeting.jst' });
18702 * compiled(data);
18703 * // => find the source of "greeting.jst" under the Sources tab or Resources panel of the web inspector
18704 *
18705 * // using the `variable` option to ensure a with-statement isn't used in the compiled template
18706 * var compiled = _.template('hi <%= data.user %>!', { 'variable': 'data' });
18707 * compiled.source;
18708 * // => function(data) {
18709 * // var __t, __p = '';
18710 * // __p += 'hi ' + ((__t = ( data.user )) == null ? '' : __t) + '!';
18711 * // return __p;
18712 * // }
18713 *
18714 * // using the `source` property to inline compiled templates for meaningful
18715 * // line numbers in error messages and a stack trace
18716 * fs.writeFileSync(path.join(cwd, 'jst.js'), '\
18717 * var JST = {\
18718 * "main": ' + _.template(mainText).source + '\
18719 * };\
18720 * ');
18721 */
18722 function template(string, options, otherOptions) {
18723 // Based on John Resig's `tmpl` implementation (http://ejohn.org/blog/javascript-micro-templating/)
18724 // and Laura Doktorova's doT.js (https://github.com/olado/doT).
18725 var settings = lodash.templateSettings;
18726
18727 if (otherOptions && isIterateeCall(string, options, otherOptions)) {
18728 options = otherOptions = undefined;
18729 }
18730 string = baseToString(string);
18731 options = assignWith(baseAssign({}, otherOptions || options), settings, assignOwnDefaults);
18732
18733 var imports = assignWith(baseAssign({}, options.imports), settings.imports, assignOwnDefaults),
18734 importsKeys = keys(imports),
18735 importsValues = baseValues(imports, importsKeys);
18736
18737 var isEscaping,
18738 isEvaluating,
18739 index = 0,
18740 interpolate = options.interpolate || reNoMatch,
18741 source = "__p += '";
18742
18743 // Compile the regexp to match each delimiter.
18744 var reDelimiters = RegExp(
18745 (options.escape || reNoMatch).source + '|' +
18746 interpolate.source + '|' +
18747 (interpolate === reInterpolate ? reEsTemplate : reNoMatch).source + '|' +
18748 (options.evaluate || reNoMatch).source + '|$'
18749 , 'g');
18750
18751 // Use a sourceURL for easier debugging.
18752 var sourceURL = '//# sourceURL=' +
18753 ('sourceURL' in options
18754 ? options.sourceURL
18755 : ('lodash.templateSources[' + (++templateCounter) + ']')
18756 ) + '\n';
18757
18758 string.replace(reDelimiters, function(match, escapeValue, interpolateValue, esTemplateValue, evaluateValue, offset) {
18759 interpolateValue || (interpolateValue = esTemplateValue);
18760
18761 // Escape characters that can't be included in string literals.
18762 source += string.slice(index, offset).replace(reUnescapedString, escapeStringChar);
18763
18764 // Replace delimiters with snippets.
18765 if (escapeValue) {
18766 isEscaping = true;
18767 source += "' +\n__e(" + escapeValue + ") +\n'";
18768 }
18769 if (evaluateValue) {
18770 isEvaluating = true;
18771 source += "';\n" + evaluateValue + ";\n__p += '";
18772 }
18773 if (interpolateValue) {
18774 source += "' +\n((__t = (" + interpolateValue + ")) == null ? '' : __t) +\n'";
18775 }
18776 index = offset + match.length;
18777
18778 // The JS engine embedded in Adobe products requires returning the `match`
18779 // string in order to produce the correct `offset` value.
18780 return match;
18781 });
18782
18783 source += "';\n";
18784
18785 // If `variable` is not specified wrap a with-statement around the generated
18786 // code to add the data object to the top of the scope chain.
18787 var variable = options.variable;
18788 if (!variable) {
18789 source = 'with (obj) {\n' + source + '\n}\n';
18790 }
18791 // Cleanup code by stripping empty strings.
18792 source = (isEvaluating ? source.replace(reEmptyStringLeading, '') : source)
18793 .replace(reEmptyStringMiddle, '$1')
18794 .replace(reEmptyStringTrailing, '$1;');
18795
18796 // Frame code as the function body.
18797 source = 'function(' + (variable || 'obj') + ') {\n' +
18798 (variable
18799 ? ''
18800 : 'obj || (obj = {});\n'
18801 ) +
18802 "var __t, __p = ''" +
18803 (isEscaping
18804 ? ', __e = _.escape'
18805 : ''
18806 ) +
18807 (isEvaluating
18808 ? ', __j = Array.prototype.join;\n' +
18809 "function print() { __p += __j.call(arguments, '') }\n"
18810 : ';\n'
18811 ) +
18812 source +
18813 'return __p\n}';
18814
18815 var result = attempt(function() {
18816 return Function(importsKeys, sourceURL + 'return ' + source).apply(undefined, importsValues);
18817 });
18818
18819 // Provide the compiled function's source by its `toString` method or
18820 // the `source` property as a convenience for inlining compiled templates.
18821 result.source = source;
18822 if (isError(result)) {
18823 throw result;
18824 }
18825 return result;
18826 }
18827
18828 /**
18829 * Removes leading and trailing whitespace or specified characters from `string`.
18830 *
18831 * @static
18832 * @memberOf _
18833 * @category String
18834 * @param {string} [string=''] The string to trim.
18835 * @param {string} [chars=whitespace] The characters to trim.
18836 * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
18837 * @returns {string} Returns the trimmed string.
18838 * @example
18839 *
18840 * _.trim(' abc ');
18841 * // => 'abc'
18842 *
18843 * _.trim('-_-abc-_-', '_-');
18844 * // => 'abc'
18845 *
18846 * _.map([' foo ', ' bar '], _.trim);
18847 * // => ['foo', 'bar']
18848 */
18849 function trim(string, chars, guard) {
18850 var value = string;
18851 string = baseToString(string);
18852 if (!string) {
18853 return string;
18854 }
18855 if (guard ? isIterateeCall(value, chars, guard) : chars == null) {
18856 return string.slice(trimmedLeftIndex(string), trimmedRightIndex(string) + 1);
18857 }
18858 chars = (chars + '');
18859 return string.slice(charsLeftIndex(string, chars), charsRightIndex(string, chars) + 1);
18860 }
18861
18862 /**
18863 * Removes leading whitespace or specified characters from `string`.
18864 *
18865 * @static
18866 * @memberOf _
18867 * @category String
18868 * @param {string} [string=''] The string to trim.
18869 * @param {string} [chars=whitespace] The characters to trim.
18870 * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
18871 * @returns {string} Returns the trimmed string.
18872 * @example
18873 *
18874 * _.trimLeft(' abc ');
18875 * // => 'abc '
18876 *
18877 * _.trimLeft('-_-abc-_-', '_-');
18878 * // => 'abc-_-'
18879 */
18880 function trimLeft(string, chars, guard) {
18881 var value = string;
18882 string = baseToString(string);
18883 if (!string) {
18884 return string;
18885 }
18886 if (guard ? isIterateeCall(value, chars, guard) : chars == null) {
18887 return string.slice(trimmedLeftIndex(string));
18888 }
18889 return string.slice(charsLeftIndex(string, (chars + '')));
18890 }
18891
18892 /**
18893 * Removes trailing whitespace or specified characters from `string`.
18894 *
18895 * @static
18896 * @memberOf _
18897 * @category String
18898 * @param {string} [string=''] The string to trim.
18899 * @param {string} [chars=whitespace] The characters to trim.
18900 * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
18901 * @returns {string} Returns the trimmed string.
18902 * @example
18903 *
18904 * _.trimRight(' abc ');
18905 * // => ' abc'
18906 *
18907 * _.trimRight('-_-abc-_-', '_-');
18908 * // => '-_-abc'
18909 */
18910 function trimRight(string, chars, guard) {
18911 var value = string;
18912 string = baseToString(string);
18913 if (!string) {
18914 return string;
18915 }
18916 if (guard ? isIterateeCall(value, chars, guard) : chars == null) {
18917 return string.slice(0, trimmedRightIndex(string) + 1);
18918 }
18919 return string.slice(0, charsRightIndex(string, (chars + '')) + 1);
18920 }
18921
18922 /**
18923 * Truncates `string` if it's longer than the given maximum string length.
18924 * The last characters of the truncated string are replaced with the omission
18925 * string which defaults to "...".
18926 *
18927 * @static
18928 * @memberOf _
18929 * @category String
18930 * @param {string} [string=''] The string to truncate.
18931 * @param {Object|number} [options] The options object or maximum string length.
18932 * @param {number} [options.length=30] The maximum string length.
18933 * @param {string} [options.omission='...'] The string to indicate text is omitted.
18934 * @param {RegExp|string} [options.separator] The separator pattern to truncate to.
18935 * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
18936 * @returns {string} Returns the truncated string.
18937 * @example
18938 *
18939 * _.trunc('hi-diddly-ho there, neighborino');
18940 * // => 'hi-diddly-ho there, neighbo...'
18941 *
18942 * _.trunc('hi-diddly-ho there, neighborino', 24);
18943 * // => 'hi-diddly-ho there, n...'
18944 *
18945 * _.trunc('hi-diddly-ho there, neighborino', {
18946 * 'length': 24,
18947 * 'separator': ' '
18948 * });
18949 * // => 'hi-diddly-ho there,...'
18950 *
18951 * _.trunc('hi-diddly-ho there, neighborino', {
18952 * 'length': 24,
18953 * 'separator': /,? +/
18954 * });
18955 * // => 'hi-diddly-ho there...'
18956 *
18957 * _.trunc('hi-diddly-ho there, neighborino', {
18958 * 'omission': ' [...]'
18959 * });
18960 * // => 'hi-diddly-ho there, neig [...]'
18961 */
18962 function trunc(string, options, guard) {
18963 if (guard && isIterateeCall(string, options, guard)) {
18964 options = undefined;
18965 }
18966 var length = DEFAULT_TRUNC_LENGTH,
18967 omission = DEFAULT_TRUNC_OMISSION;
18968
18969 if (options != null) {
18970 if (isObject(options)) {
18971 var separator = 'separator' in options ? options.separator : separator;
18972 length = 'length' in options ? (+options.length || 0) : length;
18973 omission = 'omission' in options ? baseToString(options.omission) : omission;
18974 } else {
18975 length = +options || 0;
18976 }
18977 }
18978 string = baseToString(string);
18979 if (length >= string.length) {
18980 return string;
18981 }
18982 var end = length - omission.length;
18983 if (end < 1) {
18984 return omission;
18985 }
18986 var result = string.slice(0, end);
18987 if (separator == null) {
18988 return result + omission;
18989 }
18990 if (isRegExp(separator)) {
18991 if (string.slice(end).search(separator)) {
18992 var match,
18993 newEnd,
18994 substring = string.slice(0, end);
18995
18996 if (!separator.global) {
18997 separator = RegExp(separator.source, (reFlags.exec(separator) || '') + 'g');
18998 }
18999 separator.lastIndex = 0;
19000 while ((match = separator.exec(substring))) {
19001 newEnd = match.index;
19002 }
19003 result = result.slice(0, newEnd == null ? end : newEnd);
19004 }
19005 } else if (string.indexOf(separator, end) != end) {
19006 var index = result.lastIndexOf(separator);
19007 if (index > -1) {
19008 result = result.slice(0, index);
19009 }
19010 }
19011 return result + omission;
19012 }
19013
19014 /**
19015 * The inverse of `_.escape`; this method converts the HTML entities
19016 * `&amp;`, `&lt;`, `&gt;`, `&quot;`, `&#39;`, and `&#96;` in `string` to their
19017 * corresponding characters.
19018 *
19019 * **Note:** No other HTML entities are unescaped. To unescape additional HTML
19020 * entities use a third-party library like [_he_](https://mths.be/he).
19021 *
19022 * @static
19023 * @memberOf _
19024 * @category String
19025 * @param {string} [string=''] The string to unescape.
19026 * @returns {string} Returns the unescaped string.
19027 * @example
19028 *
19029 * _.unescape('fred, barney, &amp; pebbles');
19030 * // => 'fred, barney, & pebbles'
19031 */
19032 function unescape(string) {
19033 string = baseToString(string);
19034 return (string && reHasEscapedHtml.test(string))
19035 ? string.replace(reEscapedHtml, unescapeHtmlChar)
19036 : string;
19037 }
19038
19039 /**
19040 * Splits `string` into an array of its words.
19041 *
19042 * @static
19043 * @memberOf _
19044 * @category String
19045 * @param {string} [string=''] The string to inspect.
19046 * @param {RegExp|string} [pattern] The pattern to match words.
19047 * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
19048 * @returns {Array} Returns the words of `string`.
19049 * @example
19050 *
19051 * _.words('fred, barney, & pebbles');
19052 * // => ['fred', 'barney', 'pebbles']
19053 *
19054 * _.words('fred, barney, & pebbles', /[^, ]+/g);
19055 * // => ['fred', 'barney', '&', 'pebbles']
19056 */
19057 function words(string, pattern, guard) {
19058 if (guard && isIterateeCall(string, pattern, guard)) {
19059 pattern = undefined;
19060 }
19061 string = baseToString(string);
19062 return string.match(pattern || reWords) || [];
19063 }
19064
19065 /*------------------------------------------------------------------------*/
19066
19067 /**
19068 * Attempts to invoke `func`, returning either the result or the caught error
19069 * object. Any additional arguments are provided to `func` when it is invoked.
19070 *
19071 * @static
19072 * @memberOf _
19073 * @category Utility
19074 * @param {Function} func The function to attempt.
19075 * @returns {*} Returns the `func` result or error object.
19076 * @example
19077 *
19078 * // avoid throwing errors for invalid selectors
19079 * var elements = _.attempt(function(selector) {
19080 * return document.querySelectorAll(selector);
19081 * }, '>_>');
19082 *
19083 * if (_.isError(elements)) {
19084 * elements = [];
19085 * }
19086 */
19087 var attempt = restParam(function(func, args) {
19088 try {
19089 return func.apply(undefined, args);
19090 } catch(e) {
19091 return isError(e) ? e : new Error(e);
19092 }
19093 });
19094
19095 /**
19096 * Creates a function that invokes `func` with the `this` binding of `thisArg`
19097 * and arguments of the created function. If `func` is a property name the
19098 * created callback returns the property value for a given element. If `func`
19099 * is an object the created callback returns `true` for elements that contain
19100 * the equivalent object properties, otherwise it returns `false`.
19101 *
19102 * @static
19103 * @memberOf _
19104 * @alias iteratee
19105 * @category Utility
19106 * @param {*} [func=_.identity] The value to convert to a callback.
19107 * @param {*} [thisArg] The `this` binding of `func`.
19108 * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
19109 * @returns {Function} Returns the callback.
19110 * @example
19111 *
19112 * var users = [
19113 * { 'user': 'barney', 'age': 36 },
19114 * { 'user': 'fred', 'age': 40 }
19115 * ];
19116 *
19117 * // wrap to create custom callback shorthands
19118 * _.callback = _.wrap(_.callback, function(callback, func, thisArg) {
19119 * var match = /^(.+?)__([gl]t)(.+)$/.exec(func);
19120 * if (!match) {
19121 * return callback(func, thisArg);
19122 * }
19123 * return function(object) {
19124 * return match[2] == 'gt'
19125 * ? object[match[1]] > match[3]
19126 * : object[match[1]] < match[3];
19127 * };
19128 * });
19129 *
19130 * _.filter(users, 'age__gt36');
19131 * // => [{ 'user': 'fred', 'age': 40 }]
19132 */
19133 function callback(func, thisArg, guard) {
19134 if (guard && isIterateeCall(func, thisArg, guard)) {
19135 thisArg = undefined;
19136 }
19137 return isObjectLike(func)
19138 ? matches(func)
19139 : baseCallback(func, thisArg);
19140 }
19141
19142 /**
19143 * Creates a function that returns `value`.
19144 *
19145 * @static
19146 * @memberOf _
19147 * @category Utility
19148 * @param {*} value The value to return from the new function.
19149 * @returns {Function} Returns the new function.
19150 * @example
19151 *
19152 * var object = { 'user': 'fred' };
19153 * var getter = _.constant(object);
19154 *
19155 * getter() === object;
19156 * // => true
19157 */
19158 function constant(value) {
19159 return function() {
19160 return value;
19161 };
19162 }
19163
19164 /**
19165 * This method returns the first argument provided to it.
19166 *
19167 * @static
19168 * @memberOf _
19169 * @category Utility
19170 * @param {*} value Any value.
19171 * @returns {*} Returns `value`.
19172 * @example
19173 *
19174 * var object = { 'user': 'fred' };
19175 *
19176 * _.identity(object) === object;
19177 * // => true
19178 */
19179 function identity(value) {
19180 return value;
19181 }
19182
19183 /**
19184 * Creates a function that performs a deep comparison between a given object
19185 * and `source`, returning `true` if the given object has equivalent property
19186 * values, else `false`.
19187 *
19188 * **Note:** This method supports comparing arrays, booleans, `Date` objects,
19189 * numbers, `Object` objects, regexes, and strings. Objects are compared by
19190 * their own, not inherited, enumerable properties. For comparing a single
19191 * own or inherited property value see `_.matchesProperty`.
19192 *
19193 * @static
19194 * @memberOf _
19195 * @category Utility
19196 * @param {Object} source The object of property values to match.
19197 * @returns {Function} Returns the new function.
19198 * @example
19199 *
19200 * var users = [
19201 * { 'user': 'barney', 'age': 36, 'active': true },
19202 * { 'user': 'fred', 'age': 40, 'active': false }
19203 * ];
19204 *
19205 * _.filter(users, _.matches({ 'age': 40, 'active': false }));
19206 * // => [{ 'user': 'fred', 'age': 40, 'active': false }]
19207 */
19208 function matches(source) {
19209 return baseMatches(baseClone(source, true));
19210 }
19211
19212 /**
19213 * Creates a function that compares the property value of `path` on a given
19214 * object to `value`.
19215 *
19216 * **Note:** This method supports comparing arrays, booleans, `Date` objects,
19217 * numbers, `Object` objects, regexes, and strings. Objects are compared by
19218 * their own, not inherited, enumerable properties.
19219 *
19220 * @static
19221 * @memberOf _
19222 * @category Utility
19223 * @param {Array|string} path The path of the property to get.
19224 * @param {*} srcValue The value to match.
19225 * @returns {Function} Returns the new function.
19226 * @example
19227 *
19228 * var users = [
19229 * { 'user': 'barney' },
19230 * { 'user': 'fred' }
19231 * ];
19232 *
19233 * _.find(users, _.matchesProperty('user', 'fred'));
19234 * // => { 'user': 'fred' }
19235 */
19236 function matchesProperty(path, srcValue) {
19237 return baseMatchesProperty(path, baseClone(srcValue, true));
19238 }
19239
19240 /**
19241 * Creates a function that invokes the method at `path` on a given object.
19242 * Any additional arguments are provided to the invoked method.
19243 *
19244 * @static
19245 * @memberOf _
19246 * @category Utility
19247 * @param {Array|string} path The path of the method to invoke.
19248 * @param {...*} [args] The arguments to invoke the method with.
19249 * @returns {Function} Returns the new function.
19250 * @example
19251 *
19252 * var objects = [
19253 * { 'a': { 'b': { 'c': _.constant(2) } } },
19254 * { 'a': { 'b': { 'c': _.constant(1) } } }
19255 * ];
19256 *
19257 * _.map(objects, _.method('a.b.c'));
19258 * // => [2, 1]
19259 *
19260 * _.invoke(_.sortBy(objects, _.method(['a', 'b', 'c'])), 'a.b.c');
19261 * // => [1, 2]
19262 */
19263 var method = restParam(function(path, args) {
19264 return function(object) {
19265 return invokePath(object, path, args);
19266 };
19267 });
19268
19269 /**
19270 * The opposite of `_.method`; this method creates a function that invokes
19271 * the method at a given path on `object`. Any additional arguments are
19272 * provided to the invoked method.
19273 *
19274 * @static
19275 * @memberOf _
19276 * @category Utility
19277 * @param {Object} object The object to query.
19278 * @param {...*} [args] The arguments to invoke the method with.
19279 * @returns {Function} Returns the new function.
19280 * @example
19281 *
19282 * var array = _.times(3, _.constant),
19283 * object = { 'a': array, 'b': array, 'c': array };
19284 *
19285 * _.map(['a[2]', 'c[0]'], _.methodOf(object));
19286 * // => [2, 0]
19287 *
19288 * _.map([['a', '2'], ['c', '0']], _.methodOf(object));
19289 * // => [2, 0]
19290 */
19291 var methodOf = restParam(function(object, args) {
19292 return function(path) {
19293 return invokePath(object, path, args);
19294 };
19295 });
19296
19297 /**
19298 * Adds all own enumerable function properties of a source object to the
19299 * destination object. If `object` is a function then methods are added to
19300 * its prototype as well.
19301 *
19302 * **Note:** Use `_.runInContext` to create a pristine `lodash` function to
19303 * avoid conflicts caused by modifying the original.
19304 *
19305 * @static
19306 * @memberOf _
19307 * @category Utility
19308 * @param {Function|Object} [object=lodash] The destination object.
19309 * @param {Object} source The object of functions to add.
19310 * @param {Object} [options] The options object.
19311 * @param {boolean} [options.chain=true] Specify whether the functions added
19312 * are chainable.
19313 * @returns {Function|Object} Returns `object`.
19314 * @example
19315 *
19316 * function vowels(string) {
19317 * return _.filter(string, function(v) {
19318 * return /[aeiou]/i.test(v);
19319 * });
19320 * }
19321 *
19322 * _.mixin({ 'vowels': vowels });
19323 * _.vowels('fred');
19324 * // => ['e']
19325 *
19326 * _('fred').vowels().value();
19327 * // => ['e']
19328 *
19329 * _.mixin({ 'vowels': vowels }, { 'chain': false });
19330 * _('fred').vowels();
19331 * // => ['e']
19332 */
19333 function mixin(object, source, options) {
19334 if (options == null) {
19335 var isObj = isObject(source),
19336 props = isObj ? keys(source) : undefined,
19337 methodNames = (props && props.length) ? baseFunctions(source, props) : undefined;
19338
19339 if (!(methodNames ? methodNames.length : isObj)) {
19340 methodNames = false;
19341 options = source;
19342 source = object;
19343 object = this;
19344 }
19345 }
19346 if (!methodNames) {
19347 methodNames = baseFunctions(source, keys(source));
19348 }
19349 var chain = true,
19350 index = -1,
19351 isFunc = isFunction(object),
19352 length = methodNames.length;
19353
19354 if (options === false) {
19355 chain = false;
19356 } else if (isObject(options) && 'chain' in options) {
19357 chain = options.chain;
19358 }
19359 while (++index < length) {
19360 var methodName = methodNames[index],
19361 func = source[methodName];
19362
19363 object[methodName] = func;
19364 if (isFunc) {
19365 object.prototype[methodName] = (function(func) {
19366 return function() {
19367 var chainAll = this.__chain__;
19368 if (chain || chainAll) {
19369 var result = object(this.__wrapped__),
19370 actions = result.__actions__ = arrayCopy(this.__actions__);
19371
19372 actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
19373 result.__chain__ = chainAll;
19374 return result;
19375 }
19376 return func.apply(object, arrayPush([this.value()], arguments));
19377 };
19378 }(func));
19379 }
19380 }
19381 return object;
19382 }
19383
19384 /**
19385 * Reverts the `_` variable to its previous value and returns a reference to
19386 * the `lodash` function.
19387 *
19388 * @static
19389 * @memberOf _
19390 * @category Utility
19391 * @returns {Function} Returns the `lodash` function.
19392 * @example
19393 *
19394 * var lodash = _.noConflict();
19395 */
19396 function noConflict() {
19397 root._ = oldDash;
19398 return this;
19399 }
19400
19401 /**
19402 * A no-operation function that returns `undefined` regardless of the
19403 * arguments it receives.
19404 *
19405 * @static
19406 * @memberOf _
19407 * @category Utility
19408 * @example
19409 *
19410 * var object = { 'user': 'fred' };
19411 *
19412 * _.noop(object) === undefined;
19413 * // => true
19414 */
19415 function noop() {
19416 // No operation performed.
19417 }
19418
19419 /**
19420 * Creates a function that returns the property value at `path` on a
19421 * given object.
19422 *
19423 * @static
19424 * @memberOf _
19425 * @category Utility
19426 * @param {Array|string} path The path of the property to get.
19427 * @returns {Function} Returns the new function.
19428 * @example
19429 *
19430 * var objects = [
19431 * { 'a': { 'b': { 'c': 2 } } },
19432 * { 'a': { 'b': { 'c': 1 } } }
19433 * ];
19434 *
19435 * _.map(objects, _.property('a.b.c'));
19436 * // => [2, 1]
19437 *
19438 * _.pluck(_.sortBy(objects, _.property(['a', 'b', 'c'])), 'a.b.c');
19439 * // => [1, 2]
19440 */
19441 function property(path) {
19442 return isKey(path) ? baseProperty(path) : basePropertyDeep(path);
19443 }
19444
19445 /**
19446 * The opposite of `_.property`; this method creates a function that returns
19447 * the property value at a given path on `object`.
19448 *
19449 * @static
19450 * @memberOf _
19451 * @category Utility
19452 * @param {Object} object The object to query.
19453 * @returns {Function} Returns the new function.
19454 * @example
19455 *
19456 * var array = [0, 1, 2],
19457 * object = { 'a': array, 'b': array, 'c': array };
19458 *
19459 * _.map(['a[2]', 'c[0]'], _.propertyOf(object));
19460 * // => [2, 0]
19461 *
19462 * _.map([['a', '2'], ['c', '0']], _.propertyOf(object));
19463 * // => [2, 0]
19464 */
19465 function propertyOf(object) {
19466 return function(path) {
19467 return baseGet(object, toPath(path), path + '');
19468 };
19469 }
19470
19471 /**
19472 * Creates an array of numbers (positive and/or negative) progressing from
19473 * `start` up to, but not including, `end`. If `end` is not specified it is
19474 * set to `start` with `start` then set to `0`. If `end` is less than `start`
19475 * a zero-length range is created unless a negative `step` is specified.
19476 *
19477 * @static
19478 * @memberOf _
19479 * @category Utility
19480 * @param {number} [start=0] The start of the range.
19481 * @param {number} end The end of the range.
19482 * @param {number} [step=1] The value to increment or decrement by.
19483 * @returns {Array} Returns the new array of numbers.
19484 * @example
19485 *
19486 * _.range(4);
19487 * // => [0, 1, 2, 3]
19488 *
19489 * _.range(1, 5);
19490 * // => [1, 2, 3, 4]
19491 *
19492 * _.range(0, 20, 5);
19493 * // => [0, 5, 10, 15]
19494 *
19495 * _.range(0, -4, -1);
19496 * // => [0, -1, -2, -3]
19497 *
19498 * _.range(1, 4, 0);
19499 * // => [1, 1, 1]
19500 *
19501 * _.range(0);
19502 * // => []
19503 */
19504 function range(start, end, step) {
19505 if (step && isIterateeCall(start, end, step)) {
19506 end = step = undefined;
19507 }
19508 start = +start || 0;
19509 step = step == null ? 1 : (+step || 0);
19510
19511 if (end == null) {
19512 end = start;
19513 start = 0;
19514 } else {
19515 end = +end || 0;
19516 }
19517 // Use `Array(length)` so engines like Chakra and V8 avoid slower modes.
19518 // See https://youtu.be/XAqIpGU8ZZk#t=17m25s for more details.
19519 var index = -1,
19520 length = nativeMax(nativeCeil((end - start) / (step || 1)), 0),
19521 result = Array(length);
19522
19523 while (++index < length) {
19524 result[index] = start;
19525 start += step;
19526 }
19527 return result;
19528 }
19529
19530 /**
19531 * Invokes the iteratee function `n` times, returning an array of the results
19532 * of each invocation. The `iteratee` is bound to `thisArg` and invoked with
19533 * one argument; (index).
19534 *
19535 * @static
19536 * @memberOf _
19537 * @category Utility
19538 * @param {number} n The number of times to invoke `iteratee`.
19539 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
19540 * @param {*} [thisArg] The `this` binding of `iteratee`.
19541 * @returns {Array} Returns the array of results.
19542 * @example
19543 *
19544 * var diceRolls = _.times(3, _.partial(_.random, 1, 6, false));
19545 * // => [3, 6, 4]
19546 *
19547 * _.times(3, function(n) {
19548 * mage.castSpell(n);
19549 * });
19550 * // => invokes `mage.castSpell(n)` three times with `n` of `0`, `1`, and `2`
19551 *
19552 * _.times(3, function(n) {
19553 * this.cast(n);
19554 * }, mage);
19555 * // => also invokes `mage.castSpell(n)` three times
19556 */
19557 function times(n, iteratee, thisArg) {
19558 n = nativeFloor(n);
19559
19560 // Exit early to avoid a JSC JIT bug in Safari 8
19561 // where `Array(0)` is treated as `Array(1)`.
19562 if (n < 1 || !nativeIsFinite(n)) {
19563 return [];
19564 }
19565 var index = -1,
19566 result = Array(nativeMin(n, MAX_ARRAY_LENGTH));
19567
19568 iteratee = bindCallback(iteratee, thisArg, 1);
19569 while (++index < n) {
19570 if (index < MAX_ARRAY_LENGTH) {
19571 result[index] = iteratee(index);
19572 } else {
19573 iteratee(index);
19574 }
19575 }
19576 return result;
19577 }
19578
19579 /**
19580 * Generates a unique ID. If `prefix` is provided the ID is appended to it.
19581 *
19582 * @static
19583 * @memberOf _
19584 * @category Utility
19585 * @param {string} [prefix] The value to prefix the ID with.
19586 * @returns {string} Returns the unique ID.
19587 * @example
19588 *
19589 * _.uniqueId('contact_');
19590 * // => 'contact_104'
19591 *
19592 * _.uniqueId();
19593 * // => '105'
19594 */
19595 function uniqueId(prefix) {
19596 var id = ++idCounter;
19597 return baseToString(prefix) + id;
19598 }
19599
19600 /*------------------------------------------------------------------------*/
19601
19602 /**
19603 * Adds two numbers.
19604 *
19605 * @static
19606 * @memberOf _
19607 * @category Math
19608 * @param {number} augend The first number to add.
19609 * @param {number} addend The second number to add.
19610 * @returns {number} Returns the sum.
19611 * @example
19612 *
19613 * _.add(6, 4);
19614 * // => 10
19615 */
19616 function add(augend, addend) {
19617 return (+augend || 0) + (+addend || 0);
19618 }
19619
19620 /**
19621 * Calculates `n` rounded up to `precision`.
19622 *
19623 * @static
19624 * @memberOf _
19625 * @category Math
19626 * @param {number} n The number to round up.
19627 * @param {number} [precision=0] The precision to round up to.
19628 * @returns {number} Returns the rounded up number.
19629 * @example
19630 *
19631 * _.ceil(4.006);
19632 * // => 5
19633 *
19634 * _.ceil(6.004, 2);
19635 * // => 6.01
19636 *
19637 * _.ceil(6040, -2);
19638 * // => 6100
19639 */
19640 var ceil = createRound('ceil');
19641
19642 /**
19643 * Calculates `n` rounded down to `precision`.
19644 *
19645 * @static
19646 * @memberOf _
19647 * @category Math
19648 * @param {number} n The number to round down.
19649 * @param {number} [precision=0] The precision to round down to.
19650 * @returns {number} Returns the rounded down number.
19651 * @example
19652 *
19653 * _.floor(4.006);
19654 * // => 4
19655 *
19656 * _.floor(0.046, 2);
19657 * // => 0.04
19658 *
19659 * _.floor(4060, -2);
19660 * // => 4000
19661 */
19662 var floor = createRound('floor');
19663
19664 /**
19665 * Gets the maximum value of `collection`. If `collection` is empty or falsey
19666 * `-Infinity` is returned. If an iteratee function is provided it is invoked
19667 * for each value in `collection` to generate the criterion by which the value
19668 * is ranked. The `iteratee` is bound to `thisArg` and invoked with three
19669 * arguments: (value, index, collection).
19670 *
19671 * If a property name is provided for `iteratee` the created `_.property`
19672 * style callback returns the property value of the given element.
19673 *
19674 * If a value is also provided for `thisArg` the created `_.matchesProperty`
19675 * style callback returns `true` for elements that have a matching property
19676 * value, else `false`.
19677 *
19678 * If an object is provided for `iteratee` the created `_.matches` style
19679 * callback returns `true` for elements that have the properties of the given
19680 * object, else `false`.
19681 *
19682 * @static
19683 * @memberOf _
19684 * @category Math
19685 * @param {Array|Object|string} collection The collection to iterate over.
19686 * @param {Function|Object|string} [iteratee] The function invoked per iteration.
19687 * @param {*} [thisArg] The `this` binding of `iteratee`.
19688 * @returns {*} Returns the maximum value.
19689 * @example
19690 *
19691 * _.max([4, 2, 8, 6]);
19692 * // => 8
19693 *
19694 * _.max([]);
19695 * // => -Infinity
19696 *
19697 * var users = [
19698 * { 'user': 'barney', 'age': 36 },
19699 * { 'user': 'fred', 'age': 40 }
19700 * ];
19701 *
19702 * _.max(users, function(chr) {
19703 * return chr.age;
19704 * });
19705 * // => { 'user': 'fred', 'age': 40 }
19706 *
19707 * // using the `_.property` callback shorthand
19708 * _.max(users, 'age');
19709 * // => { 'user': 'fred', 'age': 40 }
19710 */
19711 var max = createExtremum(gt, NEGATIVE_INFINITY);
19712
19713 /**
19714 * Gets the minimum value of `collection`. If `collection` is empty or falsey
19715 * `Infinity` is returned. If an iteratee function is provided it is invoked
19716 * for each value in `collection` to generate the criterion by which the value
19717 * is ranked. The `iteratee` is bound to `thisArg` and invoked with three
19718 * arguments: (value, index, collection).
19719 *
19720 * If a property name is provided for `iteratee` the created `_.property`
19721 * style callback returns the property value of the given element.
19722 *
19723 * If a value is also provided for `thisArg` the created `_.matchesProperty`
19724 * style callback returns `true` for elements that have a matching property
19725 * value, else `false`.
19726 *
19727 * If an object is provided for `iteratee` the created `_.matches` style
19728 * callback returns `true` for elements that have the properties of the given
19729 * object, else `false`.
19730 *
19731 * @static
19732 * @memberOf _
19733 * @category Math
19734 * @param {Array|Object|string} collection The collection to iterate over.
19735 * @param {Function|Object|string} [iteratee] The function invoked per iteration.
19736 * @param {*} [thisArg] The `this` binding of `iteratee`.
19737 * @returns {*} Returns the minimum value.
19738 * @example
19739 *
19740 * _.min([4, 2, 8, 6]);
19741 * // => 2
19742 *
19743 * _.min([]);
19744 * // => Infinity
19745 *
19746 * var users = [
19747 * { 'user': 'barney', 'age': 36 },
19748 * { 'user': 'fred', 'age': 40 }
19749 * ];
19750 *
19751 * _.min(users, function(chr) {
19752 * return chr.age;
19753 * });
19754 * // => { 'user': 'barney', 'age': 36 }
19755 *
19756 * // using the `_.property` callback shorthand
19757 * _.min(users, 'age');
19758 * // => { 'user': 'barney', 'age': 36 }
19759 */
19760 var min = createExtremum(lt, POSITIVE_INFINITY);
19761
19762 /**
19763 * Calculates `n` rounded to `precision`.
19764 *
19765 * @static
19766 * @memberOf _
19767 * @category Math
19768 * @param {number} n The number to round.
19769 * @param {number} [precision=0] The precision to round to.
19770 * @returns {number} Returns the rounded number.
19771 * @example
19772 *
19773 * _.round(4.006);
19774 * // => 4
19775 *
19776 * _.round(4.006, 2);
19777 * // => 4.01
19778 *
19779 * _.round(4060, -2);
19780 * // => 4100
19781 */
19782 var round = createRound('round');
19783
19784 /**
19785 * Gets the sum of the values in `collection`.
19786 *
19787 * @static
19788 * @memberOf _
19789 * @category Math
19790 * @param {Array|Object|string} collection The collection to iterate over.
19791 * @param {Function|Object|string} [iteratee] The function invoked per iteration.
19792 * @param {*} [thisArg] The `this` binding of `iteratee`.
19793 * @returns {number} Returns the sum.
19794 * @example
19795 *
19796 * _.sum([4, 6]);
19797 * // => 10
19798 *
19799 * _.sum({ 'a': 4, 'b': 6 });
19800 * // => 10
19801 *
19802 * var objects = [
19803 * { 'n': 4 },
19804 * { 'n': 6 }
19805 * ];
19806 *
19807 * _.sum(objects, function(object) {
19808 * return object.n;
19809 * });
19810 * // => 10
19811 *
19812 * // using the `_.property` callback shorthand
19813 * _.sum(objects, 'n');
19814 * // => 10
19815 */
19816 function sum(collection, iteratee, thisArg) {
19817 if (thisArg && isIterateeCall(collection, iteratee, thisArg)) {
19818 iteratee = undefined;
19819 }
19820 iteratee = getCallback(iteratee, thisArg, 3);
19821 return iteratee.length == 1
19822 ? arraySum(isArray(collection) ? collection : toIterable(collection), iteratee)
19823 : baseSum(collection, iteratee);
19824 }
19825
19826 /*------------------------------------------------------------------------*/
19827
19828 // Ensure wrappers are instances of `baseLodash`.
19829 lodash.prototype = baseLodash.prototype;
19830
19831 LodashWrapper.prototype = baseCreate(baseLodash.prototype);
19832 LodashWrapper.prototype.constructor = LodashWrapper;
19833
19834 LazyWrapper.prototype = baseCreate(baseLodash.prototype);
19835 LazyWrapper.prototype.constructor = LazyWrapper;
19836
19837 // Add functions to the `Map` cache.
19838 MapCache.prototype['delete'] = mapDelete;
19839 MapCache.prototype.get = mapGet;
19840 MapCache.prototype.has = mapHas;
19841 MapCache.prototype.set = mapSet;
19842
19843 // Add functions to the `Set` cache.
19844 SetCache.prototype.push = cachePush;
19845
19846 // Assign cache to `_.memoize`.
19847 memoize.Cache = MapCache;
19848
19849 // Add functions that return wrapped values when chaining.
19850 lodash.after = after;
19851 lodash.ary = ary;
19852 lodash.assign = assign;
19853 lodash.at = at;
19854 lodash.before = before;
19855 lodash.bind = bind;
19856 lodash.bindAll = bindAll;
19857 lodash.bindKey = bindKey;
19858 lodash.callback = callback;
19859 lodash.chain = chain;
19860 lodash.chunk = chunk;
19861 lodash.compact = compact;
19862 lodash.constant = constant;
19863 lodash.countBy = countBy;
19864 lodash.create = create;
19865 lodash.curry = curry;
19866 lodash.curryRight = curryRight;
19867 lodash.debounce = debounce;
19868 lodash.defaults = defaults;
19869 lodash.defaultsDeep = defaultsDeep;
19870 lodash.defer = defer;
19871 lodash.delay = delay;
19872 lodash.difference = difference;
19873 lodash.drop = drop;
19874 lodash.dropRight = dropRight;
19875 lodash.dropRightWhile = dropRightWhile;
19876 lodash.dropWhile = dropWhile;
19877 lodash.fill = fill;
19878 lodash.filter = filter;
19879 lodash.flatten = flatten;
19880 lodash.flattenDeep = flattenDeep;
19881 lodash.flow = flow;
19882 lodash.flowRight = flowRight;
19883 lodash.forEach = forEach;
19884 lodash.forEachRight = forEachRight;
19885 lodash.forIn = forIn;
19886 lodash.forInRight = forInRight;
19887 lodash.forOwn = forOwn;
19888 lodash.forOwnRight = forOwnRight;
19889 lodash.functions = functions;
19890 lodash.groupBy = groupBy;
19891 lodash.indexBy = indexBy;
19892 lodash.initial = initial;
19893 lodash.intersection = intersection;
19894 lodash.invert = invert;
19895 lodash.invoke = invoke;
19896 lodash.keys = keys;
19897 lodash.keysIn = keysIn;
19898 lodash.map = map;
19899 lodash.mapKeys = mapKeys;
19900 lodash.mapValues = mapValues;
19901 lodash.matches = matches;
19902 lodash.matchesProperty = matchesProperty;
19903 lodash.memoize = memoize;
19904 lodash.merge = merge;
19905 lodash.method = method;
19906 lodash.methodOf = methodOf;
19907 lodash.mixin = mixin;
19908 lodash.modArgs = modArgs;
19909 lodash.negate = negate;
19910 lodash.omit = omit;
19911 lodash.once = once;
19912 lodash.pairs = pairs;
19913 lodash.partial = partial;
19914 lodash.partialRight = partialRight;
19915 lodash.partition = partition;
19916 lodash.pick = pick;
19917 lodash.pluck = pluck;
19918 lodash.property = property;
19919 lodash.propertyOf = propertyOf;
19920 lodash.pull = pull;
19921 lodash.pullAt = pullAt;
19922 lodash.range = range;
19923 lodash.rearg = rearg;
19924 lodash.reject = reject;
19925 lodash.remove = remove;
19926 lodash.rest = rest;
19927 lodash.restParam = restParam;
19928 lodash.set = set;
19929 lodash.shuffle = shuffle;
19930 lodash.slice = slice;
19931 lodash.sortBy = sortBy;
19932 lodash.sortByAll = sortByAll;
19933 lodash.sortByOrder = sortByOrder;
19934 lodash.spread = spread;
19935 lodash.take = take;
19936 lodash.takeRight = takeRight;
19937 lodash.takeRightWhile = takeRightWhile;
19938 lodash.takeWhile = takeWhile;
19939 lodash.tap = tap;
19940 lodash.throttle = throttle;
19941 lodash.thru = thru;
19942 lodash.times = times;
19943 lodash.toArray = toArray;
19944 lodash.toPlainObject = toPlainObject;
19945 lodash.transform = transform;
19946 lodash.union = union;
19947 lodash.uniq = uniq;
19948 lodash.unzip = unzip;
19949 lodash.unzipWith = unzipWith;
19950 lodash.values = values;
19951 lodash.valuesIn = valuesIn;
19952 lodash.where = where;
19953 lodash.without = without;
19954 lodash.wrap = wrap;
19955 lodash.xor = xor;
19956 lodash.zip = zip;
19957 lodash.zipObject = zipObject;
19958 lodash.zipWith = zipWith;
19959
19960 // Add aliases.
19961 lodash.backflow = flowRight;
19962 lodash.collect = map;
19963 lodash.compose = flowRight;
19964 lodash.each = forEach;
19965 lodash.eachRight = forEachRight;
19966 lodash.extend = assign;
19967 lodash.iteratee = callback;
19968 lodash.methods = functions;
19969 lodash.object = zipObject;
19970 lodash.select = filter;
19971 lodash.tail = rest;
19972 lodash.unique = uniq;
19973
19974 // Add functions to `lodash.prototype`.
19975 mixin(lodash, lodash);
19976
19977 /*------------------------------------------------------------------------*/
19978
19979 // Add functions that return unwrapped values when chaining.
19980 lodash.add = add;
19981 lodash.attempt = attempt;
19982 lodash.camelCase = camelCase;
19983 lodash.capitalize = capitalize;
19984 lodash.ceil = ceil;
19985 lodash.clone = clone;
19986 lodash.cloneDeep = cloneDeep;
19987 lodash.deburr = deburr;
19988 lodash.endsWith = endsWith;
19989 lodash.escape = escape;
19990 lodash.escapeRegExp = escapeRegExp;
19991 lodash.every = every;
19992 lodash.find = find;
19993 lodash.findIndex = findIndex;
19994 lodash.findKey = findKey;
19995 lodash.findLast = findLast;
19996 lodash.findLastIndex = findLastIndex;
19997 lodash.findLastKey = findLastKey;
19998 lodash.findWhere = findWhere;
19999 lodash.first = first;
20000 lodash.floor = floor;
20001 lodash.get = get;
20002 lodash.gt = gt;
20003 lodash.gte = gte;
20004 lodash.has = has;
20005 lodash.identity = identity;
20006 lodash.includes = includes;
20007 lodash.indexOf = indexOf;
20008 lodash.inRange = inRange;
20009 lodash.isArguments = isArguments;
20010 lodash.isArray = isArray;
20011 lodash.isBoolean = isBoolean;
20012 lodash.isDate = isDate;
20013 lodash.isElement = isElement;
20014 lodash.isEmpty = isEmpty;
20015 lodash.isEqual = isEqual;
20016 lodash.isError = isError;
20017 lodash.isFinite = isFinite;
20018 lodash.isFunction = isFunction;
20019 lodash.isMatch = isMatch;
20020 lodash.isNaN = isNaN;
20021 lodash.isNative = isNative;
20022 lodash.isNull = isNull;
20023 lodash.isNumber = isNumber;
20024 lodash.isObject = isObject;
20025 lodash.isPlainObject = isPlainObject;
20026 lodash.isRegExp = isRegExp;
20027 lodash.isString = isString;
20028 lodash.isTypedArray = isTypedArray;
20029 lodash.isUndefined = isUndefined;
20030 lodash.kebabCase = kebabCase;
20031 lodash.last = last;
20032 lodash.lastIndexOf = lastIndexOf;
20033 lodash.lt = lt;
20034 lodash.lte = lte;
20035 lodash.max = max;
20036 lodash.min = min;
20037 lodash.noConflict = noConflict;
20038 lodash.noop = noop;
20039 lodash.now = now;
20040 lodash.pad = pad;
20041 lodash.padLeft = padLeft;
20042 lodash.padRight = padRight;
20043 lodash.parseInt = parseInt;
20044 lodash.random = random;
20045 lodash.reduce = reduce;
20046 lodash.reduceRight = reduceRight;
20047 lodash.repeat = repeat;
20048 lodash.result = result;
20049 lodash.round = round;
20050 lodash.runInContext = runInContext;
20051 lodash.size = size;
20052 lodash.snakeCase = snakeCase;
20053 lodash.some = some;
20054 lodash.sortedIndex = sortedIndex;
20055 lodash.sortedLastIndex = sortedLastIndex;
20056 lodash.startCase = startCase;
20057 lodash.startsWith = startsWith;
20058 lodash.sum = sum;
20059 lodash.template = template;
20060 lodash.trim = trim;
20061 lodash.trimLeft = trimLeft;
20062 lodash.trimRight = trimRight;
20063 lodash.trunc = trunc;
20064 lodash.unescape = unescape;
20065 lodash.uniqueId = uniqueId;
20066 lodash.words = words;
20067
20068 // Add aliases.
20069 lodash.all = every;
20070 lodash.any = some;
20071 lodash.contains = includes;
20072 lodash.eq = isEqual;
20073 lodash.detect = find;
20074 lodash.foldl = reduce;
20075 lodash.foldr = reduceRight;
20076 lodash.head = first;
20077 lodash.include = includes;
20078 lodash.inject = reduce;
20079
20080 mixin(lodash, (function() {
20081 var source = {};
20082 baseForOwn(lodash, function(func, methodName) {
20083 if (!lodash.prototype[methodName]) {
20084 source[methodName] = func;
20085 }
20086 });
20087 return source;
20088 }()), false);
20089
20090 /*------------------------------------------------------------------------*/
20091
20092 // Add functions capable of returning wrapped and unwrapped values when chaining.
20093 lodash.sample = sample;
20094
20095 lodash.prototype.sample = function(n) {
20096 if (!this.__chain__ && n == null) {
20097 return sample(this.value());
20098 }
20099 return this.thru(function(value) {
20100 return sample(value, n);
20101 });
20102 };
20103
20104 /*------------------------------------------------------------------------*/
20105
20106 /**
20107 * The semantic version number.
20108 *
20109 * @static
20110 * @memberOf _
20111 * @type string
20112 */
20113 lodash.VERSION = VERSION;
20114
20115 // Assign default placeholders.
20116 arrayEach(['bind', 'bindKey', 'curry', 'curryRight', 'partial', 'partialRight'], function(methodName) {
20117 lodash[methodName].placeholder = lodash;
20118 });
20119
20120 // Add `LazyWrapper` methods for `_.drop` and `_.take` variants.
20121 arrayEach(['drop', 'take'], function(methodName, index) {
20122 LazyWrapper.prototype[methodName] = function(n) {
20123 var filtered = this.__filtered__;
20124 if (filtered && !index) {
20125 return new LazyWrapper(this);
20126 }
20127 n = n == null ? 1 : nativeMax(nativeFloor(n) || 0, 0);
20128
20129 var result = this.clone();
20130 if (filtered) {
20131 result.__takeCount__ = nativeMin(result.__takeCount__, n);
20132 } else {
20133 result.__views__.push({ 'size': n, 'type': methodName + (result.__dir__ < 0 ? 'Right' : '') });
20134 }
20135 return result;
20136 };
20137
20138 LazyWrapper.prototype[methodName + 'Right'] = function(n) {
20139 return this.reverse()[methodName](n).reverse();
20140 };
20141 });
20142
20143 // Add `LazyWrapper` methods that accept an `iteratee` value.
20144 arrayEach(['filter', 'map', 'takeWhile'], function(methodName, index) {
20145 var type = index + 1,
20146 isFilter = type != LAZY_MAP_FLAG;
20147
20148 LazyWrapper.prototype[methodName] = function(iteratee, thisArg) {
20149 var result = this.clone();
20150 result.__iteratees__.push({ 'iteratee': getCallback(iteratee, thisArg, 1), 'type': type });
20151 result.__filtered__ = result.__filtered__ || isFilter;
20152 return result;
20153 };
20154 });
20155
20156 // Add `LazyWrapper` methods for `_.first` and `_.last`.
20157 arrayEach(['first', 'last'], function(methodName, index) {
20158 var takeName = 'take' + (index ? 'Right' : '');
20159
20160 LazyWrapper.prototype[methodName] = function() {
20161 return this[takeName](1).value()[0];
20162 };
20163 });
20164
20165 // Add `LazyWrapper` methods for `_.initial` and `_.rest`.
20166 arrayEach(['initial', 'rest'], function(methodName, index) {
20167 var dropName = 'drop' + (index ? '' : 'Right');
20168
20169 LazyWrapper.prototype[methodName] = function() {
20170 return this.__filtered__ ? new LazyWrapper(this) : this[dropName](1);
20171 };
20172 });
20173
20174 // Add `LazyWrapper` methods for `_.pluck` and `_.where`.
20175 arrayEach(['pluck', 'where'], function(methodName, index) {
20176 var operationName = index ? 'filter' : 'map',
20177 createCallback = index ? baseMatches : property;
20178
20179 LazyWrapper.prototype[methodName] = function(value) {
20180 return this[operationName](createCallback(value));
20181 };
20182 });
20183
20184 LazyWrapper.prototype.compact = function() {
20185 return this.filter(identity);
20186 };
20187
20188 LazyWrapper.prototype.reject = function(predicate, thisArg) {
20189 predicate = getCallback(predicate, thisArg, 1);
20190 return this.filter(function(value) {
20191 return !predicate(value);
20192 });
20193 };
20194
20195 LazyWrapper.prototype.slice = function(start, end) {
20196 start = start == null ? 0 : (+start || 0);
20197
20198 var result = this;
20199 if (result.__filtered__ && (start > 0 || end < 0)) {
20200 return new LazyWrapper(result);
20201 }
20202 if (start < 0) {
20203 result = result.takeRight(-start);
20204 } else if (start) {
20205 result = result.drop(start);
20206 }
20207 if (end !== undefined) {
20208 end = (+end || 0);
20209 result = end < 0 ? result.dropRight(-end) : result.take(end - start);
20210 }
20211 return result;
20212 };
20213
20214 LazyWrapper.prototype.takeRightWhile = function(predicate, thisArg) {
20215 return this.reverse().takeWhile(predicate, thisArg).reverse();
20216 };
20217
20218 LazyWrapper.prototype.toArray = function() {
20219 return this.take(POSITIVE_INFINITY);
20220 };
20221
20222 // Add `LazyWrapper` methods to `lodash.prototype`.
20223 baseForOwn(LazyWrapper.prototype, function(func, methodName) {
20224 var checkIteratee = /^(?:filter|map|reject)|While$/.test(methodName),
20225 retUnwrapped = /^(?:first|last)$/.test(methodName),
20226 lodashFunc = lodash[retUnwrapped ? ('take' + (methodName == 'last' ? 'Right' : '')) : methodName];
20227
20228 if (!lodashFunc) {
20229 return;
20230 }
20231 lodash.prototype[methodName] = function() {
20232 var args = retUnwrapped ? [1] : arguments,
20233 chainAll = this.__chain__,
20234 value = this.__wrapped__,
20235 isHybrid = !!this.__actions__.length,
20236 isLazy = value instanceof LazyWrapper,
20237 iteratee = args[0],
20238 useLazy = isLazy || isArray(value);
20239
20240 if (useLazy && checkIteratee && typeof iteratee == 'function' && iteratee.length != 1) {
20241 // Avoid lazy use if the iteratee has a "length" value other than `1`.
20242 isLazy = useLazy = false;
20243 }
20244 var interceptor = function(value) {
20245 return (retUnwrapped && chainAll)
20246 ? lodashFunc(value, 1)[0]
20247 : lodashFunc.apply(undefined, arrayPush([value], args));
20248 };
20249
20250 var action = { 'func': thru, 'args': [interceptor], 'thisArg': undefined },
20251 onlyLazy = isLazy && !isHybrid;
20252
20253 if (retUnwrapped && !chainAll) {
20254 if (onlyLazy) {
20255 value = value.clone();
20256 value.__actions__.push(action);
20257 return func.call(value);
20258 }
20259 return lodashFunc.call(undefined, this.value())[0];
20260 }
20261 if (!retUnwrapped && useLazy) {
20262 value = onlyLazy ? value : new LazyWrapper(this);
20263 var result = func.apply(value, args);
20264 result.__actions__.push(action);
20265 return new LodashWrapper(result, chainAll);
20266 }
20267 return this.thru(interceptor);
20268 };
20269 });
20270
20271 // Add `Array` and `String` methods to `lodash.prototype`.
20272 arrayEach(['join', 'pop', 'push', 'replace', 'shift', 'sort', 'splice', 'split', 'unshift'], function(methodName) {
20273 var func = (/^(?:replace|split)$/.test(methodName) ? stringProto : arrayProto)[methodName],
20274 chainName = /^(?:push|sort|unshift)$/.test(methodName) ? 'tap' : 'thru',
20275 retUnwrapped = /^(?:join|pop|replace|shift)$/.test(methodName);
20276
20277 lodash.prototype[methodName] = function() {
20278 var args = arguments;
20279 if (retUnwrapped && !this.__chain__) {
20280 return func.apply(this.value(), args);
20281 }
20282 return this[chainName](function(value) {
20283 return func.apply(value, args);
20284 });
20285 };
20286 });
20287
20288 // Map minified function names to their real names.
20289 baseForOwn(LazyWrapper.prototype, function(func, methodName) {
20290 var lodashFunc = lodash[methodName];
20291 if (lodashFunc) {
20292 var key = lodashFunc.name,
20293 names = realNames[key] || (realNames[key] = []);
20294
20295 names.push({ 'name': methodName, 'func': lodashFunc });
20296 }
20297 });
20298
20299 realNames[createHybridWrapper(undefined, BIND_KEY_FLAG).name] = [{ 'name': 'wrapper', 'func': undefined }];
20300
20301 // Add functions to the lazy wrapper.
20302 LazyWrapper.prototype.clone = lazyClone;
20303 LazyWrapper.prototype.reverse = lazyReverse;
20304 LazyWrapper.prototype.value = lazyValue;
20305
20306 // Add chaining functions to the `lodash` wrapper.
20307 lodash.prototype.chain = wrapperChain;
20308 lodash.prototype.commit = wrapperCommit;
20309 lodash.prototype.concat = wrapperConcat;
20310 lodash.prototype.plant = wrapperPlant;
20311 lodash.prototype.reverse = wrapperReverse;
20312 lodash.prototype.toString = wrapperToString;
20313 lodash.prototype.run = lodash.prototype.toJSON = lodash.prototype.valueOf = lodash.prototype.value = wrapperValue;
20314
20315 // Add function aliases to the `lodash` wrapper.
20316 lodash.prototype.collect = lodash.prototype.map;
20317 lodash.prototype.head = lodash.prototype.first;
20318 lodash.prototype.select = lodash.prototype.filter;
20319 lodash.prototype.tail = lodash.prototype.rest;
20320
20321 return lodash;
20322 }
20323
20324 /*--------------------------------------------------------------------------*/
20325
20326 // Export lodash.
20327 var _ = runInContext();
20328
20329 // Some AMD build optimizers like r.js check for condition patterns like the following:
20330 if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) {
20331 // Expose lodash to the global object when an AMD loader is present to avoid
20332 // errors in cases where lodash is loaded by a script tag and not intended
20333 // as an AMD module. See http://requirejs.org/docs/errors.html#mismatch for
20334 // more details.
20335 root._ = _;
20336
20337 // Define as an anonymous module so, through path mapping, it can be
20338 // referenced as the "underscore" module.
20339 define(function() {
20340 return _;
20341 });
20342 }
20343 // Check for `exports` after `define` in case a build optimizer adds an `exports` object.
20344 else if (freeExports && freeModule) {
20345 // Export for Node.js or RingoJS.
20346 if (moduleExports) {
20347 (freeModule.exports = _)._ = _;
20348 }
20349 // Export for Rhino with CommonJS support.
20350 else {
20351 freeExports._ = _;
20352 }
20353 }
20354 else {
20355 // Export for a browser or Rhino.
20356 root._ = _;
20357 }
20358}.call(this));
20359
20360}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
20361},{}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/lib/index.js":[function(require,module,exports){
20362
20363/**
20364 * Module dependencies.
20365 */
20366
20367var url = require('./url');
20368var parser = require('socket.io-parser');
20369var Manager = require('./manager');
20370var debug = require('debug')('socket.io-client');
20371
20372/**
20373 * Module exports.
20374 */
20375
20376module.exports = exports = lookup;
20377
20378/**
20379 * Managers cache.
20380 */
20381
20382var cache = exports.managers = {};
20383
20384/**
20385 * Looks up an existing `Manager` for multiplexing.
20386 * If the user summons:
20387 *
20388 * `io('http://localhost/a');`
20389 * `io('http://localhost/b');`
20390 *
20391 * We reuse the existing instance based on same scheme/port/host,
20392 * and we initialize sockets for each namespace.
20393 *
20394 * @api public
20395 */
20396
20397function lookup(uri, opts) {
20398 if (typeof uri == 'object') {
20399 opts = uri;
20400 uri = undefined;
20401 }
20402
20403 opts = opts || {};
20404
20405 var parsed = url(uri);
20406 var source = parsed.source;
20407 var id = parsed.id;
20408 var path = parsed.path;
20409 var sameNamespace = cache[id] && path in cache[id].nsps;
20410 var newConnection = opts.forceNew || opts['force new connection'] ||
20411 false === opts.multiplex || sameNamespace;
20412
20413 var io;
20414
20415 if (newConnection) {
20416 debug('ignoring socket cache for %s', source);
20417 io = Manager(source, opts);
20418 } else {
20419 if (!cache[id]) {
20420 debug('new io instance for %s', source);
20421 cache[id] = Manager(source, opts);
20422 }
20423 io = cache[id];
20424 }
20425
20426 return io.socket(parsed.path);
20427}
20428
20429/**
20430 * Protocol version.
20431 *
20432 * @api public
20433 */
20434
20435exports.protocol = parser.protocol;
20436
20437/**
20438 * `connect`.
20439 *
20440 * @param {String} uri
20441 * @api public
20442 */
20443
20444exports.connect = lookup;
20445
20446/**
20447 * Expose constructors for standalone build.
20448 *
20449 * @api public
20450 */
20451
20452exports.Manager = require('./manager');
20453exports.Socket = require('./socket');
20454
20455},{"./manager":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/lib/manager.js","./socket":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/lib/socket.js","./url":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/lib/url.js","debug":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/debug/browser.js","socket.io-parser":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/socket.io-parser/index.js"}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/lib/manager.js":[function(require,module,exports){
20456
20457/**
20458 * Module dependencies.
20459 */
20460
20461var eio = require('engine.io-client');
20462var Socket = require('./socket');
20463var Emitter = require('component-emitter');
20464var parser = require('socket.io-parser');
20465var on = require('./on');
20466var bind = require('component-bind');
20467var debug = require('debug')('socket.io-client:manager');
20468var indexOf = require('indexof');
20469var Backoff = require('backo2');
20470
20471/**
20472 * IE6+ hasOwnProperty
20473 */
20474
20475var has = Object.prototype.hasOwnProperty;
20476
20477/**
20478 * Module exports
20479 */
20480
20481module.exports = Manager;
20482
20483/**
20484 * `Manager` constructor.
20485 *
20486 * @param {String} engine instance or engine uri/opts
20487 * @param {Object} options
20488 * @api public
20489 */
20490
20491function Manager(uri, opts){
20492 if (!(this instanceof Manager)) return new Manager(uri, opts);
20493 if (uri && ('object' == typeof uri)) {
20494 opts = uri;
20495 uri = undefined;
20496 }
20497 opts = opts || {};
20498
20499 opts.path = opts.path || '/socket.io';
20500 this.nsps = {};
20501 this.subs = [];
20502 this.opts = opts;
20503 this.reconnection(opts.reconnection !== false);
20504 this.reconnectionAttempts(opts.reconnectionAttempts || Infinity);
20505 this.reconnectionDelay(opts.reconnectionDelay || 1000);
20506 this.reconnectionDelayMax(opts.reconnectionDelayMax || 5000);
20507 this.randomizationFactor(opts.randomizationFactor || 0.5);
20508 this.backoff = new Backoff({
20509 min: this.reconnectionDelay(),
20510 max: this.reconnectionDelayMax(),
20511 jitter: this.randomizationFactor()
20512 });
20513 this.timeout(null == opts.timeout ? 20000 : opts.timeout);
20514 this.readyState = 'closed';
20515 this.uri = uri;
20516 this.connecting = [];
20517 this.lastPing = null;
20518 this.encoding = false;
20519 this.packetBuffer = [];
20520 this.encoder = new parser.Encoder();
20521 this.decoder = new parser.Decoder();
20522 this.autoConnect = opts.autoConnect !== false;
20523 if (this.autoConnect) this.open();
20524}
20525
20526/**
20527 * Propagate given event to sockets and emit on `this`
20528 *
20529 * @api private
20530 */
20531
20532Manager.prototype.emitAll = function() {
20533 this.emit.apply(this, arguments);
20534 for (var nsp in this.nsps) {
20535 if (has.call(this.nsps, nsp)) {
20536 this.nsps[nsp].emit.apply(this.nsps[nsp], arguments);
20537 }
20538 }
20539};
20540
20541/**
20542 * Update `socket.id` of all sockets
20543 *
20544 * @api private
20545 */
20546
20547Manager.prototype.updateSocketIds = function(){
20548 for (var nsp in this.nsps) {
20549 if (has.call(this.nsps, nsp)) {
20550 this.nsps[nsp].id = this.engine.id;
20551 }
20552 }
20553};
20554
20555/**
20556 * Mix in `Emitter`.
20557 */
20558
20559Emitter(Manager.prototype);
20560
20561/**
20562 * Sets the `reconnection` config.
20563 *
20564 * @param {Boolean} true/false if it should automatically reconnect
20565 * @return {Manager} self or value
20566 * @api public
20567 */
20568
20569Manager.prototype.reconnection = function(v){
20570 if (!arguments.length) return this._reconnection;
20571 this._reconnection = !!v;
20572 return this;
20573};
20574
20575/**
20576 * Sets the reconnection attempts config.
20577 *
20578 * @param {Number} max reconnection attempts before giving up
20579 * @return {Manager} self or value
20580 * @api public
20581 */
20582
20583Manager.prototype.reconnectionAttempts = function(v){
20584 if (!arguments.length) return this._reconnectionAttempts;
20585 this._reconnectionAttempts = v;
20586 return this;
20587};
20588
20589/**
20590 * Sets the delay between reconnections.
20591 *
20592 * @param {Number} delay
20593 * @return {Manager} self or value
20594 * @api public
20595 */
20596
20597Manager.prototype.reconnectionDelay = function(v){
20598 if (!arguments.length) return this._reconnectionDelay;
20599 this._reconnectionDelay = v;
20600 this.backoff && this.backoff.setMin(v);
20601 return this;
20602};
20603
20604Manager.prototype.randomizationFactor = function(v){
20605 if (!arguments.length) return this._randomizationFactor;
20606 this._randomizationFactor = v;
20607 this.backoff && this.backoff.setJitter(v);
20608 return this;
20609};
20610
20611/**
20612 * Sets the maximum delay between reconnections.
20613 *
20614 * @param {Number} delay
20615 * @return {Manager} self or value
20616 * @api public
20617 */
20618
20619Manager.prototype.reconnectionDelayMax = function(v){
20620 if (!arguments.length) return this._reconnectionDelayMax;
20621 this._reconnectionDelayMax = v;
20622 this.backoff && this.backoff.setMax(v);
20623 return this;
20624};
20625
20626/**
20627 * Sets the connection timeout. `false` to disable
20628 *
20629 * @return {Manager} self or value
20630 * @api public
20631 */
20632
20633Manager.prototype.timeout = function(v){
20634 if (!arguments.length) return this._timeout;
20635 this._timeout = v;
20636 return this;
20637};
20638
20639/**
20640 * Starts trying to reconnect if reconnection is enabled and we have not
20641 * started reconnecting yet
20642 *
20643 * @api private
20644 */
20645
20646Manager.prototype.maybeReconnectOnOpen = function() {
20647 // Only try to reconnect if it's the first time we're connecting
20648 if (!this.reconnecting && this._reconnection && this.backoff.attempts === 0) {
20649 // keeps reconnection from firing twice for the same reconnection loop
20650 this.reconnect();
20651 }
20652};
20653
20654
20655/**
20656 * Sets the current transport `socket`.
20657 *
20658 * @param {Function} optional, callback
20659 * @return {Manager} self
20660 * @api public
20661 */
20662
20663Manager.prototype.open =
20664Manager.prototype.connect = function(fn){
20665 debug('readyState %s', this.readyState);
20666 if (~this.readyState.indexOf('open')) return this;
20667
20668 debug('opening %s', this.uri);
20669 this.engine = eio(this.uri, this.opts);
20670 var socket = this.engine;
20671 var self = this;
20672 this.readyState = 'opening';
20673 this.skipReconnect = false;
20674
20675 // emit `open`
20676 var openSub = on(socket, 'open', function() {
20677 self.onopen();
20678 fn && fn();
20679 });
20680
20681 // emit `connect_error`
20682 var errorSub = on(socket, 'error', function(data){
20683 debug('connect_error');
20684 self.cleanup();
20685 self.readyState = 'closed';
20686 self.emitAll('connect_error', data);
20687 if (fn) {
20688 var err = new Error('Connection error');
20689 err.data = data;
20690 fn(err);
20691 } else {
20692 // Only do this if there is no fn to handle the error
20693 self.maybeReconnectOnOpen();
20694 }
20695 });
20696
20697 // emit `connect_timeout`
20698 if (false !== this._timeout) {
20699 var timeout = this._timeout;
20700 debug('connect attempt will timeout after %d', timeout);
20701
20702 // set timer
20703 var timer = setTimeout(function(){
20704 debug('connect attempt timed out after %d', timeout);
20705 openSub.destroy();
20706 socket.close();
20707 socket.emit('error', 'timeout');
20708 self.emitAll('connect_timeout', timeout);
20709 }, timeout);
20710
20711 this.subs.push({
20712 destroy: function(){
20713 clearTimeout(timer);
20714 }
20715 });
20716 }
20717
20718 this.subs.push(openSub);
20719 this.subs.push(errorSub);
20720
20721 return this;
20722};
20723
20724/**
20725 * Called upon transport open.
20726 *
20727 * @api private
20728 */
20729
20730Manager.prototype.onopen = function(){
20731 debug('open');
20732
20733 // clear old subs
20734 this.cleanup();
20735
20736 // mark as open
20737 this.readyState = 'open';
20738 this.emit('open');
20739
20740 // add new subs
20741 var socket = this.engine;
20742 this.subs.push(on(socket, 'data', bind(this, 'ondata')));
20743 this.subs.push(on(socket, 'ping', bind(this, 'onping')));
20744 this.subs.push(on(socket, 'pong', bind(this, 'onpong')));
20745 this.subs.push(on(socket, 'error', bind(this, 'onerror')));
20746 this.subs.push(on(socket, 'close', bind(this, 'onclose')));
20747 this.subs.push(on(this.decoder, 'decoded', bind(this, 'ondecoded')));
20748};
20749
20750/**
20751 * Called upon a ping.
20752 *
20753 * @api private
20754 */
20755
20756Manager.prototype.onping = function(){
20757 this.lastPing = new Date;
20758 this.emitAll('ping');
20759};
20760
20761/**
20762 * Called upon a packet.
20763 *
20764 * @api private
20765 */
20766
20767Manager.prototype.onpong = function(){
20768 this.emitAll('pong', new Date - this.lastPing);
20769};
20770
20771/**
20772 * Called with data.
20773 *
20774 * @api private
20775 */
20776
20777Manager.prototype.ondata = function(data){
20778 this.decoder.add(data);
20779};
20780
20781/**
20782 * Called when parser fully decodes a packet.
20783 *
20784 * @api private
20785 */
20786
20787Manager.prototype.ondecoded = function(packet) {
20788 this.emit('packet', packet);
20789};
20790
20791/**
20792 * Called upon socket error.
20793 *
20794 * @api private
20795 */
20796
20797Manager.prototype.onerror = function(err){
20798 debug('error', err);
20799 this.emitAll('error', err);
20800};
20801
20802/**
20803 * Creates a new socket for the given `nsp`.
20804 *
20805 * @return {Socket}
20806 * @api public
20807 */
20808
20809Manager.prototype.socket = function(nsp){
20810 var socket = this.nsps[nsp];
20811 if (!socket) {
20812 socket = new Socket(this, nsp);
20813 this.nsps[nsp] = socket;
20814 var self = this;
20815 socket.on('connecting', onConnecting);
20816 socket.on('connect', function(){
20817 socket.id = self.engine.id;
20818 });
20819
20820 if (this.autoConnect) {
20821 // manually call here since connecting evnet is fired before listening
20822 onConnecting();
20823 }
20824 }
20825
20826 function onConnecting() {
20827 if (!~indexOf(self.connecting, socket)) {
20828 self.connecting.push(socket);
20829 }
20830 }
20831
20832 return socket;
20833};
20834
20835/**
20836 * Called upon a socket close.
20837 *
20838 * @param {Socket} socket
20839 */
20840
20841Manager.prototype.destroy = function(socket){
20842 var index = indexOf(this.connecting, socket);
20843 if (~index) this.connecting.splice(index, 1);
20844 if (this.connecting.length) return;
20845
20846 this.close();
20847};
20848
20849/**
20850 * Writes a packet.
20851 *
20852 * @param {Object} packet
20853 * @api private
20854 */
20855
20856Manager.prototype.packet = function(packet){
20857 debug('writing packet %j', packet);
20858 var self = this;
20859
20860 if (!self.encoding) {
20861 // encode, then write to engine with result
20862 self.encoding = true;
20863 this.encoder.encode(packet, function(encodedPackets) {
20864 for (var i = 0; i < encodedPackets.length; i++) {
20865 self.engine.write(encodedPackets[i], packet.options);
20866 }
20867 self.encoding = false;
20868 self.processPacketQueue();
20869 });
20870 } else { // add packet to the queue
20871 self.packetBuffer.push(packet);
20872 }
20873};
20874
20875/**
20876 * If packet buffer is non-empty, begins encoding the
20877 * next packet in line.
20878 *
20879 * @api private
20880 */
20881
20882Manager.prototype.processPacketQueue = function() {
20883 if (this.packetBuffer.length > 0 && !this.encoding) {
20884 var pack = this.packetBuffer.shift();
20885 this.packet(pack);
20886 }
20887};
20888
20889/**
20890 * Clean up transport subscriptions and packet buffer.
20891 *
20892 * @api private
20893 */
20894
20895Manager.prototype.cleanup = function(){
20896 debug('cleanup');
20897
20898 var sub;
20899 while (sub = this.subs.shift()) sub.destroy();
20900
20901 this.packetBuffer = [];
20902 this.encoding = false;
20903 this.lastPing = null;
20904
20905 this.decoder.destroy();
20906};
20907
20908/**
20909 * Close the current socket.
20910 *
20911 * @api private
20912 */
20913
20914Manager.prototype.close =
20915Manager.prototype.disconnect = function(){
20916 debug('disconnect');
20917 this.skipReconnect = true;
20918 this.reconnecting = false;
20919 if ('opening' == this.readyState) {
20920 // `onclose` will not fire because
20921 // an open event never happened
20922 this.cleanup();
20923 }
20924 this.backoff.reset();
20925 this.readyState = 'closed';
20926 if (this.engine) this.engine.close();
20927};
20928
20929/**
20930 * Called upon engine close.
20931 *
20932 * @api private
20933 */
20934
20935Manager.prototype.onclose = function(reason){
20936 debug('onclose');
20937
20938 this.cleanup();
20939 this.backoff.reset();
20940 this.readyState = 'closed';
20941 this.emit('close', reason);
20942
20943 if (this._reconnection && !this.skipReconnect) {
20944 this.reconnect();
20945 }
20946};
20947
20948/**
20949 * Attempt a reconnection.
20950 *
20951 * @api private
20952 */
20953
20954Manager.prototype.reconnect = function(){
20955 if (this.reconnecting || this.skipReconnect) return this;
20956
20957 var self = this;
20958
20959 if (this.backoff.attempts >= this._reconnectionAttempts) {
20960 debug('reconnect failed');
20961 this.backoff.reset();
20962 this.emitAll('reconnect_failed');
20963 this.reconnecting = false;
20964 } else {
20965 var delay = this.backoff.duration();
20966 debug('will wait %dms before reconnect attempt', delay);
20967
20968 this.reconnecting = true;
20969 var timer = setTimeout(function(){
20970 if (self.skipReconnect) return;
20971
20972 debug('attempting reconnect');
20973 self.emitAll('reconnect_attempt', self.backoff.attempts);
20974 self.emitAll('reconnecting', self.backoff.attempts);
20975
20976 // check again for the case socket closed in above events
20977 if (self.skipReconnect) return;
20978
20979 self.open(function(err){
20980 if (err) {
20981 debug('reconnect attempt error');
20982 self.reconnecting = false;
20983 self.reconnect();
20984 self.emitAll('reconnect_error', err.data);
20985 } else {
20986 debug('reconnect success');
20987 self.onreconnect();
20988 }
20989 });
20990 }, delay);
20991
20992 this.subs.push({
20993 destroy: function(){
20994 clearTimeout(timer);
20995 }
20996 });
20997 }
20998};
20999
21000/**
21001 * Called upon successful reconnect.
21002 *
21003 * @api private
21004 */
21005
21006Manager.prototype.onreconnect = function(){
21007 var attempt = this.backoff.attempts;
21008 this.reconnecting = false;
21009 this.backoff.reset();
21010 this.updateSocketIds();
21011 this.emitAll('reconnect', attempt);
21012};
21013
21014},{"./on":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/lib/on.js","./socket":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/lib/socket.js","backo2":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/backo2/index.js","component-bind":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/component-bind/index.js","component-emitter":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/component-emitter/index.js","debug":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/debug/browser.js","engine.io-client":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/index.js","indexof":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/indexof/index.js","socket.io-parser":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/socket.io-parser/index.js"}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/lib/on.js":[function(require,module,exports){
21015
21016/**
21017 * Module exports.
21018 */
21019
21020module.exports = on;
21021
21022/**
21023 * Helper for subscriptions.
21024 *
21025 * @param {Object|EventEmitter} obj with `Emitter` mixin or `EventEmitter`
21026 * @param {String} event name
21027 * @param {Function} callback
21028 * @api public
21029 */
21030
21031function on(obj, ev, fn) {
21032 obj.on(ev, fn);
21033 return {
21034 destroy: function(){
21035 obj.removeListener(ev, fn);
21036 }
21037 };
21038}
21039
21040},{}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/lib/socket.js":[function(require,module,exports){
21041
21042/**
21043 * Module dependencies.
21044 */
21045
21046var parser = require('socket.io-parser');
21047var Emitter = require('component-emitter');
21048var toArray = require('to-array');
21049var on = require('./on');
21050var bind = require('component-bind');
21051var debug = require('debug')('socket.io-client:socket');
21052var hasBin = require('has-binary');
21053
21054/**
21055 * Module exports.
21056 */
21057
21058module.exports = exports = Socket;
21059
21060/**
21061 * Internal events (blacklisted).
21062 * These events can't be emitted by the user.
21063 *
21064 * @api private
21065 */
21066
21067var events = {
21068 connect: 1,
21069 connect_error: 1,
21070 connect_timeout: 1,
21071 connecting: 1,
21072 disconnect: 1,
21073 error: 1,
21074 reconnect: 1,
21075 reconnect_attempt: 1,
21076 reconnect_failed: 1,
21077 reconnect_error: 1,
21078 reconnecting: 1,
21079 ping: 1,
21080 pong: 1
21081};
21082
21083/**
21084 * Shortcut to `Emitter#emit`.
21085 */
21086
21087var emit = Emitter.prototype.emit;
21088
21089/**
21090 * `Socket` constructor.
21091 *
21092 * @api public
21093 */
21094
21095function Socket(io, nsp){
21096 this.io = io;
21097 this.nsp = nsp;
21098 this.json = this; // compat
21099 this.ids = 0;
21100 this.acks = {};
21101 this.receiveBuffer = [];
21102 this.sendBuffer = [];
21103 this.connected = false;
21104 this.disconnected = true;
21105 if (this.io.autoConnect) this.open();
21106}
21107
21108/**
21109 * Mix in `Emitter`.
21110 */
21111
21112Emitter(Socket.prototype);
21113
21114/**
21115 * Subscribe to open, close and packet events
21116 *
21117 * @api private
21118 */
21119
21120Socket.prototype.subEvents = function() {
21121 if (this.subs) return;
21122
21123 var io = this.io;
21124 this.subs = [
21125 on(io, 'open', bind(this, 'onopen')),
21126 on(io, 'packet', bind(this, 'onpacket')),
21127 on(io, 'close', bind(this, 'onclose'))
21128 ];
21129};
21130
21131/**
21132 * "Opens" the socket.
21133 *
21134 * @api public
21135 */
21136
21137Socket.prototype.open =
21138Socket.prototype.connect = function(){
21139 if (this.connected) return this;
21140
21141 this.subEvents();
21142 this.io.open(); // ensure open
21143 if ('open' == this.io.readyState) this.onopen();
21144 this.emit('connecting');
21145 return this;
21146};
21147
21148/**
21149 * Sends a `message` event.
21150 *
21151 * @return {Socket} self
21152 * @api public
21153 */
21154
21155Socket.prototype.send = function(){
21156 var args = toArray(arguments);
21157 args.unshift('message');
21158 this.emit.apply(this, args);
21159 return this;
21160};
21161
21162/**
21163 * Override `emit`.
21164 * If the event is in `events`, it's emitted normally.
21165 *
21166 * @param {String} event name
21167 * @return {Socket} self
21168 * @api public
21169 */
21170
21171Socket.prototype.emit = function(ev){
21172 if (events.hasOwnProperty(ev)) {
21173 emit.apply(this, arguments);
21174 return this;
21175 }
21176
21177 var args = toArray(arguments);
21178 var parserType = parser.EVENT; // default
21179 if (hasBin(args)) { parserType = parser.BINARY_EVENT; } // binary
21180 var packet = { type: parserType, data: args };
21181
21182 packet.options = {};
21183 packet.options.compress = !this.flags || false !== this.flags.compress;
21184
21185 // event ack callback
21186 if ('function' == typeof args[args.length - 1]) {
21187 debug('emitting packet with ack id %d', this.ids);
21188 this.acks[this.ids] = args.pop();
21189 packet.id = this.ids++;
21190 }
21191
21192 if (this.connected) {
21193 this.packet(packet);
21194 } else {
21195 this.sendBuffer.push(packet);
21196 }
21197
21198 delete this.flags;
21199
21200 return this;
21201};
21202
21203/**
21204 * Sends a packet.
21205 *
21206 * @param {Object} packet
21207 * @api private
21208 */
21209
21210Socket.prototype.packet = function(packet){
21211 packet.nsp = this.nsp;
21212 this.io.packet(packet);
21213};
21214
21215/**
21216 * Called upon engine `open`.
21217 *
21218 * @api private
21219 */
21220
21221Socket.prototype.onopen = function(){
21222 debug('transport is open - connecting');
21223
21224 // write connect packet if necessary
21225 if ('/' != this.nsp) {
21226 this.packet({ type: parser.CONNECT });
21227 }
21228};
21229
21230/**
21231 * Called upon engine `close`.
21232 *
21233 * @param {String} reason
21234 * @api private
21235 */
21236
21237Socket.prototype.onclose = function(reason){
21238 debug('close (%s)', reason);
21239 this.connected = false;
21240 this.disconnected = true;
21241 delete this.id;
21242 this.emit('disconnect', reason);
21243};
21244
21245/**
21246 * Called with socket packet.
21247 *
21248 * @param {Object} packet
21249 * @api private
21250 */
21251
21252Socket.prototype.onpacket = function(packet){
21253 if (packet.nsp != this.nsp) return;
21254
21255 switch (packet.type) {
21256 case parser.CONNECT:
21257 this.onconnect();
21258 break;
21259
21260 case parser.EVENT:
21261 this.onevent(packet);
21262 break;
21263
21264 case parser.BINARY_EVENT:
21265 this.onevent(packet);
21266 break;
21267
21268 case parser.ACK:
21269 this.onack(packet);
21270 break;
21271
21272 case parser.BINARY_ACK:
21273 this.onack(packet);
21274 break;
21275
21276 case parser.DISCONNECT:
21277 this.ondisconnect();
21278 break;
21279
21280 case parser.ERROR:
21281 this.emit('error', packet.data);
21282 break;
21283 }
21284};
21285
21286/**
21287 * Called upon a server event.
21288 *
21289 * @param {Object} packet
21290 * @api private
21291 */
21292
21293Socket.prototype.onevent = function(packet){
21294 var args = packet.data || [];
21295 debug('emitting event %j', args);
21296
21297 if (null != packet.id) {
21298 debug('attaching ack callback to event');
21299 args.push(this.ack(packet.id));
21300 }
21301
21302 if (this.connected) {
21303 emit.apply(this, args);
21304 } else {
21305 this.receiveBuffer.push(args);
21306 }
21307};
21308
21309/**
21310 * Produces an ack callback to emit with an event.
21311 *
21312 * @api private
21313 */
21314
21315Socket.prototype.ack = function(id){
21316 var self = this;
21317 var sent = false;
21318 return function(){
21319 // prevent double callbacks
21320 if (sent) return;
21321 sent = true;
21322 var args = toArray(arguments);
21323 debug('sending ack %j', args);
21324
21325 var type = hasBin(args) ? parser.BINARY_ACK : parser.ACK;
21326 self.packet({
21327 type: type,
21328 id: id,
21329 data: args
21330 });
21331 };
21332};
21333
21334/**
21335 * Called upon a server acknowlegement.
21336 *
21337 * @param {Object} packet
21338 * @api private
21339 */
21340
21341Socket.prototype.onack = function(packet){
21342 var ack = this.acks[packet.id];
21343 if ('function' == typeof ack) {
21344 debug('calling ack %s with %j', packet.id, packet.data);
21345 ack.apply(this, packet.data);
21346 delete this.acks[packet.id];
21347 } else {
21348 debug('bad ack %s', packet.id);
21349 }
21350};
21351
21352/**
21353 * Called upon server connect.
21354 *
21355 * @api private
21356 */
21357
21358Socket.prototype.onconnect = function(){
21359 this.connected = true;
21360 this.disconnected = false;
21361 this.emit('connect');
21362 this.emitBuffered();
21363};
21364
21365/**
21366 * Emit buffered events (received and emitted).
21367 *
21368 * @api private
21369 */
21370
21371Socket.prototype.emitBuffered = function(){
21372 var i;
21373 for (i = 0; i < this.receiveBuffer.length; i++) {
21374 emit.apply(this, this.receiveBuffer[i]);
21375 }
21376 this.receiveBuffer = [];
21377
21378 for (i = 0; i < this.sendBuffer.length; i++) {
21379 this.packet(this.sendBuffer[i]);
21380 }
21381 this.sendBuffer = [];
21382};
21383
21384/**
21385 * Called upon server disconnect.
21386 *
21387 * @api private
21388 */
21389
21390Socket.prototype.ondisconnect = function(){
21391 debug('server disconnect (%s)', this.nsp);
21392 this.destroy();
21393 this.onclose('io server disconnect');
21394};
21395
21396/**
21397 * Called upon forced client/server side disconnections,
21398 * this method ensures the manager stops tracking us and
21399 * that reconnections don't get triggered for this.
21400 *
21401 * @api private.
21402 */
21403
21404Socket.prototype.destroy = function(){
21405 if (this.subs) {
21406 // clean subscriptions to avoid reconnections
21407 for (var i = 0; i < this.subs.length; i++) {
21408 this.subs[i].destroy();
21409 }
21410 this.subs = null;
21411 }
21412
21413 this.io.destroy(this);
21414};
21415
21416/**
21417 * Disconnects the socket manually.
21418 *
21419 * @return {Socket} self
21420 * @api public
21421 */
21422
21423Socket.prototype.close =
21424Socket.prototype.disconnect = function(){
21425 if (this.connected) {
21426 debug('performing disconnect (%s)', this.nsp);
21427 this.packet({ type: parser.DISCONNECT });
21428 }
21429
21430 // remove socket from pool
21431 this.destroy();
21432
21433 if (this.connected) {
21434 // fire events
21435 this.onclose('io client disconnect');
21436 }
21437 return this;
21438};
21439
21440/**
21441 * Sets the compress flag.
21442 *
21443 * @param {Boolean} if `true`, compresses the sending data
21444 * @return {Socket} self
21445 * @api public
21446 */
21447
21448Socket.prototype.compress = function(compress){
21449 this.flags = this.flags || {};
21450 this.flags.compress = compress;
21451 return this;
21452};
21453
21454},{"./on":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/lib/on.js","component-bind":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/component-bind/index.js","component-emitter":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/component-emitter/index.js","debug":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/debug/browser.js","has-binary":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/has-binary/index.js","socket.io-parser":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/socket.io-parser/index.js","to-array":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/to-array/index.js"}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/lib/url.js":[function(require,module,exports){
21455(function (global){
21456
21457/**
21458 * Module dependencies.
21459 */
21460
21461var parseuri = require('parseuri');
21462var debug = require('debug')('socket.io-client:url');
21463
21464/**
21465 * Module exports.
21466 */
21467
21468module.exports = url;
21469
21470/**
21471 * URL parser.
21472 *
21473 * @param {String} url
21474 * @param {Object} An object meant to mimic window.location.
21475 * Defaults to window.location.
21476 * @api public
21477 */
21478
21479function url(uri, loc){
21480 var obj = uri;
21481
21482 // default to window.location
21483 var loc = loc || global.location;
21484 if (null == uri) uri = loc.protocol + '//' + loc.host;
21485
21486 // relative path support
21487 if ('string' == typeof uri) {
21488 if ('/' == uri.charAt(0)) {
21489 if ('/' == uri.charAt(1)) {
21490 uri = loc.protocol + uri;
21491 } else {
21492 uri = loc.host + uri;
21493 }
21494 }
21495
21496 if (!/^(https?|wss?):\/\//.test(uri)) {
21497 debug('protocol-less url %s', uri);
21498 if ('undefined' != typeof loc) {
21499 uri = loc.protocol + '//' + uri;
21500 } else {
21501 uri = 'https://' + uri;
21502 }
21503 }
21504
21505 // parse
21506 debug('parse %s', uri);
21507 obj = parseuri(uri);
21508 }
21509
21510 // make sure we treat `localhost:80` and `localhost` equally
21511 if (!obj.port) {
21512 if (/^(http|ws)$/.test(obj.protocol)) {
21513 obj.port = '80';
21514 }
21515 else if (/^(http|ws)s$/.test(obj.protocol)) {
21516 obj.port = '443';
21517 }
21518 }
21519
21520 obj.path = obj.path || '/';
21521
21522 var ipv6 = obj.host.indexOf(':') !== -1;
21523 var host = ipv6 ? '[' + obj.host + ']' : obj.host;
21524
21525 // define unique id
21526 obj.id = obj.protocol + '://' + host + ':' + obj.port;
21527 // define href
21528 obj.href = obj.protocol + '://' + host + (loc && loc.port == obj.port ? '' : (':' + obj.port));
21529
21530 return obj;
21531}
21532
21533}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
21534},{"debug":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/debug/browser.js","parseuri":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/parseuri/index.js"}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/backo2/index.js":[function(require,module,exports){
21535
21536/**
21537 * Expose `Backoff`.
21538 */
21539
21540module.exports = Backoff;
21541
21542/**
21543 * Initialize backoff timer with `opts`.
21544 *
21545 * - `min` initial timeout in milliseconds [100]
21546 * - `max` max timeout [10000]
21547 * - `jitter` [0]
21548 * - `factor` [2]
21549 *
21550 * @param {Object} opts
21551 * @api public
21552 */
21553
21554function Backoff(opts) {
21555 opts = opts || {};
21556 this.ms = opts.min || 100;
21557 this.max = opts.max || 10000;
21558 this.factor = opts.factor || 2;
21559 this.jitter = opts.jitter > 0 && opts.jitter <= 1 ? opts.jitter : 0;
21560 this.attempts = 0;
21561}
21562
21563/**
21564 * Return the backoff duration.
21565 *
21566 * @return {Number}
21567 * @api public
21568 */
21569
21570Backoff.prototype.duration = function(){
21571 var ms = this.ms * Math.pow(this.factor, this.attempts++);
21572 if (this.jitter) {
21573 var rand = Math.random();
21574 var deviation = Math.floor(rand * this.jitter * ms);
21575 ms = (Math.floor(rand * 10) & 1) == 0 ? ms - deviation : ms + deviation;
21576 }
21577 return Math.min(ms, this.max) | 0;
21578};
21579
21580/**
21581 * Reset the number of attempts.
21582 *
21583 * @api public
21584 */
21585
21586Backoff.prototype.reset = function(){
21587 this.attempts = 0;
21588};
21589
21590/**
21591 * Set the minimum duration
21592 *
21593 * @api public
21594 */
21595
21596Backoff.prototype.setMin = function(min){
21597 this.ms = min;
21598};
21599
21600/**
21601 * Set the maximum duration
21602 *
21603 * @api public
21604 */
21605
21606Backoff.prototype.setMax = function(max){
21607 this.max = max;
21608};
21609
21610/**
21611 * Set the jitter
21612 *
21613 * @api public
21614 */
21615
21616Backoff.prototype.setJitter = function(jitter){
21617 this.jitter = jitter;
21618};
21619
21620
21621},{}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/component-bind/index.js":[function(require,module,exports){
21622/**
21623 * Slice reference.
21624 */
21625
21626var slice = [].slice;
21627
21628/**
21629 * Bind `obj` to `fn`.
21630 *
21631 * @param {Object} obj
21632 * @param {Function|String} fn or string
21633 * @return {Function}
21634 * @api public
21635 */
21636
21637module.exports = function(obj, fn){
21638 if ('string' == typeof fn) fn = obj[fn];
21639 if ('function' != typeof fn) throw new Error('bind() requires a function');
21640 var args = slice.call(arguments, 2);
21641 return function(){
21642 return fn.apply(obj, args.concat(slice.call(arguments)));
21643 }
21644};
21645
21646},{}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/component-emitter/index.js":[function(require,module,exports){
21647
21648/**
21649 * Expose `Emitter`.
21650 */
21651
21652module.exports = Emitter;
21653
21654/**
21655 * Initialize a new `Emitter`.
21656 *
21657 * @api public
21658 */
21659
21660function Emitter(obj) {
21661 if (obj) return mixin(obj);
21662};
21663
21664/**
21665 * Mixin the emitter properties.
21666 *
21667 * @param {Object} obj
21668 * @return {Object}
21669 * @api private
21670 */
21671
21672function mixin(obj) {
21673 for (var key in Emitter.prototype) {
21674 obj[key] = Emitter.prototype[key];
21675 }
21676 return obj;
21677}
21678
21679/**
21680 * Listen on the given `event` with `fn`.
21681 *
21682 * @param {String} event
21683 * @param {Function} fn
21684 * @return {Emitter}
21685 * @api public
21686 */
21687
21688Emitter.prototype.on =
21689Emitter.prototype.addEventListener = function(event, fn){
21690 this._callbacks = this._callbacks || {};
21691 (this._callbacks['$' + event] = this._callbacks['$' + event] || [])
21692 .push(fn);
21693 return this;
21694};
21695
21696/**
21697 * Adds an `event` listener that will be invoked a single
21698 * time then automatically removed.
21699 *
21700 * @param {String} event
21701 * @param {Function} fn
21702 * @return {Emitter}
21703 * @api public
21704 */
21705
21706Emitter.prototype.once = function(event, fn){
21707 function on() {
21708 this.off(event, on);
21709 fn.apply(this, arguments);
21710 }
21711
21712 on.fn = fn;
21713 this.on(event, on);
21714 return this;
21715};
21716
21717/**
21718 * Remove the given callback for `event` or all
21719 * registered callbacks.
21720 *
21721 * @param {String} event
21722 * @param {Function} fn
21723 * @return {Emitter}
21724 * @api public
21725 */
21726
21727Emitter.prototype.off =
21728Emitter.prototype.removeListener =
21729Emitter.prototype.removeAllListeners =
21730Emitter.prototype.removeEventListener = function(event, fn){
21731 this._callbacks = this._callbacks || {};
21732
21733 // all
21734 if (0 == arguments.length) {
21735 this._callbacks = {};
21736 return this;
21737 }
21738
21739 // specific event
21740 var callbacks = this._callbacks['$' + event];
21741 if (!callbacks) return this;
21742
21743 // remove all handlers
21744 if (1 == arguments.length) {
21745 delete this._callbacks['$' + event];
21746 return this;
21747 }
21748
21749 // remove specific handler
21750 var cb;
21751 for (var i = 0; i < callbacks.length; i++) {
21752 cb = callbacks[i];
21753 if (cb === fn || cb.fn === fn) {
21754 callbacks.splice(i, 1);
21755 break;
21756 }
21757 }
21758 return this;
21759};
21760
21761/**
21762 * Emit `event` with the given args.
21763 *
21764 * @param {String} event
21765 * @param {Mixed} ...
21766 * @return {Emitter}
21767 */
21768
21769Emitter.prototype.emit = function(event){
21770 this._callbacks = this._callbacks || {};
21771 var args = [].slice.call(arguments, 1)
21772 , callbacks = this._callbacks['$' + event];
21773
21774 if (callbacks) {
21775 callbacks = callbacks.slice(0);
21776 for (var i = 0, len = callbacks.length; i < len; ++i) {
21777 callbacks[i].apply(this, args);
21778 }
21779 }
21780
21781 return this;
21782};
21783
21784/**
21785 * Return array of callbacks for `event`.
21786 *
21787 * @param {String} event
21788 * @return {Array}
21789 * @api public
21790 */
21791
21792Emitter.prototype.listeners = function(event){
21793 this._callbacks = this._callbacks || {};
21794 return this._callbacks['$' + event] || [];
21795};
21796
21797/**
21798 * Check if this emitter has `event` handlers.
21799 *
21800 * @param {String} event
21801 * @return {Boolean}
21802 * @api public
21803 */
21804
21805Emitter.prototype.hasListeners = function(event){
21806 return !! this.listeners(event).length;
21807};
21808
21809},{}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/debug/browser.js":[function(require,module,exports){
21810
21811/**
21812 * This is the web browser implementation of `debug()`.
21813 *
21814 * Expose `debug()` as the module.
21815 */
21816
21817exports = module.exports = require('./debug');
21818exports.log = log;
21819exports.formatArgs = formatArgs;
21820exports.save = save;
21821exports.load = load;
21822exports.useColors = useColors;
21823exports.storage = 'undefined' != typeof chrome
21824 && 'undefined' != typeof chrome.storage
21825 ? chrome.storage.local
21826 : localstorage();
21827
21828/**
21829 * Colors.
21830 */
21831
21832exports.colors = [
21833 'lightseagreen',
21834 'forestgreen',
21835 'goldenrod',
21836 'dodgerblue',
21837 'darkorchid',
21838 'crimson'
21839];
21840
21841/**
21842 * Currently only WebKit-based Web Inspectors, Firefox >= v31,
21843 * and the Firebug extension (any Firefox version) are known
21844 * to support "%c" CSS customizations.
21845 *
21846 * TODO: add a `localStorage` variable to explicitly enable/disable colors
21847 */
21848
21849function useColors() {
21850 // is webkit? http://stackoverflow.com/a/16459606/376773
21851 return ('WebkitAppearance' in document.documentElement.style) ||
21852 // is firebug? http://stackoverflow.com/a/398120/376773
21853 (window.console && (console.firebug || (console.exception && console.table))) ||
21854 // is firefox >= v31?
21855 // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
21856 (navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31);
21857}
21858
21859/**
21860 * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
21861 */
21862
21863exports.formatters.j = function(v) {
21864 return JSON.stringify(v);
21865};
21866
21867
21868/**
21869 * Colorize log arguments if enabled.
21870 *
21871 * @api public
21872 */
21873
21874function formatArgs() {
21875 var args = arguments;
21876 var useColors = this.useColors;
21877
21878 args[0] = (useColors ? '%c' : '')
21879 + this.namespace
21880 + (useColors ? ' %c' : ' ')
21881 + args[0]
21882 + (useColors ? '%c ' : ' ')
21883 + '+' + exports.humanize(this.diff);
21884
21885 if (!useColors) return args;
21886
21887 var c = 'color: ' + this.color;
21888 args = [args[0], c, 'color: inherit'].concat(Array.prototype.slice.call(args, 1));
21889
21890 // the final "%c" is somewhat tricky, because there could be other
21891 // arguments passed either before or after the %c, so we need to
21892 // figure out the correct index to insert the CSS into
21893 var index = 0;
21894 var lastC = 0;
21895 args[0].replace(/%[a-z%]/g, function(match) {
21896 if ('%%' === match) return;
21897 index++;
21898 if ('%c' === match) {
21899 // we only are interested in the *last* %c
21900 // (the user may have provided their own)
21901 lastC = index;
21902 }
21903 });
21904
21905 args.splice(lastC, 0, c);
21906 return args;
21907}
21908
21909/**
21910 * Invokes `console.log()` when available.
21911 * No-op when `console.log` is not a "function".
21912 *
21913 * @api public
21914 */
21915
21916function log() {
21917 // this hackery is required for IE8/9, where
21918 // the `console.log` function doesn't have 'apply'
21919 return 'object' === typeof console
21920 && console.log
21921 && Function.prototype.apply.call(console.log, console, arguments);
21922}
21923
21924/**
21925 * Save `namespaces`.
21926 *
21927 * @param {String} namespaces
21928 * @api private
21929 */
21930
21931function save(namespaces) {
21932 try {
21933 if (null == namespaces) {
21934 exports.storage.removeItem('debug');
21935 } else {
21936 exports.storage.debug = namespaces;
21937 }
21938 } catch(e) {}
21939}
21940
21941/**
21942 * Load `namespaces`.
21943 *
21944 * @return {String} returns the previously persisted debug modes
21945 * @api private
21946 */
21947
21948function load() {
21949 var r;
21950 try {
21951 r = exports.storage.debug;
21952 } catch(e) {}
21953 return r;
21954}
21955
21956/**
21957 * Enable namespaces listed in `localStorage.debug` initially.
21958 */
21959
21960exports.enable(load());
21961
21962/**
21963 * Localstorage attempts to return the localstorage.
21964 *
21965 * This is necessary because safari throws
21966 * when a user disables cookies/localstorage
21967 * and you attempt to access it.
21968 *
21969 * @return {LocalStorage}
21970 * @api private
21971 */
21972
21973function localstorage(){
21974 try {
21975 return window.localStorage;
21976 } catch (e) {}
21977}
21978
21979},{"./debug":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/debug/debug.js"}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/debug/debug.js":[function(require,module,exports){
21980
21981/**
21982 * This is the common logic for both the Node.js and web browser
21983 * implementations of `debug()`.
21984 *
21985 * Expose `debug()` as the module.
21986 */
21987
21988exports = module.exports = debug;
21989exports.coerce = coerce;
21990exports.disable = disable;
21991exports.enable = enable;
21992exports.enabled = enabled;
21993exports.humanize = require('ms');
21994
21995/**
21996 * The currently active debug mode names, and names to skip.
21997 */
21998
21999exports.names = [];
22000exports.skips = [];
22001
22002/**
22003 * Map of special "%n" handling functions, for the debug "format" argument.
22004 *
22005 * Valid key names are a single, lowercased letter, i.e. "n".
22006 */
22007
22008exports.formatters = {};
22009
22010/**
22011 * Previously assigned color.
22012 */
22013
22014var prevColor = 0;
22015
22016/**
22017 * Previous log timestamp.
22018 */
22019
22020var prevTime;
22021
22022/**
22023 * Select a color.
22024 *
22025 * @return {Number}
22026 * @api private
22027 */
22028
22029function selectColor() {
22030 return exports.colors[prevColor++ % exports.colors.length];
22031}
22032
22033/**
22034 * Create a debugger with the given `namespace`.
22035 *
22036 * @param {String} namespace
22037 * @return {Function}
22038 * @api public
22039 */
22040
22041function debug(namespace) {
22042
22043 // define the `disabled` version
22044 function disabled() {
22045 }
22046 disabled.enabled = false;
22047
22048 // define the `enabled` version
22049 function enabled() {
22050
22051 var self = enabled;
22052
22053 // set `diff` timestamp
22054 var curr = +new Date();
22055 var ms = curr - (prevTime || curr);
22056 self.diff = ms;
22057 self.prev = prevTime;
22058 self.curr = curr;
22059 prevTime = curr;
22060
22061 // add the `color` if not set
22062 if (null == self.useColors) self.useColors = exports.useColors();
22063 if (null == self.color && self.useColors) self.color = selectColor();
22064
22065 var args = Array.prototype.slice.call(arguments);
22066
22067 args[0] = exports.coerce(args[0]);
22068
22069 if ('string' !== typeof args[0]) {
22070 // anything else let's inspect with %o
22071 args = ['%o'].concat(args);
22072 }
22073
22074 // apply any `formatters` transformations
22075 var index = 0;
22076 args[0] = args[0].replace(/%([a-z%])/g, function(match, format) {
22077 // if we encounter an escaped % then don't increase the array index
22078 if (match === '%%') return match;
22079 index++;
22080 var formatter = exports.formatters[format];
22081 if ('function' === typeof formatter) {
22082 var val = args[index];
22083 match = formatter.call(self, val);
22084
22085 // now we need to remove `args[index]` since it's inlined in the `format`
22086 args.splice(index, 1);
22087 index--;
22088 }
22089 return match;
22090 });
22091
22092 if ('function' === typeof exports.formatArgs) {
22093 args = exports.formatArgs.apply(self, args);
22094 }
22095 var logFn = enabled.log || exports.log || console.log.bind(console);
22096 logFn.apply(self, args);
22097 }
22098 enabled.enabled = true;
22099
22100 var fn = exports.enabled(namespace) ? enabled : disabled;
22101
22102 fn.namespace = namespace;
22103
22104 return fn;
22105}
22106
22107/**
22108 * Enables a debug mode by namespaces. This can include modes
22109 * separated by a colon and wildcards.
22110 *
22111 * @param {String} namespaces
22112 * @api public
22113 */
22114
22115function enable(namespaces) {
22116 exports.save(namespaces);
22117
22118 var split = (namespaces || '').split(/[\s,]+/);
22119 var len = split.length;
22120
22121 for (var i = 0; i < len; i++) {
22122 if (!split[i]) continue; // ignore empty strings
22123 namespaces = split[i].replace(/\*/g, '.*?');
22124 if (namespaces[0] === '-') {
22125 exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
22126 } else {
22127 exports.names.push(new RegExp('^' + namespaces + '$'));
22128 }
22129 }
22130}
22131
22132/**
22133 * Disable debug output.
22134 *
22135 * @api public
22136 */
22137
22138function disable() {
22139 exports.enable('');
22140}
22141
22142/**
22143 * Returns true if the given mode name is enabled, false otherwise.
22144 *
22145 * @param {String} name
22146 * @return {Boolean}
22147 * @api public
22148 */
22149
22150function enabled(name) {
22151 var i, len;
22152 for (i = 0, len = exports.skips.length; i < len; i++) {
22153 if (exports.skips[i].test(name)) {
22154 return false;
22155 }
22156 }
22157 for (i = 0, len = exports.names.length; i < len; i++) {
22158 if (exports.names[i].test(name)) {
22159 return true;
22160 }
22161 }
22162 return false;
22163}
22164
22165/**
22166 * Coerce `val`.
22167 *
22168 * @param {Mixed} val
22169 * @return {Mixed}
22170 * @api private
22171 */
22172
22173function coerce(val) {
22174 if (val instanceof Error) return val.stack || val.message;
22175 return val;
22176}
22177
22178},{"ms":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/debug/node_modules/ms/index.js"}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/debug/node_modules/ms/index.js":[function(require,module,exports){
22179/**
22180 * Helpers.
22181 */
22182
22183var s = 1000;
22184var m = s * 60;
22185var h = m * 60;
22186var d = h * 24;
22187var y = d * 365.25;
22188
22189/**
22190 * Parse or format the given `val`.
22191 *
22192 * Options:
22193 *
22194 * - `long` verbose formatting [false]
22195 *
22196 * @param {String|Number} val
22197 * @param {Object} options
22198 * @return {String|Number}
22199 * @api public
22200 */
22201
22202module.exports = function(val, options){
22203 options = options || {};
22204 if ('string' == typeof val) return parse(val);
22205 return options.long
22206 ? long(val)
22207 : short(val);
22208};
22209
22210/**
22211 * Parse the given `str` and return milliseconds.
22212 *
22213 * @param {String} str
22214 * @return {Number}
22215 * @api private
22216 */
22217
22218function parse(str) {
22219 str = '' + str;
22220 if (str.length > 10000) return;
22221 var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(str);
22222 if (!match) return;
22223 var n = parseFloat(match[1]);
22224 var type = (match[2] || 'ms').toLowerCase();
22225 switch (type) {
22226 case 'years':
22227 case 'year':
22228 case 'yrs':
22229 case 'yr':
22230 case 'y':
22231 return n * y;
22232 case 'days':
22233 case 'day':
22234 case 'd':
22235 return n * d;
22236 case 'hours':
22237 case 'hour':
22238 case 'hrs':
22239 case 'hr':
22240 case 'h':
22241 return n * h;
22242 case 'minutes':
22243 case 'minute':
22244 case 'mins':
22245 case 'min':
22246 case 'm':
22247 return n * m;
22248 case 'seconds':
22249 case 'second':
22250 case 'secs':
22251 case 'sec':
22252 case 's':
22253 return n * s;
22254 case 'milliseconds':
22255 case 'millisecond':
22256 case 'msecs':
22257 case 'msec':
22258 case 'ms':
22259 return n;
22260 }
22261}
22262
22263/**
22264 * Short format for `ms`.
22265 *
22266 * @param {Number} ms
22267 * @return {String}
22268 * @api private
22269 */
22270
22271function short(ms) {
22272 if (ms >= d) return Math.round(ms / d) + 'd';
22273 if (ms >= h) return Math.round(ms / h) + 'h';
22274 if (ms >= m) return Math.round(ms / m) + 'm';
22275 if (ms >= s) return Math.round(ms / s) + 's';
22276 return ms + 'ms';
22277}
22278
22279/**
22280 * Long format for `ms`.
22281 *
22282 * @param {Number} ms
22283 * @return {String}
22284 * @api private
22285 */
22286
22287function long(ms) {
22288 return plural(ms, d, 'day')
22289 || plural(ms, h, 'hour')
22290 || plural(ms, m, 'minute')
22291 || plural(ms, s, 'second')
22292 || ms + ' ms';
22293}
22294
22295/**
22296 * Pluralization helper.
22297 */
22298
22299function plural(ms, n, name) {
22300 if (ms < n) return;
22301 if (ms < n * 1.5) return Math.floor(ms / n) + ' ' + name;
22302 return Math.ceil(ms / n) + ' ' + name + 's';
22303}
22304
22305},{}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/index.js":[function(require,module,exports){
22306
22307module.exports = require('./lib/');
22308
22309},{"./lib/":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/lib/index.js"}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/lib/index.js":[function(require,module,exports){
22310
22311module.exports = require('./socket');
22312
22313/**
22314 * Exports parser
22315 *
22316 * @api public
22317 *
22318 */
22319module.exports.parser = require('engine.io-parser');
22320
22321},{"./socket":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/lib/socket.js","engine.io-parser":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/node_modules/engine.io-parser/lib/browser.js"}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/lib/socket.js":[function(require,module,exports){
22322(function (global){
22323/**
22324 * Module dependencies.
22325 */
22326
22327var transports = require('./transports');
22328var Emitter = require('component-emitter');
22329var debug = require('debug')('engine.io-client:socket');
22330var index = require('indexof');
22331var parser = require('engine.io-parser');
22332var parseuri = require('parseuri');
22333var parsejson = require('parsejson');
22334var parseqs = require('parseqs');
22335
22336/**
22337 * Module exports.
22338 */
22339
22340module.exports = Socket;
22341
22342/**
22343 * Noop function.
22344 *
22345 * @api private
22346 */
22347
22348function noop(){}
22349
22350/**
22351 * Socket constructor.
22352 *
22353 * @param {String|Object} uri or options
22354 * @param {Object} options
22355 * @api public
22356 */
22357
22358function Socket(uri, opts){
22359 if (!(this instanceof Socket)) return new Socket(uri, opts);
22360
22361 opts = opts || {};
22362
22363 if (uri && 'object' == typeof uri) {
22364 opts = uri;
22365 uri = null;
22366 }
22367
22368 if (uri) {
22369 uri = parseuri(uri);
22370 opts.hostname = uri.host;
22371 opts.secure = uri.protocol == 'https' || uri.protocol == 'wss';
22372 opts.port = uri.port;
22373 if (uri.query) opts.query = uri.query;
22374 } else if (opts.host) {
22375 opts.hostname = parseuri(opts.host).host;
22376 }
22377
22378 this.secure = null != opts.secure ? opts.secure :
22379 (global.location && 'https:' == location.protocol);
22380
22381 if (opts.hostname && !opts.port) {
22382 // if no port is specified manually, use the protocol default
22383 opts.port = this.secure ? '443' : '80';
22384 }
22385
22386 this.agent = opts.agent || false;
22387 this.hostname = opts.hostname ||
22388 (global.location ? location.hostname : 'localhost');
22389 this.port = opts.port || (global.location && location.port ?
22390 location.port :
22391 (this.secure ? 443 : 80));
22392 this.query = opts.query || {};
22393 if ('string' == typeof this.query) this.query = parseqs.decode(this.query);
22394 this.upgrade = false !== opts.upgrade;
22395 this.path = (opts.path || '/engine.io').replace(/\/$/, '') + '/';
22396 this.forceJSONP = !!opts.forceJSONP;
22397 this.jsonp = false !== opts.jsonp;
22398 this.forceBase64 = !!opts.forceBase64;
22399 this.enablesXDR = !!opts.enablesXDR;
22400 this.timestampParam = opts.timestampParam || 't';
22401 this.timestampRequests = opts.timestampRequests;
22402 this.transports = opts.transports || ['polling', 'websocket'];
22403 this.readyState = '';
22404 this.writeBuffer = [];
22405 this.policyPort = opts.policyPort || 843;
22406 this.rememberUpgrade = opts.rememberUpgrade || false;
22407 this.binaryType = null;
22408 this.onlyBinaryUpgrades = opts.onlyBinaryUpgrades;
22409 this.perMessageDeflate = false !== opts.perMessageDeflate ? (opts.perMessageDeflate || {}) : false;
22410
22411 if (true === this.perMessageDeflate) this.perMessageDeflate = {};
22412 if (this.perMessageDeflate && null == this.perMessageDeflate.threshold) {
22413 this.perMessageDeflate.threshold = 1024;
22414 }
22415
22416 // SSL options for Node.js client
22417 this.pfx = opts.pfx || null;
22418 this.key = opts.key || null;
22419 this.passphrase = opts.passphrase || null;
22420 this.cert = opts.cert || null;
22421 this.ca = opts.ca || null;
22422 this.ciphers = opts.ciphers || null;
22423 this.rejectUnauthorized = opts.rejectUnauthorized === undefined ? null : opts.rejectUnauthorized;
22424
22425 // other options for Node.js client
22426 var freeGlobal = typeof global == 'object' && global;
22427 if (freeGlobal.global === freeGlobal) {
22428 if (opts.extraHeaders && Object.keys(opts.extraHeaders).length > 0) {
22429 this.extraHeaders = opts.extraHeaders;
22430 }
22431 }
22432
22433 this.open();
22434}
22435
22436Socket.priorWebsocketSuccess = false;
22437
22438/**
22439 * Mix in `Emitter`.
22440 */
22441
22442Emitter(Socket.prototype);
22443
22444/**
22445 * Protocol version.
22446 *
22447 * @api public
22448 */
22449
22450Socket.protocol = parser.protocol; // this is an int
22451
22452/**
22453 * Expose deps for legacy compatibility
22454 * and standalone browser access.
22455 */
22456
22457Socket.Socket = Socket;
22458Socket.Transport = require('./transport');
22459Socket.transports = require('./transports');
22460Socket.parser = require('engine.io-parser');
22461
22462/**
22463 * Creates transport of the given type.
22464 *
22465 * @param {String} transport name
22466 * @return {Transport}
22467 * @api private
22468 */
22469
22470Socket.prototype.createTransport = function (name) {
22471 debug('creating transport "%s"', name);
22472 var query = clone(this.query);
22473
22474 // append engine.io protocol identifier
22475 query.EIO = parser.protocol;
22476
22477 // transport name
22478 query.transport = name;
22479
22480 // session id if we already have one
22481 if (this.id) query.sid = this.id;
22482
22483 var transport = new transports[name]({
22484 agent: this.agent,
22485 hostname: this.hostname,
22486 port: this.port,
22487 secure: this.secure,
22488 path: this.path,
22489 query: query,
22490 forceJSONP: this.forceJSONP,
22491 jsonp: this.jsonp,
22492 forceBase64: this.forceBase64,
22493 enablesXDR: this.enablesXDR,
22494 timestampRequests: this.timestampRequests,
22495 timestampParam: this.timestampParam,
22496 policyPort: this.policyPort,
22497 socket: this,
22498 pfx: this.pfx,
22499 key: this.key,
22500 passphrase: this.passphrase,
22501 cert: this.cert,
22502 ca: this.ca,
22503 ciphers: this.ciphers,
22504 rejectUnauthorized: this.rejectUnauthorized,
22505 perMessageDeflate: this.perMessageDeflate,
22506 extraHeaders: this.extraHeaders
22507 });
22508
22509 return transport;
22510};
22511
22512function clone (obj) {
22513 var o = {};
22514 for (var i in obj) {
22515 if (obj.hasOwnProperty(i)) {
22516 o[i] = obj[i];
22517 }
22518 }
22519 return o;
22520}
22521
22522/**
22523 * Initializes transport to use and starts probe.
22524 *
22525 * @api private
22526 */
22527Socket.prototype.open = function () {
22528 var transport;
22529 if (this.rememberUpgrade && Socket.priorWebsocketSuccess && this.transports.indexOf('websocket') != -1) {
22530 transport = 'websocket';
22531 } else if (0 === this.transports.length) {
22532 // Emit error on next tick so it can be listened to
22533 var self = this;
22534 setTimeout(function() {
22535 self.emit('error', 'No transports available');
22536 }, 0);
22537 return;
22538 } else {
22539 transport = this.transports[0];
22540 }
22541 this.readyState = 'opening';
22542
22543 // Retry with the next transport if the transport is disabled (jsonp: false)
22544 try {
22545 transport = this.createTransport(transport);
22546 } catch (e) {
22547 this.transports.shift();
22548 this.open();
22549 return;
22550 }
22551
22552 transport.open();
22553 this.setTransport(transport);
22554};
22555
22556/**
22557 * Sets the current transport. Disables the existing one (if any).
22558 *
22559 * @api private
22560 */
22561
22562Socket.prototype.setTransport = function(transport){
22563 debug('setting transport %s', transport.name);
22564 var self = this;
22565
22566 if (this.transport) {
22567 debug('clearing existing transport %s', this.transport.name);
22568 this.transport.removeAllListeners();
22569 }
22570
22571 // set up transport
22572 this.transport = transport;
22573
22574 // set up transport listeners
22575 transport
22576 .on('drain', function(){
22577 self.onDrain();
22578 })
22579 .on('packet', function(packet){
22580 self.onPacket(packet);
22581 })
22582 .on('error', function(e){
22583 self.onError(e);
22584 })
22585 .on('close', function(){
22586 self.onClose('transport close');
22587 });
22588};
22589
22590/**
22591 * Probes a transport.
22592 *
22593 * @param {String} transport name
22594 * @api private
22595 */
22596
22597Socket.prototype.probe = function (name) {
22598 debug('probing transport "%s"', name);
22599 var transport = this.createTransport(name, { probe: 1 })
22600 , failed = false
22601 , self = this;
22602
22603 Socket.priorWebsocketSuccess = false;
22604
22605 function onTransportOpen(){
22606 if (self.onlyBinaryUpgrades) {
22607 var upgradeLosesBinary = !this.supportsBinary && self.transport.supportsBinary;
22608 failed = failed || upgradeLosesBinary;
22609 }
22610 if (failed) return;
22611
22612 debug('probe transport "%s" opened', name);
22613 transport.send([{ type: 'ping', data: 'probe' }]);
22614 transport.once('packet', function (msg) {
22615 if (failed) return;
22616 if ('pong' == msg.type && 'probe' == msg.data) {
22617 debug('probe transport "%s" pong', name);
22618 self.upgrading = true;
22619 self.emit('upgrading', transport);
22620 if (!transport) return;
22621 Socket.priorWebsocketSuccess = 'websocket' == transport.name;
22622
22623 debug('pausing current transport "%s"', self.transport.name);
22624 self.transport.pause(function () {
22625 if (failed) return;
22626 if ('closed' == self.readyState) return;
22627 debug('changing transport and sending upgrade packet');
22628
22629 cleanup();
22630
22631 self.setTransport(transport);
22632 transport.send([{ type: 'upgrade' }]);
22633 self.emit('upgrade', transport);
22634 transport = null;
22635 self.upgrading = false;
22636 self.flush();
22637 });
22638 } else {
22639 debug('probe transport "%s" failed', name);
22640 var err = new Error('probe error');
22641 err.transport = transport.name;
22642 self.emit('upgradeError', err);
22643 }
22644 });
22645 }
22646
22647 function freezeTransport() {
22648 if (failed) return;
22649
22650 // Any callback called by transport should be ignored since now
22651 failed = true;
22652
22653 cleanup();
22654
22655 transport.close();
22656 transport = null;
22657 }
22658
22659 //Handle any error that happens while probing
22660 function onerror(err) {
22661 var error = new Error('probe error: ' + err);
22662 error.transport = transport.name;
22663
22664 freezeTransport();
22665
22666 debug('probe transport "%s" failed because of error: %s', name, err);
22667
22668 self.emit('upgradeError', error);
22669 }
22670
22671 function onTransportClose(){
22672 onerror("transport closed");
22673 }
22674
22675 //When the socket is closed while we're probing
22676 function onclose(){
22677 onerror("socket closed");
22678 }
22679
22680 //When the socket is upgraded while we're probing
22681 function onupgrade(to){
22682 if (transport && to.name != transport.name) {
22683 debug('"%s" works - aborting "%s"', to.name, transport.name);
22684 freezeTransport();
22685 }
22686 }
22687
22688 //Remove all listeners on the transport and on self
22689 function cleanup(){
22690 transport.removeListener('open', onTransportOpen);
22691 transport.removeListener('error', onerror);
22692 transport.removeListener('close', onTransportClose);
22693 self.removeListener('close', onclose);
22694 self.removeListener('upgrading', onupgrade);
22695 }
22696
22697 transport.once('open', onTransportOpen);
22698 transport.once('error', onerror);
22699 transport.once('close', onTransportClose);
22700
22701 this.once('close', onclose);
22702 this.once('upgrading', onupgrade);
22703
22704 transport.open();
22705
22706};
22707
22708/**
22709 * Called when connection is deemed open.
22710 *
22711 * @api public
22712 */
22713
22714Socket.prototype.onOpen = function () {
22715 debug('socket open');
22716 this.readyState = 'open';
22717 Socket.priorWebsocketSuccess = 'websocket' == this.transport.name;
22718 this.emit('open');
22719 this.flush();
22720
22721 // we check for `readyState` in case an `open`
22722 // listener already closed the socket
22723 if ('open' == this.readyState && this.upgrade && this.transport.pause) {
22724 debug('starting upgrade probes');
22725 for (var i = 0, l = this.upgrades.length; i < l; i++) {
22726 this.probe(this.upgrades[i]);
22727 }
22728 }
22729};
22730
22731/**
22732 * Handles a packet.
22733 *
22734 * @api private
22735 */
22736
22737Socket.prototype.onPacket = function (packet) {
22738 if ('opening' == this.readyState || 'open' == this.readyState) {
22739 debug('socket receive: type "%s", data "%s"', packet.type, packet.data);
22740
22741 this.emit('packet', packet);
22742
22743 // Socket is live - any packet counts
22744 this.emit('heartbeat');
22745
22746 switch (packet.type) {
22747 case 'open':
22748 this.onHandshake(parsejson(packet.data));
22749 break;
22750
22751 case 'pong':
22752 this.setPing();
22753 this.emit('pong');
22754 break;
22755
22756 case 'error':
22757 var err = new Error('server error');
22758 err.code = packet.data;
22759 this.onError(err);
22760 break;
22761
22762 case 'message':
22763 this.emit('data', packet.data);
22764 this.emit('message', packet.data);
22765 break;
22766 }
22767 } else {
22768 debug('packet received with socket readyState "%s"', this.readyState);
22769 }
22770};
22771
22772/**
22773 * Called upon handshake completion.
22774 *
22775 * @param {Object} handshake obj
22776 * @api private
22777 */
22778
22779Socket.prototype.onHandshake = function (data) {
22780 this.emit('handshake', data);
22781 this.id = data.sid;
22782 this.transport.query.sid = data.sid;
22783 this.upgrades = this.filterUpgrades(data.upgrades);
22784 this.pingInterval = data.pingInterval;
22785 this.pingTimeout = data.pingTimeout;
22786 this.onOpen();
22787 // In case open handler closes socket
22788 if ('closed' == this.readyState) return;
22789 this.setPing();
22790
22791 // Prolong liveness of socket on heartbeat
22792 this.removeListener('heartbeat', this.onHeartbeat);
22793 this.on('heartbeat', this.onHeartbeat);
22794};
22795
22796/**
22797 * Resets ping timeout.
22798 *
22799 * @api private
22800 */
22801
22802Socket.prototype.onHeartbeat = function (timeout) {
22803 clearTimeout(this.pingTimeoutTimer);
22804 var self = this;
22805 self.pingTimeoutTimer = setTimeout(function () {
22806 if ('closed' == self.readyState) return;
22807 self.onClose('ping timeout');
22808 }, timeout || (self.pingInterval + self.pingTimeout));
22809};
22810
22811/**
22812 * Pings server every `this.pingInterval` and expects response
22813 * within `this.pingTimeout` or closes connection.
22814 *
22815 * @api private
22816 */
22817
22818Socket.prototype.setPing = function () {
22819 var self = this;
22820 clearTimeout(self.pingIntervalTimer);
22821 self.pingIntervalTimer = setTimeout(function () {
22822 debug('writing ping packet - expecting pong within %sms', self.pingTimeout);
22823 self.ping();
22824 self.onHeartbeat(self.pingTimeout);
22825 }, self.pingInterval);
22826};
22827
22828/**
22829* Sends a ping packet.
22830*
22831* @api private
22832*/
22833
22834Socket.prototype.ping = function () {
22835 var self = this;
22836 this.sendPacket('ping', function(){
22837 self.emit('ping');
22838 });
22839};
22840
22841/**
22842 * Called on `drain` event
22843 *
22844 * @api private
22845 */
22846
22847Socket.prototype.onDrain = function() {
22848 this.writeBuffer.splice(0, this.prevBufferLen);
22849
22850 // setting prevBufferLen = 0 is very important
22851 // for example, when upgrading, upgrade packet is sent over,
22852 // and a nonzero prevBufferLen could cause problems on `drain`
22853 this.prevBufferLen = 0;
22854
22855 if (0 === this.writeBuffer.length) {
22856 this.emit('drain');
22857 } else {
22858 this.flush();
22859 }
22860};
22861
22862/**
22863 * Flush write buffers.
22864 *
22865 * @api private
22866 */
22867
22868Socket.prototype.flush = function () {
22869 if ('closed' != this.readyState && this.transport.writable &&
22870 !this.upgrading && this.writeBuffer.length) {
22871 debug('flushing %d packets in socket', this.writeBuffer.length);
22872 this.transport.send(this.writeBuffer);
22873 // keep track of current length of writeBuffer
22874 // splice writeBuffer and callbackBuffer on `drain`
22875 this.prevBufferLen = this.writeBuffer.length;
22876 this.emit('flush');
22877 }
22878};
22879
22880/**
22881 * Sends a message.
22882 *
22883 * @param {String} message.
22884 * @param {Function} callback function.
22885 * @param {Object} options.
22886 * @return {Socket} for chaining.
22887 * @api public
22888 */
22889
22890Socket.prototype.write =
22891Socket.prototype.send = function (msg, options, fn) {
22892 this.sendPacket('message', msg, options, fn);
22893 return this;
22894};
22895
22896/**
22897 * Sends a packet.
22898 *
22899 * @param {String} packet type.
22900 * @param {String} data.
22901 * @param {Object} options.
22902 * @param {Function} callback function.
22903 * @api private
22904 */
22905
22906Socket.prototype.sendPacket = function (type, data, options, fn) {
22907 if('function' == typeof data) {
22908 fn = data;
22909 data = undefined;
22910 }
22911
22912 if ('function' == typeof options) {
22913 fn = options;
22914 options = null;
22915 }
22916
22917 if ('closing' == this.readyState || 'closed' == this.readyState) {
22918 return;
22919 }
22920
22921 options = options || {};
22922 options.compress = false !== options.compress;
22923
22924 var packet = {
22925 type: type,
22926 data: data,
22927 options: options
22928 };
22929 this.emit('packetCreate', packet);
22930 this.writeBuffer.push(packet);
22931 if (fn) this.once('flush', fn);
22932 this.flush();
22933};
22934
22935/**
22936 * Closes the connection.
22937 *
22938 * @api private
22939 */
22940
22941Socket.prototype.close = function () {
22942 if ('opening' == this.readyState || 'open' == this.readyState) {
22943 this.readyState = 'closing';
22944
22945 var self = this;
22946
22947 if (this.writeBuffer.length) {
22948 this.once('drain', function() {
22949 if (this.upgrading) {
22950 waitForUpgrade();
22951 } else {
22952 close();
22953 }
22954 });
22955 } else if (this.upgrading) {
22956 waitForUpgrade();
22957 } else {
22958 close();
22959 }
22960 }
22961
22962 function close() {
22963 self.onClose('forced close');
22964 debug('socket closing - telling transport to close');
22965 self.transport.close();
22966 }
22967
22968 function cleanupAndClose() {
22969 self.removeListener('upgrade', cleanupAndClose);
22970 self.removeListener('upgradeError', cleanupAndClose);
22971 close();
22972 }
22973
22974 function waitForUpgrade() {
22975 // wait for upgrade to finish since we can't send packets while pausing a transport
22976 self.once('upgrade', cleanupAndClose);
22977 self.once('upgradeError', cleanupAndClose);
22978 }
22979
22980 return this;
22981};
22982
22983/**
22984 * Called upon transport error
22985 *
22986 * @api private
22987 */
22988
22989Socket.prototype.onError = function (err) {
22990 debug('socket error %j', err);
22991 Socket.priorWebsocketSuccess = false;
22992 this.emit('error', err);
22993 this.onClose('transport error', err);
22994};
22995
22996/**
22997 * Called upon transport close.
22998 *
22999 * @api private
23000 */
23001
23002Socket.prototype.onClose = function (reason, desc) {
23003 if ('opening' == this.readyState || 'open' == this.readyState || 'closing' == this.readyState) {
23004 debug('socket close with reason: "%s"', reason);
23005 var self = this;
23006
23007 // clear timers
23008 clearTimeout(this.pingIntervalTimer);
23009 clearTimeout(this.pingTimeoutTimer);
23010
23011 // stop event from firing again for transport
23012 this.transport.removeAllListeners('close');
23013
23014 // ensure transport won't stay open
23015 this.transport.close();
23016
23017 // ignore further transport communication
23018 this.transport.removeAllListeners();
23019
23020 // set ready state
23021 this.readyState = 'closed';
23022
23023 // clear session id
23024 this.id = null;
23025
23026 // emit close event
23027 this.emit('close', reason, desc);
23028
23029 // clean buffers after, so users can still
23030 // grab the buffers on `close` event
23031 self.writeBuffer = [];
23032 self.prevBufferLen = 0;
23033 }
23034};
23035
23036/**
23037 * Filters upgrades, returning only those matching client transports.
23038 *
23039 * @param {Array} server upgrades
23040 * @api private
23041 *
23042 */
23043
23044Socket.prototype.filterUpgrades = function (upgrades) {
23045 var filteredUpgrades = [];
23046 for (var i = 0, j = upgrades.length; i<j; i++) {
23047 if (~index(this.transports, upgrades[i])) filteredUpgrades.push(upgrades[i]);
23048 }
23049 return filteredUpgrades;
23050};
23051
23052}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
23053},{"./transport":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/lib/transport.js","./transports":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/lib/transports/index.js","component-emitter":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/node_modules/component-emitter/index.js","debug":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/debug/browser.js","engine.io-parser":"/home/employee-2klic/projects/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/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/indexof/index.js","parsejson":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/node_modules/parsejson/index.js","parseqs":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/node_modules/parseqs/index.js","parseuri":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/parseuri/index.js"}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/lib/transport.js":[function(require,module,exports){
23054/**
23055 * Module dependencies.
23056 */
23057
23058var parser = require('engine.io-parser');
23059var Emitter = require('component-emitter');
23060
23061/**
23062 * Module exports.
23063 */
23064
23065module.exports = Transport;
23066
23067/**
23068 * Transport abstract constructor.
23069 *
23070 * @param {Object} options.
23071 * @api private
23072 */
23073
23074function Transport (opts) {
23075 this.path = opts.path;
23076 this.hostname = opts.hostname;
23077 this.port = opts.port;
23078 this.secure = opts.secure;
23079 this.query = opts.query;
23080 this.timestampParam = opts.timestampParam;
23081 this.timestampRequests = opts.timestampRequests;
23082 this.readyState = '';
23083 this.agent = opts.agent || false;
23084 this.socket = opts.socket;
23085 this.enablesXDR = opts.enablesXDR;
23086
23087 // SSL options for Node.js client
23088 this.pfx = opts.pfx;
23089 this.key = opts.key;
23090 this.passphrase = opts.passphrase;
23091 this.cert = opts.cert;
23092 this.ca = opts.ca;
23093 this.ciphers = opts.ciphers;
23094 this.rejectUnauthorized = opts.rejectUnauthorized;
23095
23096 // other options for Node.js client
23097 this.extraHeaders = opts.extraHeaders;
23098}
23099
23100/**
23101 * Mix in `Emitter`.
23102 */
23103
23104Emitter(Transport.prototype);
23105
23106/**
23107 * Emits an error.
23108 *
23109 * @param {String} str
23110 * @return {Transport} for chaining
23111 * @api public
23112 */
23113
23114Transport.prototype.onError = function (msg, desc) {
23115 var err = new Error(msg);
23116 err.type = 'TransportError';
23117 err.description = desc;
23118 this.emit('error', err);
23119 return this;
23120};
23121
23122/**
23123 * Opens the transport.
23124 *
23125 * @api public
23126 */
23127
23128Transport.prototype.open = function () {
23129 if ('closed' == this.readyState || '' == this.readyState) {
23130 this.readyState = 'opening';
23131 this.doOpen();
23132 }
23133
23134 return this;
23135};
23136
23137/**
23138 * Closes the transport.
23139 *
23140 * @api private
23141 */
23142
23143Transport.prototype.close = function () {
23144 if ('opening' == this.readyState || 'open' == this.readyState) {
23145 this.doClose();
23146 this.onClose();
23147 }
23148
23149 return this;
23150};
23151
23152/**
23153 * Sends multiple packets.
23154 *
23155 * @param {Array} packets
23156 * @api private
23157 */
23158
23159Transport.prototype.send = function(packets){
23160 if ('open' == this.readyState) {
23161 this.write(packets);
23162 } else {
23163 throw new Error('Transport not open');
23164 }
23165};
23166
23167/**
23168 * Called upon open
23169 *
23170 * @api private
23171 */
23172
23173Transport.prototype.onOpen = function () {
23174 this.readyState = 'open';
23175 this.writable = true;
23176 this.emit('open');
23177};
23178
23179/**
23180 * Called with data.
23181 *
23182 * @param {String} data
23183 * @api private
23184 */
23185
23186Transport.prototype.onData = function(data){
23187 var packet = parser.decodePacket(data, this.socket.binaryType);
23188 this.onPacket(packet);
23189};
23190
23191/**
23192 * Called with a decoded packet.
23193 */
23194
23195Transport.prototype.onPacket = function (packet) {
23196 this.emit('packet', packet);
23197};
23198
23199/**
23200 * Called upon close.
23201 *
23202 * @api private
23203 */
23204
23205Transport.prototype.onClose = function () {
23206 this.readyState = 'closed';
23207 this.emit('close');
23208};
23209
23210},{"component-emitter":"/home/employee-2klic/projects/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/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/node_modules/engine.io-parser/lib/browser.js"}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/lib/transports/index.js":[function(require,module,exports){
23211(function (global){
23212/**
23213 * Module dependencies
23214 */
23215
23216var XMLHttpRequest = require('xmlhttprequest-ssl');
23217var XHR = require('./polling-xhr');
23218var JSONP = require('./polling-jsonp');
23219var websocket = require('./websocket');
23220
23221/**
23222 * Export transports.
23223 */
23224
23225exports.polling = polling;
23226exports.websocket = websocket;
23227
23228/**
23229 * Polling transport polymorphic constructor.
23230 * Decides on xhr vs jsonp based on feature detection.
23231 *
23232 * @api private
23233 */
23234
23235function polling(opts){
23236 var xhr;
23237 var xd = false;
23238 var xs = false;
23239 var jsonp = false !== opts.jsonp;
23240
23241 if (global.location) {
23242 var isSSL = 'https:' == location.protocol;
23243 var port = location.port;
23244
23245 // some user agents have empty `location.port`
23246 if (!port) {
23247 port = isSSL ? 443 : 80;
23248 }
23249
23250 xd = opts.hostname != location.hostname || port != opts.port;
23251 xs = opts.secure != isSSL;
23252 }
23253
23254 opts.xdomain = xd;
23255 opts.xscheme = xs;
23256 xhr = new XMLHttpRequest(opts);
23257
23258 if ('open' in xhr && !opts.forceJSONP) {
23259 return new XHR(opts);
23260 } else {
23261 if (!jsonp) throw new Error('JSONP disabled');
23262 return new JSONP(opts);
23263 }
23264}
23265
23266}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
23267},{"./polling-jsonp":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/lib/transports/polling-jsonp.js","./polling-xhr":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/lib/transports/polling-xhr.js","./websocket":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/lib/transports/websocket.js","xmlhttprequest-ssl":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/lib/xmlhttprequest.js"}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/lib/transports/polling-jsonp.js":[function(require,module,exports){
23268(function (global){
23269
23270/**
23271 * Module requirements.
23272 */
23273
23274var Polling = require('./polling');
23275var inherit = require('component-inherit');
23276
23277/**
23278 * Module exports.
23279 */
23280
23281module.exports = JSONPPolling;
23282
23283/**
23284 * Cached regular expressions.
23285 */
23286
23287var rNewline = /\n/g;
23288var rEscapedNewline = /\\n/g;
23289
23290/**
23291 * Global JSONP callbacks.
23292 */
23293
23294var callbacks;
23295
23296/**
23297 * Callbacks count.
23298 */
23299
23300var index = 0;
23301
23302/**
23303 * Noop.
23304 */
23305
23306function empty () { }
23307
23308/**
23309 * JSONP Polling constructor.
23310 *
23311 * @param {Object} opts.
23312 * @api public
23313 */
23314
23315function JSONPPolling (opts) {
23316 Polling.call(this, opts);
23317
23318 this.query = this.query || {};
23319
23320 // define global callbacks array if not present
23321 // we do this here (lazily) to avoid unneeded global pollution
23322 if (!callbacks) {
23323 // we need to consider multiple engines in the same page
23324 if (!global.___eio) global.___eio = [];
23325 callbacks = global.___eio;
23326 }
23327
23328 // callback identifier
23329 this.index = callbacks.length;
23330
23331 // add callback to jsonp global
23332 var self = this;
23333 callbacks.push(function (msg) {
23334 self.onData(msg);
23335 });
23336
23337 // append to query string
23338 this.query.j = this.index;
23339
23340 // prevent spurious errors from being emitted when the window is unloaded
23341 if (global.document && global.addEventListener) {
23342 global.addEventListener('beforeunload', function () {
23343 if (self.script) self.script.onerror = empty;
23344 }, false);
23345 }
23346}
23347
23348/**
23349 * Inherits from Polling.
23350 */
23351
23352inherit(JSONPPolling, Polling);
23353
23354/*
23355 * JSONP only supports binary as base64 encoded strings
23356 */
23357
23358JSONPPolling.prototype.supportsBinary = false;
23359
23360/**
23361 * Closes the socket.
23362 *
23363 * @api private
23364 */
23365
23366JSONPPolling.prototype.doClose = function () {
23367 if (this.script) {
23368 this.script.parentNode.removeChild(this.script);
23369 this.script = null;
23370 }
23371
23372 if (this.form) {
23373 this.form.parentNode.removeChild(this.form);
23374 this.form = null;
23375 this.iframe = null;
23376 }
23377
23378 Polling.prototype.doClose.call(this);
23379};
23380
23381/**
23382 * Starts a poll cycle.
23383 *
23384 * @api private
23385 */
23386
23387JSONPPolling.prototype.doPoll = function () {
23388 var self = this;
23389 var script = document.createElement('script');
23390
23391 if (this.script) {
23392 this.script.parentNode.removeChild(this.script);
23393 this.script = null;
23394 }
23395
23396 script.async = true;
23397 script.src = this.uri();
23398 script.onerror = function(e){
23399 self.onError('jsonp poll error',e);
23400 };
23401
23402 var insertAt = document.getElementsByTagName('script')[0];
23403 insertAt.parentNode.insertBefore(script, insertAt);
23404 this.script = script;
23405
23406 var isUAgecko = 'undefined' != typeof navigator && /gecko/i.test(navigator.userAgent);
23407
23408 if (isUAgecko) {
23409 setTimeout(function () {
23410 var iframe = document.createElement('iframe');
23411 document.body.appendChild(iframe);
23412 document.body.removeChild(iframe);
23413 }, 100);
23414 }
23415};
23416
23417/**
23418 * Writes with a hidden iframe.
23419 *
23420 * @param {String} data to send
23421 * @param {Function} called upon flush.
23422 * @api private
23423 */
23424
23425JSONPPolling.prototype.doWrite = function (data, fn) {
23426 var self = this;
23427
23428 if (!this.form) {
23429 var form = document.createElement('form');
23430 var area = document.createElement('textarea');
23431 var id = this.iframeId = 'eio_iframe_' + this.index;
23432 var iframe;
23433
23434 form.className = 'socketio';
23435 form.style.position = 'absolute';
23436 form.style.top = '-1000px';
23437 form.style.left = '-1000px';
23438 form.target = id;
23439 form.method = 'POST';
23440 form.setAttribute('accept-charset', 'utf-8');
23441 area.name = 'd';
23442 form.appendChild(area);
23443 document.body.appendChild(form);
23444
23445 this.form = form;
23446 this.area = area;
23447 }
23448
23449 this.form.action = this.uri();
23450
23451 function complete () {
23452 initIframe();
23453 fn();
23454 }
23455
23456 function initIframe () {
23457 if (self.iframe) {
23458 try {
23459 self.form.removeChild(self.iframe);
23460 } catch (e) {
23461 self.onError('jsonp polling iframe removal error', e);
23462 }
23463 }
23464
23465 try {
23466 // ie6 dynamic iframes with target="" support (thanks Chris Lambacher)
23467 var html = '<iframe src="javascript:0" name="'+ self.iframeId +'">';
23468 iframe = document.createElement(html);
23469 } catch (e) {
23470 iframe = document.createElement('iframe');
23471 iframe.name = self.iframeId;
23472 iframe.src = 'javascript:0';
23473 }
23474
23475 iframe.id = self.iframeId;
23476
23477 self.form.appendChild(iframe);
23478 self.iframe = iframe;
23479 }
23480
23481 initIframe();
23482
23483 // escape \n to prevent it from being converted into \r\n by some UAs
23484 // double escaping is required for escaped new lines because unescaping of new lines can be done safely on server-side
23485 data = data.replace(rEscapedNewline, '\\\n');
23486 this.area.value = data.replace(rNewline, '\\n');
23487
23488 try {
23489 this.form.submit();
23490 } catch(e) {}
23491
23492 if (this.iframe.attachEvent) {
23493 this.iframe.onreadystatechange = function(){
23494 if (self.iframe.readyState == 'complete') {
23495 complete();
23496 }
23497 };
23498 } else {
23499 this.iframe.onload = complete;
23500 }
23501};
23502
23503}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
23504},{"./polling":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/lib/transports/polling.js","component-inherit":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/node_modules/component-inherit/index.js"}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/lib/transports/polling-xhr.js":[function(require,module,exports){
23505(function (global){
23506/**
23507 * Module requirements.
23508 */
23509
23510var XMLHttpRequest = require('xmlhttprequest-ssl');
23511var Polling = require('./polling');
23512var Emitter = require('component-emitter');
23513var inherit = require('component-inherit');
23514var debug = require('debug')('engine.io-client:polling-xhr');
23515
23516/**
23517 * Module exports.
23518 */
23519
23520module.exports = XHR;
23521module.exports.Request = Request;
23522
23523/**
23524 * Empty function
23525 */
23526
23527function empty(){}
23528
23529/**
23530 * XHR Polling constructor.
23531 *
23532 * @param {Object} opts
23533 * @api public
23534 */
23535
23536function XHR(opts){
23537 Polling.call(this, opts);
23538
23539 if (global.location) {
23540 var isSSL = 'https:' == location.protocol;
23541 var port = location.port;
23542
23543 // some user agents have empty `location.port`
23544 if (!port) {
23545 port = isSSL ? 443 : 80;
23546 }
23547
23548 this.xd = opts.hostname != global.location.hostname ||
23549 port != opts.port;
23550 this.xs = opts.secure != isSSL;
23551 } else {
23552 this.extraHeaders = opts.extraHeaders;
23553 }
23554}
23555
23556/**
23557 * Inherits from Polling.
23558 */
23559
23560inherit(XHR, Polling);
23561
23562/**
23563 * XHR supports binary
23564 */
23565
23566XHR.prototype.supportsBinary = true;
23567
23568/**
23569 * Creates a request.
23570 *
23571 * @param {String} method
23572 * @api private
23573 */
23574
23575XHR.prototype.request = function(opts){
23576 opts = opts || {};
23577 opts.uri = this.uri();
23578 opts.xd = this.xd;
23579 opts.xs = this.xs;
23580 opts.agent = this.agent || false;
23581 opts.supportsBinary = this.supportsBinary;
23582 opts.enablesXDR = this.enablesXDR;
23583
23584 // SSL options for Node.js client
23585 opts.pfx = this.pfx;
23586 opts.key = this.key;
23587 opts.passphrase = this.passphrase;
23588 opts.cert = this.cert;
23589 opts.ca = this.ca;
23590 opts.ciphers = this.ciphers;
23591 opts.rejectUnauthorized = this.rejectUnauthorized;
23592
23593 // other options for Node.js client
23594 opts.extraHeaders = this.extraHeaders;
23595
23596 return new Request(opts);
23597};
23598
23599/**
23600 * Sends data.
23601 *
23602 * @param {String} data to send.
23603 * @param {Function} called upon flush.
23604 * @api private
23605 */
23606
23607XHR.prototype.doWrite = function(data, fn){
23608 var isBinary = typeof data !== 'string' && data !== undefined;
23609 var req = this.request({ method: 'POST', data: data, isBinary: isBinary });
23610 var self = this;
23611 req.on('success', fn);
23612 req.on('error', function(err){
23613 self.onError('xhr post error', err);
23614 });
23615 this.sendXhr = req;
23616};
23617
23618/**
23619 * Starts a poll cycle.
23620 *
23621 * @api private
23622 */
23623
23624XHR.prototype.doPoll = function(){
23625 debug('xhr poll');
23626 var req = this.request();
23627 var self = this;
23628 req.on('data', function(data){
23629 self.onData(data);
23630 });
23631 req.on('error', function(err){
23632 self.onError('xhr poll error', err);
23633 });
23634 this.pollXhr = req;
23635};
23636
23637/**
23638 * Request constructor
23639 *
23640 * @param {Object} options
23641 * @api public
23642 */
23643
23644function Request(opts){
23645 this.method = opts.method || 'GET';
23646 this.uri = opts.uri;
23647 this.xd = !!opts.xd;
23648 this.xs = !!opts.xs;
23649 this.async = false !== opts.async;
23650 this.data = undefined != opts.data ? opts.data : null;
23651 this.agent = opts.agent;
23652 this.isBinary = opts.isBinary;
23653 this.supportsBinary = opts.supportsBinary;
23654 this.enablesXDR = opts.enablesXDR;
23655
23656 // SSL options for Node.js client
23657 this.pfx = opts.pfx;
23658 this.key = opts.key;
23659 this.passphrase = opts.passphrase;
23660 this.cert = opts.cert;
23661 this.ca = opts.ca;
23662 this.ciphers = opts.ciphers;
23663 this.rejectUnauthorized = opts.rejectUnauthorized;
23664
23665 // other options for Node.js client
23666 this.extraHeaders = opts.extraHeaders;
23667
23668 this.create();
23669}
23670
23671/**
23672 * Mix in `Emitter`.
23673 */
23674
23675Emitter(Request.prototype);
23676
23677/**
23678 * Creates the XHR object and sends the request.
23679 *
23680 * @api private
23681 */
23682
23683Request.prototype.create = function(){
23684 var opts = { agent: this.agent, xdomain: this.xd, xscheme: this.xs, enablesXDR: this.enablesXDR };
23685
23686 // SSL options for Node.js client
23687 opts.pfx = this.pfx;
23688 opts.key = this.key;
23689 opts.passphrase = this.passphrase;
23690 opts.cert = this.cert;
23691 opts.ca = this.ca;
23692 opts.ciphers = this.ciphers;
23693 opts.rejectUnauthorized = this.rejectUnauthorized;
23694
23695 var xhr = this.xhr = new XMLHttpRequest(opts);
23696 var self = this;
23697
23698 try {
23699 debug('xhr open %s: %s', this.method, this.uri);
23700 xhr.open(this.method, this.uri, this.async);
23701 try {
23702 if (this.extraHeaders) {
23703 xhr.setDisableHeaderCheck(true);
23704 for (var i in this.extraHeaders) {
23705 if (this.extraHeaders.hasOwnProperty(i)) {
23706 xhr.setRequestHeader(i, this.extraHeaders[i]);
23707 }
23708 }
23709 }
23710 } catch (e) {}
23711 if (this.supportsBinary) {
23712 // This has to be done after open because Firefox is stupid
23713 // http://stackoverflow.com/questions/13216903/get-binary-data-with-xmlhttprequest-in-a-firefox-extension
23714 xhr.responseType = 'arraybuffer';
23715 }
23716
23717 if ('POST' == this.method) {
23718 try {
23719 if (this.isBinary) {
23720 xhr.setRequestHeader('Content-type', 'application/octet-stream');
23721 } else {
23722 xhr.setRequestHeader('Content-type', 'text/plain;charset=UTF-8');
23723 }
23724 } catch (e) {}
23725 }
23726
23727 // ie6 check
23728 if ('withCredentials' in xhr) {
23729 xhr.withCredentials = true;
23730 }
23731
23732 if (this.hasXDR()) {
23733 xhr.onload = function(){
23734 self.onLoad();
23735 };
23736 xhr.onerror = function(){
23737 self.onError(xhr.responseText);
23738 };
23739 } else {
23740 xhr.onreadystatechange = function(){
23741 if (4 != xhr.readyState) return;
23742 if (200 == xhr.status || 1223 == xhr.status) {
23743 self.onLoad();
23744 } else {
23745 // make sure the `error` event handler that's user-set
23746 // does not throw in the same tick and gets caught here
23747 setTimeout(function(){
23748 self.onError(xhr.status);
23749 }, 0);
23750 }
23751 };
23752 }
23753
23754 debug('xhr data %s', this.data);
23755 xhr.send(this.data);
23756 } catch (e) {
23757 // Need to defer since .create() is called directly fhrom the constructor
23758 // and thus the 'error' event can only be only bound *after* this exception
23759 // occurs. Therefore, also, we cannot throw here at all.
23760 setTimeout(function() {
23761 self.onError(e);
23762 }, 0);
23763 return;
23764 }
23765
23766 if (global.document) {
23767 this.index = Request.requestsCount++;
23768 Request.requests[this.index] = this;
23769 }
23770};
23771
23772/**
23773 * Called upon successful response.
23774 *
23775 * @api private
23776 */
23777
23778Request.prototype.onSuccess = function(){
23779 this.emit('success');
23780 this.cleanup();
23781};
23782
23783/**
23784 * Called if we have data.
23785 *
23786 * @api private
23787 */
23788
23789Request.prototype.onData = function(data){
23790 this.emit('data', data);
23791 this.onSuccess();
23792};
23793
23794/**
23795 * Called upon error.
23796 *
23797 * @api private
23798 */
23799
23800Request.prototype.onError = function(err){
23801 this.emit('error', err);
23802 this.cleanup(true);
23803};
23804
23805/**
23806 * Cleans up house.
23807 *
23808 * @api private
23809 */
23810
23811Request.prototype.cleanup = function(fromError){
23812 if ('undefined' == typeof this.xhr || null === this.xhr) {
23813 return;
23814 }
23815 // xmlhttprequest
23816 if (this.hasXDR()) {
23817 this.xhr.onload = this.xhr.onerror = empty;
23818 } else {
23819 this.xhr.onreadystatechange = empty;
23820 }
23821
23822 if (fromError) {
23823 try {
23824 this.xhr.abort();
23825 } catch(e) {}
23826 }
23827
23828 if (global.document) {
23829 delete Request.requests[this.index];
23830 }
23831
23832 this.xhr = null;
23833};
23834
23835/**
23836 * Called upon load.
23837 *
23838 * @api private
23839 */
23840
23841Request.prototype.onLoad = function(){
23842 var data;
23843 try {
23844 var contentType;
23845 try {
23846 contentType = this.xhr.getResponseHeader('Content-Type').split(';')[0];
23847 } catch (e) {}
23848 if (contentType === 'application/octet-stream') {
23849 data = this.xhr.response;
23850 } else {
23851 if (!this.supportsBinary) {
23852 data = this.xhr.responseText;
23853 } else {
23854 try {
23855 data = String.fromCharCode.apply(null, new Uint8Array(this.xhr.response));
23856 } catch (e) {
23857 var ui8Arr = new Uint8Array(this.xhr.response);
23858 var dataArray = [];
23859 for (var idx = 0, length = ui8Arr.length; idx < length; idx++) {
23860 dataArray.push(ui8Arr[idx]);
23861 }
23862
23863 data = String.fromCharCode.apply(null, dataArray);
23864 }
23865 }
23866 }
23867 } catch (e) {
23868 this.onError(e);
23869 }
23870 if (null != data) {
23871 this.onData(data);
23872 }
23873};
23874
23875/**
23876 * Check if it has XDomainRequest.
23877 *
23878 * @api private
23879 */
23880
23881Request.prototype.hasXDR = function(){
23882 return 'undefined' !== typeof global.XDomainRequest && !this.xs && this.enablesXDR;
23883};
23884
23885/**
23886 * Aborts the request.
23887 *
23888 * @api public
23889 */
23890
23891Request.prototype.abort = function(){
23892 this.cleanup();
23893};
23894
23895/**
23896 * Aborts pending requests when unloading the window. This is needed to prevent
23897 * memory leaks (e.g. when using IE) and to ensure that no spurious error is
23898 * emitted.
23899 */
23900
23901if (global.document) {
23902 Request.requestsCount = 0;
23903 Request.requests = {};
23904 if (global.attachEvent) {
23905 global.attachEvent('onunload', unloadHandler);
23906 } else if (global.addEventListener) {
23907 global.addEventListener('beforeunload', unloadHandler, false);
23908 }
23909}
23910
23911function unloadHandler() {
23912 for (var i in Request.requests) {
23913 if (Request.requests.hasOwnProperty(i)) {
23914 Request.requests[i].abort();
23915 }
23916 }
23917}
23918
23919}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
23920},{"./polling":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/lib/transports/polling.js","component-emitter":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/node_modules/component-emitter/index.js","component-inherit":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/node_modules/component-inherit/index.js","debug":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/debug/browser.js","xmlhttprequest-ssl":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/lib/xmlhttprequest.js"}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/lib/transports/polling.js":[function(require,module,exports){
23921/**
23922 * Module dependencies.
23923 */
23924
23925var Transport = require('../transport');
23926var parseqs = require('parseqs');
23927var parser = require('engine.io-parser');
23928var inherit = require('component-inherit');
23929var yeast = require('yeast');
23930var debug = require('debug')('engine.io-client:polling');
23931
23932/**
23933 * Module exports.
23934 */
23935
23936module.exports = Polling;
23937
23938/**
23939 * Is XHR2 supported?
23940 */
23941
23942var hasXHR2 = (function() {
23943 var XMLHttpRequest = require('xmlhttprequest-ssl');
23944 var xhr = new XMLHttpRequest({ xdomain: false });
23945 return null != xhr.responseType;
23946})();
23947
23948/**
23949 * Polling interface.
23950 *
23951 * @param {Object} opts
23952 * @api private
23953 */
23954
23955function Polling(opts){
23956 var forceBase64 = (opts && opts.forceBase64);
23957 if (!hasXHR2 || forceBase64) {
23958 this.supportsBinary = false;
23959 }
23960 Transport.call(this, opts);
23961}
23962
23963/**
23964 * Inherits from Transport.
23965 */
23966
23967inherit(Polling, Transport);
23968
23969/**
23970 * Transport name.
23971 */
23972
23973Polling.prototype.name = 'polling';
23974
23975/**
23976 * Opens the socket (triggers polling). We write a PING message to determine
23977 * when the transport is open.
23978 *
23979 * @api private
23980 */
23981
23982Polling.prototype.doOpen = function(){
23983 this.poll();
23984};
23985
23986/**
23987 * Pauses polling.
23988 *
23989 * @param {Function} callback upon buffers are flushed and transport is paused
23990 * @api private
23991 */
23992
23993Polling.prototype.pause = function(onPause){
23994 var pending = 0;
23995 var self = this;
23996
23997 this.readyState = 'pausing';
23998
23999 function pause(){
24000 debug('paused');
24001 self.readyState = 'paused';
24002 onPause();
24003 }
24004
24005 if (this.polling || !this.writable) {
24006 var total = 0;
24007
24008 if (this.polling) {
24009 debug('we are currently polling - waiting to pause');
24010 total++;
24011 this.once('pollComplete', function(){
24012 debug('pre-pause polling complete');
24013 --total || pause();
24014 });
24015 }
24016
24017 if (!this.writable) {
24018 debug('we are currently writing - waiting to pause');
24019 total++;
24020 this.once('drain', function(){
24021 debug('pre-pause writing complete');
24022 --total || pause();
24023 });
24024 }
24025 } else {
24026 pause();
24027 }
24028};
24029
24030/**
24031 * Starts polling cycle.
24032 *
24033 * @api public
24034 */
24035
24036Polling.prototype.poll = function(){
24037 debug('polling');
24038 this.polling = true;
24039 this.doPoll();
24040 this.emit('poll');
24041};
24042
24043/**
24044 * Overloads onData to detect payloads.
24045 *
24046 * @api private
24047 */
24048
24049Polling.prototype.onData = function(data){
24050 var self = this;
24051 debug('polling got data %s', data);
24052 var callback = function(packet, index, total) {
24053 // if its the first message we consider the transport open
24054 if ('opening' == self.readyState) {
24055 self.onOpen();
24056 }
24057
24058 // if its a close packet, we close the ongoing requests
24059 if ('close' == packet.type) {
24060 self.onClose();
24061 return false;
24062 }
24063
24064 // otherwise bypass onData and handle the message
24065 self.onPacket(packet);
24066 };
24067
24068 // decode payload
24069 parser.decodePayload(data, this.socket.binaryType, callback);
24070
24071 // if an event did not trigger closing
24072 if ('closed' != this.readyState) {
24073 // if we got data we're not polling
24074 this.polling = false;
24075 this.emit('pollComplete');
24076
24077 if ('open' == this.readyState) {
24078 this.poll();
24079 } else {
24080 debug('ignoring poll - transport state "%s"', this.readyState);
24081 }
24082 }
24083};
24084
24085/**
24086 * For polling, send a close packet.
24087 *
24088 * @api private
24089 */
24090
24091Polling.prototype.doClose = function(){
24092 var self = this;
24093
24094 function close(){
24095 debug('writing close packet');
24096 self.write([{ type: 'close' }]);
24097 }
24098
24099 if ('open' == this.readyState) {
24100 debug('transport open - closing');
24101 close();
24102 } else {
24103 // in case we're trying to close while
24104 // handshaking is in progress (GH-164)
24105 debug('transport not open - deferring close');
24106 this.once('open', close);
24107 }
24108};
24109
24110/**
24111 * Writes a packets payload.
24112 *
24113 * @param {Array} data packets
24114 * @param {Function} drain callback
24115 * @api private
24116 */
24117
24118Polling.prototype.write = function(packets){
24119 var self = this;
24120 this.writable = false;
24121 var callbackfn = function() {
24122 self.writable = true;
24123 self.emit('drain');
24124 };
24125
24126 var self = this;
24127 parser.encodePayload(packets, this.supportsBinary, function(data) {
24128 self.doWrite(data, callbackfn);
24129 });
24130};
24131
24132/**
24133 * Generates uri for connection.
24134 *
24135 * @api private
24136 */
24137
24138Polling.prototype.uri = function(){
24139 var query = this.query || {};
24140 var schema = this.secure ? 'https' : 'http';
24141 var port = '';
24142
24143 // cache busting is forced
24144 if (false !== this.timestampRequests) {
24145 query[this.timestampParam] = yeast();
24146 }
24147
24148 if (!this.supportsBinary && !query.sid) {
24149 query.b64 = 1;
24150 }
24151
24152 query = parseqs.encode(query);
24153
24154 // avoid port if default for schema
24155 if (this.port && (('https' == schema && this.port != 443) ||
24156 ('http' == schema && this.port != 80))) {
24157 port = ':' + this.port;
24158 }
24159
24160 // prepend ? to query
24161 if (query.length) {
24162 query = '?' + query;
24163 }
24164
24165 var ipv6 = this.hostname.indexOf(':') !== -1;
24166 return schema + '://' + (ipv6 ? '[' + this.hostname + ']' : this.hostname) + port + this.path + query;
24167};
24168
24169},{"../transport":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/lib/transport.js","component-inherit":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/node_modules/component-inherit/index.js","debug":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/debug/browser.js","engine.io-parser":"/home/employee-2klic/projects/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/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/node_modules/parseqs/index.js","xmlhttprequest-ssl":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/lib/xmlhttprequest.js","yeast":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/node_modules/yeast/index.js"}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/lib/transports/websocket.js":[function(require,module,exports){
24170(function (global){
24171/**
24172 * Module dependencies.
24173 */
24174
24175var Transport = require('../transport');
24176var parser = require('engine.io-parser');
24177var parseqs = require('parseqs');
24178var inherit = require('component-inherit');
24179var yeast = require('yeast');
24180var debug = require('debug')('engine.io-client:websocket');
24181
24182/**
24183 * `ws` exposes a WebSocket-compatible interface in
24184 * Node, or the `WebSocket` or `MozWebSocket` globals
24185 * in the browser.
24186 */
24187
24188var WebSocket = require('ws');
24189
24190/**
24191 * Module exports.
24192 */
24193
24194module.exports = WS;
24195
24196/**
24197 * WebSocket transport constructor.
24198 *
24199 * @api {Object} connection options
24200 * @api public
24201 */
24202
24203function WS(opts){
24204 var forceBase64 = (opts && opts.forceBase64);
24205 if (forceBase64) {
24206 this.supportsBinary = false;
24207 }
24208 this.perMessageDeflate = opts.perMessageDeflate;
24209 Transport.call(this, opts);
24210}
24211
24212/**
24213 * Inherits from Transport.
24214 */
24215
24216inherit(WS, Transport);
24217
24218/**
24219 * Transport name.
24220 *
24221 * @api public
24222 */
24223
24224WS.prototype.name = 'websocket';
24225
24226/*
24227 * WebSockets support binary
24228 */
24229
24230WS.prototype.supportsBinary = true;
24231
24232/**
24233 * Opens socket.
24234 *
24235 * @api private
24236 */
24237
24238WS.prototype.doOpen = function(){
24239 if (!this.check()) {
24240 // let probe timeout
24241 return;
24242 }
24243
24244 var self = this;
24245 var uri = this.uri();
24246 var protocols = void(0);
24247 var opts = {
24248 agent: this.agent,
24249 perMessageDeflate: this.perMessageDeflate
24250 };
24251
24252 // SSL options for Node.js client
24253 opts.pfx = this.pfx;
24254 opts.key = this.key;
24255 opts.passphrase = this.passphrase;
24256 opts.cert = this.cert;
24257 opts.ca = this.ca;
24258 opts.ciphers = this.ciphers;
24259 opts.rejectUnauthorized = this.rejectUnauthorized;
24260 if (this.extraHeaders) {
24261 opts.headers = this.extraHeaders;
24262 }
24263
24264 this.ws = new WebSocket(uri, protocols, opts);
24265
24266 if (this.ws.binaryType === undefined) {
24267 this.supportsBinary = false;
24268 }
24269
24270 if (this.ws.supports && this.ws.supports.binary) {
24271 this.supportsBinary = true;
24272 this.ws.binaryType = 'buffer';
24273 } else {
24274 this.ws.binaryType = 'arraybuffer';
24275 }
24276
24277 this.addEventListeners();
24278};
24279
24280/**
24281 * Adds event listeners to the socket
24282 *
24283 * @api private
24284 */
24285
24286WS.prototype.addEventListeners = function(){
24287 var self = this;
24288
24289 this.ws.onopen = function(){
24290 self.onOpen();
24291 };
24292 this.ws.onclose = function(){
24293 self.onClose();
24294 };
24295 this.ws.onmessage = function(ev){
24296 self.onData(ev.data);
24297 };
24298 this.ws.onerror = function(e){
24299 self.onError('websocket error', e);
24300 };
24301};
24302
24303/**
24304 * Override `onData` to use a timer on iOS.
24305 * See: https://gist.github.com/mloughran/2052006
24306 *
24307 * @api private
24308 */
24309
24310if ('undefined' != typeof navigator
24311 && /iPad|iPhone|iPod/i.test(navigator.userAgent)) {
24312 WS.prototype.onData = function(data){
24313 var self = this;
24314 setTimeout(function(){
24315 Transport.prototype.onData.call(self, data);
24316 }, 0);
24317 };
24318}
24319
24320/**
24321 * Writes data to socket.
24322 *
24323 * @param {Array} array of packets.
24324 * @api private
24325 */
24326
24327WS.prototype.write = function(packets){
24328 var self = this;
24329 this.writable = false;
24330
24331 var isBrowserWebSocket = global.WebSocket && this.ws instanceof global.WebSocket;
24332
24333 // encodePacket efficient as it uses WS framing
24334 // no need for encodePayload
24335 var total = packets.length;
24336 for (var i = 0, l = total; i < l; i++) {
24337 (function(packet) {
24338 parser.encodePacket(packet, self.supportsBinary, function(data) {
24339 if (!isBrowserWebSocket) {
24340 // always create a new object (GH-437)
24341 var opts = {};
24342 if (packet.options) {
24343 opts.compress = packet.options.compress;
24344 }
24345
24346 if (self.perMessageDeflate) {
24347 var len = 'string' == typeof data ? global.Buffer.byteLength(data) : data.length;
24348 if (len < self.perMessageDeflate.threshold) {
24349 opts.compress = false;
24350 }
24351 }
24352 }
24353
24354 //Sometimes the websocket has already been closed but the browser didn't
24355 //have a chance of informing us about it yet, in that case send will
24356 //throw an error
24357 try {
24358 if (isBrowserWebSocket) {
24359 // TypeError is thrown when passing the second argument on Safari
24360 self.ws.send(data);
24361 } else {
24362 self.ws.send(data, opts);
24363 }
24364 } catch (e){
24365 debug('websocket closed before onclose event');
24366 }
24367
24368 --total || done();
24369 });
24370 })(packets[i]);
24371 }
24372
24373 function done(){
24374 self.emit('flush');
24375
24376 // fake drain
24377 // defer to next tick to allow Socket to clear writeBuffer
24378 setTimeout(function(){
24379 self.writable = true;
24380 self.emit('drain');
24381 }, 0);
24382 }
24383};
24384
24385/**
24386 * Called upon close
24387 *
24388 * @api private
24389 */
24390
24391WS.prototype.onClose = function(){
24392 Transport.prototype.onClose.call(this);
24393};
24394
24395/**
24396 * Closes socket.
24397 *
24398 * @api private
24399 */
24400
24401WS.prototype.doClose = function(){
24402 if (typeof this.ws !== 'undefined') {
24403 this.ws.close();
24404 }
24405};
24406
24407/**
24408 * Generates uri for connection.
24409 *
24410 * @api private
24411 */
24412
24413WS.prototype.uri = function(){
24414 var query = this.query || {};
24415 var schema = this.secure ? 'wss' : 'ws';
24416 var port = '';
24417
24418 // avoid port if default for schema
24419 if (this.port && (('wss' == schema && this.port != 443)
24420 || ('ws' == schema && this.port != 80))) {
24421 port = ':' + this.port;
24422 }
24423
24424 // append timestamp to URI
24425 if (this.timestampRequests) {
24426 query[this.timestampParam] = yeast();
24427 }
24428
24429 // communicate binary support capabilities
24430 if (!this.supportsBinary) {
24431 query.b64 = 1;
24432 }
24433
24434 query = parseqs.encode(query);
24435
24436 // prepend ? to query
24437 if (query.length) {
24438 query = '?' + query;
24439 }
24440
24441 var ipv6 = this.hostname.indexOf(':') !== -1;
24442 return schema + '://' + (ipv6 ? '[' + this.hostname + ']' : this.hostname) + port + this.path + query;
24443};
24444
24445/**
24446 * Feature detection for WebSocket.
24447 *
24448 * @return {Boolean} whether this transport is available.
24449 * @api public
24450 */
24451
24452WS.prototype.check = function(){
24453 return !!WebSocket && !('__initialize' in WebSocket && this.name === WS.prototype.name);
24454};
24455
24456}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
24457},{"../transport":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/lib/transport.js","component-inherit":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/node_modules/component-inherit/index.js","debug":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/debug/browser.js","engine.io-parser":"/home/employee-2klic/projects/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/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/node_modules/parseqs/index.js","ws":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/node_modules/ws/lib/browser.js","yeast":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/node_modules/yeast/index.js"}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/lib/xmlhttprequest.js":[function(require,module,exports){
24458// browser shim for xmlhttprequest module
24459var hasCORS = require('has-cors');
24460
24461module.exports = function(opts) {
24462 var xdomain = opts.xdomain;
24463
24464 // scheme must be same when usign XDomainRequest
24465 // http://blogs.msdn.com/b/ieinternals/archive/2010/05/13/xdomainrequest-restrictions-limitations-and-workarounds.aspx
24466 var xscheme = opts.xscheme;
24467
24468 // XDomainRequest has a flow of not sending cookie, therefore it should be disabled as a default.
24469 // https://github.com/Automattic/engine.io-client/pull/217
24470 var enablesXDR = opts.enablesXDR;
24471
24472 // XMLHttpRequest can be disabled on IE
24473 try {
24474 if ('undefined' != typeof XMLHttpRequest && (!xdomain || hasCORS)) {
24475 return new XMLHttpRequest();
24476 }
24477 } catch (e) { }
24478
24479 // Use XDomainRequest for IE8 if enablesXDR is true
24480 // because loading bar keeps flashing when using jsonp-polling
24481 // https://github.com/yujiosaka/socke.io-ie8-loading-example
24482 try {
24483 if ('undefined' != typeof XDomainRequest && !xscheme && enablesXDR) {
24484 return new XDomainRequest();
24485 }
24486 } catch (e) { }
24487
24488 if (!xdomain) {
24489 try {
24490 return new ActiveXObject('Microsoft.XMLHTTP');
24491 } catch(e) { }
24492 }
24493}
24494
24495},{"has-cors":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/node_modules/has-cors/index.js"}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/node_modules/component-emitter/index.js":[function(require,module,exports){
24496
24497/**
24498 * Expose `Emitter`.
24499 */
24500
24501module.exports = Emitter;
24502
24503/**
24504 * Initialize a new `Emitter`.
24505 *
24506 * @api public
24507 */
24508
24509function Emitter(obj) {
24510 if (obj) return mixin(obj);
24511};
24512
24513/**
24514 * Mixin the emitter properties.
24515 *
24516 * @param {Object} obj
24517 * @return {Object}
24518 * @api private
24519 */
24520
24521function mixin(obj) {
24522 for (var key in Emitter.prototype) {
24523 obj[key] = Emitter.prototype[key];
24524 }
24525 return obj;
24526}
24527
24528/**
24529 * Listen on the given `event` with `fn`.
24530 *
24531 * @param {String} event
24532 * @param {Function} fn
24533 * @return {Emitter}
24534 * @api public
24535 */
24536
24537Emitter.prototype.on =
24538Emitter.prototype.addEventListener = function(event, fn){
24539 this._callbacks = this._callbacks || {};
24540 (this._callbacks[event] = this._callbacks[event] || [])
24541 .push(fn);
24542 return this;
24543};
24544
24545/**
24546 * Adds an `event` listener that will be invoked a single
24547 * time then automatically removed.
24548 *
24549 * @param {String} event
24550 * @param {Function} fn
24551 * @return {Emitter}
24552 * @api public
24553 */
24554
24555Emitter.prototype.once = function(event, fn){
24556 var self = this;
24557 this._callbacks = this._callbacks || {};
24558
24559 function on() {
24560 self.off(event, on);
24561 fn.apply(this, arguments);
24562 }
24563
24564 on.fn = fn;
24565 this.on(event, on);
24566 return this;
24567};
24568
24569/**
24570 * Remove the given callback for `event` or all
24571 * registered callbacks.
24572 *
24573 * @param {String} event
24574 * @param {Function} fn
24575 * @return {Emitter}
24576 * @api public
24577 */
24578
24579Emitter.prototype.off =
24580Emitter.prototype.removeListener =
24581Emitter.prototype.removeAllListeners =
24582Emitter.prototype.removeEventListener = function(event, fn){
24583 this._callbacks = this._callbacks || {};
24584
24585 // all
24586 if (0 == arguments.length) {
24587 this._callbacks = {};
24588 return this;
24589 }
24590
24591 // specific event
24592 var callbacks = this._callbacks[event];
24593 if (!callbacks) return this;
24594
24595 // remove all handlers
24596 if (1 == arguments.length) {
24597 delete this._callbacks[event];
24598 return this;
24599 }
24600
24601 // remove specific handler
24602 var cb;
24603 for (var i = 0; i < callbacks.length; i++) {
24604 cb = callbacks[i];
24605 if (cb === fn || cb.fn === fn) {
24606 callbacks.splice(i, 1);
24607 break;
24608 }
24609 }
24610 return this;
24611};
24612
24613/**
24614 * Emit `event` with the given args.
24615 *
24616 * @param {String} event
24617 * @param {Mixed} ...
24618 * @return {Emitter}
24619 */
24620
24621Emitter.prototype.emit = function(event){
24622 this._callbacks = this._callbacks || {};
24623 var args = [].slice.call(arguments, 1)
24624 , callbacks = this._callbacks[event];
24625
24626 if (callbacks) {
24627 callbacks = callbacks.slice(0);
24628 for (var i = 0, len = callbacks.length; i < len; ++i) {
24629 callbacks[i].apply(this, args);
24630 }
24631 }
24632
24633 return this;
24634};
24635
24636/**
24637 * Return array of callbacks for `event`.
24638 *
24639 * @param {String} event
24640 * @return {Array}
24641 * @api public
24642 */
24643
24644Emitter.prototype.listeners = function(event){
24645 this._callbacks = this._callbacks || {};
24646 return this._callbacks[event] || [];
24647};
24648
24649/**
24650 * Check if this emitter has `event` handlers.
24651 *
24652 * @param {String} event
24653 * @return {Boolean}
24654 * @api public
24655 */
24656
24657Emitter.prototype.hasListeners = function(event){
24658 return !! this.listeners(event).length;
24659};
24660
24661},{}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/node_modules/component-inherit/index.js":[function(require,module,exports){
24662
24663module.exports = function(a, b){
24664 var fn = function(){};
24665 fn.prototype = b.prototype;
24666 a.prototype = new fn;
24667 a.prototype.constructor = a;
24668};
24669},{}],"/home/employee-2klic/projects/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){
24670(function (global){
24671/**
24672 * Module dependencies.
24673 */
24674
24675var keys = require('./keys');
24676var hasBinary = require('has-binary');
24677var sliceBuffer = require('arraybuffer.slice');
24678var base64encoder = require('base64-arraybuffer');
24679var after = require('after');
24680var utf8 = require('utf8');
24681
24682/**
24683 * Check if we are running an android browser. That requires us to use
24684 * ArrayBuffer with polling transports...
24685 *
24686 * http://ghinda.net/jpeg-blob-ajax-android/
24687 */
24688
24689var isAndroid = navigator.userAgent.match(/Android/i);
24690
24691/**
24692 * Check if we are running in PhantomJS.
24693 * Uploading a Blob with PhantomJS does not work correctly, as reported here:
24694 * https://github.com/ariya/phantomjs/issues/11395
24695 * @type boolean
24696 */
24697var isPhantomJS = /PhantomJS/i.test(navigator.userAgent);
24698
24699/**
24700 * When true, avoids using Blobs to encode payloads.
24701 * @type boolean
24702 */
24703var dontSendBlobs = isAndroid || isPhantomJS;
24704
24705/**
24706 * Current protocol version.
24707 */
24708
24709exports.protocol = 3;
24710
24711/**
24712 * Packet types.
24713 */
24714
24715var packets = exports.packets = {
24716 open: 0 // non-ws
24717 , close: 1 // non-ws
24718 , ping: 2
24719 , pong: 3
24720 , message: 4
24721 , upgrade: 5
24722 , noop: 6
24723};
24724
24725var packetslist = keys(packets);
24726
24727/**
24728 * Premade error packet.
24729 */
24730
24731var err = { type: 'error', data: 'parser error' };
24732
24733/**
24734 * Create a blob api even for blob builder when vendor prefixes exist
24735 */
24736
24737var Blob = require('blob');
24738
24739/**
24740 * Encodes a packet.
24741 *
24742 * <packet type id> [ <data> ]
24743 *
24744 * Example:
24745 *
24746 * 5hello world
24747 * 3
24748 * 4
24749 *
24750 * Binary is encoded in an identical principle
24751 *
24752 * @api private
24753 */
24754
24755exports.encodePacket = function (packet, supportsBinary, utf8encode, callback) {
24756 if ('function' == typeof supportsBinary) {
24757 callback = supportsBinary;
24758 supportsBinary = false;
24759 }
24760
24761 if ('function' == typeof utf8encode) {
24762 callback = utf8encode;
24763 utf8encode = null;
24764 }
24765
24766 var data = (packet.data === undefined)
24767 ? undefined
24768 : packet.data.buffer || packet.data;
24769
24770 if (global.ArrayBuffer && data instanceof ArrayBuffer) {
24771 return encodeArrayBuffer(packet, supportsBinary, callback);
24772 } else if (Blob && data instanceof global.Blob) {
24773 return encodeBlob(packet, supportsBinary, callback);
24774 }
24775
24776 // might be an object with { base64: true, data: dataAsBase64String }
24777 if (data && data.base64) {
24778 return encodeBase64Object(packet, callback);
24779 }
24780
24781 // Sending data as a utf-8 string
24782 var encoded = packets[packet.type];
24783
24784 // data fragment is optional
24785 if (undefined !== packet.data) {
24786 encoded += utf8encode ? utf8.encode(String(packet.data)) : String(packet.data);
24787 }
24788
24789 return callback('' + encoded);
24790
24791};
24792
24793function encodeBase64Object(packet, callback) {
24794 // packet data is an object { base64: true, data: dataAsBase64String }
24795 var message = 'b' + exports.packets[packet.type] + packet.data.data;
24796 return callback(message);
24797}
24798
24799/**
24800 * Encode packet helpers for binary types
24801 */
24802
24803function encodeArrayBuffer(packet, supportsBinary, callback) {
24804 if (!supportsBinary) {
24805 return exports.encodeBase64Packet(packet, callback);
24806 }
24807
24808 var data = packet.data;
24809 var contentArray = new Uint8Array(data);
24810 var resultBuffer = new Uint8Array(1 + data.byteLength);
24811
24812 resultBuffer[0] = packets[packet.type];
24813 for (var i = 0; i < contentArray.length; i++) {
24814 resultBuffer[i+1] = contentArray[i];
24815 }
24816
24817 return callback(resultBuffer.buffer);
24818}
24819
24820function encodeBlobAsArrayBuffer(packet, supportsBinary, callback) {
24821 if (!supportsBinary) {
24822 return exports.encodeBase64Packet(packet, callback);
24823 }
24824
24825 var fr = new FileReader();
24826 fr.onload = function() {
24827 packet.data = fr.result;
24828 exports.encodePacket(packet, supportsBinary, true, callback);
24829 };
24830 return fr.readAsArrayBuffer(packet.data);
24831}
24832
24833function encodeBlob(packet, supportsBinary, callback) {
24834 if (!supportsBinary) {
24835 return exports.encodeBase64Packet(packet, callback);
24836 }
24837
24838 if (dontSendBlobs) {
24839 return encodeBlobAsArrayBuffer(packet, supportsBinary, callback);
24840 }
24841
24842 var length = new Uint8Array(1);
24843 length[0] = packets[packet.type];
24844 var blob = new Blob([length.buffer, packet.data]);
24845
24846 return callback(blob);
24847}
24848
24849/**
24850 * Encodes a packet with binary data in a base64 string
24851 *
24852 * @param {Object} packet, has `type` and `data`
24853 * @return {String} base64 encoded message
24854 */
24855
24856exports.encodeBase64Packet = function(packet, callback) {
24857 var message = 'b' + exports.packets[packet.type];
24858 if (Blob && packet.data instanceof global.Blob) {
24859 var fr = new FileReader();
24860 fr.onload = function() {
24861 var b64 = fr.result.split(',')[1];
24862 callback(message + b64);
24863 };
24864 return fr.readAsDataURL(packet.data);
24865 }
24866
24867 var b64data;
24868 try {
24869 b64data = String.fromCharCode.apply(null, new Uint8Array(packet.data));
24870 } catch (e) {
24871 // iPhone Safari doesn't let you apply with typed arrays
24872 var typed = new Uint8Array(packet.data);
24873 var basic = new Array(typed.length);
24874 for (var i = 0; i < typed.length; i++) {
24875 basic[i] = typed[i];
24876 }
24877 b64data = String.fromCharCode.apply(null, basic);
24878 }
24879 message += global.btoa(b64data);
24880 return callback(message);
24881};
24882
24883/**
24884 * Decodes a packet. Changes format to Blob if requested.
24885 *
24886 * @return {Object} with `type` and `data` (if any)
24887 * @api private
24888 */
24889
24890exports.decodePacket = function (data, binaryType, utf8decode) {
24891 // String data
24892 if (typeof data == 'string' || data === undefined) {
24893 if (data.charAt(0) == 'b') {
24894 return exports.decodeBase64Packet(data.substr(1), binaryType);
24895 }
24896
24897 if (utf8decode) {
24898 try {
24899 data = utf8.decode(data);
24900 } catch (e) {
24901 return err;
24902 }
24903 }
24904 var type = data.charAt(0);
24905
24906 if (Number(type) != type || !packetslist[type]) {
24907 return err;
24908 }
24909
24910 if (data.length > 1) {
24911 return { type: packetslist[type], data: data.substring(1) };
24912 } else {
24913 return { type: packetslist[type] };
24914 }
24915 }
24916
24917 var asArray = new Uint8Array(data);
24918 var type = asArray[0];
24919 var rest = sliceBuffer(data, 1);
24920 if (Blob && binaryType === 'blob') {
24921 rest = new Blob([rest]);
24922 }
24923 return { type: packetslist[type], data: rest };
24924};
24925
24926/**
24927 * Decodes a packet encoded in a base64 string
24928 *
24929 * @param {String} base64 encoded message
24930 * @return {Object} with `type` and `data` (if any)
24931 */
24932
24933exports.decodeBase64Packet = function(msg, binaryType) {
24934 var type = packetslist[msg.charAt(0)];
24935 if (!global.ArrayBuffer) {
24936 return { type: type, data: { base64: true, data: msg.substr(1) } };
24937 }
24938
24939 var data = base64encoder.decode(msg.substr(1));
24940
24941 if (binaryType === 'blob' && Blob) {
24942 data = new Blob([data]);
24943 }
24944
24945 return { type: type, data: data };
24946};
24947
24948/**
24949 * Encodes multiple messages (payload).
24950 *
24951 * <length>:data
24952 *
24953 * Example:
24954 *
24955 * 11:hello world2:hi
24956 *
24957 * If any contents are binary, they will be encoded as base64 strings. Base64
24958 * encoded strings are marked with a b before the length specifier
24959 *
24960 * @param {Array} packets
24961 * @api private
24962 */
24963
24964exports.encodePayload = function (packets, supportsBinary, callback) {
24965 if (typeof supportsBinary == 'function') {
24966 callback = supportsBinary;
24967 supportsBinary = null;
24968 }
24969
24970 var isBinary = hasBinary(packets);
24971
24972 if (supportsBinary && isBinary) {
24973 if (Blob && !dontSendBlobs) {
24974 return exports.encodePayloadAsBlob(packets, callback);
24975 }
24976
24977 return exports.encodePayloadAsArrayBuffer(packets, callback);
24978 }
24979
24980 if (!packets.length) {
24981 return callback('0:');
24982 }
24983
24984 function setLengthHeader(message) {
24985 return message.length + ':' + message;
24986 }
24987
24988 function encodeOne(packet, doneCallback) {
24989 exports.encodePacket(packet, !isBinary ? false : supportsBinary, true, function(message) {
24990 doneCallback(null, setLengthHeader(message));
24991 });
24992 }
24993
24994 map(packets, encodeOne, function(err, results) {
24995 return callback(results.join(''));
24996 });
24997};
24998
24999/**
25000 * Async array map using after
25001 */
25002
25003function map(ary, each, done) {
25004 var result = new Array(ary.length);
25005 var next = after(ary.length, done);
25006
25007 var eachWithIndex = function(i, el, cb) {
25008 each(el, function(error, msg) {
25009 result[i] = msg;
25010 cb(error, result);
25011 });
25012 };
25013
25014 for (var i = 0; i < ary.length; i++) {
25015 eachWithIndex(i, ary[i], next);
25016 }
25017}
25018
25019/*
25020 * Decodes data when a payload is maybe expected. Possible binary contents are
25021 * decoded from their base64 representation
25022 *
25023 * @param {String} data, callback method
25024 * @api public
25025 */
25026
25027exports.decodePayload = function (data, binaryType, callback) {
25028 if (typeof data != 'string') {
25029 return exports.decodePayloadAsBinary(data, binaryType, callback);
25030 }
25031
25032 if (typeof binaryType === 'function') {
25033 callback = binaryType;
25034 binaryType = null;
25035 }
25036
25037 var packet;
25038 if (data == '') {
25039 // parser error - ignoring payload
25040 return callback(err, 0, 1);
25041 }
25042
25043 var length = ''
25044 , n, msg;
25045
25046 for (var i = 0, l = data.length; i < l; i++) {
25047 var chr = data.charAt(i);
25048
25049 if (':' != chr) {
25050 length += chr;
25051 } else {
25052 if ('' == length || (length != (n = Number(length)))) {
25053 // parser error - ignoring payload
25054 return callback(err, 0, 1);
25055 }
25056
25057 msg = data.substr(i + 1, n);
25058
25059 if (length != msg.length) {
25060 // parser error - ignoring payload
25061 return callback(err, 0, 1);
25062 }
25063
25064 if (msg.length) {
25065 packet = exports.decodePacket(msg, binaryType, true);
25066
25067 if (err.type == packet.type && err.data == packet.data) {
25068 // parser error in individual packet - ignoring payload
25069 return callback(err, 0, 1);
25070 }
25071
25072 var ret = callback(packet, i + n, l);
25073 if (false === ret) return;
25074 }
25075
25076 // advance cursor
25077 i += n;
25078 length = '';
25079 }
25080 }
25081
25082 if (length != '') {
25083 // parser error - ignoring payload
25084 return callback(err, 0, 1);
25085 }
25086
25087};
25088
25089/**
25090 * Encodes multiple messages (payload) as binary.
25091 *
25092 * <1 = binary, 0 = string><number from 0-9><number from 0-9>[...]<number
25093 * 255><data>
25094 *
25095 * Example:
25096 * 1 3 255 1 2 3, if the binary contents are interpreted as 8 bit integers
25097 *
25098 * @param {Array} packets
25099 * @return {ArrayBuffer} encoded payload
25100 * @api private
25101 */
25102
25103exports.encodePayloadAsArrayBuffer = function(packets, callback) {
25104 if (!packets.length) {
25105 return callback(new ArrayBuffer(0));
25106 }
25107
25108 function encodeOne(packet, doneCallback) {
25109 exports.encodePacket(packet, true, true, function(data) {
25110 return doneCallback(null, data);
25111 });
25112 }
25113
25114 map(packets, encodeOne, function(err, encodedPackets) {
25115 var totalLength = encodedPackets.reduce(function(acc, p) {
25116 var len;
25117 if (typeof p === 'string'){
25118 len = p.length;
25119 } else {
25120 len = p.byteLength;
25121 }
25122 return acc + len.toString().length + len + 2; // string/binary identifier + separator = 2
25123 }, 0);
25124
25125 var resultArray = new Uint8Array(totalLength);
25126
25127 var bufferIndex = 0;
25128 encodedPackets.forEach(function(p) {
25129 var isString = typeof p === 'string';
25130 var ab = p;
25131 if (isString) {
25132 var view = new Uint8Array(p.length);
25133 for (var i = 0; i < p.length; i++) {
25134 view[i] = p.charCodeAt(i);
25135 }
25136 ab = view.buffer;
25137 }
25138
25139 if (isString) { // not true binary
25140 resultArray[bufferIndex++] = 0;
25141 } else { // true binary
25142 resultArray[bufferIndex++] = 1;
25143 }
25144
25145 var lenStr = ab.byteLength.toString();
25146 for (var i = 0; i < lenStr.length; i++) {
25147 resultArray[bufferIndex++] = parseInt(lenStr[i]);
25148 }
25149 resultArray[bufferIndex++] = 255;
25150
25151 var view = new Uint8Array(ab);
25152 for (var i = 0; i < view.length; i++) {
25153 resultArray[bufferIndex++] = view[i];
25154 }
25155 });
25156
25157 return callback(resultArray.buffer);
25158 });
25159};
25160
25161/**
25162 * Encode as Blob
25163 */
25164
25165exports.encodePayloadAsBlob = function(packets, callback) {
25166 function encodeOne(packet, doneCallback) {
25167 exports.encodePacket(packet, true, true, function(encoded) {
25168 var binaryIdentifier = new Uint8Array(1);
25169 binaryIdentifier[0] = 1;
25170 if (typeof encoded === 'string') {
25171 var view = new Uint8Array(encoded.length);
25172 for (var i = 0; i < encoded.length; i++) {
25173 view[i] = encoded.charCodeAt(i);
25174 }
25175 encoded = view.buffer;
25176 binaryIdentifier[0] = 0;
25177 }
25178
25179 var len = (encoded instanceof ArrayBuffer)
25180 ? encoded.byteLength
25181 : encoded.size;
25182
25183 var lenStr = len.toString();
25184 var lengthAry = new Uint8Array(lenStr.length + 1);
25185 for (var i = 0; i < lenStr.length; i++) {
25186 lengthAry[i] = parseInt(lenStr[i]);
25187 }
25188 lengthAry[lenStr.length] = 255;
25189
25190 if (Blob) {
25191 var blob = new Blob([binaryIdentifier.buffer, lengthAry.buffer, encoded]);
25192 doneCallback(null, blob);
25193 }
25194 });
25195 }
25196
25197 map(packets, encodeOne, function(err, results) {
25198 return callback(new Blob(results));
25199 });
25200};
25201
25202/*
25203 * Decodes data when a payload is maybe expected. Strings are decoded by
25204 * interpreting each byte as a key code for entries marked to start with 0. See
25205 * description of encodePayloadAsBinary
25206 *
25207 * @param {ArrayBuffer} data, callback method
25208 * @api public
25209 */
25210
25211exports.decodePayloadAsBinary = function (data, binaryType, callback) {
25212 if (typeof binaryType === 'function') {
25213 callback = binaryType;
25214 binaryType = null;
25215 }
25216
25217 var bufferTail = data;
25218 var buffers = [];
25219
25220 var numberTooLong = false;
25221 while (bufferTail.byteLength > 0) {
25222 var tailArray = new Uint8Array(bufferTail);
25223 var isString = tailArray[0] === 0;
25224 var msgLength = '';
25225
25226 for (var i = 1; ; i++) {
25227 if (tailArray[i] == 255) break;
25228
25229 if (msgLength.length > 310) {
25230 numberTooLong = true;
25231 break;
25232 }
25233
25234 msgLength += tailArray[i];
25235 }
25236
25237 if(numberTooLong) return callback(err, 0, 1);
25238
25239 bufferTail = sliceBuffer(bufferTail, 2 + msgLength.length);
25240 msgLength = parseInt(msgLength);
25241
25242 var msg = sliceBuffer(bufferTail, 0, msgLength);
25243 if (isString) {
25244 try {
25245 msg = String.fromCharCode.apply(null, new Uint8Array(msg));
25246 } catch (e) {
25247 // iPhone Safari doesn't let you apply to typed arrays
25248 var typed = new Uint8Array(msg);
25249 msg = '';
25250 for (var i = 0; i < typed.length; i++) {
25251 msg += String.fromCharCode(typed[i]);
25252 }
25253 }
25254 }
25255
25256 buffers.push(msg);
25257 bufferTail = sliceBuffer(bufferTail, msgLength);
25258 }
25259
25260 var total = buffers.length;
25261 buffers.forEach(function(buffer, i) {
25262 callback(exports.decodePacket(buffer, binaryType, true), i, total);
25263 });
25264};
25265
25266}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
25267},{"./keys":"/home/employee-2klic/projects/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/projects/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/projects/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/projects/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/projects/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/projects/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/projects/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/projects/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){
25268
25269/**
25270 * Gets the keys for an object.
25271 *
25272 * @return {Array} keys
25273 * @api private
25274 */
25275
25276module.exports = Object.keys || function keys (obj){
25277 var arr = [];
25278 var has = Object.prototype.hasOwnProperty;
25279
25280 for (var i in obj) {
25281 if (has.call(obj, i)) {
25282 arr.push(i);
25283 }
25284 }
25285 return arr;
25286};
25287
25288},{}],"/home/employee-2klic/projects/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){
25289module.exports = after
25290
25291function after(count, callback, err_cb) {
25292 var bail = false
25293 err_cb = err_cb || noop
25294 proxy.count = count
25295
25296 return (count === 0) ? callback() : proxy
25297
25298 function proxy(err, result) {
25299 if (proxy.count <= 0) {
25300 throw new Error('after called too many times')
25301 }
25302 --proxy.count
25303
25304 // after first error, rest are passed to err_cb
25305 if (err) {
25306 bail = true
25307 callback(err)
25308 // future error callbacks will go to error handler
25309 callback = err_cb
25310 } else if (proxy.count === 0 && !bail) {
25311 callback(null, result)
25312 }
25313 }
25314}
25315
25316function noop() {}
25317
25318},{}],"/home/employee-2klic/projects/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){
25319/**
25320 * An abstraction for slicing an arraybuffer even when
25321 * ArrayBuffer.prototype.slice is not supported
25322 *
25323 * @api public
25324 */
25325
25326module.exports = function(arraybuffer, start, end) {
25327 var bytes = arraybuffer.byteLength;
25328 start = start || 0;
25329 end = end || bytes;
25330
25331 if (arraybuffer.slice) { return arraybuffer.slice(start, end); }
25332
25333 if (start < 0) { start += bytes; }
25334 if (end < 0) { end += bytes; }
25335 if (end > bytes) { end = bytes; }
25336
25337 if (start >= bytes || start >= end || bytes === 0) {
25338 return new ArrayBuffer(0);
25339 }
25340
25341 var abv = new Uint8Array(arraybuffer);
25342 var result = new Uint8Array(end - start);
25343 for (var i = start, ii = 0; i < end; i++, ii++) {
25344 result[ii] = abv[i];
25345 }
25346 return result.buffer;
25347};
25348
25349},{}],"/home/employee-2klic/projects/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){
25350/*
25351 * base64-arraybuffer
25352 * https://github.com/niklasvh/base64-arraybuffer
25353 *
25354 * Copyright (c) 2012 Niklas von Hertzen
25355 * Licensed under the MIT license.
25356 */
25357(function(chars){
25358 "use strict";
25359
25360 exports.encode = function(arraybuffer) {
25361 var bytes = new Uint8Array(arraybuffer),
25362 i, len = bytes.length, base64 = "";
25363
25364 for (i = 0; i < len; i+=3) {
25365 base64 += chars[bytes[i] >> 2];
25366 base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];
25367 base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];
25368 base64 += chars[bytes[i + 2] & 63];
25369 }
25370
25371 if ((len % 3) === 2) {
25372 base64 = base64.substring(0, base64.length - 1) + "=";
25373 } else if (len % 3 === 1) {
25374 base64 = base64.substring(0, base64.length - 2) + "==";
25375 }
25376
25377 return base64;
25378 };
25379
25380 exports.decode = function(base64) {
25381 var bufferLength = base64.length * 0.75,
25382 len = base64.length, i, p = 0,
25383 encoded1, encoded2, encoded3, encoded4;
25384
25385 if (base64[base64.length - 1] === "=") {
25386 bufferLength--;
25387 if (base64[base64.length - 2] === "=") {
25388 bufferLength--;
25389 }
25390 }
25391
25392 var arraybuffer = new ArrayBuffer(bufferLength),
25393 bytes = new Uint8Array(arraybuffer);
25394
25395 for (i = 0; i < len; i+=4) {
25396 encoded1 = chars.indexOf(base64[i]);
25397 encoded2 = chars.indexOf(base64[i+1]);
25398 encoded3 = chars.indexOf(base64[i+2]);
25399 encoded4 = chars.indexOf(base64[i+3]);
25400
25401 bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);
25402 bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);
25403 bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);
25404 }
25405
25406 return arraybuffer;
25407 };
25408})("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/");
25409
25410},{}],"/home/employee-2klic/projects/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){
25411(function (global){
25412/**
25413 * Create a blob builder even when vendor prefixes exist
25414 */
25415
25416var BlobBuilder = global.BlobBuilder
25417 || global.WebKitBlobBuilder
25418 || global.MSBlobBuilder
25419 || global.MozBlobBuilder;
25420
25421/**
25422 * Check if Blob constructor is supported
25423 */
25424
25425var blobSupported = (function() {
25426 try {
25427 var a = new Blob(['hi']);
25428 return a.size === 2;
25429 } catch(e) {
25430 return false;
25431 }
25432})();
25433
25434/**
25435 * Check if Blob constructor supports ArrayBufferViews
25436 * Fails in Safari 6, so we need to map to ArrayBuffers there.
25437 */
25438
25439var blobSupportsArrayBufferView = blobSupported && (function() {
25440 try {
25441 var b = new Blob([new Uint8Array([1,2])]);
25442 return b.size === 2;
25443 } catch(e) {
25444 return false;
25445 }
25446})();
25447
25448/**
25449 * Check if BlobBuilder is supported
25450 */
25451
25452var blobBuilderSupported = BlobBuilder
25453 && BlobBuilder.prototype.append
25454 && BlobBuilder.prototype.getBlob;
25455
25456/**
25457 * Helper function that maps ArrayBufferViews to ArrayBuffers
25458 * Used by BlobBuilder constructor and old browsers that didn't
25459 * support it in the Blob constructor.
25460 */
25461
25462function mapArrayBufferViews(ary) {
25463 for (var i = 0; i < ary.length; i++) {
25464 var chunk = ary[i];
25465 if (chunk.buffer instanceof ArrayBuffer) {
25466 var buf = chunk.buffer;
25467
25468 // if this is a subarray, make a copy so we only
25469 // include the subarray region from the underlying buffer
25470 if (chunk.byteLength !== buf.byteLength) {
25471 var copy = new Uint8Array(chunk.byteLength);
25472 copy.set(new Uint8Array(buf, chunk.byteOffset, chunk.byteLength));
25473 buf = copy.buffer;
25474 }
25475
25476 ary[i] = buf;
25477 }
25478 }
25479}
25480
25481function BlobBuilderConstructor(ary, options) {
25482 options = options || {};
25483
25484 var bb = new BlobBuilder();
25485 mapArrayBufferViews(ary);
25486
25487 for (var i = 0; i < ary.length; i++) {
25488 bb.append(ary[i]);
25489 }
25490
25491 return (options.type) ? bb.getBlob(options.type) : bb.getBlob();
25492};
25493
25494function BlobConstructor(ary, options) {
25495 mapArrayBufferViews(ary);
25496 return new Blob(ary, options || {});
25497};
25498
25499module.exports = (function() {
25500 if (blobSupported) {
25501 return blobSupportsArrayBufferView ? global.Blob : BlobConstructor;
25502 } else if (blobBuilderSupported) {
25503 return BlobBuilderConstructor;
25504 } else {
25505 return undefined;
25506 }
25507})();
25508
25509}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
25510},{}],"/home/employee-2klic/projects/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){
25511(function (global){
25512
25513/*
25514 * Module requirements.
25515 */
25516
25517var isArray = require('isarray');
25518
25519/**
25520 * Module exports.
25521 */
25522
25523module.exports = hasBinary;
25524
25525/**
25526 * Checks for binary data.
25527 *
25528 * Right now only Buffer and ArrayBuffer are supported..
25529 *
25530 * @param {Object} anything
25531 * @api public
25532 */
25533
25534function hasBinary(data) {
25535
25536 function _hasBinary(obj) {
25537 if (!obj) return false;
25538
25539 if ( (global.Buffer && global.Buffer.isBuffer(obj)) ||
25540 (global.ArrayBuffer && obj instanceof ArrayBuffer) ||
25541 (global.Blob && obj instanceof Blob) ||
25542 (global.File && obj instanceof File)
25543 ) {
25544 return true;
25545 }
25546
25547 if (isArray(obj)) {
25548 for (var i = 0; i < obj.length; i++) {
25549 if (_hasBinary(obj[i])) {
25550 return true;
25551 }
25552 }
25553 } else if (obj && 'object' == typeof obj) {
25554 if (obj.toJSON) {
25555 obj = obj.toJSON();
25556 }
25557
25558 for (var key in obj) {
25559 if (Object.prototype.hasOwnProperty.call(obj, key) && _hasBinary(obj[key])) {
25560 return true;
25561 }
25562 }
25563 }
25564
25565 return false;
25566 }
25567
25568 return _hasBinary(data);
25569}
25570
25571}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
25572},{"isarray":"/home/employee-2klic/projects/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/projects/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){
25573module.exports = Array.isArray || function (arr) {
25574 return Object.prototype.toString.call(arr) == '[object Array]';
25575};
25576
25577},{}],"/home/employee-2klic/projects/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){
25578(function (global){
25579/*! https://mths.be/utf8js v2.0.0 by @mathias */
25580;(function(root) {
25581
25582 // Detect free variables `exports`
25583 var freeExports = typeof exports == 'object' && exports;
25584
25585 // Detect free variable `module`
25586 var freeModule = typeof module == 'object' && module &&
25587 module.exports == freeExports && module;
25588
25589 // Detect free variable `global`, from Node.js or Browserified code,
25590 // and use it as `root`
25591 var freeGlobal = typeof global == 'object' && global;
25592 if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) {
25593 root = freeGlobal;
25594 }
25595
25596 /*--------------------------------------------------------------------------*/
25597
25598 var stringFromCharCode = String.fromCharCode;
25599
25600 // Taken from https://mths.be/punycode
25601 function ucs2decode(string) {
25602 var output = [];
25603 var counter = 0;
25604 var length = string.length;
25605 var value;
25606 var extra;
25607 while (counter < length) {
25608 value = string.charCodeAt(counter++);
25609 if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
25610 // high surrogate, and there is a next character
25611 extra = string.charCodeAt(counter++);
25612 if ((extra & 0xFC00) == 0xDC00) { // low surrogate
25613 output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
25614 } else {
25615 // unmatched surrogate; only append this code unit, in case the next
25616 // code unit is the high surrogate of a surrogate pair
25617 output.push(value);
25618 counter--;
25619 }
25620 } else {
25621 output.push(value);
25622 }
25623 }
25624 return output;
25625 }
25626
25627 // Taken from https://mths.be/punycode
25628 function ucs2encode(array) {
25629 var length = array.length;
25630 var index = -1;
25631 var value;
25632 var output = '';
25633 while (++index < length) {
25634 value = array[index];
25635 if (value > 0xFFFF) {
25636 value -= 0x10000;
25637 output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
25638 value = 0xDC00 | value & 0x3FF;
25639 }
25640 output += stringFromCharCode(value);
25641 }
25642 return output;
25643 }
25644
25645 function checkScalarValue(codePoint) {
25646 if (codePoint >= 0xD800 && codePoint <= 0xDFFF) {
25647 throw Error(
25648 'Lone surrogate U+' + codePoint.toString(16).toUpperCase() +
25649 ' is not a scalar value'
25650 );
25651 }
25652 }
25653 /*--------------------------------------------------------------------------*/
25654
25655 function createByte(codePoint, shift) {
25656 return stringFromCharCode(((codePoint >> shift) & 0x3F) | 0x80);
25657 }
25658
25659 function encodeCodePoint(codePoint) {
25660 if ((codePoint & 0xFFFFFF80) == 0) { // 1-byte sequence
25661 return stringFromCharCode(codePoint);
25662 }
25663 var symbol = '';
25664 if ((codePoint & 0xFFFFF800) == 0) { // 2-byte sequence
25665 symbol = stringFromCharCode(((codePoint >> 6) & 0x1F) | 0xC0);
25666 }
25667 else if ((codePoint & 0xFFFF0000) == 0) { // 3-byte sequence
25668 checkScalarValue(codePoint);
25669 symbol = stringFromCharCode(((codePoint >> 12) & 0x0F) | 0xE0);
25670 symbol += createByte(codePoint, 6);
25671 }
25672 else if ((codePoint & 0xFFE00000) == 0) { // 4-byte sequence
25673 symbol = stringFromCharCode(((codePoint >> 18) & 0x07) | 0xF0);
25674 symbol += createByte(codePoint, 12);
25675 symbol += createByte(codePoint, 6);
25676 }
25677 symbol += stringFromCharCode((codePoint & 0x3F) | 0x80);
25678 return symbol;
25679 }
25680
25681 function utf8encode(string) {
25682 var codePoints = ucs2decode(string);
25683 var length = codePoints.length;
25684 var index = -1;
25685 var codePoint;
25686 var byteString = '';
25687 while (++index < length) {
25688 codePoint = codePoints[index];
25689 byteString += encodeCodePoint(codePoint);
25690 }
25691 return byteString;
25692 }
25693
25694 /*--------------------------------------------------------------------------*/
25695
25696 function readContinuationByte() {
25697 if (byteIndex >= byteCount) {
25698 throw Error('Invalid byte index');
25699 }
25700
25701 var continuationByte = byteArray[byteIndex] & 0xFF;
25702 byteIndex++;
25703
25704 if ((continuationByte & 0xC0) == 0x80) {
25705 return continuationByte & 0x3F;
25706 }
25707
25708 // If we end up here, it’s not a continuation byte
25709 throw Error('Invalid continuation byte');
25710 }
25711
25712 function decodeSymbol() {
25713 var byte1;
25714 var byte2;
25715 var byte3;
25716 var byte4;
25717 var codePoint;
25718
25719 if (byteIndex > byteCount) {
25720 throw Error('Invalid byte index');
25721 }
25722
25723 if (byteIndex == byteCount) {
25724 return false;
25725 }
25726
25727 // Read first byte
25728 byte1 = byteArray[byteIndex] & 0xFF;
25729 byteIndex++;
25730
25731 // 1-byte sequence (no continuation bytes)
25732 if ((byte1 & 0x80) == 0) {
25733 return byte1;
25734 }
25735
25736 // 2-byte sequence
25737 if ((byte1 & 0xE0) == 0xC0) {
25738 var byte2 = readContinuationByte();
25739 codePoint = ((byte1 & 0x1F) << 6) | byte2;
25740 if (codePoint >= 0x80) {
25741 return codePoint;
25742 } else {
25743 throw Error('Invalid continuation byte');
25744 }
25745 }
25746
25747 // 3-byte sequence (may include unpaired surrogates)
25748 if ((byte1 & 0xF0) == 0xE0) {
25749 byte2 = readContinuationByte();
25750 byte3 = readContinuationByte();
25751 codePoint = ((byte1 & 0x0F) << 12) | (byte2 << 6) | byte3;
25752 if (codePoint >= 0x0800) {
25753 checkScalarValue(codePoint);
25754 return codePoint;
25755 } else {
25756 throw Error('Invalid continuation byte');
25757 }
25758 }
25759
25760 // 4-byte sequence
25761 if ((byte1 & 0xF8) == 0xF0) {
25762 byte2 = readContinuationByte();
25763 byte3 = readContinuationByte();
25764 byte4 = readContinuationByte();
25765 codePoint = ((byte1 & 0x0F) << 0x12) | (byte2 << 0x0C) |
25766 (byte3 << 0x06) | byte4;
25767 if (codePoint >= 0x010000 && codePoint <= 0x10FFFF) {
25768 return codePoint;
25769 }
25770 }
25771
25772 throw Error('Invalid UTF-8 detected');
25773 }
25774
25775 var byteArray;
25776 var byteCount;
25777 var byteIndex;
25778 function utf8decode(byteString) {
25779 byteArray = ucs2decode(byteString);
25780 byteCount = byteArray.length;
25781 byteIndex = 0;
25782 var codePoints = [];
25783 var tmp;
25784 while ((tmp = decodeSymbol()) !== false) {
25785 codePoints.push(tmp);
25786 }
25787 return ucs2encode(codePoints);
25788 }
25789
25790 /*--------------------------------------------------------------------------*/
25791
25792 var utf8 = {
25793 'version': '2.0.0',
25794 'encode': utf8encode,
25795 'decode': utf8decode
25796 };
25797
25798 // Some AMD build optimizers, like r.js, check for specific condition patterns
25799 // like the following:
25800 if (
25801 typeof define == 'function' &&
25802 typeof define.amd == 'object' &&
25803 define.amd
25804 ) {
25805 define(function() {
25806 return utf8;
25807 });
25808 } else if (freeExports && !freeExports.nodeType) {
25809 if (freeModule) { // in Node.js or RingoJS v0.8.0+
25810 freeModule.exports = utf8;
25811 } else { // in Narwhal or RingoJS v0.7.0-
25812 var object = {};
25813 var hasOwnProperty = object.hasOwnProperty;
25814 for (var key in utf8) {
25815 hasOwnProperty.call(utf8, key) && (freeExports[key] = utf8[key]);
25816 }
25817 }
25818 } else { // in Rhino or a web browser
25819 root.utf8 = utf8;
25820 }
25821
25822}(this));
25823
25824}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
25825},{}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/node_modules/has-cors/index.js":[function(require,module,exports){
25826
25827/**
25828 * Module exports.
25829 *
25830 * Logic borrowed from Modernizr:
25831 *
25832 * - https://github.com/Modernizr/Modernizr/blob/master/feature-detects/cors.js
25833 */
25834
25835try {
25836 module.exports = typeof XMLHttpRequest !== 'undefined' &&
25837 'withCredentials' in new XMLHttpRequest();
25838} catch (err) {
25839 // if XMLHttp support is disabled in IE then it will throw
25840 // when trying to create
25841 module.exports = false;
25842}
25843
25844},{}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/node_modules/parsejson/index.js":[function(require,module,exports){
25845(function (global){
25846/**
25847 * JSON parse.
25848 *
25849 * @see Based on jQuery#parseJSON (MIT) and JSON2
25850 * @api private
25851 */
25852
25853var rvalidchars = /^[\],:{}\s]*$/;
25854var rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g;
25855var rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g;
25856var rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g;
25857var rtrimLeft = /^\s+/;
25858var rtrimRight = /\s+$/;
25859
25860module.exports = function parsejson(data) {
25861 if ('string' != typeof data || !data) {
25862 return null;
25863 }
25864
25865 data = data.replace(rtrimLeft, '').replace(rtrimRight, '');
25866
25867 // Attempt to parse using the native JSON parser first
25868 if (global.JSON && JSON.parse) {
25869 return JSON.parse(data);
25870 }
25871
25872 if (rvalidchars.test(data.replace(rvalidescape, '@')
25873 .replace(rvalidtokens, ']')
25874 .replace(rvalidbraces, ''))) {
25875 return (new Function('return ' + data))();
25876 }
25877};
25878}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
25879},{}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/node_modules/parseqs/index.js":[function(require,module,exports){
25880/**
25881 * Compiles a querystring
25882 * Returns string representation of the object
25883 *
25884 * @param {Object}
25885 * @api private
25886 */
25887
25888exports.encode = function (obj) {
25889 var str = '';
25890
25891 for (var i in obj) {
25892 if (obj.hasOwnProperty(i)) {
25893 if (str.length) str += '&';
25894 str += encodeURIComponent(i) + '=' + encodeURIComponent(obj[i]);
25895 }
25896 }
25897
25898 return str;
25899};
25900
25901/**
25902 * Parses a simple querystring into an object
25903 *
25904 * @param {String} qs
25905 * @api private
25906 */
25907
25908exports.decode = function(qs){
25909 var qry = {};
25910 var pairs = qs.split('&');
25911 for (var i = 0, l = pairs.length; i < l; i++) {
25912 var pair = pairs[i].split('=');
25913 qry[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
25914 }
25915 return qry;
25916};
25917
25918},{}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/node_modules/ws/lib/browser.js":[function(require,module,exports){
25919
25920/**
25921 * Module dependencies.
25922 */
25923
25924var global = (function() { return this; })();
25925
25926/**
25927 * WebSocket constructor.
25928 */
25929
25930var WebSocket = global.WebSocket || global.MozWebSocket;
25931
25932/**
25933 * Module exports.
25934 */
25935
25936module.exports = WebSocket ? ws : null;
25937
25938/**
25939 * WebSocket constructor.
25940 *
25941 * The third `opts` options object gets ignored in web browsers, since it's
25942 * non-standard, and throws a TypeError if passed to the constructor.
25943 * See: https://github.com/einaros/ws/issues/227
25944 *
25945 * @param {String} uri
25946 * @param {Array} protocols (optional)
25947 * @param {Object) opts (optional)
25948 * @api public
25949 */
25950
25951function ws(uri, protocols, opts) {
25952 var instance;
25953 if (protocols) {
25954 instance = new WebSocket(uri, protocols);
25955 } else {
25956 instance = new WebSocket(uri);
25957 }
25958 return instance;
25959}
25960
25961if (WebSocket) ws.prototype = WebSocket.prototype;
25962
25963},{}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/node_modules/yeast/index.js":[function(require,module,exports){
25964'use strict';
25965
25966var alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_'.split('')
25967 , length = 64
25968 , map = {}
25969 , seed = 0
25970 , i = 0
25971 , prev;
25972
25973/**
25974 * Return a string representing the specified number.
25975 *
25976 * @param {Number} num The number to convert.
25977 * @returns {String} The string representation of the number.
25978 * @api public
25979 */
25980function encode(num) {
25981 var encoded = '';
25982
25983 do {
25984 encoded = alphabet[num % length] + encoded;
25985 num = Math.floor(num / length);
25986 } while (num > 0);
25987
25988 return encoded;
25989}
25990
25991/**
25992 * Return the integer value specified by the given string.
25993 *
25994 * @param {String} str The string to convert.
25995 * @returns {Number} The integer value represented by the string.
25996 * @api public
25997 */
25998function decode(str) {
25999 var decoded = 0;
26000
26001 for (i = 0; i < str.length; i++) {
26002 decoded = decoded * length + map[str.charAt(i)];
26003 }
26004
26005 return decoded;
26006}
26007
26008/**
26009 * Yeast: A tiny growing id generator.
26010 *
26011 * @returns {String} A unique id.
26012 * @api public
26013 */
26014function yeast() {
26015 var now = encode(+new Date());
26016
26017 if (now !== prev) return seed = 0, prev = now;
26018 return now +'.'+ encode(seed++);
26019}
26020
26021//
26022// Map each character to its index.
26023//
26024for (; i < length; i++) map[alphabet[i]] = i;
26025
26026//
26027// Expose the `yeast`, `encode` and `decode` functions.
26028//
26029yeast.encode = encode;
26030yeast.decode = decode;
26031module.exports = yeast;
26032
26033},{}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/has-binary/index.js":[function(require,module,exports){
26034(function (global){
26035
26036/*
26037 * Module requirements.
26038 */
26039
26040var isArray = require('isarray');
26041
26042/**
26043 * Module exports.
26044 */
26045
26046module.exports = hasBinary;
26047
26048/**
26049 * Checks for binary data.
26050 *
26051 * Right now only Buffer and ArrayBuffer are supported..
26052 *
26053 * @param {Object} anything
26054 * @api public
26055 */
26056
26057function hasBinary(data) {
26058
26059 function _hasBinary(obj) {
26060 if (!obj) return false;
26061
26062 if ( (global.Buffer && global.Buffer.isBuffer && global.Buffer.isBuffer(obj)) ||
26063 (global.ArrayBuffer && obj instanceof ArrayBuffer) ||
26064 (global.Blob && obj instanceof Blob) ||
26065 (global.File && obj instanceof File)
26066 ) {
26067 return true;
26068 }
26069
26070 if (isArray(obj)) {
26071 for (var i = 0; i < obj.length; i++) {
26072 if (_hasBinary(obj[i])) {
26073 return true;
26074 }
26075 }
26076 } else if (obj && 'object' == typeof obj) {
26077 // see: https://github.com/Automattic/has-binary/pull/4
26078 if (obj.toJSON && 'function' == typeof obj.toJSON) {
26079 obj = obj.toJSON();
26080 }
26081
26082 for (var key in obj) {
26083 if (Object.prototype.hasOwnProperty.call(obj, key) && _hasBinary(obj[key])) {
26084 return true;
26085 }
26086 }
26087 }
26088
26089 return false;
26090 }
26091
26092 return _hasBinary(data);
26093}
26094
26095}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
26096},{"isarray":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/has-binary/node_modules/isarray/index.js"}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/has-binary/node_modules/isarray/index.js":[function(require,module,exports){
26097arguments[4]["/home/employee-2klic/projects/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)
26098},{}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/indexof/index.js":[function(require,module,exports){
26099
26100var indexOf = [].indexOf;
26101
26102module.exports = function(arr, obj){
26103 if (indexOf) return arr.indexOf(obj);
26104 for (var i = 0; i < arr.length; ++i) {
26105 if (arr[i] === obj) return i;
26106 }
26107 return -1;
26108};
26109},{}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/parseuri/index.js":[function(require,module,exports){
26110/**
26111 * Parses an URI
26112 *
26113 * @author Steven Levithan <stevenlevithan.com> (MIT license)
26114 * @api private
26115 */
26116
26117var re = /^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
26118
26119var parts = [
26120 'source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'
26121];
26122
26123module.exports = function parseuri(str) {
26124 var src = str,
26125 b = str.indexOf('['),
26126 e = str.indexOf(']');
26127
26128 if (b != -1 && e != -1) {
26129 str = str.substring(0, b) + str.substring(b, e).replace(/:/g, ';') + str.substring(e, str.length);
26130 }
26131
26132 var m = re.exec(str || ''),
26133 uri = {},
26134 i = 14;
26135
26136 while (i--) {
26137 uri[parts[i]] = m[i] || '';
26138 }
26139
26140 if (b != -1 && e != -1) {
26141 uri.source = src;
26142 uri.host = uri.host.substring(1, uri.host.length - 1).replace(/;/g, ':');
26143 uri.authority = uri.authority.replace('[', '').replace(']', '').replace(/;/g, ':');
26144 uri.ipv6uri = true;
26145 }
26146
26147 return uri;
26148};
26149
26150},{}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/socket.io-parser/binary.js":[function(require,module,exports){
26151(function (global){
26152/*global Blob,File*/
26153
26154/**
26155 * Module requirements
26156 */
26157
26158var isArray = require('isarray');
26159var isBuf = require('./is-buffer');
26160
26161/**
26162 * Replaces every Buffer | ArrayBuffer in packet with a numbered placeholder.
26163 * Anything with blobs or files should be fed through removeBlobs before coming
26164 * here.
26165 *
26166 * @param {Object} packet - socket.io event packet
26167 * @return {Object} with deconstructed packet and list of buffers
26168 * @api public
26169 */
26170
26171exports.deconstructPacket = function(packet){
26172 var buffers = [];
26173 var packetData = packet.data;
26174
26175 function _deconstructPacket(data) {
26176 if (!data) return data;
26177
26178 if (isBuf(data)) {
26179 var placeholder = { _placeholder: true, num: buffers.length };
26180 buffers.push(data);
26181 return placeholder;
26182 } else if (isArray(data)) {
26183 var newData = new Array(data.length);
26184 for (var i = 0; i < data.length; i++) {
26185 newData[i] = _deconstructPacket(data[i]);
26186 }
26187 return newData;
26188 } else if ('object' == typeof data && !(data instanceof Date)) {
26189 var newData = {};
26190 for (var key in data) {
26191 newData[key] = _deconstructPacket(data[key]);
26192 }
26193 return newData;
26194 }
26195 return data;
26196 }
26197
26198 var pack = packet;
26199 pack.data = _deconstructPacket(packetData);
26200 pack.attachments = buffers.length; // number of binary 'attachments'
26201 return {packet: pack, buffers: buffers};
26202};
26203
26204/**
26205 * Reconstructs a binary packet from its placeholder packet and buffers
26206 *
26207 * @param {Object} packet - event packet with placeholders
26208 * @param {Array} buffers - binary buffers to put in placeholder positions
26209 * @return {Object} reconstructed packet
26210 * @api public
26211 */
26212
26213exports.reconstructPacket = function(packet, buffers) {
26214 var curPlaceHolder = 0;
26215
26216 function _reconstructPacket(data) {
26217 if (data && data._placeholder) {
26218 var buf = buffers[data.num]; // appropriate buffer (should be natural order anyway)
26219 return buf;
26220 } else if (isArray(data)) {
26221 for (var i = 0; i < data.length; i++) {
26222 data[i] = _reconstructPacket(data[i]);
26223 }
26224 return data;
26225 } else if (data && 'object' == typeof data) {
26226 for (var key in data) {
26227 data[key] = _reconstructPacket(data[key]);
26228 }
26229 return data;
26230 }
26231 return data;
26232 }
26233
26234 packet.data = _reconstructPacket(packet.data);
26235 packet.attachments = undefined; // no longer useful
26236 return packet;
26237};
26238
26239/**
26240 * Asynchronously removes Blobs or Files from data via
26241 * FileReader's readAsArrayBuffer method. Used before encoding
26242 * data as msgpack. Calls callback with the blobless data.
26243 *
26244 * @param {Object} data
26245 * @param {Function} callback
26246 * @api private
26247 */
26248
26249exports.removeBlobs = function(data, callback) {
26250 function _removeBlobs(obj, curKey, containingObject) {
26251 if (!obj) return obj;
26252
26253 // convert any blob
26254 if ((global.Blob && obj instanceof Blob) ||
26255 (global.File && obj instanceof File)) {
26256 pendingBlobs++;
26257
26258 // async filereader
26259 var fileReader = new FileReader();
26260 fileReader.onload = function() { // this.result == arraybuffer
26261 if (containingObject) {
26262 containingObject[curKey] = this.result;
26263 }
26264 else {
26265 bloblessData = this.result;
26266 }
26267
26268 // if nothing pending its callback time
26269 if(! --pendingBlobs) {
26270 callback(bloblessData);
26271 }
26272 };
26273
26274 fileReader.readAsArrayBuffer(obj); // blob -> arraybuffer
26275 } else if (isArray(obj)) { // handle array
26276 for (var i = 0; i < obj.length; i++) {
26277 _removeBlobs(obj[i], i, obj);
26278 }
26279 } else if (obj && 'object' == typeof obj && !isBuf(obj)) { // and object
26280 for (var key in obj) {
26281 _removeBlobs(obj[key], key, obj);
26282 }
26283 }
26284 }
26285
26286 var pendingBlobs = 0;
26287 var bloblessData = data;
26288 _removeBlobs(bloblessData);
26289 if (!pendingBlobs) {
26290 callback(bloblessData);
26291 }
26292};
26293
26294}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
26295},{"./is-buffer":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/socket.io-parser/is-buffer.js","isarray":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/socket.io-parser/node_modules/isarray/index.js"}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/socket.io-parser/index.js":[function(require,module,exports){
26296
26297/**
26298 * Module dependencies.
26299 */
26300
26301var debug = require('debug')('socket.io-parser');
26302var json = require('json3');
26303var isArray = require('isarray');
26304var Emitter = require('component-emitter');
26305var binary = require('./binary');
26306var isBuf = require('./is-buffer');
26307
26308/**
26309 * Protocol version.
26310 *
26311 * @api public
26312 */
26313
26314exports.protocol = 4;
26315
26316/**
26317 * Packet types.
26318 *
26319 * @api public
26320 */
26321
26322exports.types = [
26323 'CONNECT',
26324 'DISCONNECT',
26325 'EVENT',
26326 'BINARY_EVENT',
26327 'ACK',
26328 'BINARY_ACK',
26329 'ERROR'
26330];
26331
26332/**
26333 * Packet type `connect`.
26334 *
26335 * @api public
26336 */
26337
26338exports.CONNECT = 0;
26339
26340/**
26341 * Packet type `disconnect`.
26342 *
26343 * @api public
26344 */
26345
26346exports.DISCONNECT = 1;
26347
26348/**
26349 * Packet type `event`.
26350 *
26351 * @api public
26352 */
26353
26354exports.EVENT = 2;
26355
26356/**
26357 * Packet type `ack`.
26358 *
26359 * @api public
26360 */
26361
26362exports.ACK = 3;
26363
26364/**
26365 * Packet type `error`.
26366 *
26367 * @api public
26368 */
26369
26370exports.ERROR = 4;
26371
26372/**
26373 * Packet type 'binary event'
26374 *
26375 * @api public
26376 */
26377
26378exports.BINARY_EVENT = 5;
26379
26380/**
26381 * Packet type `binary ack`. For acks with binary arguments.
26382 *
26383 * @api public
26384 */
26385
26386exports.BINARY_ACK = 6;
26387
26388/**
26389 * Encoder constructor.
26390 *
26391 * @api public
26392 */
26393
26394exports.Encoder = Encoder;
26395
26396/**
26397 * Decoder constructor.
26398 *
26399 * @api public
26400 */
26401
26402exports.Decoder = Decoder;
26403
26404/**
26405 * A socket.io Encoder instance
26406 *
26407 * @api public
26408 */
26409
26410function Encoder() {}
26411
26412/**
26413 * Encode a packet as a single string if non-binary, or as a
26414 * buffer sequence, depending on packet type.
26415 *
26416 * @param {Object} obj - packet object
26417 * @param {Function} callback - function to handle encodings (likely engine.write)
26418 * @return Calls callback with Array of encodings
26419 * @api public
26420 */
26421
26422Encoder.prototype.encode = function(obj, callback){
26423 debug('encoding packet %j', obj);
26424
26425 if (exports.BINARY_EVENT == obj.type || exports.BINARY_ACK == obj.type) {
26426 encodeAsBinary(obj, callback);
26427 }
26428 else {
26429 var encoding = encodeAsString(obj);
26430 callback([encoding]);
26431 }
26432};
26433
26434/**
26435 * Encode packet as string.
26436 *
26437 * @param {Object} packet
26438 * @return {String} encoded
26439 * @api private
26440 */
26441
26442function encodeAsString(obj) {
26443 var str = '';
26444 var nsp = false;
26445
26446 // first is type
26447 str += obj.type;
26448
26449 // attachments if we have them
26450 if (exports.BINARY_EVENT == obj.type || exports.BINARY_ACK == obj.type) {
26451 str += obj.attachments;
26452 str += '-';
26453 }
26454
26455 // if we have a namespace other than `/`
26456 // we append it followed by a comma `,`
26457 if (obj.nsp && '/' != obj.nsp) {
26458 nsp = true;
26459 str += obj.nsp;
26460 }
26461
26462 // immediately followed by the id
26463 if (null != obj.id) {
26464 if (nsp) {
26465 str += ',';
26466 nsp = false;
26467 }
26468 str += obj.id;
26469 }
26470
26471 // json data
26472 if (null != obj.data) {
26473 if (nsp) str += ',';
26474 str += json.stringify(obj.data);
26475 }
26476
26477 debug('encoded %j as %s', obj, str);
26478 return str;
26479}
26480
26481/**
26482 * Encode packet as 'buffer sequence' by removing blobs, and
26483 * deconstructing packet into object with placeholders and
26484 * a list of buffers.
26485 *
26486 * @param {Object} packet
26487 * @return {Buffer} encoded
26488 * @api private
26489 */
26490
26491function encodeAsBinary(obj, callback) {
26492
26493 function writeEncoding(bloblessData) {
26494 var deconstruction = binary.deconstructPacket(bloblessData);
26495 var pack = encodeAsString(deconstruction.packet);
26496 var buffers = deconstruction.buffers;
26497
26498 buffers.unshift(pack); // add packet info to beginning of data list
26499 callback(buffers); // write all the buffers
26500 }
26501
26502 binary.removeBlobs(obj, writeEncoding);
26503}
26504
26505/**
26506 * A socket.io Decoder instance
26507 *
26508 * @return {Object} decoder
26509 * @api public
26510 */
26511
26512function Decoder() {
26513 this.reconstructor = null;
26514}
26515
26516/**
26517 * Mix in `Emitter` with Decoder.
26518 */
26519
26520Emitter(Decoder.prototype);
26521
26522/**
26523 * Decodes an ecoded packet string into packet JSON.
26524 *
26525 * @param {String} obj - encoded packet
26526 * @return {Object} packet
26527 * @api public
26528 */
26529
26530Decoder.prototype.add = function(obj) {
26531 var packet;
26532 if ('string' == typeof obj) {
26533 packet = decodeString(obj);
26534 if (exports.BINARY_EVENT == packet.type || exports.BINARY_ACK == packet.type) { // binary packet's json
26535 this.reconstructor = new BinaryReconstructor(packet);
26536
26537 // no attachments, labeled binary but no binary data to follow
26538 if (this.reconstructor.reconPack.attachments === 0) {
26539 this.emit('decoded', packet);
26540 }
26541 } else { // non-binary full packet
26542 this.emit('decoded', packet);
26543 }
26544 }
26545 else if (isBuf(obj) || obj.base64) { // raw binary data
26546 if (!this.reconstructor) {
26547 throw new Error('got binary data when not reconstructing a packet');
26548 } else {
26549 packet = this.reconstructor.takeBinaryData(obj);
26550 if (packet) { // received final buffer
26551 this.reconstructor = null;
26552 this.emit('decoded', packet);
26553 }
26554 }
26555 }
26556 else {
26557 throw new Error('Unknown type: ' + obj);
26558 }
26559};
26560
26561/**
26562 * Decode a packet String (JSON data)
26563 *
26564 * @param {String} str
26565 * @return {Object} packet
26566 * @api private
26567 */
26568
26569function decodeString(str) {
26570 var p = {};
26571 var i = 0;
26572
26573 // look up type
26574 p.type = Number(str.charAt(0));
26575 if (null == exports.types[p.type]) return error();
26576
26577 // look up attachments if type binary
26578 if (exports.BINARY_EVENT == p.type || exports.BINARY_ACK == p.type) {
26579 var buf = '';
26580 while (str.charAt(++i) != '-') {
26581 buf += str.charAt(i);
26582 if (i == str.length) break;
26583 }
26584 if (buf != Number(buf) || str.charAt(i) != '-') {
26585 throw new Error('Illegal attachments');
26586 }
26587 p.attachments = Number(buf);
26588 }
26589
26590 // look up namespace (if any)
26591 if ('/' == str.charAt(i + 1)) {
26592 p.nsp = '';
26593 while (++i) {
26594 var c = str.charAt(i);
26595 if (',' == c) break;
26596 p.nsp += c;
26597 if (i == str.length) break;
26598 }
26599 } else {
26600 p.nsp = '/';
26601 }
26602
26603 // look up id
26604 var next = str.charAt(i + 1);
26605 if ('' !== next && Number(next) == next) {
26606 p.id = '';
26607 while (++i) {
26608 var c = str.charAt(i);
26609 if (null == c || Number(c) != c) {
26610 --i;
26611 break;
26612 }
26613 p.id += str.charAt(i);
26614 if (i == str.length) break;
26615 }
26616 p.id = Number(p.id);
26617 }
26618
26619 // look up json data
26620 if (str.charAt(++i)) {
26621 try {
26622 p.data = json.parse(str.substr(i));
26623 } catch(e){
26624 return error();
26625 }
26626 }
26627
26628 debug('decoded %s as %j', str, p);
26629 return p;
26630}
26631
26632/**
26633 * Deallocates a parser's resources
26634 *
26635 * @api public
26636 */
26637
26638Decoder.prototype.destroy = function() {
26639 if (this.reconstructor) {
26640 this.reconstructor.finishedReconstruction();
26641 }
26642};
26643
26644/**
26645 * A manager of a binary event's 'buffer sequence'. Should
26646 * be constructed whenever a packet of type BINARY_EVENT is
26647 * decoded.
26648 *
26649 * @param {Object} packet
26650 * @return {BinaryReconstructor} initialized reconstructor
26651 * @api private
26652 */
26653
26654function BinaryReconstructor(packet) {
26655 this.reconPack = packet;
26656 this.buffers = [];
26657}
26658
26659/**
26660 * Method to be called when binary data received from connection
26661 * after a BINARY_EVENT packet.
26662 *
26663 * @param {Buffer | ArrayBuffer} binData - the raw binary data received
26664 * @return {null | Object} returns null if more binary data is expected or
26665 * a reconstructed packet object if all buffers have been received.
26666 * @api private
26667 */
26668
26669BinaryReconstructor.prototype.takeBinaryData = function(binData) {
26670 this.buffers.push(binData);
26671 if (this.buffers.length == this.reconPack.attachments) { // done with buffer list
26672 var packet = binary.reconstructPacket(this.reconPack, this.buffers);
26673 this.finishedReconstruction();
26674 return packet;
26675 }
26676 return null;
26677};
26678
26679/**
26680 * Cleans up binary packet reconstruction variables.
26681 *
26682 * @api private
26683 */
26684
26685BinaryReconstructor.prototype.finishedReconstruction = function() {
26686 this.reconPack = null;
26687 this.buffers = [];
26688};
26689
26690function error(data){
26691 return {
26692 type: exports.ERROR,
26693 data: 'parser error'
26694 };
26695}
26696
26697},{"./binary":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/socket.io-parser/binary.js","./is-buffer":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/socket.io-parser/is-buffer.js","component-emitter":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/socket.io-parser/node_modules/component-emitter/index.js","debug":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/debug/browser.js","isarray":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/socket.io-parser/node_modules/isarray/index.js","json3":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/socket.io-parser/node_modules/json3/lib/json3.js"}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/socket.io-parser/is-buffer.js":[function(require,module,exports){
26698(function (global){
26699
26700module.exports = isBuf;
26701
26702/**
26703 * Returns true if obj is a buffer or an arraybuffer.
26704 *
26705 * @api private
26706 */
26707
26708function isBuf(obj) {
26709 return (global.Buffer && global.Buffer.isBuffer(obj)) ||
26710 (global.ArrayBuffer && obj instanceof ArrayBuffer);
26711}
26712
26713}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
26714},{}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/socket.io-parser/node_modules/component-emitter/index.js":[function(require,module,exports){
26715arguments[4]["/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/engine.io-client/node_modules/component-emitter/index.js"][0].apply(exports,arguments)
26716},{}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/socket.io-parser/node_modules/isarray/index.js":[function(require,module,exports){
26717arguments[4]["/home/employee-2klic/projects/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)
26718},{}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/socket.io-parser/node_modules/json3/lib/json3.js":[function(require,module,exports){
26719(function (global){
26720/*! JSON v3.3.2 | http://bestiejs.github.io/json3 | Copyright 2012-2014, Kit Cambridge | http://kit.mit-license.org */
26721;(function () {
26722 // Detect the `define` function exposed by asynchronous module loaders. The
26723 // strict `define` check is necessary for compatibility with `r.js`.
26724 var isLoader = typeof define === "function" && define.amd;
26725
26726 // A set of types used to distinguish objects from primitives.
26727 var objectTypes = {
26728 "function": true,
26729 "object": true
26730 };
26731
26732 // Detect the `exports` object exposed by CommonJS implementations.
26733 var freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports;
26734
26735 // Use the `global` object exposed by Node (including Browserify via
26736 // `insert-module-globals`), Narwhal, and Ringo as the default context,
26737 // and the `window` object in browsers. Rhino exports a `global` function
26738 // instead.
26739 var root = objectTypes[typeof window] && window || this,
26740 freeGlobal = freeExports && objectTypes[typeof module] && module && !module.nodeType && typeof global == "object" && global;
26741
26742 if (freeGlobal && (freeGlobal["global"] === freeGlobal || freeGlobal["window"] === freeGlobal || freeGlobal["self"] === freeGlobal)) {
26743 root = freeGlobal;
26744 }
26745
26746 // Public: Initializes JSON 3 using the given `context` object, attaching the
26747 // `stringify` and `parse` functions to the specified `exports` object.
26748 function runInContext(context, exports) {
26749 context || (context = root["Object"]());
26750 exports || (exports = root["Object"]());
26751
26752 // Native constructor aliases.
26753 var Number = context["Number"] || root["Number"],
26754 String = context["String"] || root["String"],
26755 Object = context["Object"] || root["Object"],
26756 Date = context["Date"] || root["Date"],
26757 SyntaxError = context["SyntaxError"] || root["SyntaxError"],
26758 TypeError = context["TypeError"] || root["TypeError"],
26759 Math = context["Math"] || root["Math"],
26760 nativeJSON = context["JSON"] || root["JSON"];
26761
26762 // Delegate to the native `stringify` and `parse` implementations.
26763 if (typeof nativeJSON == "object" && nativeJSON) {
26764 exports.stringify = nativeJSON.stringify;
26765 exports.parse = nativeJSON.parse;
26766 }
26767
26768 // Convenience aliases.
26769 var objectProto = Object.prototype,
26770 getClass = objectProto.toString,
26771 isProperty, forEach, undef;
26772
26773 // Test the `Date#getUTC*` methods. Based on work by @Yaffle.
26774 var isExtended = new Date(-3509827334573292);
26775 try {
26776 // The `getUTCFullYear`, `Month`, and `Date` methods return nonsensical
26777 // results for certain dates in Opera >= 10.53.
26778 isExtended = isExtended.getUTCFullYear() == -109252 && isExtended.getUTCMonth() === 0 && isExtended.getUTCDate() === 1 &&
26779 // Safari < 2.0.2 stores the internal millisecond time value correctly,
26780 // but clips the values returned by the date methods to the range of
26781 // signed 32-bit integers ([-2 ** 31, 2 ** 31 - 1]).
26782 isExtended.getUTCHours() == 10 && isExtended.getUTCMinutes() == 37 && isExtended.getUTCSeconds() == 6 && isExtended.getUTCMilliseconds() == 708;
26783 } catch (exception) {}
26784
26785 // Internal: Determines whether the native `JSON.stringify` and `parse`
26786 // implementations are spec-compliant. Based on work by Ken Snyder.
26787 function has(name) {
26788 if (has[name] !== undef) {
26789 // Return cached feature test result.
26790 return has[name];
26791 }
26792 var isSupported;
26793 if (name == "bug-string-char-index") {
26794 // IE <= 7 doesn't support accessing string characters using square
26795 // bracket notation. IE 8 only supports this for primitives.
26796 isSupported = "a"[0] != "a";
26797 } else if (name == "json") {
26798 // Indicates whether both `JSON.stringify` and `JSON.parse` are
26799 // supported.
26800 isSupported = has("json-stringify") && has("json-parse");
26801 } else {
26802 var value, serialized = '{"a":[1,true,false,null,"\\u0000\\b\\n\\f\\r\\t"]}';
26803 // Test `JSON.stringify`.
26804 if (name == "json-stringify") {
26805 var stringify = exports.stringify, stringifySupported = typeof stringify == "function" && isExtended;
26806 if (stringifySupported) {
26807 // A test function object with a custom `toJSON` method.
26808 (value = function () {
26809 return 1;
26810 }).toJSON = value;
26811 try {
26812 stringifySupported =
26813 // Firefox 3.1b1 and b2 serialize string, number, and boolean
26814 // primitives as object literals.
26815 stringify(0) === "0" &&
26816 // FF 3.1b1, b2, and JSON 2 serialize wrapped primitives as object
26817 // literals.
26818 stringify(new Number()) === "0" &&
26819 stringify(new String()) == '""' &&
26820 // FF 3.1b1, 2 throw an error if the value is `null`, `undefined`, or
26821 // does not define a canonical JSON representation (this applies to
26822 // objects with `toJSON` properties as well, *unless* they are nested
26823 // within an object or array).
26824 stringify(getClass) === undef &&
26825 // IE 8 serializes `undefined` as `"undefined"`. Safari <= 5.1.7 and
26826 // FF 3.1b3 pass this test.
26827 stringify(undef) === undef &&
26828 // Safari <= 5.1.7 and FF 3.1b3 throw `Error`s and `TypeError`s,
26829 // respectively, if the value is omitted entirely.
26830 stringify() === undef &&
26831 // FF 3.1b1, 2 throw an error if the given value is not a number,
26832 // string, array, object, Boolean, or `null` literal. This applies to
26833 // objects with custom `toJSON` methods as well, unless they are nested
26834 // inside object or array literals. YUI 3.0.0b1 ignores custom `toJSON`
26835 // methods entirely.
26836 stringify(value) === "1" &&
26837 stringify([value]) == "[1]" &&
26838 // Prototype <= 1.6.1 serializes `[undefined]` as `"[]"` instead of
26839 // `"[null]"`.
26840 stringify([undef]) == "[null]" &&
26841 // YUI 3.0.0b1 fails to serialize `null` literals.
26842 stringify(null) == "null" &&
26843 // FF 3.1b1, 2 halts serialization if an array contains a function:
26844 // `[1, true, getClass, 1]` serializes as "[1,true,],". FF 3.1b3
26845 // elides non-JSON values from objects and arrays, unless they
26846 // define custom `toJSON` methods.
26847 stringify([undef, getClass, null]) == "[null,null,null]" &&
26848 // Simple serialization test. FF 3.1b1 uses Unicode escape sequences
26849 // where character escape codes are expected (e.g., `\b` => `\u0008`).
26850 stringify({ "a": [value, true, false, null, "\x00\b\n\f\r\t"] }) == serialized &&
26851 // FF 3.1b1 and b2 ignore the `filter` and `width` arguments.
26852 stringify(null, value) === "1" &&
26853 stringify([1, 2], null, 1) == "[\n 1,\n 2\n]" &&
26854 // JSON 2, Prototype <= 1.7, and older WebKit builds incorrectly
26855 // serialize extended years.
26856 stringify(new Date(-8.64e15)) == '"-271821-04-20T00:00:00.000Z"' &&
26857 // The milliseconds are optional in ES 5, but required in 5.1.
26858 stringify(new Date(8.64e15)) == '"+275760-09-13T00:00:00.000Z"' &&
26859 // Firefox <= 11.0 incorrectly serializes years prior to 0 as negative
26860 // four-digit years instead of six-digit years. Credits: @Yaffle.
26861 stringify(new Date(-621987552e5)) == '"-000001-01-01T00:00:00.000Z"' &&
26862 // Safari <= 5.1.5 and Opera >= 10.53 incorrectly serialize millisecond
26863 // values less than 1000. Credits: @Yaffle.
26864 stringify(new Date(-1)) == '"1969-12-31T23:59:59.999Z"';
26865 } catch (exception) {
26866 stringifySupported = false;
26867 }
26868 }
26869 isSupported = stringifySupported;
26870 }
26871 // Test `JSON.parse`.
26872 if (name == "json-parse") {
26873 var parse = exports.parse;
26874 if (typeof parse == "function") {
26875 try {
26876 // FF 3.1b1, b2 will throw an exception if a bare literal is provided.
26877 // Conforming implementations should also coerce the initial argument to
26878 // a string prior to parsing.
26879 if (parse("0") === 0 && !parse(false)) {
26880 // Simple parsing test.
26881 value = parse(serialized);
26882 var parseSupported = value["a"].length == 5 && value["a"][0] === 1;
26883 if (parseSupported) {
26884 try {
26885 // Safari <= 5.1.2 and FF 3.1b1 allow unescaped tabs in strings.
26886 parseSupported = !parse('"\t"');
26887 } catch (exception) {}
26888 if (parseSupported) {
26889 try {
26890 // FF 4.0 and 4.0.1 allow leading `+` signs and leading
26891 // decimal points. FF 4.0, 4.0.1, and IE 9-10 also allow
26892 // certain octal literals.
26893 parseSupported = parse("01") !== 1;
26894 } catch (exception) {}
26895 }
26896 if (parseSupported) {
26897 try {
26898 // FF 4.0, 4.0.1, and Rhino 1.7R3-R4 allow trailing decimal
26899 // points. These environments, along with FF 3.1b1 and 2,
26900 // also allow trailing commas in JSON objects and arrays.
26901 parseSupported = parse("1.") !== 1;
26902 } catch (exception) {}
26903 }
26904 }
26905 }
26906 } catch (exception) {
26907 parseSupported = false;
26908 }
26909 }
26910 isSupported = parseSupported;
26911 }
26912 }
26913 return has[name] = !!isSupported;
26914 }
26915
26916 if (!has("json")) {
26917 // Common `[[Class]]` name aliases.
26918 var functionClass = "[object Function]",
26919 dateClass = "[object Date]",
26920 numberClass = "[object Number]",
26921 stringClass = "[object String]",
26922 arrayClass = "[object Array]",
26923 booleanClass = "[object Boolean]";
26924
26925 // Detect incomplete support for accessing string characters by index.
26926 var charIndexBuggy = has("bug-string-char-index");
26927
26928 // Define additional utility methods if the `Date` methods are buggy.
26929 if (!isExtended) {
26930 var floor = Math.floor;
26931 // A mapping between the months of the year and the number of days between
26932 // January 1st and the first of the respective month.
26933 var Months = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
26934 // Internal: Calculates the number of days between the Unix epoch and the
26935 // first day of the given month.
26936 var getDay = function (year, month) {
26937 return Months[month] + 365 * (year - 1970) + floor((year - 1969 + (month = +(month > 1))) / 4) - floor((year - 1901 + month) / 100) + floor((year - 1601 + month) / 400);
26938 };
26939 }
26940
26941 // Internal: Determines if a property is a direct property of the given
26942 // object. Delegates to the native `Object#hasOwnProperty` method.
26943 if (!(isProperty = objectProto.hasOwnProperty)) {
26944 isProperty = function (property) {
26945 var members = {}, constructor;
26946 if ((members.__proto__ = null, members.__proto__ = {
26947 // The *proto* property cannot be set multiple times in recent
26948 // versions of Firefox and SeaMonkey.
26949 "toString": 1
26950 }, members).toString != getClass) {
26951 // Safari <= 2.0.3 doesn't implement `Object#hasOwnProperty`, but
26952 // supports the mutable *proto* property.
26953 isProperty = function (property) {
26954 // Capture and break the object's prototype chain (see section 8.6.2
26955 // of the ES 5.1 spec). The parenthesized expression prevents an
26956 // unsafe transformation by the Closure Compiler.
26957 var original = this.__proto__, result = property in (this.__proto__ = null, this);
26958 // Restore the original prototype chain.
26959 this.__proto__ = original;
26960 return result;
26961 };
26962 } else {
26963 // Capture a reference to the top-level `Object` constructor.
26964 constructor = members.constructor;
26965 // Use the `constructor` property to simulate `Object#hasOwnProperty` in
26966 // other environments.
26967 isProperty = function (property) {
26968 var parent = (this.constructor || constructor).prototype;
26969 return property in this && !(property in parent && this[property] === parent[property]);
26970 };
26971 }
26972 members = null;
26973 return isProperty.call(this, property);
26974 };
26975 }
26976
26977 // Internal: Normalizes the `for...in` iteration algorithm across
26978 // environments. Each enumerated key is yielded to a `callback` function.
26979 forEach = function (object, callback) {
26980 var size = 0, Properties, members, property;
26981
26982 // Tests for bugs in the current environment's `for...in` algorithm. The
26983 // `valueOf` property inherits the non-enumerable flag from
26984 // `Object.prototype` in older versions of IE, Netscape, and Mozilla.
26985 (Properties = function () {
26986 this.valueOf = 0;
26987 }).prototype.valueOf = 0;
26988
26989 // Iterate over a new instance of the `Properties` class.
26990 members = new Properties();
26991 for (property in members) {
26992 // Ignore all properties inherited from `Object.prototype`.
26993 if (isProperty.call(members, property)) {
26994 size++;
26995 }
26996 }
26997 Properties = members = null;
26998
26999 // Normalize the iteration algorithm.
27000 if (!size) {
27001 // A list of non-enumerable properties inherited from `Object.prototype`.
27002 members = ["valueOf", "toString", "toLocaleString", "propertyIsEnumerable", "isPrototypeOf", "hasOwnProperty", "constructor"];
27003 // IE <= 8, Mozilla 1.0, and Netscape 6.2 ignore shadowed non-enumerable
27004 // properties.
27005 forEach = function (object, callback) {
27006 var isFunction = getClass.call(object) == functionClass, property, length;
27007 var hasProperty = !isFunction && typeof object.constructor != "function" && objectTypes[typeof object.hasOwnProperty] && object.hasOwnProperty || isProperty;
27008 for (property in object) {
27009 // Gecko <= 1.0 enumerates the `prototype` property of functions under
27010 // certain conditions; IE does not.
27011 if (!(isFunction && property == "prototype") && hasProperty.call(object, property)) {
27012 callback(property);
27013 }
27014 }
27015 // Manually invoke the callback for each non-enumerable property.
27016 for (length = members.length; property = members[--length]; hasProperty.call(object, property) && callback(property));
27017 };
27018 } else if (size == 2) {
27019 // Safari <= 2.0.4 enumerates shadowed properties twice.
27020 forEach = function (object, callback) {
27021 // Create a set of iterated properties.
27022 var members = {}, isFunction = getClass.call(object) == functionClass, property;
27023 for (property in object) {
27024 // Store each property name to prevent double enumeration. The
27025 // `prototype` property of functions is not enumerated due to cross-
27026 // environment inconsistencies.
27027 if (!(isFunction && property == "prototype") && !isProperty.call(members, property) && (members[property] = 1) && isProperty.call(object, property)) {
27028 callback(property);
27029 }
27030 }
27031 };
27032 } else {
27033 // No bugs detected; use the standard `for...in` algorithm.
27034 forEach = function (object, callback) {
27035 var isFunction = getClass.call(object) == functionClass, property, isConstructor;
27036 for (property in object) {
27037 if (!(isFunction && property == "prototype") && isProperty.call(object, property) && !(isConstructor = property === "constructor")) {
27038 callback(property);
27039 }
27040 }
27041 // Manually invoke the callback for the `constructor` property due to
27042 // cross-environment inconsistencies.
27043 if (isConstructor || isProperty.call(object, (property = "constructor"))) {
27044 callback(property);
27045 }
27046 };
27047 }
27048 return forEach(object, callback);
27049 };
27050
27051 // Public: Serializes a JavaScript `value` as a JSON string. The optional
27052 // `filter` argument may specify either a function that alters how object and
27053 // array members are serialized, or an array of strings and numbers that
27054 // indicates which properties should be serialized. The optional `width`
27055 // argument may be either a string or number that specifies the indentation
27056 // level of the output.
27057 if (!has("json-stringify")) {
27058 // Internal: A map of control characters and their escaped equivalents.
27059 var Escapes = {
27060 92: "\\\\",
27061 34: '\\"',
27062 8: "\\b",
27063 12: "\\f",
27064 10: "\\n",
27065 13: "\\r",
27066 9: "\\t"
27067 };
27068
27069 // Internal: Converts `value` into a zero-padded string such that its
27070 // length is at least equal to `width`. The `width` must be <= 6.
27071 var leadingZeroes = "000000";
27072 var toPaddedString = function (width, value) {
27073 // The `|| 0` expression is necessary to work around a bug in
27074 // Opera <= 7.54u2 where `0 == -0`, but `String(-0) !== "0"`.
27075 return (leadingZeroes + (value || 0)).slice(-width);
27076 };
27077
27078 // Internal: Double-quotes a string `value`, replacing all ASCII control
27079 // characters (characters with code unit values between 0 and 31) with
27080 // their escaped equivalents. This is an implementation of the
27081 // `Quote(value)` operation defined in ES 5.1 section 15.12.3.
27082 var unicodePrefix = "\\u00";
27083 var quote = function (value) {
27084 var result = '"', index = 0, length = value.length, useCharIndex = !charIndexBuggy || length > 10;
27085 var symbols = useCharIndex && (charIndexBuggy ? value.split("") : value);
27086 for (; index < length; index++) {
27087 var charCode = value.charCodeAt(index);
27088 // If the character is a control character, append its Unicode or
27089 // shorthand escape sequence; otherwise, append the character as-is.
27090 switch (charCode) {
27091 case 8: case 9: case 10: case 12: case 13: case 34: case 92:
27092 result += Escapes[charCode];
27093 break;
27094 default:
27095 if (charCode < 32) {
27096 result += unicodePrefix + toPaddedString(2, charCode.toString(16));
27097 break;
27098 }
27099 result += useCharIndex ? symbols[index] : value.charAt(index);
27100 }
27101 }
27102 return result + '"';
27103 };
27104
27105 // Internal: Recursively serializes an object. Implements the
27106 // `Str(key, holder)`, `JO(value)`, and `JA(value)` operations.
27107 var serialize = function (property, object, callback, properties, whitespace, indentation, stack) {
27108 var value, className, year, month, date, time, hours, minutes, seconds, milliseconds, results, element, index, length, prefix, result;
27109 try {
27110 // Necessary for host object support.
27111 value = object[property];
27112 } catch (exception) {}
27113 if (typeof value == "object" && value) {
27114 className = getClass.call(value);
27115 if (className == dateClass && !isProperty.call(value, "toJSON")) {
27116 if (value > -1 / 0 && value < 1 / 0) {
27117 // Dates are serialized according to the `Date#toJSON` method
27118 // specified in ES 5.1 section 15.9.5.44. See section 15.9.1.15
27119 // for the ISO 8601 date time string format.
27120 if (getDay) {
27121 // Manually compute the year, month, date, hours, minutes,
27122 // seconds, and milliseconds if the `getUTC*` methods are
27123 // buggy. Adapted from @Yaffle's `date-shim` project.
27124 date = floor(value / 864e5);
27125 for (year = floor(date / 365.2425) + 1970 - 1; getDay(year + 1, 0) <= date; year++);
27126 for (month = floor((date - getDay(year, 0)) / 30.42); getDay(year, month + 1) <= date; month++);
27127 date = 1 + date - getDay(year, month);
27128 // The `time` value specifies the time within the day (see ES
27129 // 5.1 section 15.9.1.2). The formula `(A % B + B) % B` is used
27130 // to compute `A modulo B`, as the `%` operator does not
27131 // correspond to the `modulo` operation for negative numbers.
27132 time = (value % 864e5 + 864e5) % 864e5;
27133 // The hours, minutes, seconds, and milliseconds are obtained by
27134 // decomposing the time within the day. See section 15.9.1.10.
27135 hours = floor(time / 36e5) % 24;
27136 minutes = floor(time / 6e4) % 60;
27137 seconds = floor(time / 1e3) % 60;
27138 milliseconds = time % 1e3;
27139 } else {
27140 year = value.getUTCFullYear();
27141 month = value.getUTCMonth();
27142 date = value.getUTCDate();
27143 hours = value.getUTCHours();
27144 minutes = value.getUTCMinutes();
27145 seconds = value.getUTCSeconds();
27146 milliseconds = value.getUTCMilliseconds();
27147 }
27148 // Serialize extended years correctly.
27149 value = (year <= 0 || year >= 1e4 ? (year < 0 ? "-" : "+") + toPaddedString(6, year < 0 ? -year : year) : toPaddedString(4, year)) +
27150 "-" + toPaddedString(2, month + 1) + "-" + toPaddedString(2, date) +
27151 // Months, dates, hours, minutes, and seconds should have two
27152 // digits; milliseconds should have three.
27153 "T" + toPaddedString(2, hours) + ":" + toPaddedString(2, minutes) + ":" + toPaddedString(2, seconds) +
27154 // Milliseconds are optional in ES 5.0, but required in 5.1.
27155 "." + toPaddedString(3, milliseconds) + "Z";
27156 } else {
27157 value = null;
27158 }
27159 } else if (typeof value.toJSON == "function" && ((className != numberClass && className != stringClass && className != arrayClass) || isProperty.call(value, "toJSON"))) {
27160 // Prototype <= 1.6.1 adds non-standard `toJSON` methods to the
27161 // `Number`, `String`, `Date`, and `Array` prototypes. JSON 3
27162 // ignores all `toJSON` methods on these objects unless they are
27163 // defined directly on an instance.
27164 value = value.toJSON(property);
27165 }
27166 }
27167 if (callback) {
27168 // If a replacement function was provided, call it to obtain the value
27169 // for serialization.
27170 value = callback.call(object, property, value);
27171 }
27172 if (value === null) {
27173 return "null";
27174 }
27175 className = getClass.call(value);
27176 if (className == booleanClass) {
27177 // Booleans are represented literally.
27178 return "" + value;
27179 } else if (className == numberClass) {
27180 // JSON numbers must be finite. `Infinity` and `NaN` are serialized as
27181 // `"null"`.
27182 return value > -1 / 0 && value < 1 / 0 ? "" + value : "null";
27183 } else if (className == stringClass) {
27184 // Strings are double-quoted and escaped.
27185 return quote("" + value);
27186 }
27187 // Recursively serialize objects and arrays.
27188 if (typeof value == "object") {
27189 // Check for cyclic structures. This is a linear search; performance
27190 // is inversely proportional to the number of unique nested objects.
27191 for (length = stack.length; length--;) {
27192 if (stack[length] === value) {
27193 // Cyclic structures cannot be serialized by `JSON.stringify`.
27194 throw TypeError();
27195 }
27196 }
27197 // Add the object to the stack of traversed objects.
27198 stack.push(value);
27199 results = [];
27200 // Save the current indentation level and indent one additional level.
27201 prefix = indentation;
27202 indentation += whitespace;
27203 if (className == arrayClass) {
27204 // Recursively serialize array elements.
27205 for (index = 0, length = value.length; index < length; index++) {
27206 element = serialize(index, value, callback, properties, whitespace, indentation, stack);
27207 results.push(element === undef ? "null" : element);
27208 }
27209 result = results.length ? (whitespace ? "[\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "]" : ("[" + results.join(",") + "]")) : "[]";
27210 } else {
27211 // Recursively serialize object members. Members are selected from
27212 // either a user-specified list of property names, or the object
27213 // itself.
27214 forEach(properties || value, function (property) {
27215 var element = serialize(property, value, callback, properties, whitespace, indentation, stack);
27216 if (element !== undef) {
27217 // According to ES 5.1 section 15.12.3: "If `gap` {whitespace}
27218 // is not the empty string, let `member` {quote(property) + ":"}
27219 // be the concatenation of `member` and the `space` character."
27220 // The "`space` character" refers to the literal space
27221 // character, not the `space` {width} argument provided to
27222 // `JSON.stringify`.
27223 results.push(quote(property) + ":" + (whitespace ? " " : "") + element);
27224 }
27225 });
27226 result = results.length ? (whitespace ? "{\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "}" : ("{" + results.join(",") + "}")) : "{}";
27227 }
27228 // Remove the object from the traversed object stack.
27229 stack.pop();
27230 return result;
27231 }
27232 };
27233
27234 // Public: `JSON.stringify`. See ES 5.1 section 15.12.3.
27235 exports.stringify = function (source, filter, width) {
27236 var whitespace, callback, properties, className;
27237 if (objectTypes[typeof filter] && filter) {
27238 if ((className = getClass.call(filter)) == functionClass) {
27239 callback = filter;
27240 } else if (className == arrayClass) {
27241 // Convert the property names array into a makeshift set.
27242 properties = {};
27243 for (var index = 0, length = filter.length, value; index < length; value = filter[index++], ((className = getClass.call(value)), className == stringClass || className == numberClass) && (properties[value] = 1));
27244 }
27245 }
27246 if (width) {
27247 if ((className = getClass.call(width)) == numberClass) {
27248 // Convert the `width` to an integer and create a string containing
27249 // `width` number of space characters.
27250 if ((width -= width % 1) > 0) {
27251 for (whitespace = "", width > 10 && (width = 10); whitespace.length < width; whitespace += " ");
27252 }
27253 } else if (className == stringClass) {
27254 whitespace = width.length <= 10 ? width : width.slice(0, 10);
27255 }
27256 }
27257 // Opera <= 7.54u2 discards the values associated with empty string keys
27258 // (`""`) only if they are used directly within an object member list
27259 // (e.g., `!("" in { "": 1})`).
27260 return serialize("", (value = {}, value[""] = source, value), callback, properties, whitespace, "", []);
27261 };
27262 }
27263
27264 // Public: Parses a JSON source string.
27265 if (!has("json-parse")) {
27266 var fromCharCode = String.fromCharCode;
27267
27268 // Internal: A map of escaped control characters and their unescaped
27269 // equivalents.
27270 var Unescapes = {
27271 92: "\\",
27272 34: '"',
27273 47: "/",
27274 98: "\b",
27275 116: "\t",
27276 110: "\n",
27277 102: "\f",
27278 114: "\r"
27279 };
27280
27281 // Internal: Stores the parser state.
27282 var Index, Source;
27283
27284 // Internal: Resets the parser state and throws a `SyntaxError`.
27285 var abort = function () {
27286 Index = Source = null;
27287 throw SyntaxError();
27288 };
27289
27290 // Internal: Returns the next token, or `"$"` if the parser has reached
27291 // the end of the source string. A token may be a string, number, `null`
27292 // literal, or Boolean literal.
27293 var lex = function () {
27294 var source = Source, length = source.length, value, begin, position, isSigned, charCode;
27295 while (Index < length) {
27296 charCode = source.charCodeAt(Index);
27297 switch (charCode) {
27298 case 9: case 10: case 13: case 32:
27299 // Skip whitespace tokens, including tabs, carriage returns, line
27300 // feeds, and space characters.
27301 Index++;
27302 break;
27303 case 123: case 125: case 91: case 93: case 58: case 44:
27304 // Parse a punctuator token (`{`, `}`, `[`, `]`, `:`, or `,`) at
27305 // the current position.
27306 value = charIndexBuggy ? source.charAt(Index) : source[Index];
27307 Index++;
27308 return value;
27309 case 34:
27310 // `"` delimits a JSON string; advance to the next character and
27311 // begin parsing the string. String tokens are prefixed with the
27312 // sentinel `@` character to distinguish them from punctuators and
27313 // end-of-string tokens.
27314 for (value = "@", Index++; Index < length;) {
27315 charCode = source.charCodeAt(Index);
27316 if (charCode < 32) {
27317 // Unescaped ASCII control characters (those with a code unit
27318 // less than the space character) are not permitted.
27319 abort();
27320 } else if (charCode == 92) {
27321 // A reverse solidus (`\`) marks the beginning of an escaped
27322 // control character (including `"`, `\`, and `/`) or Unicode
27323 // escape sequence.
27324 charCode = source.charCodeAt(++Index);
27325 switch (charCode) {
27326 case 92: case 34: case 47: case 98: case 116: case 110: case 102: case 114:
27327 // Revive escaped control characters.
27328 value += Unescapes[charCode];
27329 Index++;
27330 break;
27331 case 117:
27332 // `\u` marks the beginning of a Unicode escape sequence.
27333 // Advance to the first character and validate the
27334 // four-digit code point.
27335 begin = ++Index;
27336 for (position = Index + 4; Index < position; Index++) {
27337 charCode = source.charCodeAt(Index);
27338 // A valid sequence comprises four hexdigits (case-
27339 // insensitive) that form a single hexadecimal value.
27340 if (!(charCode >= 48 && charCode <= 57 || charCode >= 97 && charCode <= 102 || charCode >= 65 && charCode <= 70)) {
27341 // Invalid Unicode escape sequence.
27342 abort();
27343 }
27344 }
27345 // Revive the escaped character.
27346 value += fromCharCode("0x" + source.slice(begin, Index));
27347 break;
27348 default:
27349 // Invalid escape sequence.
27350 abort();
27351 }
27352 } else {
27353 if (charCode == 34) {
27354 // An unescaped double-quote character marks the end of the
27355 // string.
27356 break;
27357 }
27358 charCode = source.charCodeAt(Index);
27359 begin = Index;
27360 // Optimize for the common case where a string is valid.
27361 while (charCode >= 32 && charCode != 92 && charCode != 34) {
27362 charCode = source.charCodeAt(++Index);
27363 }
27364 // Append the string as-is.
27365 value += source.slice(begin, Index);
27366 }
27367 }
27368 if (source.charCodeAt(Index) == 34) {
27369 // Advance to the next character and return the revived string.
27370 Index++;
27371 return value;
27372 }
27373 // Unterminated string.
27374 abort();
27375 default:
27376 // Parse numbers and literals.
27377 begin = Index;
27378 // Advance past the negative sign, if one is specified.
27379 if (charCode == 45) {
27380 isSigned = true;
27381 charCode = source.charCodeAt(++Index);
27382 }
27383 // Parse an integer or floating-point value.
27384 if (charCode >= 48 && charCode <= 57) {
27385 // Leading zeroes are interpreted as octal literals.
27386 if (charCode == 48 && ((charCode = source.charCodeAt(Index + 1)), charCode >= 48 && charCode <= 57)) {
27387 // Illegal octal literal.
27388 abort();
27389 }
27390 isSigned = false;
27391 // Parse the integer component.
27392 for (; Index < length && ((charCode = source.charCodeAt(Index)), charCode >= 48 && charCode <= 57); Index++);
27393 // Floats cannot contain a leading decimal point; however, this
27394 // case is already accounted for by the parser.
27395 if (source.charCodeAt(Index) == 46) {
27396 position = ++Index;
27397 // Parse the decimal component.
27398 for (; position < length && ((charCode = source.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++);
27399 if (position == Index) {
27400 // Illegal trailing decimal.
27401 abort();
27402 }
27403 Index = position;
27404 }
27405 // Parse exponents. The `e` denoting the exponent is
27406 // case-insensitive.
27407 charCode = source.charCodeAt(Index);
27408 if (charCode == 101 || charCode == 69) {
27409 charCode = source.charCodeAt(++Index);
27410 // Skip past the sign following the exponent, if one is
27411 // specified.
27412 if (charCode == 43 || charCode == 45) {
27413 Index++;
27414 }
27415 // Parse the exponential component.
27416 for (position = Index; position < length && ((charCode = source.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++);
27417 if (position == Index) {
27418 // Illegal empty exponent.
27419 abort();
27420 }
27421 Index = position;
27422 }
27423 // Coerce the parsed value to a JavaScript number.
27424 return +source.slice(begin, Index);
27425 }
27426 // A negative sign may only precede numbers.
27427 if (isSigned) {
27428 abort();
27429 }
27430 // `true`, `false`, and `null` literals.
27431 if (source.slice(Index, Index + 4) == "true") {
27432 Index += 4;
27433 return true;
27434 } else if (source.slice(Index, Index + 5) == "false") {
27435 Index += 5;
27436 return false;
27437 } else if (source.slice(Index, Index + 4) == "null") {
27438 Index += 4;
27439 return null;
27440 }
27441 // Unrecognized token.
27442 abort();
27443 }
27444 }
27445 // Return the sentinel `$` character if the parser has reached the end
27446 // of the source string.
27447 return "$";
27448 };
27449
27450 // Internal: Parses a JSON `value` token.
27451 var get = function (value) {
27452 var results, hasMembers;
27453 if (value == "$") {
27454 // Unexpected end of input.
27455 abort();
27456 }
27457 if (typeof value == "string") {
27458 if ((charIndexBuggy ? value.charAt(0) : value[0]) == "@") {
27459 // Remove the sentinel `@` character.
27460 return value.slice(1);
27461 }
27462 // Parse object and array literals.
27463 if (value == "[") {
27464 // Parses a JSON array, returning a new JavaScript array.
27465 results = [];
27466 for (;; hasMembers || (hasMembers = true)) {
27467 value = lex();
27468 // A closing square bracket marks the end of the array literal.
27469 if (value == "]") {
27470 break;
27471 }
27472 // If the array literal contains elements, the current token
27473 // should be a comma separating the previous element from the
27474 // next.
27475 if (hasMembers) {
27476 if (value == ",") {
27477 value = lex();
27478 if (value == "]") {
27479 // Unexpected trailing `,` in array literal.
27480 abort();
27481 }
27482 } else {
27483 // A `,` must separate each array element.
27484 abort();
27485 }
27486 }
27487 // Elisions and leading commas are not permitted.
27488 if (value == ",") {
27489 abort();
27490 }
27491 results.push(get(value));
27492 }
27493 return results;
27494 } else if (value == "{") {
27495 // Parses a JSON object, returning a new JavaScript object.
27496 results = {};
27497 for (;; hasMembers || (hasMembers = true)) {
27498 value = lex();
27499 // A closing curly brace marks the end of the object literal.
27500 if (value == "}") {
27501 break;
27502 }
27503 // If the object literal contains members, the current token
27504 // should be a comma separator.
27505 if (hasMembers) {
27506 if (value == ",") {
27507 value = lex();
27508 if (value == "}") {
27509 // Unexpected trailing `,` in object literal.
27510 abort();
27511 }
27512 } else {
27513 // A `,` must separate each object member.
27514 abort();
27515 }
27516 }
27517 // Leading commas are not permitted, object property names must be
27518 // double-quoted strings, and a `:` must separate each property
27519 // name and value.
27520 if (value == "," || typeof value != "string" || (charIndexBuggy ? value.charAt(0) : value[0]) != "@" || lex() != ":") {
27521 abort();
27522 }
27523 results[value.slice(1)] = get(lex());
27524 }
27525 return results;
27526 }
27527 // Unexpected token encountered.
27528 abort();
27529 }
27530 return value;
27531 };
27532
27533 // Internal: Updates a traversed object member.
27534 var update = function (source, property, callback) {
27535 var element = walk(source, property, callback);
27536 if (element === undef) {
27537 delete source[property];
27538 } else {
27539 source[property] = element;
27540 }
27541 };
27542
27543 // Internal: Recursively traverses a parsed JSON object, invoking the
27544 // `callback` function for each value. This is an implementation of the
27545 // `Walk(holder, name)` operation defined in ES 5.1 section 15.12.2.
27546 var walk = function (source, property, callback) {
27547 var value = source[property], length;
27548 if (typeof value == "object" && value) {
27549 // `forEach` can't be used to traverse an array in Opera <= 8.54
27550 // because its `Object#hasOwnProperty` implementation returns `false`
27551 // for array indices (e.g., `![1, 2, 3].hasOwnProperty("0")`).
27552 if (getClass.call(value) == arrayClass) {
27553 for (length = value.length; length--;) {
27554 update(value, length, callback);
27555 }
27556 } else {
27557 forEach(value, function (property) {
27558 update(value, property, callback);
27559 });
27560 }
27561 }
27562 return callback.call(source, property, value);
27563 };
27564
27565 // Public: `JSON.parse`. See ES 5.1 section 15.12.2.
27566 exports.parse = function (source, callback) {
27567 var result, value;
27568 Index = 0;
27569 Source = "" + source;
27570 result = get(lex());
27571 // If a JSON string contains multiple tokens, it is invalid.
27572 if (lex() != "$") {
27573 abort();
27574 }
27575 // Reset the parser state.
27576 Index = Source = null;
27577 return callback && getClass.call(callback) == functionClass ? walk((value = {}, value[""] = result, value), "", callback) : result;
27578 };
27579 }
27580 }
27581
27582 exports["runInContext"] = runInContext;
27583 return exports;
27584 }
27585
27586 if (freeExports && !isLoader) {
27587 // Export for CommonJS environments.
27588 runInContext(root, freeExports);
27589 } else {
27590 // Export for web browsers and JavaScript engines.
27591 var nativeJSON = root.JSON,
27592 previousJSON = root["JSON3"],
27593 isRestored = false;
27594
27595 var JSON3 = runInContext(root, (root["JSON3"] = {
27596 // Public: Restores the original value of the global `JSON` object and
27597 // returns a reference to the `JSON3` object.
27598 "noConflict": function () {
27599 if (!isRestored) {
27600 isRestored = true;
27601 root.JSON = nativeJSON;
27602 root["JSON3"] = previousJSON;
27603 nativeJSON = previousJSON = null;
27604 }
27605 return JSON3;
27606 }
27607 }));
27608
27609 root.JSON = {
27610 "parse": JSON3.parse,
27611 "stringify": JSON3.stringify
27612 };
27613 }
27614
27615 // Export for asynchronous module loaders.
27616 if (isLoader) {
27617 define(function () {
27618 return JSON3;
27619 });
27620 }
27621}).call(this);
27622
27623}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
27624},{}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/node_modules/to-array/index.js":[function(require,module,exports){
27625module.exports = toArray
27626
27627function toArray(list, index) {
27628 var array = []
27629
27630 index = index || 0
27631
27632 for (var i = index || 0; i < list.length; i++) {
27633 array[i - index] = list[i]
27634 }
27635
27636 return array
27637}
27638
27639},{}],"/home/employee-2klic/projects/2klic_io-sdk/src/index.js":[function(require,module,exports){
27640var HttpClient = require('./lib/http-client');
27641var events = require('events');
27642var inherits = require('inherits');
27643var StreamAPI = require('./lib/stream_api');
27644var _ = require('lodash');
27645var Logger = require('./lib/logger');
27646
27647function Klic(options){
27648 options = options || {};
27649 this.base_url = options.url || "https://api.2klic.io";
27650 this.apiVersion = options.apiVersion || "1.0";
27651 this.auth = options.auth || {};
27652
27653 this.logger = new Logger(options.log_level || 6);
27654
27655 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 });
27656
27657 // Install all supported API endpoints
27658 this.alarm = require("./lib/methods/alarm/alarm")({ platform: this });
27659 this.zones = require("./lib/methods/alarm/zones")({ platform: this });
27660 //this.sectors = require("./lib/methods/sectors")({ platform: this });
27661 this.noc = require("./lib/methods/noc/noc")({ platform: this });
27662 this.cameras = require("./lib/methods/cameras")({ platform: this });
27663 this.streams = require("./lib/methods/streams")({ platform: this });
27664 this.devices = require("./lib/methods/devices")({ platform: this });
27665 this.zwave = require("./lib/methods/zwave")({ platform: this });
27666 this.events = require("./lib/methods/events")({ platform: this });
27667 this.locations = require("./lib/methods/locations")({ platform: this });
27668 this.scenarios = require("./lib/methods/scenarios")({ platform: this });
27669 this.models = require("./lib/methods/models")({ platform: this });
27670 this.notifications = require("./lib/methods/notifications")({ platform: this });
27671 this.translations = require("./lib/methods/translations")({ platform: this });
27672 this.user = require("./lib/methods/user")({ platform: this });
27673 this.templates = require("./lib/methods/templates")({ platform: this });
27674 this.system = require("./lib/methods/system")({ platform: this });
27675 this.access = require("./lib/methods/access/access")({ platform: this });
27676}
27677
27678inherits(Klic, events.EventEmitter);
27679
27680Klic.prototype.authenticate = require('./lib/methods/authenticate');
27681Klic.prototype.register = require('./lib/methods/register');
27682
27683module.exports = Klic;
27684
27685},{"./lib/http-client":"/home/employee-2klic/projects/2klic_io-sdk/src/lib/http-client.js","./lib/logger":"/home/employee-2klic/projects/2klic_io-sdk/src/lib/logger.js","./lib/methods/access/access":"/home/employee-2klic/projects/2klic_io-sdk/src/lib/methods/access/access.js","./lib/methods/alarm/alarm":"/home/employee-2klic/projects/2klic_io-sdk/src/lib/methods/alarm/alarm.js","./lib/methods/alarm/zones":"/home/employee-2klic/projects/2klic_io-sdk/src/lib/methods/alarm/zones.js","./lib/methods/authenticate":"/home/employee-2klic/projects/2klic_io-sdk/src/lib/methods/authenticate.js","./lib/methods/cameras":"/home/employee-2klic/projects/2klic_io-sdk/src/lib/methods/cameras.js","./lib/methods/devices":"/home/employee-2klic/projects/2klic_io-sdk/src/lib/methods/devices.js","./lib/methods/events":"/home/employee-2klic/projects/2klic_io-sdk/src/lib/methods/events.js","./lib/methods/locations":"/home/employee-2klic/projects/2klic_io-sdk/src/lib/methods/locations.js","./lib/methods/models":"/home/employee-2klic/projects/2klic_io-sdk/src/lib/methods/models.js","./lib/methods/noc/noc":"/home/employee-2klic/projects/2klic_io-sdk/src/lib/methods/noc/noc.js","./lib/methods/notifications":"/home/employee-2klic/projects/2klic_io-sdk/src/lib/methods/notifications.js","./lib/methods/register":"/home/employee-2klic/projects/2klic_io-sdk/src/lib/methods/register.js","./lib/methods/scenarios":"/home/employee-2klic/projects/2klic_io-sdk/src/lib/methods/scenarios.js","./lib/methods/streams":"/home/employee-2klic/projects/2klic_io-sdk/src/lib/methods/streams.js","./lib/methods/system":"/home/employee-2klic/projects/2klic_io-sdk/src/lib/methods/system.js","./lib/methods/templates":"/home/employee-2klic/projects/2klic_io-sdk/src/lib/methods/templates.js","./lib/methods/translations":"/home/employee-2klic/projects/2klic_io-sdk/src/lib/methods/translations.js","./lib/methods/user":"/home/employee-2klic/projects/2klic_io-sdk/src/lib/methods/user.js","./lib/methods/zwave":"/home/employee-2klic/projects/2klic_io-sdk/src/lib/methods/zwave.js","./lib/stream_api":"/home/employee-2klic/projects/2klic_io-sdk/src/lib/stream_api.js","events":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/browserify/node_modules/events/events.js","inherits":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/inherits/inherits_browser.js","lodash":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/lodash/index.js"}],"/home/employee-2klic/projects/2klic_io-sdk/src/lib/http-client.js":[function(require,module,exports){
27686(function (Buffer){
27687var request = require('request');
27688
27689var MixinPromise = require('./mixin_promise');
27690var _ = require('lodash');
27691
27692function HttpClient(baseUrl, options) {
27693 options = options || {};
27694 this.url = baseUrl;
27695 this.app_key = options.app_key;
27696 this.app_type = options.app_type || 'browser';
27697 this.app_secret = options.app_secret;
27698 this.unsafe = options.unsafe;
27699 this.logger = options.logger;
27700 this.api_version = options.api_version;
27701 this.callback = _.noop;
27702 this.enableCallback = options.enableCallback || true;
27703}
27704
27705HttpClient.prototype.request = function(method, path, body, options) {
27706 var _this = this;
27707 this.logger.trace("Executing HTTP request " + method + " " + path);
27708
27709 if(arguments.length === 3) {
27710 options = body;
27711 body = undefined;
27712 }
27713 else if(arguments.length === 2) {
27714 options = {};
27715 }
27716
27717 options = options || {};
27718
27719 return new MixinPromise(function(resolve, reject) {
27720
27721 var headers = {};
27722
27723 if (options.token) {
27724 _this.logger.trace("Token was provided. Adding Authorization header");
27725 headers['authorization'] = "Bearer " + options.token;
27726 _this.logger.trace(headers['authorization']);
27727 }
27728 else if (options.basic) {
27729 _this.logger.trace("Basic credentials were provided. Adding Authorization header");
27730 var str = new Buffer(options.basic.username + ":" + options.basic.password, "utf8").toString("base64");
27731 headers['authorization'] = "Basic " + str;
27732 }
27733
27734 if (options.app_key || _this.app_key) {
27735 _this.logger.trace("Configuring X-App-Key to ", options.app_key || _this.app_key);
27736 headers['x-app-key'] = options.app_key || _this.app_key;
27737 }
27738
27739 if (options.unsafe || _this.unsafe) {
27740 _this.logger.trace("Indicating to the platform that we are in the browser (unsafe)");
27741 headers['x-unsafe-auth'] = options.unsafe || _this.unsafe;
27742 }
27743
27744 if (options.api_version || _this.api_version) {
27745 headers['x-api-version'] = options.api_version || _this.api_version;
27746 }
27747
27748 if (options.app_type || _this.app_type) {
27749 headers['x-app-type'] = options.app_type || _this.app_type;
27750 }
27751
27752 _this.logger.trace("Request URL is: " + method + " " + _this.url + path);
27753
27754 return new MixinPromise(function (resolve, reject) {
27755 request({
27756 method: method,
27757 url: _this.url + path,
27758 json: body,
27759 headers: headers,
27760 verbose: false,
27761 //withCredentials: true,
27762 timeout: options.timeout || 30000,
27763 qs: options.query || null
27764 }, function (err, resp, body) {
27765 if (err) {
27766 _this.logger.error("HTTP ERROR:", err);
27767 reject(err);
27768 }
27769 else {
27770 _this.logger.trace("Receive a valid HTTP response");
27771 if (resp.statusCode >= 400) {
27772 _this.logger.error("Receive status code %d", resp.statusCode);
27773 err = new Error("HTTP " + resp.statusCode + ": " + method + " " + path);
27774 err.statusCode = resp.statusCode;
27775 err.statusText = resp.statusText;
27776
27777 if (_isJson(body)) body = JSON.parse(body);
27778 err.code = body.code;
27779 err.parameters = body.parameters;
27780 err.message = body.message;
27781
27782 if (body.details) err.details = body.details;
27783
27784 err.error = resp.error;
27785 err.body = body;
27786 reject(err);
27787 }
27788 else if (resp.statusCode === 0) {
27789 _this.logger.error("Unable to connect to platform");
27790 err = new Error("Unable to connect to server");
27791 err.statusCode = 0;
27792 reject(err);
27793 }
27794 else if (body) {
27795 _this.logger.trace("Receive a valid body");
27796 if (_.isString(body)) {
27797 body = JSON.parse(body);
27798 }
27799
27800 if (body.data) {
27801 resolve(body);
27802 }
27803 else {
27804 _this.logger.trace("Resolving response promise. Status Code=", resp.statusCode);
27805 resolve({statusCode: resp.statusCode, data: body});
27806 }
27807 }
27808 else {
27809 _this.logger.trace("Resolving without body. Status code = %d", resp.statusCode);
27810 resolve({statusCode: resp.statusCode});
27811 }
27812 }
27813 });
27814 }).then(function (res) {
27815 resolve(res);
27816 }).catch(function (error) {
27817 if (_this.enableCallback) {
27818 var p = _this.callback(error);
27819 var isPromise = _.isObject(p) && _.isFunction(p.then);
27820
27821 if (isPromise) {
27822 p.then(function () {
27823 reject(error);
27824 });
27825 }
27826 else reject(error);
27827 }
27828 });
27829 });
27830};
27831
27832HttpClient.prototype.post = function(path, body, options) {
27833 if(typeof(body) === 'object') body = _.omit(body, function(prop){ if(typeof(prop)==='string' && !prop.length) return true });
27834 return this.request('POST', path, body, options);
27835};
27836
27837HttpClient.prototype.delete = function(path, options) {
27838 return this.request('DELETE', path, options);
27839};
27840
27841HttpClient.prototype.get = function(path, options) {
27842 return this.request('GET', path, options);
27843};
27844
27845HttpClient.prototype.put = function(path, body, options) {
27846 if(typeof(body) === 'object') body = _.omit(body, function(prop){ if(typeof(prop)==='string' && !prop.length) return true });
27847 if(arguments.length === 2) {
27848 options = body;
27849 body = undefined;
27850 }
27851 return this.request('PUT', path, body, options);
27852};
27853
27854HttpClient.prototype.patch = function(path, body, options) {
27855 if(typeof(body) === 'object') body = _.omit(body, function(prop){ if(typeof(prop)==='string' && !prop.length) return true });
27856 return this.request('PATCH', path, body, options);
27857};
27858
27859function _isJson(str) {
27860 try {
27861 JSON.parse(str);
27862 } catch (e) {
27863 return false;
27864 }
27865 return true;
27866}
27867
27868module.exports = HttpClient;
27869}).call(this,require("buffer").Buffer)
27870},{"./mixin_promise":"/home/employee-2klic/projects/2klic_io-sdk/src/lib/mixin_promise.js","buffer":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/browserify/node_modules/buffer/index.js","lodash":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/lodash/index.js","request":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/browser-request/index.js"}],"/home/employee-2klic/projects/2klic_io-sdk/src/lib/logger.js":[function(require,module,exports){
27871function Logger(level) {
27872 this.level = level;
27873}
27874
27875Logger.prototype.trace = function() {
27876 if(this.level > 9) {
27877 console.log.apply(console, arguments);
27878 }
27879};
27880
27881Logger.prototype.debug = function() {
27882 if(this.level > 7) {
27883 console.log.apply(console, arguments);
27884 }
27885};
27886
27887Logger.prototype.info = function() {
27888 if(this.level > 5) {
27889 console.log.apply(console, arguments);
27890 }
27891};
27892
27893Logger.prototype.warn = function() {
27894 if(this.level > 3) {
27895 console.log.apply(console, arguments);
27896 }
27897};
27898
27899Logger.prototype.error = function() {
27900 if(this.level > 1) {
27901 console.log.apply(console, arguments);
27902 }
27903};
27904
27905Logger.prototype.fatal = function() {
27906 console.log.apply(console, arguments);
27907};
27908
27909module.exports = Logger;
27910},{}],"/home/employee-2klic/projects/2klic_io-sdk/src/lib/methods/access/access.js":[function(require,module,exports){
27911'use strict';
27912var Cards = require("./cards");
27913
27914function Access(options) {
27915 options = options || {};
27916 this.platform = options.platform;
27917 this.cards = new Cards ({ platform: this.platform });
27918}
27919
27920Access.prototype.list = function(params){
27921 return this.platform.http.get('/access/', { query: params, token: this.platform.auth.token });
27922};
27923
27924Access.prototype.get = function(id, params){
27925 return this.platform.http.get('/access/'+id, { query: params, token: this.platform.auth.token });
27926};
27927
27928Access.prototype.create = function(accessData){
27929 return this.platform.http.post('/access', accessData, { token: this.platform.auth.token });
27930};
27931
27932Access.prototype.update = function(id, accessData){
27933 return this.platform.http.put('/access/' + id, accessData, { token: this.platform.auth.token });
27934};
27935
27936Access.prototype.patch = function(id, accessData){
27937 return this.platform.http.patch('/access/' + d, accessData, { token: this.platform.auth.token });
27938};
27939
27940Access.prototype.patch = function(id, accessData){
27941 return this.platform.http.patch('/access/' + id, accessData, { token: this.platform.auth.token });
27942};
27943
27944
27945module.exports = function(options) {
27946 options = options || {};
27947 return new Access(options);
27948};
27949
27950},{"./cards":"/home/employee-2klic/projects/2klic_io-sdk/src/lib/methods/access/cards.js"}],"/home/employee-2klic/projects/2klic_io-sdk/src/lib/methods/access/cards.js":[function(require,module,exports){
27951'use strict';
27952
27953function Cards(options) {
27954 options = options || {};
27955 this.platform = options.platform;
27956}
27957
27958Cards.prototype.list= function(){
27959 return this.platform.http.get('/access/cards', { token: this.platform.auth.token });
27960};
27961
27962Cards.prototype.get= function(id){
27963 return this.platform.http.get('/access/cards/' + id, { token: this.platform.auth.token });
27964};
27965
27966Cards.prototype.create= function(cardData){
27967 return this.platform.http.post('/access/cards', cardData, { token: this.platform.auth.token });
27968};
27969
27970Cards.prototype.update= function(id, cardData){
27971 return this.platform.http.put('/access/cards/' + id, cardData, { token: this.platform.auth.token });
27972};
27973
27974Cards.prototype.patch = function(id, cardData){
27975 return this.platform.http.patch ('/access/cards/' + id, cardData, { token: this.platform.auth.token });
27976};
27977
27978module.exports = function(options) {
27979 options = options || {};
27980 return new Cards(options);
27981};
27982
27983},{}],"/home/employee-2klic/projects/2klic_io-sdk/src/lib/methods/alarm/alarm.js":[function(require,module,exports){
27984'use strict';
27985var User = require("./user");
27986var Pin = require("./pin");
27987var Zone = require("./zones");
27988
27989function Alarm(options) {
27990 options = options || {};
27991 this.platform = options.platform;
27992 this.user = new User({ platform: this.platform });
27993 this.pin = new Pin({ platform: this.platform });
27994 this.zones = new Zone({ platform: this.platform });
27995}
27996
27997// Provision an alarm system
27998Alarm.prototype.create = function(alarm){
27999 return this.platform.http.post('/alarms', alarm, { token: this.platform.auth.token });
28000};
28001
28002// Get a an alarm system state
28003Alarm.prototype.get = function(alarmId){
28004 return this.platform.http.get('/alarms/'+alarmId, { token: this.platform.auth.token });
28005};
28006
28007Alarm.prototype.list = function(){
28008 return this.platform.http.get('/alarms', { token: this.platform.auth.token });
28009};
28010
28011Alarm.prototype.patch = function(alarm, alarmId){
28012 return this.platform.http.patch('/alarms/'+alarmId, alarm, { token: this.platform.auth.token });
28013};
28014
28015Alarm.prototype.delete = function(alarmId){
28016 return this.platform.http.delete('/alarms/'+alarmId, { token: this.platform.auth.token });
28017};
28018
28019Alarm.prototype.getToken = function(alarmId, pin){
28020 return this.platform.http.post('/alarms/'+alarmId+'/auth/token', { pin: pin }, { token: this.platform.auth.token });
28021};
28022
28023// Reset the alarm service
28024Alarm.prototype.reset = function(alarmId){
28025 return this.platform.http.post('/alarms/'+alarmId+'/reset', {}, { token: this.platform.auth.token });
28026};
28027
28028Alarm.prototype.arm = function(alarmId, armToken, state, bypassedZoneIds){
28029 return this.platform.http.put('/alarms/'+alarmId, { state: state, bypassed: bypassedZoneIds }, { query: { armToken: armToken }, token: this.platform.auth.token });
28030};
28031
28032module.exports = function(options) {
28033 options = options || {};
28034 return new Alarm(options);
28035};
28036
28037
28038},{"./pin":"/home/employee-2klic/projects/2klic_io-sdk/src/lib/methods/alarm/pin.js","./user":"/home/employee-2klic/projects/2klic_io-sdk/src/lib/methods/alarm/user.js","./zones":"/home/employee-2klic/projects/2klic_io-sdk/src/lib/methods/alarm/zones.js"}],"/home/employee-2klic/projects/2klic_io-sdk/src/lib/methods/alarm/pin.js":[function(require,module,exports){
28039'use strict';
28040
28041function Pin(options) {
28042 options = options || {};
28043 this.platform = options.platform;
28044}
28045
28046Pin.prototype.update = function(alarmId, userId, pin){
28047 return this.platform.http.put('/alarms/'+alarmId+'/users/'+userId+'/pin', pin, { token: this.platform.auth.token });
28048};
28049
28050module.exports = function(options) {
28051 options = options || {};
28052 return new Pin(options);
28053};
28054
28055
28056},{}],"/home/employee-2klic/projects/2klic_io-sdk/src/lib/methods/alarm/user.js":[function(require,module,exports){
28057'use strict';
28058
28059function User(options) {
28060 options = options || {};
28061 this.platform = options.platform;
28062}
28063
28064// Add a user to an alarm system
28065User.prototype.create = function(alarmId, userId){
28066 return this.platform.http.post('/alarms/'+alarmId+'/users/'+userId, {}, { token: this.platform.auth.token });
28067};
28068
28069// List users in an alarm system
28070User.prototype.list = function(alarmId){
28071 return this.platform.http.get('/alarms/'+alarmId+'/users', { token: this.platform.auth.token });
28072};
28073
28074// Delete a user in an alarm system
28075User.prototype.delete = function(alarmId, userId){
28076 if(userId) return this.platform.http.delete('/alarms/'+alarmId+'/users/'+userId, { token: this.platform.auth.token });
28077 else return this.platform.http.delete('/alarms/'+alarmId+'/users', { token: this.platform.auth.token });
28078};
28079
28080
28081
28082module.exports = function(options) {
28083 options = options || {};
28084 return new User(options);
28085};
28086
28087
28088},{}],"/home/employee-2klic/projects/2klic_io-sdk/src/lib/methods/alarm/zones.js":[function(require,module,exports){
28089'use strict';
28090
28091var _ = require('lodash');
28092
28093function Zones(options) {
28094 options = options || {};
28095 this.platform = options.platform;
28096}
28097
28098// Zones
28099Zones.prototype.create = function(alarmId, zone, query){
28100 if(_.get(query, 'populate')) query.populate = query.populate.toString();
28101 return this.platform.http.post('/alarms/'+alarmId+'/zones', zone, { query: query, token: this.platform.auth.token });
28102};
28103
28104Zones.prototype.list = function(alarmId, query){
28105 if(_.get(query, 'populate')) query.populate = query.populate.toString();
28106 return this.platform.http.get('/alarms/'+alarmId+'/zones', { query: query, token: this.platform.auth.token });
28107};
28108
28109Zones.prototype.get = function(alarmId, zoneId, query){
28110 if(_.get(query, 'populate')) query.populate = query.populate.toString();
28111 return this.platform.http.get('/alarms/'+alarmId+'/zones/'+zoneId, { query: query, token: this.platform.auth.token });
28112};
28113
28114Zones.prototype.update = function(alarmId, zone, query){
28115 if(_.get(query, 'populate')) query.populate = query.populate.toString();
28116 return this.platform.http.put('/alarms/'+alarmId+'/zones/'+zone._id, zone, { query: query, token: this.platform.auth.token });
28117};
28118
28119Zones.prototype.patch = function(alarmId, obj, zoneId, query){
28120 if(_.get(query, 'populate')) query.populate = query.populate.toString();
28121 return this.platform.http.patch('/alarms/'+alarmId+'/zones/'+zoneId, obj, { query: query, token: this.platform.auth.token });
28122};
28123
28124Zones.prototype.delete = function(alarmId, zoneId, query){
28125 if(_.get(query, 'populate')) query.populate = query.populate.toString();
28126 if(zoneId) return this.platform.http.delete('/alarms/'+alarmId+'/zones/'+zoneId, { token: this.platform.auth.token });
28127 else return this.platform.http.delete('/alarms/'+alarmId+'/zones', { query: query, token: this.platform.auth.token });
28128};
28129
28130module.exports = function(options) {
28131 options = options || {};
28132 return new Zones(options);
28133};
28134
28135
28136},{"lodash":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/lodash/index.js"}],"/home/employee-2klic/projects/2klic_io-sdk/src/lib/methods/authenticate.js":[function(require,module,exports){
28137module.exports = (function() {
28138
28139 return function(credentials, options) {
28140 var _this = this, logger = this.logger;
28141 options = options || {};
28142
28143 logger.debug("Executing HTTP request GET /auth/token");
28144 return this.http.post("/auth/token", {}, {
28145 basic: {
28146 username: credentials.username,
28147 password: credentials.password
28148 }
28149 }).then(function(resp) {
28150 logger.trace(resp);
28151 if(!_this.auth) {
28152 logger.debug("No existing platform auth field. Initializing it");
28153 _this.auth = {};
28154 }
28155 if(resp) {
28156 logger.debug("Installing token %s as default platform auth mechanism", resp.data.token);
28157 _this.auth.token = resp.data.token;
28158 return resp.data;
28159 }
28160 else {
28161 logger.error("Invalid response received from platform");
28162 }
28163
28164 });
28165
28166 };
28167
28168})();
28169},{}],"/home/employee-2klic/projects/2klic_io-sdk/src/lib/methods/cameras.js":[function(require,module,exports){
28170'use strict';
28171
28172function Cameras(options) {
28173 options = options || {};
28174 this.platform = options.platform;
28175}
28176
28177Cameras.prototype.get = function(propertyId){
28178 return this.platform.http.get('/homes/'+propertyId+'/cameras/stream/all', { token: this.platform.auth.token });
28179};
28180
28181module.exports = function(options) {
28182 options = options || {};
28183 return new Cameras(options);
28184};
28185
28186
28187},{}],"/home/employee-2klic/projects/2klic_io-sdk/src/lib/methods/devices.js":[function(require,module,exports){
28188'use strict';
28189
28190var _ = require('lodash');
28191
28192function Devices(options) {
28193 options = options || {};
28194 this.platform = options.platform;
28195}
28196
28197Devices.prototype.list = function(query){
28198 if(_.get(query, 'populate')) query.populate = query.populate.toString();
28199 return this.platform.http.get('/devices', { query: query, token: this.platform.auth.token });
28200};
28201
28202Devices.prototype.get = function(deviceId, query){
28203 if(_.get(query, 'populate')) query.populate = query.populate.toString();
28204 return this.platform.http.get('/devices/'+deviceId, { query: query, token: this.platform.auth.token });
28205};
28206
28207Devices.prototype.getChildren = function(deviceId, level, query){
28208 if(_.get(query, 'populate')) query.populate = query.populate.toString();
28209 var query = _.merge({ showChildren: true, level: level }, query);
28210 return this.platform.http.get('/devices/'+deviceId, { query: query, token: this.platform.auth.token });
28211};
28212
28213Devices.prototype.create = function(device, query){
28214 if(_.get(query, 'populate')) query.populate = query.populate.toString();
28215 return this.platform.http.post('/devices', device, { query: query, token: this.platform.auth.token });
28216};
28217
28218Devices.prototype.update = function(device, query){
28219 if(_.get(query, 'populate')) query.populate = query.populate.toString();
28220 return this.platform.http.put('/devices/'+device._id, device, { query: query, token: this.platform.auth.token });
28221};
28222
28223Devices.prototype.patch = function(obj, deviceId, query){
28224 if(_.get(query, 'populate')) query.populate = query.populate.toString();
28225 return this.platform.http.patch('/devices/'+deviceId, obj, { query: query, token: this.platform.auth.token });
28226};
28227
28228Devices.prototype.delete = function(deviceId, query){
28229 if(_.get(query, 'populate')) query.populate = query.populate.toString();
28230 return this.platform.http.delete('/devices/'+deviceId, { query: query, token: this.platform.auth.token });
28231};
28232
28233// Reset a hub
28234Devices.prototype.reset = function(deviceId){
28235 return this.platform.http.put('/devices/'+deviceId+'/reset', {}, { token: this.platform.auth.token });
28236};
28237
28238Devices.prototype.updateCapability = function(deviceId, capabilityId, value, unit, timestamp){
28239 return this.platform.http.put('/devices/'+deviceId+'/caps/'+capabilityId, { value: value, unit: unit, timestamp: timestamp }, { token: this.platform.auth.token });
28240};
28241
28242Devices.prototype.patchCapability = function(deviceId, capabilityId, obj){
28243 return this.platform.http.patch('/devices/'+deviceId+'/caps/'+capabilityId, obj, { token: this.platform.auth.token });
28244};
28245
28246Devices.prototype.getCapability = function(deviceId, capabilityId){
28247 return this.platform.http.get('/devices/'+deviceId+'/caps/'+capabilityId, { token: this.platform.auth.token });
28248};
28249
28250Devices.prototype.listCapability = function(deviceId){
28251 return this.platform.http.get('/devices/'+deviceId+'/caps', { token: this.platform.auth.token });
28252};
28253
28254// Hub provisioning
28255Devices.prototype.provision = function(name, mac, model, location){
28256 var _this = this;
28257 var obj = _.merge({ name:name, mac:mac, model:model }, { location: location }); // optional location parameter
28258 return this.platform.http.post('/devices', obj)
28259 .then(function(res){
28260 //logger.debug("Installing token %s as default platform auth mechanism", resp.data.token);
28261 if(res.data.token) _this.platform.auth.token = res.data.token;
28262 return res;
28263 })
28264};
28265
28266// Controller Heartbeat
28267Devices.prototype.heartbeat = function(deviceId, sysHealth){
28268 return this.platform.http.post('/devices/'+deviceId+'/heartbeat', sysHealth, { token: this.platform.auth.token });
28269};
28270
28271Devices.prototype.listHeartbeat = function(deviceId, query){
28272 return this.platform.http.get('/devices/'+deviceId+'/heartbeat', { query: query, token: this.platform.auth.token });
28273};
28274
28275// Controller ping
28276Devices.prototype.ping = function(deviceId){
28277 return this.platform.http.post('/devices/'+deviceId+'/ping', {}, { token: this.platform.auth.token });
28278};
28279
28280module.exports = function(options) {
28281 options = options || {};
28282 return new Devices(options);
28283};
28284
28285
28286},{"lodash":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/lodash/index.js"}],"/home/employee-2klic/projects/2klic_io-sdk/src/lib/methods/events.js":[function(require,module,exports){
28287'use strict';
28288
28289function Events(options) {
28290 options = options || {};
28291 this.platform = options.platform;
28292}
28293
28294Events.prototype.create = function(resourcePath, eventType, resource, timestamp, requestId){
28295 return this.platform.http.post('/events', { path: resourcePath, resource: resource, timestamp: timestamp, type: eventType, request: requestId }, { token: this.platform.auth.token });
28296};
28297
28298module.exports = function(options) {
28299 options = options || {};
28300 return new Events(options);
28301};
28302
28303
28304},{}],"/home/employee-2klic/projects/2klic_io-sdk/src/lib/methods/locations.js":[function(require,module,exports){
28305'use strict';
28306
28307function Locations(options) {
28308 options = options || {};
28309 this.platform = options.platform;
28310}
28311
28312Locations.prototype.list = function(level){
28313 return this.platform.http.get('/locations', { query:{ level: level }, token: this.platform.auth.token });
28314};
28315
28316Locations.prototype.get = function(locationId, level){
28317 return this.platform.http.get('/locations/'+locationId, { query: { level: level }, token: this.platform.auth.token });
28318};
28319
28320Locations.prototype.getRoot = function(locationId, level){
28321 return this.platform.http.get('/locations/'+locationId, { query: { root: true, level: level }, token: this.platform.auth.token });
28322};
28323
28324Locations.prototype.create = function(location){
28325 return this.platform.http.post('/locations', location, { token: this.platform.auth.token });
28326};
28327
28328Locations.prototype.update = function(location){
28329 return this.platform.http.put('/locations/'+location._id, location, { token: this.platform.auth.token });
28330};
28331
28332Locations.prototype.patch = function(obj, locationId){
28333 return this.platform.http.patch('/locations/'+locationId, obj, { token: this.platform.auth.token });
28334};
28335
28336Locations.prototype.delete = function(locationId){
28337 return this.platform.http.delete('/locations/'+locationId, { token: this.platform.auth.token });
28338};
28339
28340module.exports = function(options) {
28341 options = options || {};
28342 return new Locations(options);
28343};
28344
28345
28346},{}],"/home/employee-2klic/projects/2klic_io-sdk/src/lib/methods/models.js":[function(require,module,exports){
28347'use strict';
28348
28349function Models(options) {
28350 options = options || {};
28351 this.platform = options.platform;
28352}
28353
28354Models.prototype.list = function(query){
28355 return this.platform.http.get('/models', { query: query, token: this.platform.auth.token });
28356};
28357
28358Models.prototype.get = function(id, query){
28359 return this.platform.http.get('/models/'+id, { query: query, token: this.platform.auth.token });
28360};
28361
28362Models.prototype.search = function(query){
28363 return this.platform.http.get('/models', { query: query, token: this.platform.auth.token });
28364};
28365
28366module.exports = function(options) {
28367 options = options || {};
28368 return new Models(options);
28369};
28370
28371
28372},{}],"/home/employee-2klic/projects/2klic_io-sdk/src/lib/methods/noc/customers.js":[function(require,module,exports){
28373'use strict';
28374
28375function NocCustomers(options) {
28376 options = options || {};
28377 this.platform = options.platform;
28378}
28379
28380NocCustomers.prototype.list= function(nocId){
28381 return this.platform.http.get('/nocs/' + nocId + '/customers', { token: this.platform.auth.token });
28382};
28383
28384NocCustomers.prototype.get= function(nocId, customerId){
28385 return this.platform.http.get('/nocs/' + nocId + '/customers/' + customerId, { token: this.platform.auth.token });
28386};
28387
28388NocCustomers.prototype.create= function(nocId, customer){
28389 return this.platform.http.post('/nocs/' + nocId + '/customers', customer, { token: this.platform.auth.token });
28390};
28391
28392NocCustomers.prototype.update= function(nocId, customerId, customer){
28393 return this.platform.http.put('/nocs/' + nocId + '/customers/' + customerId, customer, { token: this.platform.auth.token });
28394};
28395
28396NocCustomers.prototype.patch = function(nocId, customerId, customer){
28397 return this.platform.http.patch ('/nocs/' + nocId + '/customers/' + customerId, customer, { token: this.platform.auth.token });
28398};
28399
28400NocCustomers.prototype.listDevices = function(nocId, customerId, alarmSystemId){
28401 return this.platform.http.get('/nocs/' + nocId + '/customers/' + customerId + '/devices/' + alarmSystemId, { token: this.platform.auth.token });
28402};
28403
28404NocCustomers.prototype.getPredefinedServiceActions= function(nocId, customerId, alarmSystemId){
28405 return this.platform.http.get('/nocs/' + nocId + '/customers/' + customerId + '/alarmsystem/' + alarmSystemId + '/predefined-service-actions', { token: this.platform.auth.token });
28406};
28407
28408NocCustomers.prototype.listServiceActions= function(nocId, customerId){
28409 return this.platform.http.get('/nocs/' + nocId + '/customers/' + customerId + '/actions', { token: this.platform.auth.token });
28410};
28411
28412NocCustomers.prototype.getServiceAction= function(nocId, customerId, actionId){
28413 return this.platform.http.get('/nocs/' + nocId + '/customers/' + customerId + '/actions/' + actionId, { token: this.platform.auth.token });
28414};
28415
28416NocCustomers.prototype.createServiceAction= function(nocId, customerId, actionData){
28417 return this.platform.http.post('/nocs/' + nocId + '/customers/' + customerId + '/actions', actionData, { token: this.platform.auth.token });
28418};
28419
28420NocCustomers.prototype.updateServiceAction = function(nocId, customerId, actionId, actionData){
28421 return this.platform.http.put('/nocs/' + nocId + '/customers/' + customerId + '/actions/' + actionId, actionData, { token: this.platform.auth.token });
28422};
28423
28424NocCustomers.prototype.listInstallations= function(nocId){
28425 return this.platform.http.get('/nocs/' + nocId + '/customers/installations', { token: this.platform.auth.token });
28426};
28427
28428NocCustomers.prototype.getInstallation= function(nocId, installationId){
28429 return this.platform.http.get('/nocs/' + nocId + '/customers/installations/' + installationId, { token: this.platform.auth.token });
28430};
28431
28432NocCustomers.prototype.createInstallation= function(nocId, installationData){
28433 return this.platform.http.post('/nocs/' + nocId + '/customers/installations', installationData, { token: this.platform.auth.token });
28434};
28435
28436NocCustomers.prototype.updateInstallation= function(nocId, installationId, installationData){
28437 return this.platform.http.put('/nocs/' + nocId + '/customers/installations/' + installationId, installationData, { token: this.platform.auth.token });
28438};
28439
28440
28441module.exports = function(options) {
28442 options = options || {};
28443 return new NocCustomers(options);
28444};
28445
28446},{}],"/home/employee-2klic/projects/2klic_io-sdk/src/lib/methods/noc/noc.js":[function(require,module,exports){
28447'use strict';
28448var NocCustomers = require("./customers");
28449var NocTickets = require("./tickets");
28450var NocServices = require("./services");
28451var NocServiceActions = require("./service_actions");
28452
28453function Noc(options) {
28454 options = options || {};
28455 this.platform = options.platform;
28456 this.customers = new NocCustomers({ platform: this.platform });
28457 this.tickets = new NocTickets({ platform: this.platform });
28458 this.services = new NocServices({ platform: this.platform });
28459 this.service_actions = new NocServiceActions({ platform: this.platform });
28460}
28461
28462Noc.prototype.list = function() {
28463 return this.platform.http.get('/nocs/', { token: this.platform.auth.token });
28464};
28465
28466Noc.prototype.get = function(nocId){
28467 return this.platform.http.get('/nocs/' + nocId, { token: this.platform.auth.token });
28468};
28469
28470Noc.prototype.create = function(noc){
28471 return this.platform.http.post('/nocs', noc, { token: this.platform.auth.token });
28472};
28473
28474Noc.prototype.update = function(nocId, noc){
28475 return this.platform.http.put('/nocs/' + nocId, noc, { token: this.platform.auth.token });
28476};
28477
28478Noc.prototype.patch = function(nocId, noc){
28479 return this.platform.http.patch('/nocs/' + nocId, noc, { token: this.platform.auth.token });
28480};
28481
28482Noc.prototype.approve = function(nocId, approvalToken){
28483 return this.platform.http.put('/nocs/' + nocId + '/approve/' + approvalToken);
28484};
28485
28486Noc.prototype.approval_link = function(email){
28487 return this.platform.http.get('/nocs/approval-link/' + email);
28488};
28489
28490module.exports = function(options) {
28491 options = options || {};
28492 return new Noc(options);
28493};
28494
28495},{"./customers":"/home/employee-2klic/projects/2klic_io-sdk/src/lib/methods/noc/customers.js","./service_actions":"/home/employee-2klic/projects/2klic_io-sdk/src/lib/methods/noc/service_actions.js","./services":"/home/employee-2klic/projects/2klic_io-sdk/src/lib/methods/noc/services.js","./tickets":"/home/employee-2klic/projects/2klic_io-sdk/src/lib/methods/noc/tickets.js"}],"/home/employee-2klic/projects/2klic_io-sdk/src/lib/methods/noc/service_actions.js":[function(require,module,exports){
28496'use strict';
28497
28498function NocServiceActions(options) {
28499 options = options || {};
28500 this.platform = options.platform;
28501}
28502
28503NocServiceActions.prototype.list= function(nocId){
28504 return this.platform.http.get('/nocs/' + nocId + '/service_actions', { token: this.platform.auth.token });
28505};
28506
28507NocServiceActions.prototype.get= function(nocId, serviceId){
28508 return this.platform.http.get('/nocs/' + nocId + '/service_actions/' + serviceId, { token: this.platform.auth.token });
28509};
28510
28511NocServiceActions.prototype.getPredefinedServiceActions= function(nocId){
28512 return this.platform.http.get('/nocs/' + nocId + '/service_actions/predefined', { token: this.platform.auth.token });
28513};
28514
28515NocServiceActions.prototype.create= function(nocId, serviceActions){
28516 return this.platform.http.post('/nocs/' + nocId + '/service_actions', serviceActions, { token: this.platform.auth.token });
28517};
28518
28519NocServiceActions.prototype.update= function(nocId, serviceId, serviceActions){
28520 return this.platform.http.put('/nocs/' + nocId + '/service_actions/' + serviceId, serviceActions, { token: this.platform.auth.token });
28521};
28522
28523NocServiceActions.prototype.patch = function(nocId, serviceId, serviceActions){
28524 return this.platform.http.patch ('/nocs/' + nocId + '/service_actions/' + serviceId, serviceActions, { token: this.platform.auth.token });
28525};
28526
28527module.exports = function(options) {
28528 options = options || {};
28529 return new NocServiceActions(options);
28530};
28531
28532},{}],"/home/employee-2klic/projects/2klic_io-sdk/src/lib/methods/noc/services.js":[function(require,module,exports){
28533'use strict';
28534
28535function NocServices(options) {
28536 options = options || {};
28537 this.platform = options.platform;
28538}
28539
28540NocServices.prototype.list= function(nocId){
28541 return this.platform.http.get('/nocs/' + nocId + '/services', { token: this.platform.auth.token });
28542};
28543
28544NocServices.prototype.get= function(nocId, serviceId){
28545 return this.platform.http.get('/nocs/' + nocId + '/services/' + serviceId, { token: this.platform.auth.token });
28546};
28547
28548NocServices.prototype.create= function(nocId, service){
28549 return this.platform.http.post('/nocs/' + nocId + '/services', service, { token: this.platform.auth.token });
28550};
28551
28552NocServices.prototype.update= function(nocId, serviceId, service){
28553 return this.platform.http.put('/nocs/' + nocId + '/services/' + serviceId, service, { token: this.platform.auth.token });
28554};
28555
28556NocServices.prototype.patch = function(nocId, serviceId, service){
28557 return this.platform.http.patch ('/nocs/' + nocId + '/services/' + serviceId, service, { token: this.platform.auth.token });
28558};
28559
28560module.exports = function(options) {
28561 options = options || {};
28562 return new NocServices(options);
28563};
28564
28565},{}],"/home/employee-2klic/projects/2klic_io-sdk/src/lib/methods/noc/tickets.js":[function(require,module,exports){
28566'use strict';
28567
28568function NocTickets(options) {
28569 options = options || {};
28570 this.platform = options.platform;
28571}
28572
28573NocTickets.prototype.list = function(nocId){
28574 return this.platform.http.get('/nocs/' + nocId + '/noc_tickets', { token: this.platform.auth.token });
28575};
28576
28577NocTickets.prototype.get = function(nocId, ticketId){
28578 return this.platform.http.get('/nocs/' + nocId + '/noc_tickets/' + ticketId, { token: this.platform.auth.token });
28579};
28580
28581NocTickets.prototype.update = function(nocId, ticketId, ticket){
28582 return this.platform.http.put('/nocs/' + nocId + '/noc_tickets/' + ticketId, ticket, { token: this.platform.auth.token });
28583};
28584
28585NocTickets.prototype.patch = function(nocId, ticketId, ticket){
28586 return this.platform.http.patch ('/nocs/' + nocId + '/noc_tickets/' + ticketId, ticket, { token: this.platform.auth.token });
28587};
28588
28589NocTickets.prototype.create = function(nocId, ticket){
28590 return this.platform.http.post('/nocs' + nocId + '/noc_ticket', ticket, { token: this.platform.auth.token });
28591};
28592
28593NocTickets.prototype.listDevices = function(nocId, ticketId){
28594 return this.platform.http.get('/nocs/' + nocId + '/noc_tickets/' + ticketId + '/devices', { token: this.platform.auth.token });
28595};
28596
28597NocTickets.prototype.listEvents = function(nocId, ticketId){
28598 return this.platform.http.get('/nocs/' + nocId + '/noc_tickets/' + ticketId + '/noc_ticket_events', { token: this.platform.auth.token });
28599};
28600
28601NocTickets.prototype.getEvent = function(nocId, ticketId, ticketEventId){
28602 return this.platform.http.get('/nocs/' + nocId + '/noc_tickets/' + ticketId + '/noc_ticket_events/' + ticketEventId, { token: this.platform.auth.token });
28603};
28604
28605NocTickets.prototype.createEvent = function(nocId, ticketId, ticketEvent){
28606 return this.platform.http.post('/nocs/' + nocId + '/noc_tickets/' + ticketId + '/noc_ticket_events', ticketEvent, { token: this.platform.auth.token });
28607};
28608
28609NocTickets.prototype.updateEvent= function(nocId, ticketId, ticketEventId, ticketEvent){
28610 return this.platform.http.put('/nocs/' + nocId + '/noc_tickets/' + ticketId + '/noc_ticket_events/' + ticketEventId, ticketEvent, { token: this.platform.auth.token });
28611};
28612
28613NocTickets.prototype.patchEvent = function(nocId, ticketId, ticketEventId, ticketEvent){
28614 return this.platform.http.patch ('/nocs/' + nocId + '/noc_tickets/' + ticketId + '/noc_ticket_events/' + ticketEventId, ticketEvent, { token: this.platform.auth.token });
28615};
28616
28617module.exports = function(options) {
28618 options = options || {};
28619 return new NocTickets(options);
28620};
28621
28622},{}],"/home/employee-2klic/projects/2klic_io-sdk/src/lib/methods/notifications.js":[function(require,module,exports){
28623'use strict';
28624
28625function Notifications(options) {
28626 options = options || {};
28627 this.platform = options.platform;
28628}
28629
28630Notifications.prototype.list = function(params){
28631 return this.platform.http.get('/notifications', { query: params, token: this.platform.auth.token });
28632};
28633
28634Notifications.prototype.get = function(locationId, params){
28635 return this.platform.http.get('/locations/'+locationId+'/notifications', { query: params, token: this.platform.auth.token });
28636};
28637
28638Notifications.prototype.patch = function(notificationId, obj){
28639 return this.platform.http.patch('/notifications/'+notificationId, obj, { token: this.platform.auth.token });
28640};
28641
28642Notifications.prototype.markRead = function(notificationId){
28643 return this.platform.http.patch('/notifications/'+notificationId, { read: true, readTs: Date.now() }, { token: this.platform.auth.token });
28644};
28645
28646Notifications.prototype.getConfig = function(){
28647 return this.platform.http.get('/notifications/config', { token: this.platform.auth.token });
28648};
28649
28650Notifications.prototype.updateConfig = function(config){
28651 return this.platform.http.put('/notifications/config' + (config._id ? "/"+config._id:""), config, { token: this.platform.auth.token });
28652};
28653
28654module.exports = function(options) {
28655 options = options || {};
28656 return new Notifications(options);
28657};
28658
28659
28660},{}],"/home/employee-2klic/projects/2klic_io-sdk/src/lib/methods/register.js":[function(require,module,exports){
28661module.exports = (function() {
28662
28663 return function(user, options) {
28664 var _this = this, logger = this.logger;
28665 options = options || {};
28666
28667 logger.debug("Executing HTTP request GET /auth/register");
28668 return this.http.post("/auth/register", user, options).then(function(resp) {
28669 logger.debug(resp);
28670 if(resp) {
28671 return resp.data;
28672 }
28673 else {
28674 logger.error("Invalid response received from platform");
28675 }
28676
28677 });
28678
28679 };
28680
28681})();
28682
28683},{}],"/home/employee-2klic/projects/2klic_io-sdk/src/lib/methods/scenarios.js":[function(require,module,exports){
28684'use strict';
28685
28686function Scenarios(options) {
28687 options = options || {};
28688 this.platform = options.platform;
28689}
28690
28691Scenarios.prototype.list = function(){
28692 return this.platform.http.get('/scenarios', { token: this.platform.auth.token });
28693};
28694
28695Scenarios.prototype.get = function(scenarioId){
28696 return this.platform.http.get('/scenarios/'+scenarioId, { token: this.platform.auth.token });
28697};
28698
28699Scenarios.prototype.create = function(scenario){
28700 return this.platform.http.post('/scenarios', scenario, { token: this.platform.auth.token });
28701};
28702
28703Scenarios.prototype.update = function(scenario){
28704 return this.platform.http.put('/scenarios/'+scenario._id, scenario, { token: this.platform.auth.token });
28705};
28706
28707Scenarios.prototype.patch = function(scenarioId, obj){
28708 return this.platform.http.patch('/scenarios/'+scenarioId, obj, { token: this.platform.auth.token });
28709};
28710
28711Scenarios.prototype.delete = function(scenarioId){
28712 return this.platform.http.delete('/scenarios/'+scenarioId, { token: this.platform.auth.token });
28713};
28714
28715module.exports = function(options) {
28716 options = options || {};
28717 return new Scenarios(options);
28718};
28719
28720
28721},{}],"/home/employee-2klic/projects/2klic_io-sdk/src/lib/methods/streams.js":[function(require,module,exports){
28722'use strict';
28723
28724function Streams(options) {
28725 options = options || {};
28726 this.platform = options.platform;
28727}
28728
28729//Streams.prototype.get = function(propertyId){
28730Streams.prototype.list = function(){
28731 //return this.platform.http.get('/homes/'+propertyId+'/cameras/stream/all', { token: this.platform.auth.token });
28732 return this.platform.http.get('/streams', { token: this.platform.auth.token });
28733};
28734
28735module.exports = function(options) {
28736 options = options || {};
28737 return new Streams(options);
28738};
28739
28740
28741},{}],"/home/employee-2klic/projects/2klic_io-sdk/src/lib/methods/system.js":[function(require,module,exports){
28742'use strict';
28743
28744function System(options) {
28745 options = options || {};
28746 this.platform = options.platform;
28747}
28748
28749System.prototype.info = function(){
28750 return this.platform.http.get('/system/info');
28751};
28752
28753module.exports = function(options) {
28754 options = options || {};
28755 return new System(options);
28756};
28757
28758},{}],"/home/employee-2klic/projects/2klic_io-sdk/src/lib/methods/templates.js":[function(require,module,exports){
28759'use strict';
28760
28761function Templates(options) {
28762 options = options || {};
28763 this.platform = options.platform;
28764}
28765
28766Templates.prototype.list = function(){
28767 return this.platform.http.get('/templates', { token: this.platform.auth.token });
28768};
28769
28770Templates.prototype.get = function(templateId, level){
28771 return this.platform.http.get('/templates/'+templateId, { query: { level: level }, token: this.platform.auth.token });
28772};
28773
28774Templates.prototype.create = function(template){
28775 return this.platform.http.post('/templates', template, { token: this.platform.auth.token });
28776};
28777
28778Templates.prototype.patch = function(obj, templateId){
28779 return this.platform.http.patch('/templates/'+templateId, obj, { token: this.platform.auth.token });
28780};
28781
28782Templates.prototype.delete = function(templateId){
28783 return this.platform.http.delete('/templates/'+templateId, { token: this.platform.auth.token });
28784};
28785
28786module.exports = function(options) {
28787 options = options || {};
28788 return new Templates(options);
28789};
28790
28791},{}],"/home/employee-2klic/projects/2klic_io-sdk/src/lib/methods/translations.js":[function(require,module,exports){
28792'use strict';
28793
28794function Translations(options) {
28795 options = options || {};
28796 this.platform = options.platform;
28797}
28798
28799Translations.prototype.list = function(){
28800 return this.platform.http.get('/translations', { token: this.platform.auth.token });
28801};
28802
28803Translations.prototype.get = function(key){
28804 return this.platform.http.get('/translations/'+key, { token: this.platform.auth.token });
28805};
28806
28807Translations.prototype.create = function(translation){
28808 return this.platform.http.post('/translations', translation, { token: this.platform.auth.token });
28809};
28810
28811Translations.prototype.update = function(key, translation){
28812 return this.platform.http.put('/translations/'+key, translation, { token: this.platform.auth.token });
28813};
28814
28815
28816module.exports = function(options) {
28817 options = options || {};
28818 return new Translations(options);
28819};
28820
28821
28822},{}],"/home/employee-2klic/projects/2klic_io-sdk/src/lib/methods/user.js":[function(require,module,exports){
28823'use strict';
28824
28825function User(options) {
28826 options = options || {};
28827 this.platform = options.platform;
28828}
28829
28830User.prototype.get = function(username){
28831 return this.platform.http.get('/users/'+username, { token: this.platform.auth.token });
28832};
28833
28834User.prototype.register = function(user){
28835 return this.platform.http.post('/auth/register', user);
28836};
28837
28838User.prototype.forgot = function(email){
28839 return this.platform.http.get('/auth/forgot/'+email);
28840};
28841
28842User.prototype.reset = function(resetToken){
28843 return this.platform.http.get('/auth/reset/'+resetToken);
28844};
28845
28846User.prototype.resetPassword = function(resetToken, passwordInfo){
28847 return this.platform.http.post('/auth/reset/'+resetToken, passwordInfo);
28848};
28849
28850User.prototype.confirm = function(key){
28851 return this.platform.http.get('/auth/confirm/'+key);
28852};
28853
28854User.prototype.changePassword = function(username, currentPassword, password){
28855 return this.platform.http.put('/users/'+username+'/password', { current:currentPassword, password:password }, { token: this.platform.auth.token });
28856};
28857
28858User.prototype.list = function(){
28859 return this.platform.http.get('/users', { token: this.platform.auth.token });
28860};
28861
28862User.prototype.listAlarmSystems = function(userId){
28863 return this.platform.http.get('/users/' + userId + '/alarms', { token: this.platform.auth.token });
28864};
28865
28866User.prototype.getCurrentUser = function(options){
28867 var token;
28868 options ? token = options.token : token = undefined;
28869 return this.platform.http.get('/users/me', { token: token || this.platform.auth.token });
28870};
28871
28872User.prototype.update = function(username, user){
28873 return this.platform.http.put('/users/'+username, user, { token: this.platform.auth.token });
28874};
28875
28876User.prototype.patch = function(username, obj){
28877 return this.platform.http.patch('/users/'+username, obj, { token: this.platform.auth.token });
28878};
28879
28880User.prototype.delete = function(username){
28881 return this.platform.http.delete('/users/'+username, { token: this.platform.auth.token });
28882};
28883
28884User.prototype.bindDevice = function(mac, location){
28885 return this.platform.http.post('/devices/bind', { mac: mac, location: location }, { token: this.platform.auth.token });
28886};
28887
28888module.exports = function(options) {
28889 options = options || {};
28890 return new User(options);
28891};
28892
28893},{}],"/home/employee-2klic/projects/2klic_io-sdk/src/lib/methods/zwave.js":[function(require,module,exports){
28894'use strict';
28895
28896function ZWave(options) {
28897 options = options || {};
28898 this.platform = options.platform;
28899}
28900
28901ZWave.prototype.exclusion = function(gatewayId){
28902 return this.platform.http.post('/devices/'+gatewayId+'/zwave/exclude', {}, { token: this.platform.auth.token });
28903};
28904
28905ZWave.prototype.removeFailed = function(gatewayId){
28906 return this.platform.http.delete('/devices/'+gatewayId+'/zwave/failed', {}, { token: this.platform.auth.token });
28907};
28908
28909module.exports = function(options) {
28910 options = options || {};
28911 return new ZWave(options);
28912};
28913
28914
28915},{}],"/home/employee-2klic/projects/2klic_io-sdk/src/lib/mixin_promise.js":[function(require,module,exports){
28916var P = require("bluebird").noConflict();
28917
28918P.prototype.mixin = function(cstor) {
28919 var o = new cstor();
28920 o.__p = this;
28921
28922 o.catch = function(fn) {
28923 this.__p.catch.call(this.__p, fn.bind(this));
28924 return this;
28925 };
28926
28927 o.then = o.ready = function(fn) {
28928 this.__p.then.call(this.__p, fn.bind(this));
28929 return this;
28930 };
28931
28932 o.finally = function(fn) {
28933 this.__p.finally.apply(this.__p, fn.bind(this));
28934 return this;
28935 };
28936
28937 return o;
28938};
28939
28940module.exports = P;
28941},{"bluebird":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/bluebird/js/browser/bluebird.js"}],"/home/employee-2klic/projects/2klic_io-sdk/src/lib/stream_api.js":[function(require,module,exports){
28942var socketIOClient = require('socket.io-client');
28943var events = require('events');
28944var inherits = require('inherits');
28945var _ = require('lodash');
28946
28947function Subscriber(channelString, handler) {
28948 this.channelString = channelString;
28949 this.handler = handler;
28950}
28951
28952Subscriber.prototype.handle = function(event) {
28953
28954 if(this.channelString.indexOf('*') !== -1) {
28955 var channel = this.channelString.split('/')[0];
28956 if(event.type.indexOf(channel) !== -1) {
28957 this.handler(event);
28958 }
28959 }
28960 else if(this.channelString === event.type) {
28961 return this.handler(event);
28962 }
28963
28964};
28965
28966function Channel(key, api) {
28967 this.key = key;
28968 this.api = api;
28969 events.EventEmitter.call(this);
28970}
28971inherits(Channel, events.EventEmitter);
28972
28973/*
28974 * Subscribe to the channel using scope token and
28975 * @param: options
28976 * token: A valid platform token providing access to private events as per the token scope
28977 * type: A string or array of event type to be notified (optional)
28978 * handler: A function that will be called with the event data
28979 * scope: The scope that will be used when calling the callback. default to global.
28980 * persistence: (optional). Provide a persistence strategy for unreceived events. (TBD)
28981 */
28982Channel.subscribe = function(options) {
28983 var subscribeKey = "/" + this.key + "/";
28984 if(_.isString(options.type)) {
28985 subscribeKey += options.type;
28986 }
28987 else {
28988 subscribeKey += "*";
28989 }
28990
28991 return this.api.subscribe(subscribeKey, (function(options) {
28992 var types = [];
28993 if(_.isString(options.type)) {
28994 types = options.type.split(',');
28995 }
28996 else {
28997 types = options.types;
28998 }
28999
29000 return function(event) {
29001 if(types.indexOf(event.type) !== -1) {
29002 options.handler.call(options.scope || this, event);
29003 }
29004 }
29005 })(options), { token: options.token, persistence: options.persistence });
29006};
29007
29008function _handleEvent(event) {
29009 var _this = this;
29010
29011 _.each(this.subscribers, function(subscriber) {
29012
29013 // Provide a simple mechanism to handle replies to specific events
29014 subscriber.handle(event, function(reply) {
29015 _this.socket.emit('reply', {
29016 replyTo: event.id,
29017 data: reply
29018 });
29019 });
29020
29021 });
29022
29023}
29024
29025function StreamAPI(options) {
29026 options = options || {};
29027
29028 this.url = options.url;
29029 this.subscribers = [];
29030
29031 this.socket = socketIOClient(options.url, options.socket);
29032
29033 events.EventEmitter.call(this);
29034
29035 // Connect all stream API event handlers
29036 this.socket.on('connect', function() {
29037 console.log("Stream API is CONNECTED to %s", this.url);
29038 this.emit('connect');
29039 }.bind(this));
29040
29041 this.socket.on('disconnect', function() {
29042 console.log("Stream API is DISCONNECTED from %s", this.url);
29043 this.emit('disconnect');
29044 }.bind(this));
29045
29046 this.socket.on('event', _handleEvent.bind(this));
29047
29048 // Create all secure channels
29049 StreamAPI.catalog = new Channel("catalog", this);
29050 StreamAPI.klic = new Channel("2klic", this);
29051 StreamAPI.marketplace = new Channel("marketplace", this);
29052 StreamAPI.social = new Channel("social", this);
29053 StreamAPI.profile = new Channel("profile", this);
29054 StreamAPI.system = new Channel("system", this);
29055
29056}
29057
29058inherits(StreamAPI, events.EventEmitter);
29059
29060StreamAPI.prototype.subscribe = function(channelString, handler, options) {
29061 options = options || {};
29062
29063 // Register a listener in our socket
29064 this.subscribers.push(new Subscriber(channelString, handler));
29065
29066 this.socket.emit('subscribe', {
29067 channel: channelString,
29068 token: options.token,
29069 persistence: options.persistence
29070 });
29071};
29072
29073module.exports = StreamAPI;
29074},{"events":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/browserify/node_modules/events/events.js","inherits":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/inherits/inherits_browser.js","lodash":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/lodash/index.js","socket.io-client":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/lib/index.js"}]},{},["/home/employee-2klic/projects/2klic_io-sdk/src/index.js"])("/home/employee-2klic/projects/2klic_io-sdk/src/index.js")
29075});
29076//# sourceMappingURL=2klic.js.map