UNPKG

921 kBJavaScriptView Raw
1(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.Klic = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({"/home/employee-2klic/projects/2klic_io-sdk/node_modules/after/index.js":[function(require,module,exports){
2module.exports = after
3
4function after(count, callback, err_cb) {
5 var bail = false
6 err_cb = err_cb || noop
7 proxy.count = count
8
9 return (count === 0) ? callback() : proxy
10
11 function proxy(err, result) {
12 if (proxy.count <= 0) {
13 throw new Error('after called too many times')
14 }
15 --proxy.count
16
17 // after first error, rest are passed to err_cb
18 if (err) {
19 bail = true
20 callback(err)
21 // future error callbacks will go to error handler
22 callback = err_cb
23 } else if (proxy.count === 0 && !bail) {
24 callback(null, result)
25 }
26 }
27}
28
29function noop() {}
30
31},{}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/arraybuffer.slice/index.js":[function(require,module,exports){
32/**
33 * An abstraction for slicing an arraybuffer even when
34 * ArrayBuffer.prototype.slice is not supported
35 *
36 * @api public
37 */
38
39module.exports = function(arraybuffer, start, end) {
40 var bytes = arraybuffer.byteLength;
41 start = start || 0;
42 end = end || bytes;
43
44 if (arraybuffer.slice) { return arraybuffer.slice(start, end); }
45
46 if (start < 0) { start += bytes; }
47 if (end < 0) { end += bytes; }
48 if (end > bytes) { end = bytes; }
49
50 if (start >= bytes || start >= end || bytes === 0) {
51 return new ArrayBuffer(0);
52 }
53
54 var abv = new Uint8Array(arraybuffer);
55 var result = new Uint8Array(end - start);
56 for (var i = start, ii = 0; i < end; i++, ii++) {
57 result[ii] = abv[i];
58 }
59 return result.buffer;
60};
61
62},{}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/backo2/index.js":[function(require,module,exports){
63
64/**
65 * Expose `Backoff`.
66 */
67
68module.exports = Backoff;
69
70/**
71 * Initialize backoff timer with `opts`.
72 *
73 * - `min` initial timeout in milliseconds [100]
74 * - `max` max timeout [10000]
75 * - `jitter` [0]
76 * - `factor` [2]
77 *
78 * @param {Object} opts
79 * @api public
80 */
81
82function Backoff(opts) {
83 opts = opts || {};
84 this.ms = opts.min || 100;
85 this.max = opts.max || 10000;
86 this.factor = opts.factor || 2;
87 this.jitter = opts.jitter > 0 && opts.jitter <= 1 ? opts.jitter : 0;
88 this.attempts = 0;
89}
90
91/**
92 * Return the backoff duration.
93 *
94 * @return {Number}
95 * @api public
96 */
97
98Backoff.prototype.duration = function(){
99 var ms = this.ms * Math.pow(this.factor, this.attempts++);
100 if (this.jitter) {
101 var rand = Math.random();
102 var deviation = Math.floor(rand * this.jitter * ms);
103 ms = (Math.floor(rand * 10) & 1) == 0 ? ms - deviation : ms + deviation;
104 }
105 return Math.min(ms, this.max) | 0;
106};
107
108/**
109 * Reset the number of attempts.
110 *
111 * @api public
112 */
113
114Backoff.prototype.reset = function(){
115 this.attempts = 0;
116};
117
118/**
119 * Set the minimum duration
120 *
121 * @api public
122 */
123
124Backoff.prototype.setMin = function(min){
125 this.ms = min;
126};
127
128/**
129 * Set the maximum duration
130 *
131 * @api public
132 */
133
134Backoff.prototype.setMax = function(max){
135 this.max = max;
136};
137
138/**
139 * Set the jitter
140 *
141 * @api public
142 */
143
144Backoff.prototype.setJitter = function(jitter){
145 this.jitter = jitter;
146};
147
148
149},{}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/base64-arraybuffer/lib/base64-arraybuffer.js":[function(require,module,exports){
150/*
151 * base64-arraybuffer
152 * https://github.com/niklasvh/base64-arraybuffer
153 *
154 * Copyright (c) 2012 Niklas von Hertzen
155 * Licensed under the MIT license.
156 */
157(function(chars){
158 "use strict";
159
160 exports.encode = function(arraybuffer) {
161 var bytes = new Uint8Array(arraybuffer),
162 i, len = bytes.length, base64 = "";
163
164 for (i = 0; i < len; i+=3) {
165 base64 += chars[bytes[i] >> 2];
166 base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];
167 base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];
168 base64 += chars[bytes[i + 2] & 63];
169 }
170
171 if ((len % 3) === 2) {
172 base64 = base64.substring(0, base64.length - 1) + "=";
173 } else if (len % 3 === 1) {
174 base64 = base64.substring(0, base64.length - 2) + "==";
175 }
176
177 return base64;
178 };
179
180 exports.decode = function(base64) {
181 var bufferLength = base64.length * 0.75,
182 len = base64.length, i, p = 0,
183 encoded1, encoded2, encoded3, encoded4;
184
185 if (base64[base64.length - 1] === "=") {
186 bufferLength--;
187 if (base64[base64.length - 2] === "=") {
188 bufferLength--;
189 }
190 }
191
192 var arraybuffer = new ArrayBuffer(bufferLength),
193 bytes = new Uint8Array(arraybuffer);
194
195 for (i = 0; i < len; i+=4) {
196 encoded1 = chars.indexOf(base64[i]);
197 encoded2 = chars.indexOf(base64[i+1]);
198 encoded3 = chars.indexOf(base64[i+2]);
199 encoded4 = chars.indexOf(base64[i+3]);
200
201 bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);
202 bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);
203 bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);
204 }
205
206 return arraybuffer;
207 };
208})("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/");
209
210},{}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/base64-js/lib/b64.js":[function(require,module,exports){
211var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
212
213;(function (exports) {
214 'use strict';
215
216 var Arr = (typeof Uint8Array !== 'undefined')
217 ? Uint8Array
218 : Array
219
220 var PLUS = '+'.charCodeAt(0)
221 var SLASH = '/'.charCodeAt(0)
222 var NUMBER = '0'.charCodeAt(0)
223 var LOWER = 'a'.charCodeAt(0)
224 var UPPER = 'A'.charCodeAt(0)
225 var PLUS_URL_SAFE = '-'.charCodeAt(0)
226 var SLASH_URL_SAFE = '_'.charCodeAt(0)
227
228 function decode (elt) {
229 var code = elt.charCodeAt(0)
230 if (code === PLUS ||
231 code === PLUS_URL_SAFE)
232 return 62 // '+'
233 if (code === SLASH ||
234 code === SLASH_URL_SAFE)
235 return 63 // '/'
236 if (code < NUMBER)
237 return -1 //no match
238 if (code < NUMBER + 10)
239 return code - NUMBER + 26 + 26
240 if (code < UPPER + 26)
241 return code - UPPER
242 if (code < LOWER + 26)
243 return code - LOWER + 26
244 }
245
246 function b64ToByteArray (b64) {
247 var i, j, l, tmp, placeHolders, arr
248
249 if (b64.length % 4 > 0) {
250 throw new Error('Invalid string. Length must be a multiple of 4')
251 }
252
253 // the number of equal signs (place holders)
254 // if there are two placeholders, than the two characters before it
255 // represent one byte
256 // if there is only one, then the three characters before it represent 2 bytes
257 // this is just a cheap hack to not do indexOf twice
258 var len = b64.length
259 placeHolders = '=' === b64.charAt(len - 2) ? 2 : '=' === b64.charAt(len - 1) ? 1 : 0
260
261 // base64 is 4/3 + up to two characters of the original data
262 arr = new Arr(b64.length * 3 / 4 - placeHolders)
263
264 // if there are placeholders, only get up to the last complete 4 chars
265 l = placeHolders > 0 ? b64.length - 4 : b64.length
266
267 var L = 0
268
269 function push (v) {
270 arr[L++] = v
271 }
272
273 for (i = 0, j = 0; i < l; i += 4, j += 3) {
274 tmp = (decode(b64.charAt(i)) << 18) | (decode(b64.charAt(i + 1)) << 12) | (decode(b64.charAt(i + 2)) << 6) | decode(b64.charAt(i + 3))
275 push((tmp & 0xFF0000) >> 16)
276 push((tmp & 0xFF00) >> 8)
277 push(tmp & 0xFF)
278 }
279
280 if (placeHolders === 2) {
281 tmp = (decode(b64.charAt(i)) << 2) | (decode(b64.charAt(i + 1)) >> 4)
282 push(tmp & 0xFF)
283 } else if (placeHolders === 1) {
284 tmp = (decode(b64.charAt(i)) << 10) | (decode(b64.charAt(i + 1)) << 4) | (decode(b64.charAt(i + 2)) >> 2)
285 push((tmp >> 8) & 0xFF)
286 push(tmp & 0xFF)
287 }
288
289 return arr
290 }
291
292 function uint8ToBase64 (uint8) {
293 var i,
294 extraBytes = uint8.length % 3, // if we have 1 byte left, pad 2 bytes
295 output = "",
296 temp, length
297
298 function encode (num) {
299 return lookup.charAt(num)
300 }
301
302 function tripletToBase64 (num) {
303 return encode(num >> 18 & 0x3F) + encode(num >> 12 & 0x3F) + encode(num >> 6 & 0x3F) + encode(num & 0x3F)
304 }
305
306 // go through the array every three bytes, we'll deal with trailing stuff later
307 for (i = 0, length = uint8.length - extraBytes; i < length; i += 3) {
308 temp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])
309 output += tripletToBase64(temp)
310 }
311
312 // pad the end with zeros, but make sure to not forget the extra bytes
313 switch (extraBytes) {
314 case 1:
315 temp = uint8[uint8.length - 1]
316 output += encode(temp >> 2)
317 output += encode((temp << 4) & 0x3F)
318 output += '=='
319 break
320 case 2:
321 temp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1])
322 output += encode(temp >> 10)
323 output += encode((temp >> 4) & 0x3F)
324 output += encode((temp << 2) & 0x3F)
325 output += '='
326 break
327 }
328
329 return output
330 }
331
332 exports.toByteArray = b64ToByteArray
333 exports.fromByteArray = uint8ToBase64
334}(typeof exports === 'undefined' ? (this.base64js = {}) : exports))
335
336},{}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/blob/index.js":[function(require,module,exports){
337(function (global){
338/**
339 * Create a blob builder even when vendor prefixes exist
340 */
341
342var BlobBuilder = global.BlobBuilder
343 || global.WebKitBlobBuilder
344 || global.MSBlobBuilder
345 || global.MozBlobBuilder;
346
347/**
348 * Check if Blob constructor is supported
349 */
350
351var blobSupported = (function() {
352 try {
353 var a = new Blob(['hi']);
354 return a.size === 2;
355 } catch(e) {
356 return false;
357 }
358})();
359
360/**
361 * Check if Blob constructor supports ArrayBufferViews
362 * Fails in Safari 6, so we need to map to ArrayBuffers there.
363 */
364
365var blobSupportsArrayBufferView = blobSupported && (function() {
366 try {
367 var b = new Blob([new Uint8Array([1,2])]);
368 return b.size === 2;
369 } catch(e) {
370 return false;
371 }
372})();
373
374/**
375 * Check if BlobBuilder is supported
376 */
377
378var blobBuilderSupported = BlobBuilder
379 && BlobBuilder.prototype.append
380 && BlobBuilder.prototype.getBlob;
381
382/**
383 * Helper function that maps ArrayBufferViews to ArrayBuffers
384 * Used by BlobBuilder constructor and old browsers that didn't
385 * support it in the Blob constructor.
386 */
387
388function mapArrayBufferViews(ary) {
389 for (var i = 0; i < ary.length; i++) {
390 var chunk = ary[i];
391 if (chunk.buffer instanceof ArrayBuffer) {
392 var buf = chunk.buffer;
393
394 // if this is a subarray, make a copy so we only
395 // include the subarray region from the underlying buffer
396 if (chunk.byteLength !== buf.byteLength) {
397 var copy = new Uint8Array(chunk.byteLength);
398 copy.set(new Uint8Array(buf, chunk.byteOffset, chunk.byteLength));
399 buf = copy.buffer;
400 }
401
402 ary[i] = buf;
403 }
404 }
405}
406
407function BlobBuilderConstructor(ary, options) {
408 options = options || {};
409
410 var bb = new BlobBuilder();
411 mapArrayBufferViews(ary);
412
413 for (var i = 0; i < ary.length; i++) {
414 bb.append(ary[i]);
415 }
416
417 return (options.type) ? bb.getBlob(options.type) : bb.getBlob();
418};
419
420function BlobConstructor(ary, options) {
421 mapArrayBufferViews(ary);
422 return new Blob(ary, options || {});
423};
424
425module.exports = (function() {
426 if (blobSupported) {
427 return blobSupportsArrayBufferView ? global.Blob : BlobConstructor;
428 } else if (blobBuilderSupported) {
429 return BlobBuilderConstructor;
430 } else {
431 return undefined;
432 }
433})();
434
435}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
436},{}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/bluebird/js/browser/bluebird.js":[function(require,module,exports){
437(function (process,global){
438/* @preserve
439 * The MIT License (MIT)
440 *
441 * Copyright (c) 2013-2015 Petka Antonov
442 *
443 * Permission is hereby granted, free of charge, to any person obtaining a copy
444 * of this software and associated documentation files (the "Software"), to deal
445 * in the Software without restriction, including without limitation the rights
446 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
447 * copies of the Software, and to permit persons to whom the Software is
448 * furnished to do so, subject to the following conditions:
449 *
450 * The above copyright notice and this permission notice shall be included in
451 * all copies or substantial portions of the Software.
452 *
453 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
454 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
455 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
456 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
457 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
458 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
459 * THE SOFTWARE.
460 *
461 */
462/**
463 * bluebird build version 3.4.6
464 * Features enabled: core, race, call_get, generators, map, nodeify, promisify, props, reduce, settle, some, using, timers, filter, any, each
465*/
466!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){
467"use strict";
468module.exports = function(Promise) {
469var SomePromiseArray = Promise._SomePromiseArray;
470function any(promises) {
471 var ret = new SomePromiseArray(promises);
472 var promise = ret.promise();
473 ret.setHowMany(1);
474 ret.setUnwrap();
475 ret.init();
476 return promise;
477}
478
479Promise.any = function (promises) {
480 return any(promises);
481};
482
483Promise.prototype.any = function () {
484 return any(this);
485};
486
487};
488
489},{}],2:[function(_dereq_,module,exports){
490"use strict";
491var firstLineError;
492try {throw new Error(); } catch (e) {firstLineError = e;}
493var schedule = _dereq_("./schedule");
494var Queue = _dereq_("./queue");
495var util = _dereq_("./util");
496
497function Async() {
498 this._customScheduler = false;
499 this._isTickUsed = false;
500 this._lateQueue = new Queue(16);
501 this._normalQueue = new Queue(16);
502 this._haveDrainedQueues = false;
503 this._trampolineEnabled = true;
504 var self = this;
505 this.drainQueues = function () {
506 self._drainQueues();
507 };
508 this._schedule = schedule;
509}
510
511Async.prototype.setScheduler = function(fn) {
512 var prev = this._schedule;
513 this._schedule = fn;
514 this._customScheduler = true;
515 return prev;
516};
517
518Async.prototype.hasCustomScheduler = function() {
519 return this._customScheduler;
520};
521
522Async.prototype.enableTrampoline = function() {
523 this._trampolineEnabled = true;
524};
525
526Async.prototype.disableTrampolineIfNecessary = function() {
527 if (util.hasDevTools) {
528 this._trampolineEnabled = false;
529 }
530};
531
532Async.prototype.haveItemsQueued = function () {
533 return this._isTickUsed || this._haveDrainedQueues;
534};
535
536
537Async.prototype.fatalError = function(e, isNode) {
538 if (isNode) {
539 process.stderr.write("Fatal " + (e instanceof Error ? e.stack : e) +
540 "\n");
541 process.exit(2);
542 } else {
543 this.throwLater(e);
544 }
545};
546
547Async.prototype.throwLater = function(fn, arg) {
548 if (arguments.length === 1) {
549 arg = fn;
550 fn = function () { throw arg; };
551 }
552 if (typeof setTimeout !== "undefined") {
553 setTimeout(function() {
554 fn(arg);
555 }, 0);
556 } else try {
557 this._schedule(function() {
558 fn(arg);
559 });
560 } catch (e) {
561 throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/MqrFmX\u000a");
562 }
563};
564
565function AsyncInvokeLater(fn, receiver, arg) {
566 this._lateQueue.push(fn, receiver, arg);
567 this._queueTick();
568}
569
570function AsyncInvoke(fn, receiver, arg) {
571 this._normalQueue.push(fn, receiver, arg);
572 this._queueTick();
573}
574
575function AsyncSettlePromises(promise) {
576 this._normalQueue._pushOne(promise);
577 this._queueTick();
578}
579
580if (!util.hasDevTools) {
581 Async.prototype.invokeLater = AsyncInvokeLater;
582 Async.prototype.invoke = AsyncInvoke;
583 Async.prototype.settlePromises = AsyncSettlePromises;
584} else {
585 Async.prototype.invokeLater = function (fn, receiver, arg) {
586 if (this._trampolineEnabled) {
587 AsyncInvokeLater.call(this, fn, receiver, arg);
588 } else {
589 this._schedule(function() {
590 setTimeout(function() {
591 fn.call(receiver, arg);
592 }, 100);
593 });
594 }
595 };
596
597 Async.prototype.invoke = function (fn, receiver, arg) {
598 if (this._trampolineEnabled) {
599 AsyncInvoke.call(this, fn, receiver, arg);
600 } else {
601 this._schedule(function() {
602 fn.call(receiver, arg);
603 });
604 }
605 };
606
607 Async.prototype.settlePromises = function(promise) {
608 if (this._trampolineEnabled) {
609 AsyncSettlePromises.call(this, promise);
610 } else {
611 this._schedule(function() {
612 promise._settlePromises();
613 });
614 }
615 };
616}
617
618Async.prototype.invokeFirst = function (fn, receiver, arg) {
619 this._normalQueue.unshift(fn, receiver, arg);
620 this._queueTick();
621};
622
623Async.prototype._drainQueue = function(queue) {
624 while (queue.length() > 0) {
625 var fn = queue.shift();
626 if (typeof fn !== "function") {
627 fn._settlePromises();
628 continue;
629 }
630 var receiver = queue.shift();
631 var arg = queue.shift();
632 fn.call(receiver, arg);
633 }
634};
635
636Async.prototype._drainQueues = function () {
637 this._drainQueue(this._normalQueue);
638 this._reset();
639 this._haveDrainedQueues = true;
640 this._drainQueue(this._lateQueue);
641};
642
643Async.prototype._queueTick = function () {
644 if (!this._isTickUsed) {
645 this._isTickUsed = true;
646 this._schedule(this.drainQueues);
647 }
648};
649
650Async.prototype._reset = function () {
651 this._isTickUsed = false;
652};
653
654module.exports = Async;
655module.exports.firstLineError = firstLineError;
656
657},{"./queue":26,"./schedule":29,"./util":36}],3:[function(_dereq_,module,exports){
658"use strict";
659module.exports = function(Promise, INTERNAL, tryConvertToPromise, debug) {
660var calledBind = false;
661var rejectThis = function(_, e) {
662 this._reject(e);
663};
664
665var targetRejected = function(e, context) {
666 context.promiseRejectionQueued = true;
667 context.bindingPromise._then(rejectThis, rejectThis, null, this, e);
668};
669
670var bindingResolved = function(thisArg, context) {
671 if (((this._bitField & 50397184) === 0)) {
672 this._resolveCallback(context.target);
673 }
674};
675
676var bindingRejected = function(e, context) {
677 if (!context.promiseRejectionQueued) this._reject(e);
678};
679
680Promise.prototype.bind = function (thisArg) {
681 if (!calledBind) {
682 calledBind = true;
683 Promise.prototype._propagateFrom = debug.propagateFromFunction();
684 Promise.prototype._boundValue = debug.boundValueFunction();
685 }
686 var maybePromise = tryConvertToPromise(thisArg);
687 var ret = new Promise(INTERNAL);
688 ret._propagateFrom(this, 1);
689 var target = this._target();
690 ret._setBoundTo(maybePromise);
691 if (maybePromise instanceof Promise) {
692 var context = {
693 promiseRejectionQueued: false,
694 promise: ret,
695 target: target,
696 bindingPromise: maybePromise
697 };
698 target._then(INTERNAL, targetRejected, undefined, ret, context);
699 maybePromise._then(
700 bindingResolved, bindingRejected, undefined, ret, context);
701 ret._setOnCancel(maybePromise);
702 } else {
703 ret._resolveCallback(target);
704 }
705 return ret;
706};
707
708Promise.prototype._setBoundTo = function (obj) {
709 if (obj !== undefined) {
710 this._bitField = this._bitField | 2097152;
711 this._boundTo = obj;
712 } else {
713 this._bitField = this._bitField & (~2097152);
714 }
715};
716
717Promise.prototype._isBound = function () {
718 return (this._bitField & 2097152) === 2097152;
719};
720
721Promise.bind = function (thisArg, value) {
722 return Promise.resolve(value).bind(thisArg);
723};
724};
725
726},{}],4:[function(_dereq_,module,exports){
727"use strict";
728var old;
729if (typeof Promise !== "undefined") old = Promise;
730function noConflict() {
731 try { if (Promise === bluebird) Promise = old; }
732 catch (e) {}
733 return bluebird;
734}
735var bluebird = _dereq_("./promise")();
736bluebird.noConflict = noConflict;
737module.exports = bluebird;
738
739},{"./promise":22}],5:[function(_dereq_,module,exports){
740"use strict";
741var cr = Object.create;
742if (cr) {
743 var callerCache = cr(null);
744 var getterCache = cr(null);
745 callerCache[" size"] = getterCache[" size"] = 0;
746}
747
748module.exports = function(Promise) {
749var util = _dereq_("./util");
750var canEvaluate = util.canEvaluate;
751var isIdentifier = util.isIdentifier;
752
753var getMethodCaller;
754var getGetter;
755if (!true) {
756var makeMethodCaller = function (methodName) {
757 return new Function("ensureMethod", " \n\
758 return function(obj) { \n\
759 'use strict' \n\
760 var len = this.length; \n\
761 ensureMethod(obj, 'methodName'); \n\
762 switch(len) { \n\
763 case 1: return obj.methodName(this[0]); \n\
764 case 2: return obj.methodName(this[0], this[1]); \n\
765 case 3: return obj.methodName(this[0], this[1], this[2]); \n\
766 case 0: return obj.methodName(); \n\
767 default: \n\
768 return obj.methodName.apply(obj, this); \n\
769 } \n\
770 }; \n\
771 ".replace(/methodName/g, methodName))(ensureMethod);
772};
773
774var makeGetter = function (propertyName) {
775 return new Function("obj", " \n\
776 'use strict'; \n\
777 return obj.propertyName; \n\
778 ".replace("propertyName", propertyName));
779};
780
781var getCompiled = function(name, compiler, cache) {
782 var ret = cache[name];
783 if (typeof ret !== "function") {
784 if (!isIdentifier(name)) {
785 return null;
786 }
787 ret = compiler(name);
788 cache[name] = ret;
789 cache[" size"]++;
790 if (cache[" size"] > 512) {
791 var keys = Object.keys(cache);
792 for (var i = 0; i < 256; ++i) delete cache[keys[i]];
793 cache[" size"] = keys.length - 256;
794 }
795 }
796 return ret;
797};
798
799getMethodCaller = function(name) {
800 return getCompiled(name, makeMethodCaller, callerCache);
801};
802
803getGetter = function(name) {
804 return getCompiled(name, makeGetter, getterCache);
805};
806}
807
808function ensureMethod(obj, methodName) {
809 var fn;
810 if (obj != null) fn = obj[methodName];
811 if (typeof fn !== "function") {
812 var message = "Object " + util.classString(obj) + " has no method '" +
813 util.toString(methodName) + "'";
814 throw new Promise.TypeError(message);
815 }
816 return fn;
817}
818
819function caller(obj) {
820 var methodName = this.pop();
821 var fn = ensureMethod(obj, methodName);
822 return fn.apply(obj, this);
823}
824Promise.prototype.call = function (methodName) {
825 var args = [].slice.call(arguments, 1);;
826 if (!true) {
827 if (canEvaluate) {
828 var maybeCaller = getMethodCaller(methodName);
829 if (maybeCaller !== null) {
830 return this._then(
831 maybeCaller, undefined, undefined, args, undefined);
832 }
833 }
834 }
835 args.push(methodName);
836 return this._then(caller, undefined, undefined, args, undefined);
837};
838
839function namedGetter(obj) {
840 return obj[this];
841}
842function indexedGetter(obj) {
843 var index = +this;
844 if (index < 0) index = Math.max(0, index + obj.length);
845 return obj[index];
846}
847Promise.prototype.get = function (propertyName) {
848 var isIndex = (typeof propertyName === "number");
849 var getter;
850 if (!isIndex) {
851 if (canEvaluate) {
852 var maybeGetter = getGetter(propertyName);
853 getter = maybeGetter !== null ? maybeGetter : namedGetter;
854 } else {
855 getter = namedGetter;
856 }
857 } else {
858 getter = indexedGetter;
859 }
860 return this._then(getter, undefined, undefined, propertyName, undefined);
861};
862};
863
864},{"./util":36}],6:[function(_dereq_,module,exports){
865"use strict";
866module.exports = function(Promise, PromiseArray, apiRejection, debug) {
867var util = _dereq_("./util");
868var tryCatch = util.tryCatch;
869var errorObj = util.errorObj;
870var async = Promise._async;
871
872Promise.prototype["break"] = Promise.prototype.cancel = function() {
873 if (!debug.cancellation()) return this._warn("cancellation is disabled");
874
875 var promise = this;
876 var child = promise;
877 while (promise._isCancellable()) {
878 if (!promise._cancelBy(child)) {
879 if (child._isFollowing()) {
880 child._followee().cancel();
881 } else {
882 child._cancelBranched();
883 }
884 break;
885 }
886
887 var parent = promise._cancellationParent;
888 if (parent == null || !parent._isCancellable()) {
889 if (promise._isFollowing()) {
890 promise._followee().cancel();
891 } else {
892 promise._cancelBranched();
893 }
894 break;
895 } else {
896 if (promise._isFollowing()) promise._followee().cancel();
897 promise._setWillBeCancelled();
898 child = promise;
899 promise = parent;
900 }
901 }
902};
903
904Promise.prototype._branchHasCancelled = function() {
905 this._branchesRemainingToCancel--;
906};
907
908Promise.prototype._enoughBranchesHaveCancelled = function() {
909 return this._branchesRemainingToCancel === undefined ||
910 this._branchesRemainingToCancel <= 0;
911};
912
913Promise.prototype._cancelBy = function(canceller) {
914 if (canceller === this) {
915 this._branchesRemainingToCancel = 0;
916 this._invokeOnCancel();
917 return true;
918 } else {
919 this._branchHasCancelled();
920 if (this._enoughBranchesHaveCancelled()) {
921 this._invokeOnCancel();
922 return true;
923 }
924 }
925 return false;
926};
927
928Promise.prototype._cancelBranched = function() {
929 if (this._enoughBranchesHaveCancelled()) {
930 this._cancel();
931 }
932};
933
934Promise.prototype._cancel = function() {
935 if (!this._isCancellable()) return;
936 this._setCancelled();
937 async.invoke(this._cancelPromises, this, undefined);
938};
939
940Promise.prototype._cancelPromises = function() {
941 if (this._length() > 0) this._settlePromises();
942};
943
944Promise.prototype._unsetOnCancel = function() {
945 this._onCancelField = undefined;
946};
947
948Promise.prototype._isCancellable = function() {
949 return this.isPending() && !this._isCancelled();
950};
951
952Promise.prototype.isCancellable = function() {
953 return this.isPending() && !this.isCancelled();
954};
955
956Promise.prototype._doInvokeOnCancel = function(onCancelCallback, internalOnly) {
957 if (util.isArray(onCancelCallback)) {
958 for (var i = 0; i < onCancelCallback.length; ++i) {
959 this._doInvokeOnCancel(onCancelCallback[i], internalOnly);
960 }
961 } else if (onCancelCallback !== undefined) {
962 if (typeof onCancelCallback === "function") {
963 if (!internalOnly) {
964 var e = tryCatch(onCancelCallback).call(this._boundValue());
965 if (e === errorObj) {
966 this._attachExtraTrace(e.e);
967 async.throwLater(e.e);
968 }
969 }
970 } else {
971 onCancelCallback._resultCancelled(this);
972 }
973 }
974};
975
976Promise.prototype._invokeOnCancel = function() {
977 var onCancelCallback = this._onCancel();
978 this._unsetOnCancel();
979 async.invoke(this._doInvokeOnCancel, this, onCancelCallback);
980};
981
982Promise.prototype._invokeInternalOnCancel = function() {
983 if (this._isCancellable()) {
984 this._doInvokeOnCancel(this._onCancel(), true);
985 this._unsetOnCancel();
986 }
987};
988
989Promise.prototype._resultCancelled = function() {
990 this.cancel();
991};
992
993};
994
995},{"./util":36}],7:[function(_dereq_,module,exports){
996"use strict";
997module.exports = function(NEXT_FILTER) {
998var util = _dereq_("./util");
999var getKeys = _dereq_("./es5").keys;
1000var tryCatch = util.tryCatch;
1001var errorObj = util.errorObj;
1002
1003function catchFilter(instances, cb, promise) {
1004 return function(e) {
1005 var boundTo = promise._boundValue();
1006 predicateLoop: for (var i = 0; i < instances.length; ++i) {
1007 var item = instances[i];
1008
1009 if (item === Error ||
1010 (item != null && item.prototype instanceof Error)) {
1011 if (e instanceof item) {
1012 return tryCatch(cb).call(boundTo, e);
1013 }
1014 } else if (typeof item === "function") {
1015 var matchesPredicate = tryCatch(item).call(boundTo, e);
1016 if (matchesPredicate === errorObj) {
1017 return matchesPredicate;
1018 } else if (matchesPredicate) {
1019 return tryCatch(cb).call(boundTo, e);
1020 }
1021 } else if (util.isObject(e)) {
1022 var keys = getKeys(item);
1023 for (var j = 0; j < keys.length; ++j) {
1024 var key = keys[j];
1025 if (item[key] != e[key]) {
1026 continue predicateLoop;
1027 }
1028 }
1029 return tryCatch(cb).call(boundTo, e);
1030 }
1031 }
1032 return NEXT_FILTER;
1033 };
1034}
1035
1036return catchFilter;
1037};
1038
1039},{"./es5":13,"./util":36}],8:[function(_dereq_,module,exports){
1040"use strict";
1041module.exports = function(Promise) {
1042var longStackTraces = false;
1043var contextStack = [];
1044
1045Promise.prototype._promiseCreated = function() {};
1046Promise.prototype._pushContext = function() {};
1047Promise.prototype._popContext = function() {return null;};
1048Promise._peekContext = Promise.prototype._peekContext = function() {};
1049
1050function Context() {
1051 this._trace = new Context.CapturedTrace(peekContext());
1052}
1053Context.prototype._pushContext = function () {
1054 if (this._trace !== undefined) {
1055 this._trace._promiseCreated = null;
1056 contextStack.push(this._trace);
1057 }
1058};
1059
1060Context.prototype._popContext = function () {
1061 if (this._trace !== undefined) {
1062 var trace = contextStack.pop();
1063 var ret = trace._promiseCreated;
1064 trace._promiseCreated = null;
1065 return ret;
1066 }
1067 return null;
1068};
1069
1070function createContext() {
1071 if (longStackTraces) return new Context();
1072}
1073
1074function peekContext() {
1075 var lastIndex = contextStack.length - 1;
1076 if (lastIndex >= 0) {
1077 return contextStack[lastIndex];
1078 }
1079 return undefined;
1080}
1081Context.CapturedTrace = null;
1082Context.create = createContext;
1083Context.deactivateLongStackTraces = function() {};
1084Context.activateLongStackTraces = function() {
1085 var Promise_pushContext = Promise.prototype._pushContext;
1086 var Promise_popContext = Promise.prototype._popContext;
1087 var Promise_PeekContext = Promise._peekContext;
1088 var Promise_peekContext = Promise.prototype._peekContext;
1089 var Promise_promiseCreated = Promise.prototype._promiseCreated;
1090 Context.deactivateLongStackTraces = function() {
1091 Promise.prototype._pushContext = Promise_pushContext;
1092 Promise.prototype._popContext = Promise_popContext;
1093 Promise._peekContext = Promise_PeekContext;
1094 Promise.prototype._peekContext = Promise_peekContext;
1095 Promise.prototype._promiseCreated = Promise_promiseCreated;
1096 longStackTraces = false;
1097 };
1098 longStackTraces = true;
1099 Promise.prototype._pushContext = Context.prototype._pushContext;
1100 Promise.prototype._popContext = Context.prototype._popContext;
1101 Promise._peekContext = Promise.prototype._peekContext = peekContext;
1102 Promise.prototype._promiseCreated = function() {
1103 var ctx = this._peekContext();
1104 if (ctx && ctx._promiseCreated == null) ctx._promiseCreated = this;
1105 };
1106};
1107return Context;
1108};
1109
1110},{}],9:[function(_dereq_,module,exports){
1111"use strict";
1112module.exports = function(Promise, Context) {
1113var getDomain = Promise._getDomain;
1114var async = Promise._async;
1115var Warning = _dereq_("./errors").Warning;
1116var util = _dereq_("./util");
1117var canAttachTrace = util.canAttachTrace;
1118var unhandledRejectionHandled;
1119var possiblyUnhandledRejection;
1120var bluebirdFramePattern =
1121 /[\\\/]bluebird[\\\/]js[\\\/](release|debug|instrumented)/;
1122var nodeFramePattern = /\((?:timers\.js):\d+:\d+\)/;
1123var parseLinePattern = /[\/<\(](.+?):(\d+):(\d+)\)?\s*$/;
1124var stackFramePattern = null;
1125var formatStack = null;
1126var indentStackFrames = false;
1127var printWarning;
1128var debugging = !!(util.env("BLUEBIRD_DEBUG") != 0 &&
1129 (true ||
1130 util.env("BLUEBIRD_DEBUG") ||
1131 util.env("NODE_ENV") === "development"));
1132
1133var warnings = !!(util.env("BLUEBIRD_WARNINGS") != 0 &&
1134 (debugging || util.env("BLUEBIRD_WARNINGS")));
1135
1136var longStackTraces = !!(util.env("BLUEBIRD_LONG_STACK_TRACES") != 0 &&
1137 (debugging || util.env("BLUEBIRD_LONG_STACK_TRACES")));
1138
1139var wForgottenReturn = util.env("BLUEBIRD_W_FORGOTTEN_RETURN") != 0 &&
1140 (warnings || !!util.env("BLUEBIRD_W_FORGOTTEN_RETURN"));
1141
1142Promise.prototype.suppressUnhandledRejections = function() {
1143 var target = this._target();
1144 target._bitField = ((target._bitField & (~1048576)) |
1145 524288);
1146};
1147
1148Promise.prototype._ensurePossibleRejectionHandled = function () {
1149 if ((this._bitField & 524288) !== 0) return;
1150 this._setRejectionIsUnhandled();
1151 async.invokeLater(this._notifyUnhandledRejection, this, undefined);
1152};
1153
1154Promise.prototype._notifyUnhandledRejectionIsHandled = function () {
1155 fireRejectionEvent("rejectionHandled",
1156 unhandledRejectionHandled, undefined, this);
1157};
1158
1159Promise.prototype._setReturnedNonUndefined = function() {
1160 this._bitField = this._bitField | 268435456;
1161};
1162
1163Promise.prototype._returnedNonUndefined = function() {
1164 return (this._bitField & 268435456) !== 0;
1165};
1166
1167Promise.prototype._notifyUnhandledRejection = function () {
1168 if (this._isRejectionUnhandled()) {
1169 var reason = this._settledValue();
1170 this._setUnhandledRejectionIsNotified();
1171 fireRejectionEvent("unhandledRejection",
1172 possiblyUnhandledRejection, reason, this);
1173 }
1174};
1175
1176Promise.prototype._setUnhandledRejectionIsNotified = function () {
1177 this._bitField = this._bitField | 262144;
1178};
1179
1180Promise.prototype._unsetUnhandledRejectionIsNotified = function () {
1181 this._bitField = this._bitField & (~262144);
1182};
1183
1184Promise.prototype._isUnhandledRejectionNotified = function () {
1185 return (this._bitField & 262144) > 0;
1186};
1187
1188Promise.prototype._setRejectionIsUnhandled = function () {
1189 this._bitField = this._bitField | 1048576;
1190};
1191
1192Promise.prototype._unsetRejectionIsUnhandled = function () {
1193 this._bitField = this._bitField & (~1048576);
1194 if (this._isUnhandledRejectionNotified()) {
1195 this._unsetUnhandledRejectionIsNotified();
1196 this._notifyUnhandledRejectionIsHandled();
1197 }
1198};
1199
1200Promise.prototype._isRejectionUnhandled = function () {
1201 return (this._bitField & 1048576) > 0;
1202};
1203
1204Promise.prototype._warn = function(message, shouldUseOwnTrace, promise) {
1205 return warn(message, shouldUseOwnTrace, promise || this);
1206};
1207
1208Promise.onPossiblyUnhandledRejection = function (fn) {
1209 var domain = getDomain();
1210 possiblyUnhandledRejection =
1211 typeof fn === "function" ? (domain === null ?
1212 fn : util.domainBind(domain, fn))
1213 : undefined;
1214};
1215
1216Promise.onUnhandledRejectionHandled = function (fn) {
1217 var domain = getDomain();
1218 unhandledRejectionHandled =
1219 typeof fn === "function" ? (domain === null ?
1220 fn : util.domainBind(domain, fn))
1221 : undefined;
1222};
1223
1224var disableLongStackTraces = function() {};
1225Promise.longStackTraces = function () {
1226 if (async.haveItemsQueued() && !config.longStackTraces) {
1227 throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a");
1228 }
1229 if (!config.longStackTraces && longStackTracesIsSupported()) {
1230 var Promise_captureStackTrace = Promise.prototype._captureStackTrace;
1231 var Promise_attachExtraTrace = Promise.prototype._attachExtraTrace;
1232 config.longStackTraces = true;
1233 disableLongStackTraces = function() {
1234 if (async.haveItemsQueued() && !config.longStackTraces) {
1235 throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a");
1236 }
1237 Promise.prototype._captureStackTrace = Promise_captureStackTrace;
1238 Promise.prototype._attachExtraTrace = Promise_attachExtraTrace;
1239 Context.deactivateLongStackTraces();
1240 async.enableTrampoline();
1241 config.longStackTraces = false;
1242 };
1243 Promise.prototype._captureStackTrace = longStackTracesCaptureStackTrace;
1244 Promise.prototype._attachExtraTrace = longStackTracesAttachExtraTrace;
1245 Context.activateLongStackTraces();
1246 async.disableTrampolineIfNecessary();
1247 }
1248};
1249
1250Promise.hasLongStackTraces = function () {
1251 return config.longStackTraces && longStackTracesIsSupported();
1252};
1253
1254var fireDomEvent = (function() {
1255 try {
1256 if (typeof CustomEvent === "function") {
1257 var event = new CustomEvent("CustomEvent");
1258 util.global.dispatchEvent(event);
1259 return function(name, event) {
1260 var domEvent = new CustomEvent(name.toLowerCase(), {
1261 detail: event,
1262 cancelable: true
1263 });
1264 return !util.global.dispatchEvent(domEvent);
1265 };
1266 } else if (typeof Event === "function") {
1267 var event = new Event("CustomEvent");
1268 util.global.dispatchEvent(event);
1269 return function(name, event) {
1270 var domEvent = new Event(name.toLowerCase(), {
1271 cancelable: true
1272 });
1273 domEvent.detail = event;
1274 return !util.global.dispatchEvent(domEvent);
1275 };
1276 } else {
1277 var event = document.createEvent("CustomEvent");
1278 event.initCustomEvent("testingtheevent", false, true, {});
1279 util.global.dispatchEvent(event);
1280 return function(name, event) {
1281 var domEvent = document.createEvent("CustomEvent");
1282 domEvent.initCustomEvent(name.toLowerCase(), false, true,
1283 event);
1284 return !util.global.dispatchEvent(domEvent);
1285 };
1286 }
1287 } catch (e) {}
1288 return function() {
1289 return false;
1290 };
1291})();
1292
1293var fireGlobalEvent = (function() {
1294 if (util.isNode) {
1295 return function() {
1296 return process.emit.apply(process, arguments);
1297 };
1298 } else {
1299 if (!util.global) {
1300 return function() {
1301 return false;
1302 };
1303 }
1304 return function(name) {
1305 var methodName = "on" + name.toLowerCase();
1306 var method = util.global[methodName];
1307 if (!method) return false;
1308 method.apply(util.global, [].slice.call(arguments, 1));
1309 return true;
1310 };
1311 }
1312})();
1313
1314function generatePromiseLifecycleEventObject(name, promise) {
1315 return {promise: promise};
1316}
1317
1318var eventToObjectGenerator = {
1319 promiseCreated: generatePromiseLifecycleEventObject,
1320 promiseFulfilled: generatePromiseLifecycleEventObject,
1321 promiseRejected: generatePromiseLifecycleEventObject,
1322 promiseResolved: generatePromiseLifecycleEventObject,
1323 promiseCancelled: generatePromiseLifecycleEventObject,
1324 promiseChained: function(name, promise, child) {
1325 return {promise: promise, child: child};
1326 },
1327 warning: function(name, warning) {
1328 return {warning: warning};
1329 },
1330 unhandledRejection: function (name, reason, promise) {
1331 return {reason: reason, promise: promise};
1332 },
1333 rejectionHandled: generatePromiseLifecycleEventObject
1334};
1335
1336var activeFireEvent = function (name) {
1337 var globalEventFired = false;
1338 try {
1339 globalEventFired = fireGlobalEvent.apply(null, arguments);
1340 } catch (e) {
1341 async.throwLater(e);
1342 globalEventFired = true;
1343 }
1344
1345 var domEventFired = false;
1346 try {
1347 domEventFired = fireDomEvent(name,
1348 eventToObjectGenerator[name].apply(null, arguments));
1349 } catch (e) {
1350 async.throwLater(e);
1351 domEventFired = true;
1352 }
1353
1354 return domEventFired || globalEventFired;
1355};
1356
1357Promise.config = function(opts) {
1358 opts = Object(opts);
1359 if ("longStackTraces" in opts) {
1360 if (opts.longStackTraces) {
1361 Promise.longStackTraces();
1362 } else if (!opts.longStackTraces && Promise.hasLongStackTraces()) {
1363 disableLongStackTraces();
1364 }
1365 }
1366 if ("warnings" in opts) {
1367 var warningsOption = opts.warnings;
1368 config.warnings = !!warningsOption;
1369 wForgottenReturn = config.warnings;
1370
1371 if (util.isObject(warningsOption)) {
1372 if ("wForgottenReturn" in warningsOption) {
1373 wForgottenReturn = !!warningsOption.wForgottenReturn;
1374 }
1375 }
1376 }
1377 if ("cancellation" in opts && opts.cancellation && !config.cancellation) {
1378 if (async.haveItemsQueued()) {
1379 throw new Error(
1380 "cannot enable cancellation after promises are in use");
1381 }
1382 Promise.prototype._clearCancellationData =
1383 cancellationClearCancellationData;
1384 Promise.prototype._propagateFrom = cancellationPropagateFrom;
1385 Promise.prototype._onCancel = cancellationOnCancel;
1386 Promise.prototype._setOnCancel = cancellationSetOnCancel;
1387 Promise.prototype._attachCancellationCallback =
1388 cancellationAttachCancellationCallback;
1389 Promise.prototype._execute = cancellationExecute;
1390 propagateFromFunction = cancellationPropagateFrom;
1391 config.cancellation = true;
1392 }
1393 if ("monitoring" in opts) {
1394 if (opts.monitoring && !config.monitoring) {
1395 config.monitoring = true;
1396 Promise.prototype._fireEvent = activeFireEvent;
1397 } else if (!opts.monitoring && config.monitoring) {
1398 config.monitoring = false;
1399 Promise.prototype._fireEvent = defaultFireEvent;
1400 }
1401 }
1402};
1403
1404function defaultFireEvent() { return false; }
1405
1406Promise.prototype._fireEvent = defaultFireEvent;
1407Promise.prototype._execute = function(executor, resolve, reject) {
1408 try {
1409 executor(resolve, reject);
1410 } catch (e) {
1411 return e;
1412 }
1413};
1414Promise.prototype._onCancel = function () {};
1415Promise.prototype._setOnCancel = function (handler) { ; };
1416Promise.prototype._attachCancellationCallback = function(onCancel) {
1417 ;
1418};
1419Promise.prototype._captureStackTrace = function () {};
1420Promise.prototype._attachExtraTrace = function () {};
1421Promise.prototype._clearCancellationData = function() {};
1422Promise.prototype._propagateFrom = function (parent, flags) {
1423 ;
1424 ;
1425};
1426
1427function cancellationExecute(executor, resolve, reject) {
1428 var promise = this;
1429 try {
1430 executor(resolve, reject, function(onCancel) {
1431 if (typeof onCancel !== "function") {
1432 throw new TypeError("onCancel must be a function, got: " +
1433 util.toString(onCancel));
1434 }
1435 promise._attachCancellationCallback(onCancel);
1436 });
1437 } catch (e) {
1438 return e;
1439 }
1440}
1441
1442function cancellationAttachCancellationCallback(onCancel) {
1443 if (!this._isCancellable()) return this;
1444
1445 var previousOnCancel = this._onCancel();
1446 if (previousOnCancel !== undefined) {
1447 if (util.isArray(previousOnCancel)) {
1448 previousOnCancel.push(onCancel);
1449 } else {
1450 this._setOnCancel([previousOnCancel, onCancel]);
1451 }
1452 } else {
1453 this._setOnCancel(onCancel);
1454 }
1455}
1456
1457function cancellationOnCancel() {
1458 return this._onCancelField;
1459}
1460
1461function cancellationSetOnCancel(onCancel) {
1462 this._onCancelField = onCancel;
1463}
1464
1465function cancellationClearCancellationData() {
1466 this._cancellationParent = undefined;
1467 this._onCancelField = undefined;
1468}
1469
1470function cancellationPropagateFrom(parent, flags) {
1471 if ((flags & 1) !== 0) {
1472 this._cancellationParent = parent;
1473 var branchesRemainingToCancel = parent._branchesRemainingToCancel;
1474 if (branchesRemainingToCancel === undefined) {
1475 branchesRemainingToCancel = 0;
1476 }
1477 parent._branchesRemainingToCancel = branchesRemainingToCancel + 1;
1478 }
1479 if ((flags & 2) !== 0 && parent._isBound()) {
1480 this._setBoundTo(parent._boundTo);
1481 }
1482}
1483
1484function bindingPropagateFrom(parent, flags) {
1485 if ((flags & 2) !== 0 && parent._isBound()) {
1486 this._setBoundTo(parent._boundTo);
1487 }
1488}
1489var propagateFromFunction = bindingPropagateFrom;
1490
1491function boundValueFunction() {
1492 var ret = this._boundTo;
1493 if (ret !== undefined) {
1494 if (ret instanceof Promise) {
1495 if (ret.isFulfilled()) {
1496 return ret.value();
1497 } else {
1498 return undefined;
1499 }
1500 }
1501 }
1502 return ret;
1503}
1504
1505function longStackTracesCaptureStackTrace() {
1506 this._trace = new CapturedTrace(this._peekContext());
1507}
1508
1509function longStackTracesAttachExtraTrace(error, ignoreSelf) {
1510 if (canAttachTrace(error)) {
1511 var trace = this._trace;
1512 if (trace !== undefined) {
1513 if (ignoreSelf) trace = trace._parent;
1514 }
1515 if (trace !== undefined) {
1516 trace.attachExtraTrace(error);
1517 } else if (!error.__stackCleaned__) {
1518 var parsed = parseStackAndMessage(error);
1519 util.notEnumerableProp(error, "stack",
1520 parsed.message + "\n" + parsed.stack.join("\n"));
1521 util.notEnumerableProp(error, "__stackCleaned__", true);
1522 }
1523 }
1524}
1525
1526function checkForgottenReturns(returnValue, promiseCreated, name, promise,
1527 parent) {
1528 if (returnValue === undefined && promiseCreated !== null &&
1529 wForgottenReturn) {
1530 if (parent !== undefined && parent._returnedNonUndefined()) return;
1531 if ((promise._bitField & 65535) === 0) return;
1532
1533 if (name) name = name + " ";
1534 var handlerLine = "";
1535 var creatorLine = "";
1536 if (promiseCreated._trace) {
1537 var traceLines = promiseCreated._trace.stack.split("\n");
1538 var stack = cleanStack(traceLines);
1539 for (var i = stack.length - 1; i >= 0; --i) {
1540 var line = stack[i];
1541 if (!nodeFramePattern.test(line)) {
1542 var lineMatches = line.match(parseLinePattern);
1543 if (lineMatches) {
1544 handlerLine = "at " + lineMatches[1] +
1545 ":" + lineMatches[2] + ":" + lineMatches[3] + " ";
1546 }
1547 break;
1548 }
1549 }
1550
1551 if (stack.length > 0) {
1552 var firstUserLine = stack[0];
1553 for (var i = 0; i < traceLines.length; ++i) {
1554
1555 if (traceLines[i] === firstUserLine) {
1556 if (i > 0) {
1557 creatorLine = "\n" + traceLines[i - 1];
1558 }
1559 break;
1560 }
1561 }
1562
1563 }
1564 }
1565 var msg = "a promise was created in a " + name +
1566 "handler " + handlerLine + "but was not returned from it, " +
1567 "see http://goo.gl/rRqMUw" +
1568 creatorLine;
1569 promise._warn(msg, true, promiseCreated);
1570 }
1571}
1572
1573function deprecated(name, replacement) {
1574 var message = name +
1575 " is deprecated and will be removed in a future version.";
1576 if (replacement) message += " Use " + replacement + " instead.";
1577 return warn(message);
1578}
1579
1580function warn(message, shouldUseOwnTrace, promise) {
1581 if (!config.warnings) return;
1582 var warning = new Warning(message);
1583 var ctx;
1584 if (shouldUseOwnTrace) {
1585 promise._attachExtraTrace(warning);
1586 } else if (config.longStackTraces && (ctx = Promise._peekContext())) {
1587 ctx.attachExtraTrace(warning);
1588 } else {
1589 var parsed = parseStackAndMessage(warning);
1590 warning.stack = parsed.message + "\n" + parsed.stack.join("\n");
1591 }
1592
1593 if (!activeFireEvent("warning", warning)) {
1594 formatAndLogError(warning, "", true);
1595 }
1596}
1597
1598function reconstructStack(message, stacks) {
1599 for (var i = 0; i < stacks.length - 1; ++i) {
1600 stacks[i].push("From previous event:");
1601 stacks[i] = stacks[i].join("\n");
1602 }
1603 if (i < stacks.length) {
1604 stacks[i] = stacks[i].join("\n");
1605 }
1606 return message + "\n" + stacks.join("\n");
1607}
1608
1609function removeDuplicateOrEmptyJumps(stacks) {
1610 for (var i = 0; i < stacks.length; ++i) {
1611 if (stacks[i].length === 0 ||
1612 ((i + 1 < stacks.length) && stacks[i][0] === stacks[i+1][0])) {
1613 stacks.splice(i, 1);
1614 i--;
1615 }
1616 }
1617}
1618
1619function removeCommonRoots(stacks) {
1620 var current = stacks[0];
1621 for (var i = 1; i < stacks.length; ++i) {
1622 var prev = stacks[i];
1623 var currentLastIndex = current.length - 1;
1624 var currentLastLine = current[currentLastIndex];
1625 var commonRootMeetPoint = -1;
1626
1627 for (var j = prev.length - 1; j >= 0; --j) {
1628 if (prev[j] === currentLastLine) {
1629 commonRootMeetPoint = j;
1630 break;
1631 }
1632 }
1633
1634 for (var j = commonRootMeetPoint; j >= 0; --j) {
1635 var line = prev[j];
1636 if (current[currentLastIndex] === line) {
1637 current.pop();
1638 currentLastIndex--;
1639 } else {
1640 break;
1641 }
1642 }
1643 current = prev;
1644 }
1645}
1646
1647function cleanStack(stack) {
1648 var ret = [];
1649 for (var i = 0; i < stack.length; ++i) {
1650 var line = stack[i];
1651 var isTraceLine = " (No stack trace)" === line ||
1652 stackFramePattern.test(line);
1653 var isInternalFrame = isTraceLine && shouldIgnore(line);
1654 if (isTraceLine && !isInternalFrame) {
1655 if (indentStackFrames && line.charAt(0) !== " ") {
1656 line = " " + line;
1657 }
1658 ret.push(line);
1659 }
1660 }
1661 return ret;
1662}
1663
1664function stackFramesAsArray(error) {
1665 var stack = error.stack.replace(/\s+$/g, "").split("\n");
1666 for (var i = 0; i < stack.length; ++i) {
1667 var line = stack[i];
1668 if (" (No stack trace)" === line || stackFramePattern.test(line)) {
1669 break;
1670 }
1671 }
1672 if (i > 0) {
1673 stack = stack.slice(i);
1674 }
1675 return stack;
1676}
1677
1678function parseStackAndMessage(error) {
1679 var stack = error.stack;
1680 var message = error.toString();
1681 stack = typeof stack === "string" && stack.length > 0
1682 ? stackFramesAsArray(error) : [" (No stack trace)"];
1683 return {
1684 message: message,
1685 stack: cleanStack(stack)
1686 };
1687}
1688
1689function formatAndLogError(error, title, isSoft) {
1690 if (typeof console !== "undefined") {
1691 var message;
1692 if (util.isObject(error)) {
1693 var stack = error.stack;
1694 message = title + formatStack(stack, error);
1695 } else {
1696 message = title + String(error);
1697 }
1698 if (typeof printWarning === "function") {
1699 printWarning(message, isSoft);
1700 } else if (typeof console.log === "function" ||
1701 typeof console.log === "object") {
1702 console.log(message);
1703 }
1704 }
1705}
1706
1707function fireRejectionEvent(name, localHandler, reason, promise) {
1708 var localEventFired = false;
1709 try {
1710 if (typeof localHandler === "function") {
1711 localEventFired = true;
1712 if (name === "rejectionHandled") {
1713 localHandler(promise);
1714 } else {
1715 localHandler(reason, promise);
1716 }
1717 }
1718 } catch (e) {
1719 async.throwLater(e);
1720 }
1721
1722 if (name === "unhandledRejection") {
1723 if (!activeFireEvent(name, reason, promise) && !localEventFired) {
1724 formatAndLogError(reason, "Unhandled rejection ");
1725 }
1726 } else {
1727 activeFireEvent(name, promise);
1728 }
1729}
1730
1731function formatNonError(obj) {
1732 var str;
1733 if (typeof obj === "function") {
1734 str = "[function " +
1735 (obj.name || "anonymous") +
1736 "]";
1737 } else {
1738 str = obj && typeof obj.toString === "function"
1739 ? obj.toString() : util.toString(obj);
1740 var ruselessToString = /\[object [a-zA-Z0-9$_]+\]/;
1741 if (ruselessToString.test(str)) {
1742 try {
1743 var newStr = JSON.stringify(obj);
1744 str = newStr;
1745 }
1746 catch(e) {
1747
1748 }
1749 }
1750 if (str.length === 0) {
1751 str = "(empty array)";
1752 }
1753 }
1754 return ("(<" + snip(str) + ">, no stack trace)");
1755}
1756
1757function snip(str) {
1758 var maxChars = 41;
1759 if (str.length < maxChars) {
1760 return str;
1761 }
1762 return str.substr(0, maxChars - 3) + "...";
1763}
1764
1765function longStackTracesIsSupported() {
1766 return typeof captureStackTrace === "function";
1767}
1768
1769var shouldIgnore = function() { return false; };
1770var parseLineInfoRegex = /[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/;
1771function parseLineInfo(line) {
1772 var matches = line.match(parseLineInfoRegex);
1773 if (matches) {
1774 return {
1775 fileName: matches[1],
1776 line: parseInt(matches[2], 10)
1777 };
1778 }
1779}
1780
1781function setBounds(firstLineError, lastLineError) {
1782 if (!longStackTracesIsSupported()) return;
1783 var firstStackLines = firstLineError.stack.split("\n");
1784 var lastStackLines = lastLineError.stack.split("\n");
1785 var firstIndex = -1;
1786 var lastIndex = -1;
1787 var firstFileName;
1788 var lastFileName;
1789 for (var i = 0; i < firstStackLines.length; ++i) {
1790 var result = parseLineInfo(firstStackLines[i]);
1791 if (result) {
1792 firstFileName = result.fileName;
1793 firstIndex = result.line;
1794 break;
1795 }
1796 }
1797 for (var i = 0; i < lastStackLines.length; ++i) {
1798 var result = parseLineInfo(lastStackLines[i]);
1799 if (result) {
1800 lastFileName = result.fileName;
1801 lastIndex = result.line;
1802 break;
1803 }
1804 }
1805 if (firstIndex < 0 || lastIndex < 0 || !firstFileName || !lastFileName ||
1806 firstFileName !== lastFileName || firstIndex >= lastIndex) {
1807 return;
1808 }
1809
1810 shouldIgnore = function(line) {
1811 if (bluebirdFramePattern.test(line)) return true;
1812 var info = parseLineInfo(line);
1813 if (info) {
1814 if (info.fileName === firstFileName &&
1815 (firstIndex <= info.line && info.line <= lastIndex)) {
1816 return true;
1817 }
1818 }
1819 return false;
1820 };
1821}
1822
1823function CapturedTrace(parent) {
1824 this._parent = parent;
1825 this._promisesCreated = 0;
1826 var length = this._length = 1 + (parent === undefined ? 0 : parent._length);
1827 captureStackTrace(this, CapturedTrace);
1828 if (length > 32) this.uncycle();
1829}
1830util.inherits(CapturedTrace, Error);
1831Context.CapturedTrace = CapturedTrace;
1832
1833CapturedTrace.prototype.uncycle = function() {
1834 var length = this._length;
1835 if (length < 2) return;
1836 var nodes = [];
1837 var stackToIndex = {};
1838
1839 for (var i = 0, node = this; node !== undefined; ++i) {
1840 nodes.push(node);
1841 node = node._parent;
1842 }
1843 length = this._length = i;
1844 for (var i = length - 1; i >= 0; --i) {
1845 var stack = nodes[i].stack;
1846 if (stackToIndex[stack] === undefined) {
1847 stackToIndex[stack] = i;
1848 }
1849 }
1850 for (var i = 0; i < length; ++i) {
1851 var currentStack = nodes[i].stack;
1852 var index = stackToIndex[currentStack];
1853 if (index !== undefined && index !== i) {
1854 if (index > 0) {
1855 nodes[index - 1]._parent = undefined;
1856 nodes[index - 1]._length = 1;
1857 }
1858 nodes[i]._parent = undefined;
1859 nodes[i]._length = 1;
1860 var cycleEdgeNode = i > 0 ? nodes[i - 1] : this;
1861
1862 if (index < length - 1) {
1863 cycleEdgeNode._parent = nodes[index + 1];
1864 cycleEdgeNode._parent.uncycle();
1865 cycleEdgeNode._length =
1866 cycleEdgeNode._parent._length + 1;
1867 } else {
1868 cycleEdgeNode._parent = undefined;
1869 cycleEdgeNode._length = 1;
1870 }
1871 var currentChildLength = cycleEdgeNode._length + 1;
1872 for (var j = i - 2; j >= 0; --j) {
1873 nodes[j]._length = currentChildLength;
1874 currentChildLength++;
1875 }
1876 return;
1877 }
1878 }
1879};
1880
1881CapturedTrace.prototype.attachExtraTrace = function(error) {
1882 if (error.__stackCleaned__) return;
1883 this.uncycle();
1884 var parsed = parseStackAndMessage(error);
1885 var message = parsed.message;
1886 var stacks = [parsed.stack];
1887
1888 var trace = this;
1889 while (trace !== undefined) {
1890 stacks.push(cleanStack(trace.stack.split("\n")));
1891 trace = trace._parent;
1892 }
1893 removeCommonRoots(stacks);
1894 removeDuplicateOrEmptyJumps(stacks);
1895 util.notEnumerableProp(error, "stack", reconstructStack(message, stacks));
1896 util.notEnumerableProp(error, "__stackCleaned__", true);
1897};
1898
1899var captureStackTrace = (function stackDetection() {
1900 var v8stackFramePattern = /^\s*at\s*/;
1901 var v8stackFormatter = function(stack, error) {
1902 if (typeof stack === "string") return stack;
1903
1904 if (error.name !== undefined &&
1905 error.message !== undefined) {
1906 return error.toString();
1907 }
1908 return formatNonError(error);
1909 };
1910
1911 if (typeof Error.stackTraceLimit === "number" &&
1912 typeof Error.captureStackTrace === "function") {
1913 Error.stackTraceLimit += 6;
1914 stackFramePattern = v8stackFramePattern;
1915 formatStack = v8stackFormatter;
1916 var captureStackTrace = Error.captureStackTrace;
1917
1918 shouldIgnore = function(line) {
1919 return bluebirdFramePattern.test(line);
1920 };
1921 return function(receiver, ignoreUntil) {
1922 Error.stackTraceLimit += 6;
1923 captureStackTrace(receiver, ignoreUntil);
1924 Error.stackTraceLimit -= 6;
1925 };
1926 }
1927 var err = new Error();
1928
1929 if (typeof err.stack === "string" &&
1930 err.stack.split("\n")[0].indexOf("stackDetection@") >= 0) {
1931 stackFramePattern = /@/;
1932 formatStack = v8stackFormatter;
1933 indentStackFrames = true;
1934 return function captureStackTrace(o) {
1935 o.stack = new Error().stack;
1936 };
1937 }
1938
1939 var hasStackAfterThrow;
1940 try { throw new Error(); }
1941 catch(e) {
1942 hasStackAfterThrow = ("stack" in e);
1943 }
1944 if (!("stack" in err) && hasStackAfterThrow &&
1945 typeof Error.stackTraceLimit === "number") {
1946 stackFramePattern = v8stackFramePattern;
1947 formatStack = v8stackFormatter;
1948 return function captureStackTrace(o) {
1949 Error.stackTraceLimit += 6;
1950 try { throw new Error(); }
1951 catch(e) { o.stack = e.stack; }
1952 Error.stackTraceLimit -= 6;
1953 };
1954 }
1955
1956 formatStack = function(stack, error) {
1957 if (typeof stack === "string") return stack;
1958
1959 if ((typeof error === "object" ||
1960 typeof error === "function") &&
1961 error.name !== undefined &&
1962 error.message !== undefined) {
1963 return error.toString();
1964 }
1965 return formatNonError(error);
1966 };
1967
1968 return null;
1969
1970})([]);
1971
1972if (typeof console !== "undefined" && typeof console.warn !== "undefined") {
1973 printWarning = function (message) {
1974 console.warn(message);
1975 };
1976 if (util.isNode && process.stderr.isTTY) {
1977 printWarning = function(message, isSoft) {
1978 var color = isSoft ? "\u001b[33m" : "\u001b[31m";
1979 console.warn(color + message + "\u001b[0m\n");
1980 };
1981 } else if (!util.isNode && typeof (new Error().stack) === "string") {
1982 printWarning = function(message, isSoft) {
1983 console.warn("%c" + message,
1984 isSoft ? "color: darkorange" : "color: red");
1985 };
1986 }
1987}
1988
1989var config = {
1990 warnings: warnings,
1991 longStackTraces: false,
1992 cancellation: false,
1993 monitoring: false
1994};
1995
1996if (longStackTraces) Promise.longStackTraces();
1997
1998return {
1999 longStackTraces: function() {
2000 return config.longStackTraces;
2001 },
2002 warnings: function() {
2003 return config.warnings;
2004 },
2005 cancellation: function() {
2006 return config.cancellation;
2007 },
2008 monitoring: function() {
2009 return config.monitoring;
2010 },
2011 propagateFromFunction: function() {
2012 return propagateFromFunction;
2013 },
2014 boundValueFunction: function() {
2015 return boundValueFunction;
2016 },
2017 checkForgottenReturns: checkForgottenReturns,
2018 setBounds: setBounds,
2019 warn: warn,
2020 deprecated: deprecated,
2021 CapturedTrace: CapturedTrace,
2022 fireDomEvent: fireDomEvent,
2023 fireGlobalEvent: fireGlobalEvent
2024};
2025};
2026
2027},{"./errors":12,"./util":36}],10:[function(_dereq_,module,exports){
2028"use strict";
2029module.exports = function(Promise) {
2030function returner() {
2031 return this.value;
2032}
2033function thrower() {
2034 throw this.reason;
2035}
2036
2037Promise.prototype["return"] =
2038Promise.prototype.thenReturn = function (value) {
2039 if (value instanceof Promise) value.suppressUnhandledRejections();
2040 return this._then(
2041 returner, undefined, undefined, {value: value}, undefined);
2042};
2043
2044Promise.prototype["throw"] =
2045Promise.prototype.thenThrow = function (reason) {
2046 return this._then(
2047 thrower, undefined, undefined, {reason: reason}, undefined);
2048};
2049
2050Promise.prototype.catchThrow = function (reason) {
2051 if (arguments.length <= 1) {
2052 return this._then(
2053 undefined, thrower, undefined, {reason: reason}, undefined);
2054 } else {
2055 var _reason = arguments[1];
2056 var handler = function() {throw _reason;};
2057 return this.caught(reason, handler);
2058 }
2059};
2060
2061Promise.prototype.catchReturn = function (value) {
2062 if (arguments.length <= 1) {
2063 if (value instanceof Promise) value.suppressUnhandledRejections();
2064 return this._then(
2065 undefined, returner, undefined, {value: value}, undefined);
2066 } else {
2067 var _value = arguments[1];
2068 if (_value instanceof Promise) _value.suppressUnhandledRejections();
2069 var handler = function() {return _value;};
2070 return this.caught(value, handler);
2071 }
2072};
2073};
2074
2075},{}],11:[function(_dereq_,module,exports){
2076"use strict";
2077module.exports = function(Promise, INTERNAL) {
2078var PromiseReduce = Promise.reduce;
2079var PromiseAll = Promise.all;
2080
2081function promiseAllThis() {
2082 return PromiseAll(this);
2083}
2084
2085function PromiseMapSeries(promises, fn) {
2086 return PromiseReduce(promises, fn, INTERNAL, INTERNAL);
2087}
2088
2089Promise.prototype.each = function (fn) {
2090 return PromiseReduce(this, fn, INTERNAL, 0)
2091 ._then(promiseAllThis, undefined, undefined, this, undefined);
2092};
2093
2094Promise.prototype.mapSeries = function (fn) {
2095 return PromiseReduce(this, fn, INTERNAL, INTERNAL);
2096};
2097
2098Promise.each = function (promises, fn) {
2099 return PromiseReduce(promises, fn, INTERNAL, 0)
2100 ._then(promiseAllThis, undefined, undefined, promises, undefined);
2101};
2102
2103Promise.mapSeries = PromiseMapSeries;
2104};
2105
2106
2107},{}],12:[function(_dereq_,module,exports){
2108"use strict";
2109var es5 = _dereq_("./es5");
2110var Objectfreeze = es5.freeze;
2111var util = _dereq_("./util");
2112var inherits = util.inherits;
2113var notEnumerableProp = util.notEnumerableProp;
2114
2115function subError(nameProperty, defaultMessage) {
2116 function SubError(message) {
2117 if (!(this instanceof SubError)) return new SubError(message);
2118 notEnumerableProp(this, "message",
2119 typeof message === "string" ? message : defaultMessage);
2120 notEnumerableProp(this, "name", nameProperty);
2121 if (Error.captureStackTrace) {
2122 Error.captureStackTrace(this, this.constructor);
2123 } else {
2124 Error.call(this);
2125 }
2126 }
2127 inherits(SubError, Error);
2128 return SubError;
2129}
2130
2131var _TypeError, _RangeError;
2132var Warning = subError("Warning", "warning");
2133var CancellationError = subError("CancellationError", "cancellation error");
2134var TimeoutError = subError("TimeoutError", "timeout error");
2135var AggregateError = subError("AggregateError", "aggregate error");
2136try {
2137 _TypeError = TypeError;
2138 _RangeError = RangeError;
2139} catch(e) {
2140 _TypeError = subError("TypeError", "type error");
2141 _RangeError = subError("RangeError", "range error");
2142}
2143
2144var methods = ("join pop push shift unshift slice filter forEach some " +
2145 "every map indexOf lastIndexOf reduce reduceRight sort reverse").split(" ");
2146
2147for (var i = 0; i < methods.length; ++i) {
2148 if (typeof Array.prototype[methods[i]] === "function") {
2149 AggregateError.prototype[methods[i]] = Array.prototype[methods[i]];
2150 }
2151}
2152
2153es5.defineProperty(AggregateError.prototype, "length", {
2154 value: 0,
2155 configurable: false,
2156 writable: true,
2157 enumerable: true
2158});
2159AggregateError.prototype["isOperational"] = true;
2160var level = 0;
2161AggregateError.prototype.toString = function() {
2162 var indent = Array(level * 4 + 1).join(" ");
2163 var ret = "\n" + indent + "AggregateError of:" + "\n";
2164 level++;
2165 indent = Array(level * 4 + 1).join(" ");
2166 for (var i = 0; i < this.length; ++i) {
2167 var str = this[i] === this ? "[Circular AggregateError]" : this[i] + "";
2168 var lines = str.split("\n");
2169 for (var j = 0; j < lines.length; ++j) {
2170 lines[j] = indent + lines[j];
2171 }
2172 str = lines.join("\n");
2173 ret += str + "\n";
2174 }
2175 level--;
2176 return ret;
2177};
2178
2179function OperationalError(message) {
2180 if (!(this instanceof OperationalError))
2181 return new OperationalError(message);
2182 notEnumerableProp(this, "name", "OperationalError");
2183 notEnumerableProp(this, "message", message);
2184 this.cause = message;
2185 this["isOperational"] = true;
2186
2187 if (message instanceof Error) {
2188 notEnumerableProp(this, "message", message.message);
2189 notEnumerableProp(this, "stack", message.stack);
2190 } else if (Error.captureStackTrace) {
2191 Error.captureStackTrace(this, this.constructor);
2192 }
2193
2194}
2195inherits(OperationalError, Error);
2196
2197var errorTypes = Error["__BluebirdErrorTypes__"];
2198if (!errorTypes) {
2199 errorTypes = Objectfreeze({
2200 CancellationError: CancellationError,
2201 TimeoutError: TimeoutError,
2202 OperationalError: OperationalError,
2203 RejectionError: OperationalError,
2204 AggregateError: AggregateError
2205 });
2206 es5.defineProperty(Error, "__BluebirdErrorTypes__", {
2207 value: errorTypes,
2208 writable: false,
2209 enumerable: false,
2210 configurable: false
2211 });
2212}
2213
2214module.exports = {
2215 Error: Error,
2216 TypeError: _TypeError,
2217 RangeError: _RangeError,
2218 CancellationError: errorTypes.CancellationError,
2219 OperationalError: errorTypes.OperationalError,
2220 TimeoutError: errorTypes.TimeoutError,
2221 AggregateError: errorTypes.AggregateError,
2222 Warning: Warning
2223};
2224
2225},{"./es5":13,"./util":36}],13:[function(_dereq_,module,exports){
2226var isES5 = (function(){
2227 "use strict";
2228 return this === undefined;
2229})();
2230
2231if (isES5) {
2232 module.exports = {
2233 freeze: Object.freeze,
2234 defineProperty: Object.defineProperty,
2235 getDescriptor: Object.getOwnPropertyDescriptor,
2236 keys: Object.keys,
2237 names: Object.getOwnPropertyNames,
2238 getPrototypeOf: Object.getPrototypeOf,
2239 isArray: Array.isArray,
2240 isES5: isES5,
2241 propertyIsWritable: function(obj, prop) {
2242 var descriptor = Object.getOwnPropertyDescriptor(obj, prop);
2243 return !!(!descriptor || descriptor.writable || descriptor.set);
2244 }
2245 };
2246} else {
2247 var has = {}.hasOwnProperty;
2248 var str = {}.toString;
2249 var proto = {}.constructor.prototype;
2250
2251 var ObjectKeys = function (o) {
2252 var ret = [];
2253 for (var key in o) {
2254 if (has.call(o, key)) {
2255 ret.push(key);
2256 }
2257 }
2258 return ret;
2259 };
2260
2261 var ObjectGetDescriptor = function(o, key) {
2262 return {value: o[key]};
2263 };
2264
2265 var ObjectDefineProperty = function (o, key, desc) {
2266 o[key] = desc.value;
2267 return o;
2268 };
2269
2270 var ObjectFreeze = function (obj) {
2271 return obj;
2272 };
2273
2274 var ObjectGetPrototypeOf = function (obj) {
2275 try {
2276 return Object(obj).constructor.prototype;
2277 }
2278 catch (e) {
2279 return proto;
2280 }
2281 };
2282
2283 var ArrayIsArray = function (obj) {
2284 try {
2285 return str.call(obj) === "[object Array]";
2286 }
2287 catch(e) {
2288 return false;
2289 }
2290 };
2291
2292 module.exports = {
2293 isArray: ArrayIsArray,
2294 keys: ObjectKeys,
2295 names: ObjectKeys,
2296 defineProperty: ObjectDefineProperty,
2297 getDescriptor: ObjectGetDescriptor,
2298 freeze: ObjectFreeze,
2299 getPrototypeOf: ObjectGetPrototypeOf,
2300 isES5: isES5,
2301 propertyIsWritable: function() {
2302 return true;
2303 }
2304 };
2305}
2306
2307},{}],14:[function(_dereq_,module,exports){
2308"use strict";
2309module.exports = function(Promise, INTERNAL) {
2310var PromiseMap = Promise.map;
2311
2312Promise.prototype.filter = function (fn, options) {
2313 return PromiseMap(this, fn, options, INTERNAL);
2314};
2315
2316Promise.filter = function (promises, fn, options) {
2317 return PromiseMap(promises, fn, options, INTERNAL);
2318};
2319};
2320
2321},{}],15:[function(_dereq_,module,exports){
2322"use strict";
2323module.exports = function(Promise, tryConvertToPromise) {
2324var util = _dereq_("./util");
2325var CancellationError = Promise.CancellationError;
2326var errorObj = util.errorObj;
2327
2328function PassThroughHandlerContext(promise, type, handler) {
2329 this.promise = promise;
2330 this.type = type;
2331 this.handler = handler;
2332 this.called = false;
2333 this.cancelPromise = null;
2334}
2335
2336PassThroughHandlerContext.prototype.isFinallyHandler = function() {
2337 return this.type === 0;
2338};
2339
2340function FinallyHandlerCancelReaction(finallyHandler) {
2341 this.finallyHandler = finallyHandler;
2342}
2343
2344FinallyHandlerCancelReaction.prototype._resultCancelled = function() {
2345 checkCancel(this.finallyHandler);
2346};
2347
2348function checkCancel(ctx, reason) {
2349 if (ctx.cancelPromise != null) {
2350 if (arguments.length > 1) {
2351 ctx.cancelPromise._reject(reason);
2352 } else {
2353 ctx.cancelPromise._cancel();
2354 }
2355 ctx.cancelPromise = null;
2356 return true;
2357 }
2358 return false;
2359}
2360
2361function succeed() {
2362 return finallyHandler.call(this, this.promise._target()._settledValue());
2363}
2364function fail(reason) {
2365 if (checkCancel(this, reason)) return;
2366 errorObj.e = reason;
2367 return errorObj;
2368}
2369function finallyHandler(reasonOrValue) {
2370 var promise = this.promise;
2371 var handler = this.handler;
2372
2373 if (!this.called) {
2374 this.called = true;
2375 var ret = this.isFinallyHandler()
2376 ? handler.call(promise._boundValue())
2377 : handler.call(promise._boundValue(), reasonOrValue);
2378 if (ret !== undefined) {
2379 promise._setReturnedNonUndefined();
2380 var maybePromise = tryConvertToPromise(ret, promise);
2381 if (maybePromise instanceof Promise) {
2382 if (this.cancelPromise != null) {
2383 if (maybePromise._isCancelled()) {
2384 var reason =
2385 new CancellationError("late cancellation observer");
2386 promise._attachExtraTrace(reason);
2387 errorObj.e = reason;
2388 return errorObj;
2389 } else if (maybePromise.isPending()) {
2390 maybePromise._attachCancellationCallback(
2391 new FinallyHandlerCancelReaction(this));
2392 }
2393 }
2394 return maybePromise._then(
2395 succeed, fail, undefined, this, undefined);
2396 }
2397 }
2398 }
2399
2400 if (promise.isRejected()) {
2401 checkCancel(this);
2402 errorObj.e = reasonOrValue;
2403 return errorObj;
2404 } else {
2405 checkCancel(this);
2406 return reasonOrValue;
2407 }
2408}
2409
2410Promise.prototype._passThrough = function(handler, type, success, fail) {
2411 if (typeof handler !== "function") return this.then();
2412 return this._then(success,
2413 fail,
2414 undefined,
2415 new PassThroughHandlerContext(this, type, handler),
2416 undefined);
2417};
2418
2419Promise.prototype.lastly =
2420Promise.prototype["finally"] = function (handler) {
2421 return this._passThrough(handler,
2422 0,
2423 finallyHandler,
2424 finallyHandler);
2425};
2426
2427Promise.prototype.tap = function (handler) {
2428 return this._passThrough(handler, 1, finallyHandler);
2429};
2430
2431return PassThroughHandlerContext;
2432};
2433
2434},{"./util":36}],16:[function(_dereq_,module,exports){
2435"use strict";
2436module.exports = function(Promise,
2437 apiRejection,
2438 INTERNAL,
2439 tryConvertToPromise,
2440 Proxyable,
2441 debug) {
2442var errors = _dereq_("./errors");
2443var TypeError = errors.TypeError;
2444var util = _dereq_("./util");
2445var errorObj = util.errorObj;
2446var tryCatch = util.tryCatch;
2447var yieldHandlers = [];
2448
2449function promiseFromYieldHandler(value, yieldHandlers, traceParent) {
2450 for (var i = 0; i < yieldHandlers.length; ++i) {
2451 traceParent._pushContext();
2452 var result = tryCatch(yieldHandlers[i])(value);
2453 traceParent._popContext();
2454 if (result === errorObj) {
2455 traceParent._pushContext();
2456 var ret = Promise.reject(errorObj.e);
2457 traceParent._popContext();
2458 return ret;
2459 }
2460 var maybePromise = tryConvertToPromise(result, traceParent);
2461 if (maybePromise instanceof Promise) return maybePromise;
2462 }
2463 return null;
2464}
2465
2466function PromiseSpawn(generatorFunction, receiver, yieldHandler, stack) {
2467 if (debug.cancellation()) {
2468 var internal = new Promise(INTERNAL);
2469 var _finallyPromise = this._finallyPromise = new Promise(INTERNAL);
2470 this._promise = internal.lastly(function() {
2471 return _finallyPromise;
2472 });
2473 internal._captureStackTrace();
2474 internal._setOnCancel(this);
2475 } else {
2476 var promise = this._promise = new Promise(INTERNAL);
2477 promise._captureStackTrace();
2478 }
2479 this._stack = stack;
2480 this._generatorFunction = generatorFunction;
2481 this._receiver = receiver;
2482 this._generator = undefined;
2483 this._yieldHandlers = typeof yieldHandler === "function"
2484 ? [yieldHandler].concat(yieldHandlers)
2485 : yieldHandlers;
2486 this._yieldedPromise = null;
2487 this._cancellationPhase = false;
2488}
2489util.inherits(PromiseSpawn, Proxyable);
2490
2491PromiseSpawn.prototype._isResolved = function() {
2492 return this._promise === null;
2493};
2494
2495PromiseSpawn.prototype._cleanup = function() {
2496 this._promise = this._generator = null;
2497 if (debug.cancellation() && this._finallyPromise !== null) {
2498 this._finallyPromise._fulfill();
2499 this._finallyPromise = null;
2500 }
2501};
2502
2503PromiseSpawn.prototype._promiseCancelled = function() {
2504 if (this._isResolved()) return;
2505 var implementsReturn = typeof this._generator["return"] !== "undefined";
2506
2507 var result;
2508 if (!implementsReturn) {
2509 var reason = new Promise.CancellationError(
2510 "generator .return() sentinel");
2511 Promise.coroutine.returnSentinel = reason;
2512 this._promise._attachExtraTrace(reason);
2513 this._promise._pushContext();
2514 result = tryCatch(this._generator["throw"]).call(this._generator,
2515 reason);
2516 this._promise._popContext();
2517 } else {
2518 this._promise._pushContext();
2519 result = tryCatch(this._generator["return"]).call(this._generator,
2520 undefined);
2521 this._promise._popContext();
2522 }
2523 this._cancellationPhase = true;
2524 this._yieldedPromise = null;
2525 this._continue(result);
2526};
2527
2528PromiseSpawn.prototype._promiseFulfilled = function(value) {
2529 this._yieldedPromise = null;
2530 this._promise._pushContext();
2531 var result = tryCatch(this._generator.next).call(this._generator, value);
2532 this._promise._popContext();
2533 this._continue(result);
2534};
2535
2536PromiseSpawn.prototype._promiseRejected = function(reason) {
2537 this._yieldedPromise = null;
2538 this._promise._attachExtraTrace(reason);
2539 this._promise._pushContext();
2540 var result = tryCatch(this._generator["throw"])
2541 .call(this._generator, reason);
2542 this._promise._popContext();
2543 this._continue(result);
2544};
2545
2546PromiseSpawn.prototype._resultCancelled = function() {
2547 if (this._yieldedPromise instanceof Promise) {
2548 var promise = this._yieldedPromise;
2549 this._yieldedPromise = null;
2550 promise.cancel();
2551 }
2552};
2553
2554PromiseSpawn.prototype.promise = function () {
2555 return this._promise;
2556};
2557
2558PromiseSpawn.prototype._run = function () {
2559 this._generator = this._generatorFunction.call(this._receiver);
2560 this._receiver =
2561 this._generatorFunction = undefined;
2562 this._promiseFulfilled(undefined);
2563};
2564
2565PromiseSpawn.prototype._continue = function (result) {
2566 var promise = this._promise;
2567 if (result === errorObj) {
2568 this._cleanup();
2569 if (this._cancellationPhase) {
2570 return promise.cancel();
2571 } else {
2572 return promise._rejectCallback(result.e, false);
2573 }
2574 }
2575
2576 var value = result.value;
2577 if (result.done === true) {
2578 this._cleanup();
2579 if (this._cancellationPhase) {
2580 return promise.cancel();
2581 } else {
2582 return promise._resolveCallback(value);
2583 }
2584 } else {
2585 var maybePromise = tryConvertToPromise(value, this._promise);
2586 if (!(maybePromise instanceof Promise)) {
2587 maybePromise =
2588 promiseFromYieldHandler(maybePromise,
2589 this._yieldHandlers,
2590 this._promise);
2591 if (maybePromise === null) {
2592 this._promiseRejected(
2593 new TypeError(
2594 "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) +
2595 "From coroutine:\u000a" +
2596 this._stack.split("\n").slice(1, -7).join("\n")
2597 )
2598 );
2599 return;
2600 }
2601 }
2602 maybePromise = maybePromise._target();
2603 var bitField = maybePromise._bitField;
2604 ;
2605 if (((bitField & 50397184) === 0)) {
2606 this._yieldedPromise = maybePromise;
2607 maybePromise._proxy(this, null);
2608 } else if (((bitField & 33554432) !== 0)) {
2609 Promise._async.invoke(
2610 this._promiseFulfilled, this, maybePromise._value()
2611 );
2612 } else if (((bitField & 16777216) !== 0)) {
2613 Promise._async.invoke(
2614 this._promiseRejected, this, maybePromise._reason()
2615 );
2616 } else {
2617 this._promiseCancelled();
2618 }
2619 }
2620};
2621
2622Promise.coroutine = function (generatorFunction, options) {
2623 if (typeof generatorFunction !== "function") {
2624 throw new TypeError("generatorFunction must be a function\u000a\u000a See http://goo.gl/MqrFmX\u000a");
2625 }
2626 var yieldHandler = Object(options).yieldHandler;
2627 var PromiseSpawn$ = PromiseSpawn;
2628 var stack = new Error().stack;
2629 return function () {
2630 var generator = generatorFunction.apply(this, arguments);
2631 var spawn = new PromiseSpawn$(undefined, undefined, yieldHandler,
2632 stack);
2633 var ret = spawn.promise();
2634 spawn._generator = generator;
2635 spawn._promiseFulfilled(undefined);
2636 return ret;
2637 };
2638};
2639
2640Promise.coroutine.addYieldHandler = function(fn) {
2641 if (typeof fn !== "function") {
2642 throw new TypeError("expecting a function but got " + util.classString(fn));
2643 }
2644 yieldHandlers.push(fn);
2645};
2646
2647Promise.spawn = function (generatorFunction) {
2648 debug.deprecated("Promise.spawn()", "Promise.coroutine()");
2649 if (typeof generatorFunction !== "function") {
2650 return apiRejection("generatorFunction must be a function\u000a\u000a See http://goo.gl/MqrFmX\u000a");
2651 }
2652 var spawn = new PromiseSpawn(generatorFunction, this);
2653 var ret = spawn.promise();
2654 spawn._run(Promise.spawn);
2655 return ret;
2656};
2657};
2658
2659},{"./errors":12,"./util":36}],17:[function(_dereq_,module,exports){
2660"use strict";
2661module.exports =
2662function(Promise, PromiseArray, tryConvertToPromise, INTERNAL, async,
2663 getDomain) {
2664var util = _dereq_("./util");
2665var canEvaluate = util.canEvaluate;
2666var tryCatch = util.tryCatch;
2667var errorObj = util.errorObj;
2668var reject;
2669
2670if (!true) {
2671if (canEvaluate) {
2672 var thenCallback = function(i) {
2673 return new Function("value", "holder", " \n\
2674 'use strict'; \n\
2675 holder.pIndex = value; \n\
2676 holder.checkFulfillment(this); \n\
2677 ".replace(/Index/g, i));
2678 };
2679
2680 var promiseSetter = function(i) {
2681 return new Function("promise", "holder", " \n\
2682 'use strict'; \n\
2683 holder.pIndex = promise; \n\
2684 ".replace(/Index/g, i));
2685 };
2686
2687 var generateHolderClass = function(total) {
2688 var props = new Array(total);
2689 for (var i = 0; i < props.length; ++i) {
2690 props[i] = "this.p" + (i+1);
2691 }
2692 var assignment = props.join(" = ") + " = null;";
2693 var cancellationCode= "var promise;\n" + props.map(function(prop) {
2694 return " \n\
2695 promise = " + prop + "; \n\
2696 if (promise instanceof Promise) { \n\
2697 promise.cancel(); \n\
2698 } \n\
2699 ";
2700 }).join("\n");
2701 var passedArguments = props.join(", ");
2702 var name = "Holder$" + total;
2703
2704
2705 var code = "return function(tryCatch, errorObj, Promise, async) { \n\
2706 'use strict'; \n\
2707 function [TheName](fn) { \n\
2708 [TheProperties] \n\
2709 this.fn = fn; \n\
2710 this.asyncNeeded = true; \n\
2711 this.now = 0; \n\
2712 } \n\
2713 \n\
2714 [TheName].prototype._callFunction = function(promise) { \n\
2715 promise._pushContext(); \n\
2716 var ret = tryCatch(this.fn)([ThePassedArguments]); \n\
2717 promise._popContext(); \n\
2718 if (ret === errorObj) { \n\
2719 promise._rejectCallback(ret.e, false); \n\
2720 } else { \n\
2721 promise._resolveCallback(ret); \n\
2722 } \n\
2723 }; \n\
2724 \n\
2725 [TheName].prototype.checkFulfillment = function(promise) { \n\
2726 var now = ++this.now; \n\
2727 if (now === [TheTotal]) { \n\
2728 if (this.asyncNeeded) { \n\
2729 async.invoke(this._callFunction, this, promise); \n\
2730 } else { \n\
2731 this._callFunction(promise); \n\
2732 } \n\
2733 \n\
2734 } \n\
2735 }; \n\
2736 \n\
2737 [TheName].prototype._resultCancelled = function() { \n\
2738 [CancellationCode] \n\
2739 }; \n\
2740 \n\
2741 return [TheName]; \n\
2742 }(tryCatch, errorObj, Promise, async); \n\
2743 ";
2744
2745 code = code.replace(/\[TheName\]/g, name)
2746 .replace(/\[TheTotal\]/g, total)
2747 .replace(/\[ThePassedArguments\]/g, passedArguments)
2748 .replace(/\[TheProperties\]/g, assignment)
2749 .replace(/\[CancellationCode\]/g, cancellationCode);
2750
2751 return new Function("tryCatch", "errorObj", "Promise", "async", code)
2752 (tryCatch, errorObj, Promise, async);
2753 };
2754
2755 var holderClasses = [];
2756 var thenCallbacks = [];
2757 var promiseSetters = [];
2758
2759 for (var i = 0; i < 8; ++i) {
2760 holderClasses.push(generateHolderClass(i + 1));
2761 thenCallbacks.push(thenCallback(i + 1));
2762 promiseSetters.push(promiseSetter(i + 1));
2763 }
2764
2765 reject = function (reason) {
2766 this._reject(reason);
2767 };
2768}}
2769
2770Promise.join = function () {
2771 var last = arguments.length - 1;
2772 var fn;
2773 if (last > 0 && typeof arguments[last] === "function") {
2774 fn = arguments[last];
2775 if (!true) {
2776 if (last <= 8 && canEvaluate) {
2777 var ret = new Promise(INTERNAL);
2778 ret._captureStackTrace();
2779 var HolderClass = holderClasses[last - 1];
2780 var holder = new HolderClass(fn);
2781 var callbacks = thenCallbacks;
2782
2783 for (var i = 0; i < last; ++i) {
2784 var maybePromise = tryConvertToPromise(arguments[i], ret);
2785 if (maybePromise instanceof Promise) {
2786 maybePromise = maybePromise._target();
2787 var bitField = maybePromise._bitField;
2788 ;
2789 if (((bitField & 50397184) === 0)) {
2790 maybePromise._then(callbacks[i], reject,
2791 undefined, ret, holder);
2792 promiseSetters[i](maybePromise, holder);
2793 holder.asyncNeeded = false;
2794 } else if (((bitField & 33554432) !== 0)) {
2795 callbacks[i].call(ret,
2796 maybePromise._value(), holder);
2797 } else if (((bitField & 16777216) !== 0)) {
2798 ret._reject(maybePromise._reason());
2799 } else {
2800 ret._cancel();
2801 }
2802 } else {
2803 callbacks[i].call(ret, maybePromise, holder);
2804 }
2805 }
2806
2807 if (!ret._isFateSealed()) {
2808 if (holder.asyncNeeded) {
2809 var domain = getDomain();
2810 if (domain !== null) {
2811 holder.fn = util.domainBind(domain, holder.fn);
2812 }
2813 }
2814 ret._setAsyncGuaranteed();
2815 ret._setOnCancel(holder);
2816 }
2817 return ret;
2818 }
2819 }
2820 }
2821 var args = [].slice.call(arguments);;
2822 if (fn) args.pop();
2823 var ret = new PromiseArray(args).promise();
2824 return fn !== undefined ? ret.spread(fn) : ret;
2825};
2826
2827};
2828
2829},{"./util":36}],18:[function(_dereq_,module,exports){
2830"use strict";
2831module.exports = function(Promise,
2832 PromiseArray,
2833 apiRejection,
2834 tryConvertToPromise,
2835 INTERNAL,
2836 debug) {
2837var getDomain = Promise._getDomain;
2838var util = _dereq_("./util");
2839var tryCatch = util.tryCatch;
2840var errorObj = util.errorObj;
2841var async = Promise._async;
2842
2843function MappingPromiseArray(promises, fn, limit, _filter) {
2844 this.constructor$(promises);
2845 this._promise._captureStackTrace();
2846 var domain = getDomain();
2847 this._callback = domain === null ? fn : util.domainBind(domain, fn);
2848 this._preservedValues = _filter === INTERNAL
2849 ? new Array(this.length())
2850 : null;
2851 this._limit = limit;
2852 this._inFlight = 0;
2853 this._queue = [];
2854 async.invoke(this._asyncInit, this, undefined);
2855}
2856util.inherits(MappingPromiseArray, PromiseArray);
2857
2858MappingPromiseArray.prototype._asyncInit = function() {
2859 this._init$(undefined, -2);
2860};
2861
2862MappingPromiseArray.prototype._init = function () {};
2863
2864MappingPromiseArray.prototype._promiseFulfilled = function (value, index) {
2865 var values = this._values;
2866 var length = this.length();
2867 var preservedValues = this._preservedValues;
2868 var limit = this._limit;
2869
2870 if (index < 0) {
2871 index = (index * -1) - 1;
2872 values[index] = value;
2873 if (limit >= 1) {
2874 this._inFlight--;
2875 this._drainQueue();
2876 if (this._isResolved()) return true;
2877 }
2878 } else {
2879 if (limit >= 1 && this._inFlight >= limit) {
2880 values[index] = value;
2881 this._queue.push(index);
2882 return false;
2883 }
2884 if (preservedValues !== null) preservedValues[index] = value;
2885
2886 var promise = this._promise;
2887 var callback = this._callback;
2888 var receiver = promise._boundValue();
2889 promise._pushContext();
2890 var ret = tryCatch(callback).call(receiver, value, index, length);
2891 var promiseCreated = promise._popContext();
2892 debug.checkForgottenReturns(
2893 ret,
2894 promiseCreated,
2895 preservedValues !== null ? "Promise.filter" : "Promise.map",
2896 promise
2897 );
2898 if (ret === errorObj) {
2899 this._reject(ret.e);
2900 return true;
2901 }
2902
2903 var maybePromise = tryConvertToPromise(ret, this._promise);
2904 if (maybePromise instanceof Promise) {
2905 maybePromise = maybePromise._target();
2906 var bitField = maybePromise._bitField;
2907 ;
2908 if (((bitField & 50397184) === 0)) {
2909 if (limit >= 1) this._inFlight++;
2910 values[index] = maybePromise;
2911 maybePromise._proxy(this, (index + 1) * -1);
2912 return false;
2913 } else if (((bitField & 33554432) !== 0)) {
2914 ret = maybePromise._value();
2915 } else if (((bitField & 16777216) !== 0)) {
2916 this._reject(maybePromise._reason());
2917 return true;
2918 } else {
2919 this._cancel();
2920 return true;
2921 }
2922 }
2923 values[index] = ret;
2924 }
2925 var totalResolved = ++this._totalResolved;
2926 if (totalResolved >= length) {
2927 if (preservedValues !== null) {
2928 this._filter(values, preservedValues);
2929 } else {
2930 this._resolve(values);
2931 }
2932 return true;
2933 }
2934 return false;
2935};
2936
2937MappingPromiseArray.prototype._drainQueue = function () {
2938 var queue = this._queue;
2939 var limit = this._limit;
2940 var values = this._values;
2941 while (queue.length > 0 && this._inFlight < limit) {
2942 if (this._isResolved()) return;
2943 var index = queue.pop();
2944 this._promiseFulfilled(values[index], index);
2945 }
2946};
2947
2948MappingPromiseArray.prototype._filter = function (booleans, values) {
2949 var len = values.length;
2950 var ret = new Array(len);
2951 var j = 0;
2952 for (var i = 0; i < len; ++i) {
2953 if (booleans[i]) ret[j++] = values[i];
2954 }
2955 ret.length = j;
2956 this._resolve(ret);
2957};
2958
2959MappingPromiseArray.prototype.preservedValues = function () {
2960 return this._preservedValues;
2961};
2962
2963function map(promises, fn, options, _filter) {
2964 if (typeof fn !== "function") {
2965 return apiRejection("expecting a function but got " + util.classString(fn));
2966 }
2967
2968 var limit = 0;
2969 if (options !== undefined) {
2970 if (typeof options === "object" && options !== null) {
2971 if (typeof options.concurrency !== "number") {
2972 return Promise.reject(
2973 new TypeError("'concurrency' must be a number but it is " +
2974 util.classString(options.concurrency)));
2975 }
2976 limit = options.concurrency;
2977 } else {
2978 return Promise.reject(new TypeError(
2979 "options argument must be an object but it is " +
2980 util.classString(options)));
2981 }
2982 }
2983 limit = typeof limit === "number" &&
2984 isFinite(limit) && limit >= 1 ? limit : 0;
2985 return new MappingPromiseArray(promises, fn, limit, _filter).promise();
2986}
2987
2988Promise.prototype.map = function (fn, options) {
2989 return map(this, fn, options, null);
2990};
2991
2992Promise.map = function (promises, fn, options, _filter) {
2993 return map(promises, fn, options, _filter);
2994};
2995
2996
2997};
2998
2999},{"./util":36}],19:[function(_dereq_,module,exports){
3000"use strict";
3001module.exports =
3002function(Promise, INTERNAL, tryConvertToPromise, apiRejection, debug) {
3003var util = _dereq_("./util");
3004var tryCatch = util.tryCatch;
3005
3006Promise.method = function (fn) {
3007 if (typeof fn !== "function") {
3008 throw new Promise.TypeError("expecting a function but got " + util.classString(fn));
3009 }
3010 return function () {
3011 var ret = new Promise(INTERNAL);
3012 ret._captureStackTrace();
3013 ret._pushContext();
3014 var value = tryCatch(fn).apply(this, arguments);
3015 var promiseCreated = ret._popContext();
3016 debug.checkForgottenReturns(
3017 value, promiseCreated, "Promise.method", ret);
3018 ret._resolveFromSyncValue(value);
3019 return ret;
3020 };
3021};
3022
3023Promise.attempt = Promise["try"] = function (fn) {
3024 if (typeof fn !== "function") {
3025 return apiRejection("expecting a function but got " + util.classString(fn));
3026 }
3027 var ret = new Promise(INTERNAL);
3028 ret._captureStackTrace();
3029 ret._pushContext();
3030 var value;
3031 if (arguments.length > 1) {
3032 debug.deprecated("calling Promise.try with more than 1 argument");
3033 var arg = arguments[1];
3034 var ctx = arguments[2];
3035 value = util.isArray(arg) ? tryCatch(fn).apply(ctx, arg)
3036 : tryCatch(fn).call(ctx, arg);
3037 } else {
3038 value = tryCatch(fn)();
3039 }
3040 var promiseCreated = ret._popContext();
3041 debug.checkForgottenReturns(
3042 value, promiseCreated, "Promise.try", ret);
3043 ret._resolveFromSyncValue(value);
3044 return ret;
3045};
3046
3047Promise.prototype._resolveFromSyncValue = function (value) {
3048 if (value === util.errorObj) {
3049 this._rejectCallback(value.e, false);
3050 } else {
3051 this._resolveCallback(value, true);
3052 }
3053};
3054};
3055
3056},{"./util":36}],20:[function(_dereq_,module,exports){
3057"use strict";
3058var util = _dereq_("./util");
3059var maybeWrapAsError = util.maybeWrapAsError;
3060var errors = _dereq_("./errors");
3061var OperationalError = errors.OperationalError;
3062var es5 = _dereq_("./es5");
3063
3064function isUntypedError(obj) {
3065 return obj instanceof Error &&
3066 es5.getPrototypeOf(obj) === Error.prototype;
3067}
3068
3069var rErrorKey = /^(?:name|message|stack|cause)$/;
3070function wrapAsOperationalError(obj) {
3071 var ret;
3072 if (isUntypedError(obj)) {
3073 ret = new OperationalError(obj);
3074 ret.name = obj.name;
3075 ret.message = obj.message;
3076 ret.stack = obj.stack;
3077 var keys = es5.keys(obj);
3078 for (var i = 0; i < keys.length; ++i) {
3079 var key = keys[i];
3080 if (!rErrorKey.test(key)) {
3081 ret[key] = obj[key];
3082 }
3083 }
3084 return ret;
3085 }
3086 util.markAsOriginatingFromRejection(obj);
3087 return obj;
3088}
3089
3090function nodebackForPromise(promise, multiArgs) {
3091 return function(err, value) {
3092 if (promise === null) return;
3093 if (err) {
3094 var wrapped = wrapAsOperationalError(maybeWrapAsError(err));
3095 promise._attachExtraTrace(wrapped);
3096 promise._reject(wrapped);
3097 } else if (!multiArgs) {
3098 promise._fulfill(value);
3099 } else {
3100 var args = [].slice.call(arguments, 1);;
3101 promise._fulfill(args);
3102 }
3103 promise = null;
3104 };
3105}
3106
3107module.exports = nodebackForPromise;
3108
3109},{"./errors":12,"./es5":13,"./util":36}],21:[function(_dereq_,module,exports){
3110"use strict";
3111module.exports = function(Promise) {
3112var util = _dereq_("./util");
3113var async = Promise._async;
3114var tryCatch = util.tryCatch;
3115var errorObj = util.errorObj;
3116
3117function spreadAdapter(val, nodeback) {
3118 var promise = this;
3119 if (!util.isArray(val)) return successAdapter.call(promise, val, nodeback);
3120 var ret =
3121 tryCatch(nodeback).apply(promise._boundValue(), [null].concat(val));
3122 if (ret === errorObj) {
3123 async.throwLater(ret.e);
3124 }
3125}
3126
3127function successAdapter(val, nodeback) {
3128 var promise = this;
3129 var receiver = promise._boundValue();
3130 var ret = val === undefined
3131 ? tryCatch(nodeback).call(receiver, null)
3132 : tryCatch(nodeback).call(receiver, null, val);
3133 if (ret === errorObj) {
3134 async.throwLater(ret.e);
3135 }
3136}
3137function errorAdapter(reason, nodeback) {
3138 var promise = this;
3139 if (!reason) {
3140 var newReason = new Error(reason + "");
3141 newReason.cause = reason;
3142 reason = newReason;
3143 }
3144 var ret = tryCatch(nodeback).call(promise._boundValue(), reason);
3145 if (ret === errorObj) {
3146 async.throwLater(ret.e);
3147 }
3148}
3149
3150Promise.prototype.asCallback = Promise.prototype.nodeify = function (nodeback,
3151 options) {
3152 if (typeof nodeback == "function") {
3153 var adapter = successAdapter;
3154 if (options !== undefined && Object(options).spread) {
3155 adapter = spreadAdapter;
3156 }
3157 this._then(
3158 adapter,
3159 errorAdapter,
3160 undefined,
3161 this,
3162 nodeback
3163 );
3164 }
3165 return this;
3166};
3167};
3168
3169},{"./util":36}],22:[function(_dereq_,module,exports){
3170"use strict";
3171module.exports = function() {
3172var makeSelfResolutionError = function () {
3173 return new TypeError("circular promise resolution chain\u000a\u000a See http://goo.gl/MqrFmX\u000a");
3174};
3175var reflectHandler = function() {
3176 return new Promise.PromiseInspection(this._target());
3177};
3178var apiRejection = function(msg) {
3179 return Promise.reject(new TypeError(msg));
3180};
3181function Proxyable() {}
3182var UNDEFINED_BINDING = {};
3183var util = _dereq_("./util");
3184
3185var getDomain;
3186if (util.isNode) {
3187 getDomain = function() {
3188 var ret = process.domain;
3189 if (ret === undefined) ret = null;
3190 return ret;
3191 };
3192} else {
3193 getDomain = function() {
3194 return null;
3195 };
3196}
3197util.notEnumerableProp(Promise, "_getDomain", getDomain);
3198
3199var es5 = _dereq_("./es5");
3200var Async = _dereq_("./async");
3201var async = new Async();
3202es5.defineProperty(Promise, "_async", {value: async});
3203var errors = _dereq_("./errors");
3204var TypeError = Promise.TypeError = errors.TypeError;
3205Promise.RangeError = errors.RangeError;
3206var CancellationError = Promise.CancellationError = errors.CancellationError;
3207Promise.TimeoutError = errors.TimeoutError;
3208Promise.OperationalError = errors.OperationalError;
3209Promise.RejectionError = errors.OperationalError;
3210Promise.AggregateError = errors.AggregateError;
3211var INTERNAL = function(){};
3212var APPLY = {};
3213var NEXT_FILTER = {};
3214var tryConvertToPromise = _dereq_("./thenables")(Promise, INTERNAL);
3215var PromiseArray =
3216 _dereq_("./promise_array")(Promise, INTERNAL,
3217 tryConvertToPromise, apiRejection, Proxyable);
3218var Context = _dereq_("./context")(Promise);
3219 /*jshint unused:false*/
3220var createContext = Context.create;
3221var debug = _dereq_("./debuggability")(Promise, Context);
3222var CapturedTrace = debug.CapturedTrace;
3223var PassThroughHandlerContext =
3224 _dereq_("./finally")(Promise, tryConvertToPromise);
3225var catchFilter = _dereq_("./catch_filter")(NEXT_FILTER);
3226var nodebackForPromise = _dereq_("./nodeback");
3227var errorObj = util.errorObj;
3228var tryCatch = util.tryCatch;
3229function check(self, executor) {
3230 if (typeof executor !== "function") {
3231 throw new TypeError("expecting a function but got " + util.classString(executor));
3232 }
3233 if (self.constructor !== Promise) {
3234 throw new TypeError("the promise constructor cannot be invoked directly\u000a\u000a See http://goo.gl/MqrFmX\u000a");
3235 }
3236}
3237
3238function Promise(executor) {
3239 this._bitField = 0;
3240 this._fulfillmentHandler0 = undefined;
3241 this._rejectionHandler0 = undefined;
3242 this._promise0 = undefined;
3243 this._receiver0 = undefined;
3244 if (executor !== INTERNAL) {
3245 check(this, executor);
3246 this._resolveFromExecutor(executor);
3247 }
3248 this._promiseCreated();
3249 this._fireEvent("promiseCreated", this);
3250}
3251
3252Promise.prototype.toString = function () {
3253 return "[object Promise]";
3254};
3255
3256Promise.prototype.caught = Promise.prototype["catch"] = function (fn) {
3257 var len = arguments.length;
3258 if (len > 1) {
3259 var catchInstances = new Array(len - 1),
3260 j = 0, i;
3261 for (i = 0; i < len - 1; ++i) {
3262 var item = arguments[i];
3263 if (util.isObject(item)) {
3264 catchInstances[j++] = item;
3265 } else {
3266 return apiRejection("expecting an object but got " +
3267 "A catch statement predicate " + util.classString(item));
3268 }
3269 }
3270 catchInstances.length = j;
3271 fn = arguments[i];
3272 return this.then(undefined, catchFilter(catchInstances, fn, this));
3273 }
3274 return this.then(undefined, fn);
3275};
3276
3277Promise.prototype.reflect = function () {
3278 return this._then(reflectHandler,
3279 reflectHandler, undefined, this, undefined);
3280};
3281
3282Promise.prototype.then = function (didFulfill, didReject) {
3283 if (debug.warnings() && arguments.length > 0 &&
3284 typeof didFulfill !== "function" &&
3285 typeof didReject !== "function") {
3286 var msg = ".then() only accepts functions but was passed: " +
3287 util.classString(didFulfill);
3288 if (arguments.length > 1) {
3289 msg += ", " + util.classString(didReject);
3290 }
3291 this._warn(msg);
3292 }
3293 return this._then(didFulfill, didReject, undefined, undefined, undefined);
3294};
3295
3296Promise.prototype.done = function (didFulfill, didReject) {
3297 var promise =
3298 this._then(didFulfill, didReject, undefined, undefined, undefined);
3299 promise._setIsFinal();
3300};
3301
3302Promise.prototype.spread = function (fn) {
3303 if (typeof fn !== "function") {
3304 return apiRejection("expecting a function but got " + util.classString(fn));
3305 }
3306 return this.all()._then(fn, undefined, undefined, APPLY, undefined);
3307};
3308
3309Promise.prototype.toJSON = function () {
3310 var ret = {
3311 isFulfilled: false,
3312 isRejected: false,
3313 fulfillmentValue: undefined,
3314 rejectionReason: undefined
3315 };
3316 if (this.isFulfilled()) {
3317 ret.fulfillmentValue = this.value();
3318 ret.isFulfilled = true;
3319 } else if (this.isRejected()) {
3320 ret.rejectionReason = this.reason();
3321 ret.isRejected = true;
3322 }
3323 return ret;
3324};
3325
3326Promise.prototype.all = function () {
3327 if (arguments.length > 0) {
3328 this._warn(".all() was passed arguments but it does not take any");
3329 }
3330 return new PromiseArray(this).promise();
3331};
3332
3333Promise.prototype.error = function (fn) {
3334 return this.caught(util.originatesFromRejection, fn);
3335};
3336
3337Promise.getNewLibraryCopy = module.exports;
3338
3339Promise.is = function (val) {
3340 return val instanceof Promise;
3341};
3342
3343Promise.fromNode = Promise.fromCallback = function(fn) {
3344 var ret = new Promise(INTERNAL);
3345 ret._captureStackTrace();
3346 var multiArgs = arguments.length > 1 ? !!Object(arguments[1]).multiArgs
3347 : false;
3348 var result = tryCatch(fn)(nodebackForPromise(ret, multiArgs));
3349 if (result === errorObj) {
3350 ret._rejectCallback(result.e, true);
3351 }
3352 if (!ret._isFateSealed()) ret._setAsyncGuaranteed();
3353 return ret;
3354};
3355
3356Promise.all = function (promises) {
3357 return new PromiseArray(promises).promise();
3358};
3359
3360Promise.cast = function (obj) {
3361 var ret = tryConvertToPromise(obj);
3362 if (!(ret instanceof Promise)) {
3363 ret = new Promise(INTERNAL);
3364 ret._captureStackTrace();
3365 ret._setFulfilled();
3366 ret._rejectionHandler0 = obj;
3367 }
3368 return ret;
3369};
3370
3371Promise.resolve = Promise.fulfilled = Promise.cast;
3372
3373Promise.reject = Promise.rejected = function (reason) {
3374 var ret = new Promise(INTERNAL);
3375 ret._captureStackTrace();
3376 ret._rejectCallback(reason, true);
3377 return ret;
3378};
3379
3380Promise.setScheduler = function(fn) {
3381 if (typeof fn !== "function") {
3382 throw new TypeError("expecting a function but got " + util.classString(fn));
3383 }
3384 return async.setScheduler(fn);
3385};
3386
3387Promise.prototype._then = function (
3388 didFulfill,
3389 didReject,
3390 _, receiver,
3391 internalData
3392) {
3393 var haveInternalData = internalData !== undefined;
3394 var promise = haveInternalData ? internalData : new Promise(INTERNAL);
3395 var target = this._target();
3396 var bitField = target._bitField;
3397
3398 if (!haveInternalData) {
3399 promise._propagateFrom(this, 3);
3400 promise._captureStackTrace();
3401 if (receiver === undefined &&
3402 ((this._bitField & 2097152) !== 0)) {
3403 if (!((bitField & 50397184) === 0)) {
3404 receiver = this._boundValue();
3405 } else {
3406 receiver = target === this ? undefined : this._boundTo;
3407 }
3408 }
3409 this._fireEvent("promiseChained", this, promise);
3410 }
3411
3412 var domain = getDomain();
3413 if (!((bitField & 50397184) === 0)) {
3414 var handler, value, settler = target._settlePromiseCtx;
3415 if (((bitField & 33554432) !== 0)) {
3416 value = target._rejectionHandler0;
3417 handler = didFulfill;
3418 } else if (((bitField & 16777216) !== 0)) {
3419 value = target._fulfillmentHandler0;
3420 handler = didReject;
3421 target._unsetRejectionIsUnhandled();
3422 } else {
3423 settler = target._settlePromiseLateCancellationObserver;
3424 value = new CancellationError("late cancellation observer");
3425 target._attachExtraTrace(value);
3426 handler = didReject;
3427 }
3428
3429 async.invoke(settler, target, {
3430 handler: domain === null ? handler
3431 : (typeof handler === "function" &&
3432 util.domainBind(domain, handler)),
3433 promise: promise,
3434 receiver: receiver,
3435 value: value
3436 });
3437 } else {
3438 target._addCallbacks(didFulfill, didReject, promise, receiver, domain);
3439 }
3440
3441 return promise;
3442};
3443
3444Promise.prototype._length = function () {
3445 return this._bitField & 65535;
3446};
3447
3448Promise.prototype._isFateSealed = function () {
3449 return (this._bitField & 117506048) !== 0;
3450};
3451
3452Promise.prototype._isFollowing = function () {
3453 return (this._bitField & 67108864) === 67108864;
3454};
3455
3456Promise.prototype._setLength = function (len) {
3457 this._bitField = (this._bitField & -65536) |
3458 (len & 65535);
3459};
3460
3461Promise.prototype._setFulfilled = function () {
3462 this._bitField = this._bitField | 33554432;
3463 this._fireEvent("promiseFulfilled", this);
3464};
3465
3466Promise.prototype._setRejected = function () {
3467 this._bitField = this._bitField | 16777216;
3468 this._fireEvent("promiseRejected", this);
3469};
3470
3471Promise.prototype._setFollowing = function () {
3472 this._bitField = this._bitField | 67108864;
3473 this._fireEvent("promiseResolved", this);
3474};
3475
3476Promise.prototype._setIsFinal = function () {
3477 this._bitField = this._bitField | 4194304;
3478};
3479
3480Promise.prototype._isFinal = function () {
3481 return (this._bitField & 4194304) > 0;
3482};
3483
3484Promise.prototype._unsetCancelled = function() {
3485 this._bitField = this._bitField & (~65536);
3486};
3487
3488Promise.prototype._setCancelled = function() {
3489 this._bitField = this._bitField | 65536;
3490 this._fireEvent("promiseCancelled", this);
3491};
3492
3493Promise.prototype._setWillBeCancelled = function() {
3494 this._bitField = this._bitField | 8388608;
3495};
3496
3497Promise.prototype._setAsyncGuaranteed = function() {
3498 if (async.hasCustomScheduler()) return;
3499 this._bitField = this._bitField | 134217728;
3500};
3501
3502Promise.prototype._receiverAt = function (index) {
3503 var ret = index === 0 ? this._receiver0 : this[
3504 index * 4 - 4 + 3];
3505 if (ret === UNDEFINED_BINDING) {
3506 return undefined;
3507 } else if (ret === undefined && this._isBound()) {
3508 return this._boundValue();
3509 }
3510 return ret;
3511};
3512
3513Promise.prototype._promiseAt = function (index) {
3514 return this[
3515 index * 4 - 4 + 2];
3516};
3517
3518Promise.prototype._fulfillmentHandlerAt = function (index) {
3519 return this[
3520 index * 4 - 4 + 0];
3521};
3522
3523Promise.prototype._rejectionHandlerAt = function (index) {
3524 return this[
3525 index * 4 - 4 + 1];
3526};
3527
3528Promise.prototype._boundValue = function() {};
3529
3530Promise.prototype._migrateCallback0 = function (follower) {
3531 var bitField = follower._bitField;
3532 var fulfill = follower._fulfillmentHandler0;
3533 var reject = follower._rejectionHandler0;
3534 var promise = follower._promise0;
3535 var receiver = follower._receiverAt(0);
3536 if (receiver === undefined) receiver = UNDEFINED_BINDING;
3537 this._addCallbacks(fulfill, reject, promise, receiver, null);
3538};
3539
3540Promise.prototype._migrateCallbackAt = function (follower, index) {
3541 var fulfill = follower._fulfillmentHandlerAt(index);
3542 var reject = follower._rejectionHandlerAt(index);
3543 var promise = follower._promiseAt(index);
3544 var receiver = follower._receiverAt(index);
3545 if (receiver === undefined) receiver = UNDEFINED_BINDING;
3546 this._addCallbacks(fulfill, reject, promise, receiver, null);
3547};
3548
3549Promise.prototype._addCallbacks = function (
3550 fulfill,
3551 reject,
3552 promise,
3553 receiver,
3554 domain
3555) {
3556 var index = this._length();
3557
3558 if (index >= 65535 - 4) {
3559 index = 0;
3560 this._setLength(0);
3561 }
3562
3563 if (index === 0) {
3564 this._promise0 = promise;
3565 this._receiver0 = receiver;
3566 if (typeof fulfill === "function") {
3567 this._fulfillmentHandler0 =
3568 domain === null ? fulfill : util.domainBind(domain, fulfill);
3569 }
3570 if (typeof reject === "function") {
3571 this._rejectionHandler0 =
3572 domain === null ? reject : util.domainBind(domain, reject);
3573 }
3574 } else {
3575 var base = index * 4 - 4;
3576 this[base + 2] = promise;
3577 this[base + 3] = receiver;
3578 if (typeof fulfill === "function") {
3579 this[base + 0] =
3580 domain === null ? fulfill : util.domainBind(domain, fulfill);
3581 }
3582 if (typeof reject === "function") {
3583 this[base + 1] =
3584 domain === null ? reject : util.domainBind(domain, reject);
3585 }
3586 }
3587 this._setLength(index + 1);
3588 return index;
3589};
3590
3591Promise.prototype._proxy = function (proxyable, arg) {
3592 this._addCallbacks(undefined, undefined, arg, proxyable, null);
3593};
3594
3595Promise.prototype._resolveCallback = function(value, shouldBind) {
3596 if (((this._bitField & 117506048) !== 0)) return;
3597 if (value === this)
3598 return this._rejectCallback(makeSelfResolutionError(), false);
3599 var maybePromise = tryConvertToPromise(value, this);
3600 if (!(maybePromise instanceof Promise)) return this._fulfill(value);
3601
3602 if (shouldBind) this._propagateFrom(maybePromise, 2);
3603
3604 var promise = maybePromise._target();
3605
3606 if (promise === this) {
3607 this._reject(makeSelfResolutionError());
3608 return;
3609 }
3610
3611 var bitField = promise._bitField;
3612 if (((bitField & 50397184) === 0)) {
3613 var len = this._length();
3614 if (len > 0) promise._migrateCallback0(this);
3615 for (var i = 1; i < len; ++i) {
3616 promise._migrateCallbackAt(this, i);
3617 }
3618 this._setFollowing();
3619 this._setLength(0);
3620 this._setFollowee(promise);
3621 } else if (((bitField & 33554432) !== 0)) {
3622 this._fulfill(promise._value());
3623 } else if (((bitField & 16777216) !== 0)) {
3624 this._reject(promise._reason());
3625 } else {
3626 var reason = new CancellationError("late cancellation observer");
3627 promise._attachExtraTrace(reason);
3628 this._reject(reason);
3629 }
3630};
3631
3632Promise.prototype._rejectCallback =
3633function(reason, synchronous, ignoreNonErrorWarnings) {
3634 var trace = util.ensureErrorObject(reason);
3635 var hasStack = trace === reason;
3636 if (!hasStack && !ignoreNonErrorWarnings && debug.warnings()) {
3637 var message = "a promise was rejected with a non-error: " +
3638 util.classString(reason);
3639 this._warn(message, true);
3640 }
3641 this._attachExtraTrace(trace, synchronous ? hasStack : false);
3642 this._reject(reason);
3643};
3644
3645Promise.prototype._resolveFromExecutor = function (executor) {
3646 var promise = this;
3647 this._captureStackTrace();
3648 this._pushContext();
3649 var synchronous = true;
3650 var r = this._execute(executor, function(value) {
3651 promise._resolveCallback(value);
3652 }, function (reason) {
3653 promise._rejectCallback(reason, synchronous);
3654 });
3655 synchronous = false;
3656 this._popContext();
3657
3658 if (r !== undefined) {
3659 promise._rejectCallback(r, true);
3660 }
3661};
3662
3663Promise.prototype._settlePromiseFromHandler = function (
3664 handler, receiver, value, promise
3665) {
3666 var bitField = promise._bitField;
3667 if (((bitField & 65536) !== 0)) return;
3668 promise._pushContext();
3669 var x;
3670 if (receiver === APPLY) {
3671 if (!value || typeof value.length !== "number") {
3672 x = errorObj;
3673 x.e = new TypeError("cannot .spread() a non-array: " +
3674 util.classString(value));
3675 } else {
3676 x = tryCatch(handler).apply(this._boundValue(), value);
3677 }
3678 } else {
3679 x = tryCatch(handler).call(receiver, value);
3680 }
3681 var promiseCreated = promise._popContext();
3682 bitField = promise._bitField;
3683 if (((bitField & 65536) !== 0)) return;
3684
3685 if (x === NEXT_FILTER) {
3686 promise._reject(value);
3687 } else if (x === errorObj) {
3688 promise._rejectCallback(x.e, false);
3689 } else {
3690 debug.checkForgottenReturns(x, promiseCreated, "", promise, this);
3691 promise._resolveCallback(x);
3692 }
3693};
3694
3695Promise.prototype._target = function() {
3696 var ret = this;
3697 while (ret._isFollowing()) ret = ret._followee();
3698 return ret;
3699};
3700
3701Promise.prototype._followee = function() {
3702 return this._rejectionHandler0;
3703};
3704
3705Promise.prototype._setFollowee = function(promise) {
3706 this._rejectionHandler0 = promise;
3707};
3708
3709Promise.prototype._settlePromise = function(promise, handler, receiver, value) {
3710 var isPromise = promise instanceof Promise;
3711 var bitField = this._bitField;
3712 var asyncGuaranteed = ((bitField & 134217728) !== 0);
3713 if (((bitField & 65536) !== 0)) {
3714 if (isPromise) promise._invokeInternalOnCancel();
3715
3716 if (receiver instanceof PassThroughHandlerContext &&
3717 receiver.isFinallyHandler()) {
3718 receiver.cancelPromise = promise;
3719 if (tryCatch(handler).call(receiver, value) === errorObj) {
3720 promise._reject(errorObj.e);
3721 }
3722 } else if (handler === reflectHandler) {
3723 promise._fulfill(reflectHandler.call(receiver));
3724 } else if (receiver instanceof Proxyable) {
3725 receiver._promiseCancelled(promise);
3726 } else if (isPromise || promise instanceof PromiseArray) {
3727 promise._cancel();
3728 } else {
3729 receiver.cancel();
3730 }
3731 } else if (typeof handler === "function") {
3732 if (!isPromise) {
3733 handler.call(receiver, value, promise);
3734 } else {
3735 if (asyncGuaranteed) promise._setAsyncGuaranteed();
3736 this._settlePromiseFromHandler(handler, receiver, value, promise);
3737 }
3738 } else if (receiver instanceof Proxyable) {
3739 if (!receiver._isResolved()) {
3740 if (((bitField & 33554432) !== 0)) {
3741 receiver._promiseFulfilled(value, promise);
3742 } else {
3743 receiver._promiseRejected(value, promise);
3744 }
3745 }
3746 } else if (isPromise) {
3747 if (asyncGuaranteed) promise._setAsyncGuaranteed();
3748 if (((bitField & 33554432) !== 0)) {
3749 promise._fulfill(value);
3750 } else {
3751 promise._reject(value);
3752 }
3753 }
3754};
3755
3756Promise.prototype._settlePromiseLateCancellationObserver = function(ctx) {
3757 var handler = ctx.handler;
3758 var promise = ctx.promise;
3759 var receiver = ctx.receiver;
3760 var value = ctx.value;
3761 if (typeof handler === "function") {
3762 if (!(promise instanceof Promise)) {
3763 handler.call(receiver, value, promise);
3764 } else {
3765 this._settlePromiseFromHandler(handler, receiver, value, promise);
3766 }
3767 } else if (promise instanceof Promise) {
3768 promise._reject(value);
3769 }
3770};
3771
3772Promise.prototype._settlePromiseCtx = function(ctx) {
3773 this._settlePromise(ctx.promise, ctx.handler, ctx.receiver, ctx.value);
3774};
3775
3776Promise.prototype._settlePromise0 = function(handler, value, bitField) {
3777 var promise = this._promise0;
3778 var receiver = this._receiverAt(0);
3779 this._promise0 = undefined;
3780 this._receiver0 = undefined;
3781 this._settlePromise(promise, handler, receiver, value);
3782};
3783
3784Promise.prototype._clearCallbackDataAtIndex = function(index) {
3785 var base = index * 4 - 4;
3786 this[base + 2] =
3787 this[base + 3] =
3788 this[base + 0] =
3789 this[base + 1] = undefined;
3790};
3791
3792Promise.prototype._fulfill = function (value) {
3793 var bitField = this._bitField;
3794 if (((bitField & 117506048) >>> 16)) return;
3795 if (value === this) {
3796 var err = makeSelfResolutionError();
3797 this._attachExtraTrace(err);
3798 return this._reject(err);
3799 }
3800 this._setFulfilled();
3801 this._rejectionHandler0 = value;
3802
3803 if ((bitField & 65535) > 0) {
3804 if (((bitField & 134217728) !== 0)) {
3805 this._settlePromises();
3806 } else {
3807 async.settlePromises(this);
3808 }
3809 }
3810};
3811
3812Promise.prototype._reject = function (reason) {
3813 var bitField = this._bitField;
3814 if (((bitField & 117506048) >>> 16)) return;
3815 this._setRejected();
3816 this._fulfillmentHandler0 = reason;
3817
3818 if (this._isFinal()) {
3819 return async.fatalError(reason, util.isNode);
3820 }
3821
3822 if ((bitField & 65535) > 0) {
3823 async.settlePromises(this);
3824 } else {
3825 this._ensurePossibleRejectionHandled();
3826 }
3827};
3828
3829Promise.prototype._fulfillPromises = function (len, value) {
3830 for (var i = 1; i < len; i++) {
3831 var handler = this._fulfillmentHandlerAt(i);
3832 var promise = this._promiseAt(i);
3833 var receiver = this._receiverAt(i);
3834 this._clearCallbackDataAtIndex(i);
3835 this._settlePromise(promise, handler, receiver, value);
3836 }
3837};
3838
3839Promise.prototype._rejectPromises = function (len, reason) {
3840 for (var i = 1; i < len; i++) {
3841 var handler = this._rejectionHandlerAt(i);
3842 var promise = this._promiseAt(i);
3843 var receiver = this._receiverAt(i);
3844 this._clearCallbackDataAtIndex(i);
3845 this._settlePromise(promise, handler, receiver, reason);
3846 }
3847};
3848
3849Promise.prototype._settlePromises = function () {
3850 var bitField = this._bitField;
3851 var len = (bitField & 65535);
3852
3853 if (len > 0) {
3854 if (((bitField & 16842752) !== 0)) {
3855 var reason = this._fulfillmentHandler0;
3856 this._settlePromise0(this._rejectionHandler0, reason, bitField);
3857 this._rejectPromises(len, reason);
3858 } else {
3859 var value = this._rejectionHandler0;
3860 this._settlePromise0(this._fulfillmentHandler0, value, bitField);
3861 this._fulfillPromises(len, value);
3862 }
3863 this._setLength(0);
3864 }
3865 this._clearCancellationData();
3866};
3867
3868Promise.prototype._settledValue = function() {
3869 var bitField = this._bitField;
3870 if (((bitField & 33554432) !== 0)) {
3871 return this._rejectionHandler0;
3872 } else if (((bitField & 16777216) !== 0)) {
3873 return this._fulfillmentHandler0;
3874 }
3875};
3876
3877function deferResolve(v) {this.promise._resolveCallback(v);}
3878function deferReject(v) {this.promise._rejectCallback(v, false);}
3879
3880Promise.defer = Promise.pending = function() {
3881 debug.deprecated("Promise.defer", "new Promise");
3882 var promise = new Promise(INTERNAL);
3883 return {
3884 promise: promise,
3885 resolve: deferResolve,
3886 reject: deferReject
3887 };
3888};
3889
3890util.notEnumerableProp(Promise,
3891 "_makeSelfResolutionError",
3892 makeSelfResolutionError);
3893
3894_dereq_("./method")(Promise, INTERNAL, tryConvertToPromise, apiRejection,
3895 debug);
3896_dereq_("./bind")(Promise, INTERNAL, tryConvertToPromise, debug);
3897_dereq_("./cancel")(Promise, PromiseArray, apiRejection, debug);
3898_dereq_("./direct_resolve")(Promise);
3899_dereq_("./synchronous_inspection")(Promise);
3900_dereq_("./join")(
3901 Promise, PromiseArray, tryConvertToPromise, INTERNAL, async, getDomain);
3902Promise.Promise = Promise;
3903Promise.version = "3.4.6";
3904_dereq_('./map.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug);
3905_dereq_('./call_get.js')(Promise);
3906_dereq_('./using.js')(Promise, apiRejection, tryConvertToPromise, createContext, INTERNAL, debug);
3907_dereq_('./timers.js')(Promise, INTERNAL, debug);
3908_dereq_('./generators.js')(Promise, apiRejection, INTERNAL, tryConvertToPromise, Proxyable, debug);
3909_dereq_('./nodeify.js')(Promise);
3910_dereq_('./promisify.js')(Promise, INTERNAL);
3911_dereq_('./props.js')(Promise, PromiseArray, tryConvertToPromise, apiRejection);
3912_dereq_('./race.js')(Promise, INTERNAL, tryConvertToPromise, apiRejection);
3913_dereq_('./reduce.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug);
3914_dereq_('./settle.js')(Promise, PromiseArray, debug);
3915_dereq_('./some.js')(Promise, PromiseArray, apiRejection);
3916_dereq_('./filter.js')(Promise, INTERNAL);
3917_dereq_('./each.js')(Promise, INTERNAL);
3918_dereq_('./any.js')(Promise);
3919
3920 util.toFastProperties(Promise);
3921 util.toFastProperties(Promise.prototype);
3922 function fillTypes(value) {
3923 var p = new Promise(INTERNAL);
3924 p._fulfillmentHandler0 = value;
3925 p._rejectionHandler0 = value;
3926 p._promise0 = value;
3927 p._receiver0 = value;
3928 }
3929 // Complete slack tracking, opt out of field-type tracking and
3930 // stabilize map
3931 fillTypes({a: 1});
3932 fillTypes({b: 2});
3933 fillTypes({c: 3});
3934 fillTypes(1);
3935 fillTypes(function(){});
3936 fillTypes(undefined);
3937 fillTypes(false);
3938 fillTypes(new Promise(INTERNAL));
3939 debug.setBounds(Async.firstLineError, util.lastLineError);
3940 return Promise;
3941
3942};
3943
3944},{"./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){
3945"use strict";
3946module.exports = function(Promise, INTERNAL, tryConvertToPromise,
3947 apiRejection, Proxyable) {
3948var util = _dereq_("./util");
3949var isArray = util.isArray;
3950
3951function toResolutionValue(val) {
3952 switch(val) {
3953 case -2: return [];
3954 case -3: return {};
3955 }
3956}
3957
3958function PromiseArray(values) {
3959 var promise = this._promise = new Promise(INTERNAL);
3960 if (values instanceof Promise) {
3961 promise._propagateFrom(values, 3);
3962 }
3963 promise._setOnCancel(this);
3964 this._values = values;
3965 this._length = 0;
3966 this._totalResolved = 0;
3967 this._init(undefined, -2);
3968}
3969util.inherits(PromiseArray, Proxyable);
3970
3971PromiseArray.prototype.length = function () {
3972 return this._length;
3973};
3974
3975PromiseArray.prototype.promise = function () {
3976 return this._promise;
3977};
3978
3979PromiseArray.prototype._init = function init(_, resolveValueIfEmpty) {
3980 var values = tryConvertToPromise(this._values, this._promise);
3981 if (values instanceof Promise) {
3982 values = values._target();
3983 var bitField = values._bitField;
3984 ;
3985 this._values = values;
3986
3987 if (((bitField & 50397184) === 0)) {
3988 this._promise._setAsyncGuaranteed();
3989 return values._then(
3990 init,
3991 this._reject,
3992 undefined,
3993 this,
3994 resolveValueIfEmpty
3995 );
3996 } else if (((bitField & 33554432) !== 0)) {
3997 values = values._value();
3998 } else if (((bitField & 16777216) !== 0)) {
3999 return this._reject(values._reason());
4000 } else {
4001 return this._cancel();
4002 }
4003 }
4004 values = util.asArray(values);
4005 if (values === null) {
4006 var err = apiRejection(
4007 "expecting an array or an iterable object but got " + util.classString(values)).reason();
4008 this._promise._rejectCallback(err, false);
4009 return;
4010 }
4011
4012 if (values.length === 0) {
4013 if (resolveValueIfEmpty === -5) {
4014 this._resolveEmptyArray();
4015 }
4016 else {
4017 this._resolve(toResolutionValue(resolveValueIfEmpty));
4018 }
4019 return;
4020 }
4021 this._iterate(values);
4022};
4023
4024PromiseArray.prototype._iterate = function(values) {
4025 var len = this.getActualLength(values.length);
4026 this._length = len;
4027 this._values = this.shouldCopyValues() ? new Array(len) : this._values;
4028 var result = this._promise;
4029 var isResolved = false;
4030 var bitField = null;
4031 for (var i = 0; i < len; ++i) {
4032 var maybePromise = tryConvertToPromise(values[i], result);
4033
4034 if (maybePromise instanceof Promise) {
4035 maybePromise = maybePromise._target();
4036 bitField = maybePromise._bitField;
4037 } else {
4038 bitField = null;
4039 }
4040
4041 if (isResolved) {
4042 if (bitField !== null) {
4043 maybePromise.suppressUnhandledRejections();
4044 }
4045 } else if (bitField !== null) {
4046 if (((bitField & 50397184) === 0)) {
4047 maybePromise._proxy(this, i);
4048 this._values[i] = maybePromise;
4049 } else if (((bitField & 33554432) !== 0)) {
4050 isResolved = this._promiseFulfilled(maybePromise._value(), i);
4051 } else if (((bitField & 16777216) !== 0)) {
4052 isResolved = this._promiseRejected(maybePromise._reason(), i);
4053 } else {
4054 isResolved = this._promiseCancelled(i);
4055 }
4056 } else {
4057 isResolved = this._promiseFulfilled(maybePromise, i);
4058 }
4059 }
4060 if (!isResolved) result._setAsyncGuaranteed();
4061};
4062
4063PromiseArray.prototype._isResolved = function () {
4064 return this._values === null;
4065};
4066
4067PromiseArray.prototype._resolve = function (value) {
4068 this._values = null;
4069 this._promise._fulfill(value);
4070};
4071
4072PromiseArray.prototype._cancel = function() {
4073 if (this._isResolved() || !this._promise._isCancellable()) return;
4074 this._values = null;
4075 this._promise._cancel();
4076};
4077
4078PromiseArray.prototype._reject = function (reason) {
4079 this._values = null;
4080 this._promise._rejectCallback(reason, false);
4081};
4082
4083PromiseArray.prototype._promiseFulfilled = function (value, index) {
4084 this._values[index] = value;
4085 var totalResolved = ++this._totalResolved;
4086 if (totalResolved >= this._length) {
4087 this._resolve(this._values);
4088 return true;
4089 }
4090 return false;
4091};
4092
4093PromiseArray.prototype._promiseCancelled = function() {
4094 this._cancel();
4095 return true;
4096};
4097
4098PromiseArray.prototype._promiseRejected = function (reason) {
4099 this._totalResolved++;
4100 this._reject(reason);
4101 return true;
4102};
4103
4104PromiseArray.prototype._resultCancelled = function() {
4105 if (this._isResolved()) return;
4106 var values = this._values;
4107 this._cancel();
4108 if (values instanceof Promise) {
4109 values.cancel();
4110 } else {
4111 for (var i = 0; i < values.length; ++i) {
4112 if (values[i] instanceof Promise) {
4113 values[i].cancel();
4114 }
4115 }
4116 }
4117};
4118
4119PromiseArray.prototype.shouldCopyValues = function () {
4120 return true;
4121};
4122
4123PromiseArray.prototype.getActualLength = function (len) {
4124 return len;
4125};
4126
4127return PromiseArray;
4128};
4129
4130},{"./util":36}],24:[function(_dereq_,module,exports){
4131"use strict";
4132module.exports = function(Promise, INTERNAL) {
4133var THIS = {};
4134var util = _dereq_("./util");
4135var nodebackForPromise = _dereq_("./nodeback");
4136var withAppended = util.withAppended;
4137var maybeWrapAsError = util.maybeWrapAsError;
4138var canEvaluate = util.canEvaluate;
4139var TypeError = _dereq_("./errors").TypeError;
4140var defaultSuffix = "Async";
4141var defaultPromisified = {__isPromisified__: true};
4142var noCopyProps = [
4143 "arity", "length",
4144 "name",
4145 "arguments",
4146 "caller",
4147 "callee",
4148 "prototype",
4149 "__isPromisified__"
4150];
4151var noCopyPropsPattern = new RegExp("^(?:" + noCopyProps.join("|") + ")$");
4152
4153var defaultFilter = function(name) {
4154 return util.isIdentifier(name) &&
4155 name.charAt(0) !== "_" &&
4156 name !== "constructor";
4157};
4158
4159function propsFilter(key) {
4160 return !noCopyPropsPattern.test(key);
4161}
4162
4163function isPromisified(fn) {
4164 try {
4165 return fn.__isPromisified__ === true;
4166 }
4167 catch (e) {
4168 return false;
4169 }
4170}
4171
4172function hasPromisified(obj, key, suffix) {
4173 var val = util.getDataPropertyOrDefault(obj, key + suffix,
4174 defaultPromisified);
4175 return val ? isPromisified(val) : false;
4176}
4177function checkValid(ret, suffix, suffixRegexp) {
4178 for (var i = 0; i < ret.length; i += 2) {
4179 var key = ret[i];
4180 if (suffixRegexp.test(key)) {
4181 var keyWithoutAsyncSuffix = key.replace(suffixRegexp, "");
4182 for (var j = 0; j < ret.length; j += 2) {
4183 if (ret[j] === keyWithoutAsyncSuffix) {
4184 throw new TypeError("Cannot promisify an API that has normal methods with '%s'-suffix\u000a\u000a See http://goo.gl/MqrFmX\u000a"
4185 .replace("%s", suffix));
4186 }
4187 }
4188 }
4189 }
4190}
4191
4192function promisifiableMethods(obj, suffix, suffixRegexp, filter) {
4193 var keys = util.inheritedDataKeys(obj);
4194 var ret = [];
4195 for (var i = 0; i < keys.length; ++i) {
4196 var key = keys[i];
4197 var value = obj[key];
4198 var passesDefaultFilter = filter === defaultFilter
4199 ? true : defaultFilter(key, value, obj);
4200 if (typeof value === "function" &&
4201 !isPromisified(value) &&
4202 !hasPromisified(obj, key, suffix) &&
4203 filter(key, value, obj, passesDefaultFilter)) {
4204 ret.push(key, value);
4205 }
4206 }
4207 checkValid(ret, suffix, suffixRegexp);
4208 return ret;
4209}
4210
4211var escapeIdentRegex = function(str) {
4212 return str.replace(/([$])/, "\\$");
4213};
4214
4215var makeNodePromisifiedEval;
4216if (!true) {
4217var switchCaseArgumentOrder = function(likelyArgumentCount) {
4218 var ret = [likelyArgumentCount];
4219 var min = Math.max(0, likelyArgumentCount - 1 - 3);
4220 for(var i = likelyArgumentCount - 1; i >= min; --i) {
4221 ret.push(i);
4222 }
4223 for(var i = likelyArgumentCount + 1; i <= 3; ++i) {
4224 ret.push(i);
4225 }
4226 return ret;
4227};
4228
4229var argumentSequence = function(argumentCount) {
4230 return util.filledRange(argumentCount, "_arg", "");
4231};
4232
4233var parameterDeclaration = function(parameterCount) {
4234 return util.filledRange(
4235 Math.max(parameterCount, 3), "_arg", "");
4236};
4237
4238var parameterCount = function(fn) {
4239 if (typeof fn.length === "number") {
4240 return Math.max(Math.min(fn.length, 1023 + 1), 0);
4241 }
4242 return 0;
4243};
4244
4245makeNodePromisifiedEval =
4246function(callback, receiver, originalName, fn, _, multiArgs) {
4247 var newParameterCount = Math.max(0, parameterCount(fn) - 1);
4248 var argumentOrder = switchCaseArgumentOrder(newParameterCount);
4249 var shouldProxyThis = typeof callback === "string" || receiver === THIS;
4250
4251 function generateCallForArgumentCount(count) {
4252 var args = argumentSequence(count).join(", ");
4253 var comma = count > 0 ? ", " : "";
4254 var ret;
4255 if (shouldProxyThis) {
4256 ret = "ret = callback.call(this, {{args}}, nodeback); break;\n";
4257 } else {
4258 ret = receiver === undefined
4259 ? "ret = callback({{args}}, nodeback); break;\n"
4260 : "ret = callback.call(receiver, {{args}}, nodeback); break;\n";
4261 }
4262 return ret.replace("{{args}}", args).replace(", ", comma);
4263 }
4264
4265 function generateArgumentSwitchCase() {
4266 var ret = "";
4267 for (var i = 0; i < argumentOrder.length; ++i) {
4268 ret += "case " + argumentOrder[i] +":" +
4269 generateCallForArgumentCount(argumentOrder[i]);
4270 }
4271
4272 ret += " \n\
4273 default: \n\
4274 var args = new Array(len + 1); \n\
4275 var i = 0; \n\
4276 for (var i = 0; i < len; ++i) { \n\
4277 args[i] = arguments[i]; \n\
4278 } \n\
4279 args[i] = nodeback; \n\
4280 [CodeForCall] \n\
4281 break; \n\
4282 ".replace("[CodeForCall]", (shouldProxyThis
4283 ? "ret = callback.apply(this, args);\n"
4284 : "ret = callback.apply(receiver, args);\n"));
4285 return ret;
4286 }
4287
4288 var getFunctionCode = typeof callback === "string"
4289 ? ("this != null ? this['"+callback+"'] : fn")
4290 : "fn";
4291 var body = "'use strict'; \n\
4292 var ret = function (Parameters) { \n\
4293 'use strict'; \n\
4294 var len = arguments.length; \n\
4295 var promise = new Promise(INTERNAL); \n\
4296 promise._captureStackTrace(); \n\
4297 var nodeback = nodebackForPromise(promise, " + multiArgs + "); \n\
4298 var ret; \n\
4299 var callback = tryCatch([GetFunctionCode]); \n\
4300 switch(len) { \n\
4301 [CodeForSwitchCase] \n\
4302 } \n\
4303 if (ret === errorObj) { \n\
4304 promise._rejectCallback(maybeWrapAsError(ret.e), true, true);\n\
4305 } \n\
4306 if (!promise._isFateSealed()) promise._setAsyncGuaranteed(); \n\
4307 return promise; \n\
4308 }; \n\
4309 notEnumerableProp(ret, '__isPromisified__', true); \n\
4310 return ret; \n\
4311 ".replace("[CodeForSwitchCase]", generateArgumentSwitchCase())
4312 .replace("[GetFunctionCode]", getFunctionCode);
4313 body = body.replace("Parameters", parameterDeclaration(newParameterCount));
4314 return new Function("Promise",
4315 "fn",
4316 "receiver",
4317 "withAppended",
4318 "maybeWrapAsError",
4319 "nodebackForPromise",
4320 "tryCatch",
4321 "errorObj",
4322 "notEnumerableProp",
4323 "INTERNAL",
4324 body)(
4325 Promise,
4326 fn,
4327 receiver,
4328 withAppended,
4329 maybeWrapAsError,
4330 nodebackForPromise,
4331 util.tryCatch,
4332 util.errorObj,
4333 util.notEnumerableProp,
4334 INTERNAL);
4335};
4336}
4337
4338function makeNodePromisifiedClosure(callback, receiver, _, fn, __, multiArgs) {
4339 var defaultThis = (function() {return this;})();
4340 var method = callback;
4341 if (typeof method === "string") {
4342 callback = fn;
4343 }
4344 function promisified() {
4345 var _receiver = receiver;
4346 if (receiver === THIS) _receiver = this;
4347 var promise = new Promise(INTERNAL);
4348 promise._captureStackTrace();
4349 var cb = typeof method === "string" && this !== defaultThis
4350 ? this[method] : callback;
4351 var fn = nodebackForPromise(promise, multiArgs);
4352 try {
4353 cb.apply(_receiver, withAppended(arguments, fn));
4354 } catch(e) {
4355 promise._rejectCallback(maybeWrapAsError(e), true, true);
4356 }
4357 if (!promise._isFateSealed()) promise._setAsyncGuaranteed();
4358 return promise;
4359 }
4360 util.notEnumerableProp(promisified, "__isPromisified__", true);
4361 return promisified;
4362}
4363
4364var makeNodePromisified = canEvaluate
4365 ? makeNodePromisifiedEval
4366 : makeNodePromisifiedClosure;
4367
4368function promisifyAll(obj, suffix, filter, promisifier, multiArgs) {
4369 var suffixRegexp = new RegExp(escapeIdentRegex(suffix) + "$");
4370 var methods =
4371 promisifiableMethods(obj, suffix, suffixRegexp, filter);
4372
4373 for (var i = 0, len = methods.length; i < len; i+= 2) {
4374 var key = methods[i];
4375 var fn = methods[i+1];
4376 var promisifiedKey = key + suffix;
4377 if (promisifier === makeNodePromisified) {
4378 obj[promisifiedKey] =
4379 makeNodePromisified(key, THIS, key, fn, suffix, multiArgs);
4380 } else {
4381 var promisified = promisifier(fn, function() {
4382 return makeNodePromisified(key, THIS, key,
4383 fn, suffix, multiArgs);
4384 });
4385 util.notEnumerableProp(promisified, "__isPromisified__", true);
4386 obj[promisifiedKey] = promisified;
4387 }
4388 }
4389 util.toFastProperties(obj);
4390 return obj;
4391}
4392
4393function promisify(callback, receiver, multiArgs) {
4394 return makeNodePromisified(callback, receiver, undefined,
4395 callback, null, multiArgs);
4396}
4397
4398Promise.promisify = function (fn, options) {
4399 if (typeof fn !== "function") {
4400 throw new TypeError("expecting a function but got " + util.classString(fn));
4401 }
4402 if (isPromisified(fn)) {
4403 return fn;
4404 }
4405 options = Object(options);
4406 var receiver = options.context === undefined ? THIS : options.context;
4407 var multiArgs = !!options.multiArgs;
4408 var ret = promisify(fn, receiver, multiArgs);
4409 util.copyDescriptors(fn, ret, propsFilter);
4410 return ret;
4411};
4412
4413Promise.promisifyAll = function (target, options) {
4414 if (typeof target !== "function" && typeof target !== "object") {
4415 throw new TypeError("the target of promisifyAll must be an object or a function\u000a\u000a See http://goo.gl/MqrFmX\u000a");
4416 }
4417 options = Object(options);
4418 var multiArgs = !!options.multiArgs;
4419 var suffix = options.suffix;
4420 if (typeof suffix !== "string") suffix = defaultSuffix;
4421 var filter = options.filter;
4422 if (typeof filter !== "function") filter = defaultFilter;
4423 var promisifier = options.promisifier;
4424 if (typeof promisifier !== "function") promisifier = makeNodePromisified;
4425
4426 if (!util.isIdentifier(suffix)) {
4427 throw new RangeError("suffix must be a valid identifier\u000a\u000a See http://goo.gl/MqrFmX\u000a");
4428 }
4429
4430 var keys = util.inheritedDataKeys(target);
4431 for (var i = 0; i < keys.length; ++i) {
4432 var value = target[keys[i]];
4433 if (keys[i] !== "constructor" &&
4434 util.isClass(value)) {
4435 promisifyAll(value.prototype, suffix, filter, promisifier,
4436 multiArgs);
4437 promisifyAll(value, suffix, filter, promisifier, multiArgs);
4438 }
4439 }
4440
4441 return promisifyAll(target, suffix, filter, promisifier, multiArgs);
4442};
4443};
4444
4445
4446},{"./errors":12,"./nodeback":20,"./util":36}],25:[function(_dereq_,module,exports){
4447"use strict";
4448module.exports = function(
4449 Promise, PromiseArray, tryConvertToPromise, apiRejection) {
4450var util = _dereq_("./util");
4451var isObject = util.isObject;
4452var es5 = _dereq_("./es5");
4453var Es6Map;
4454if (typeof Map === "function") Es6Map = Map;
4455
4456var mapToEntries = (function() {
4457 var index = 0;
4458 var size = 0;
4459
4460 function extractEntry(value, key) {
4461 this[index] = value;
4462 this[index + size] = key;
4463 index++;
4464 }
4465
4466 return function mapToEntries(map) {
4467 size = map.size;
4468 index = 0;
4469 var ret = new Array(map.size * 2);
4470 map.forEach(extractEntry, ret);
4471 return ret;
4472 };
4473})();
4474
4475var entriesToMap = function(entries) {
4476 var ret = new Es6Map();
4477 var length = entries.length / 2 | 0;
4478 for (var i = 0; i < length; ++i) {
4479 var key = entries[length + i];
4480 var value = entries[i];
4481 ret.set(key, value);
4482 }
4483 return ret;
4484};
4485
4486function PropertiesPromiseArray(obj) {
4487 var isMap = false;
4488 var entries;
4489 if (Es6Map !== undefined && obj instanceof Es6Map) {
4490 entries = mapToEntries(obj);
4491 isMap = true;
4492 } else {
4493 var keys = es5.keys(obj);
4494 var len = keys.length;
4495 entries = new Array(len * 2);
4496 for (var i = 0; i < len; ++i) {
4497 var key = keys[i];
4498 entries[i] = obj[key];
4499 entries[i + len] = key;
4500 }
4501 }
4502 this.constructor$(entries);
4503 this._isMap = isMap;
4504 this._init$(undefined, -3);
4505}
4506util.inherits(PropertiesPromiseArray, PromiseArray);
4507
4508PropertiesPromiseArray.prototype._init = function () {};
4509
4510PropertiesPromiseArray.prototype._promiseFulfilled = function (value, index) {
4511 this._values[index] = value;
4512 var totalResolved = ++this._totalResolved;
4513 if (totalResolved >= this._length) {
4514 var val;
4515 if (this._isMap) {
4516 val = entriesToMap(this._values);
4517 } else {
4518 val = {};
4519 var keyOffset = this.length();
4520 for (var i = 0, len = this.length(); i < len; ++i) {
4521 val[this._values[i + keyOffset]] = this._values[i];
4522 }
4523 }
4524 this._resolve(val);
4525 return true;
4526 }
4527 return false;
4528};
4529
4530PropertiesPromiseArray.prototype.shouldCopyValues = function () {
4531 return false;
4532};
4533
4534PropertiesPromiseArray.prototype.getActualLength = function (len) {
4535 return len >> 1;
4536};
4537
4538function props(promises) {
4539 var ret;
4540 var castValue = tryConvertToPromise(promises);
4541
4542 if (!isObject(castValue)) {
4543 return apiRejection("cannot await properties of a non-object\u000a\u000a See http://goo.gl/MqrFmX\u000a");
4544 } else if (castValue instanceof Promise) {
4545 ret = castValue._then(
4546 Promise.props, undefined, undefined, undefined, undefined);
4547 } else {
4548 ret = new PropertiesPromiseArray(castValue).promise();
4549 }
4550
4551 if (castValue instanceof Promise) {
4552 ret._propagateFrom(castValue, 2);
4553 }
4554 return ret;
4555}
4556
4557Promise.prototype.props = function () {
4558 return props(this);
4559};
4560
4561Promise.props = function (promises) {
4562 return props(promises);
4563};
4564};
4565
4566},{"./es5":13,"./util":36}],26:[function(_dereq_,module,exports){
4567"use strict";
4568function arrayMove(src, srcIndex, dst, dstIndex, len) {
4569 for (var j = 0; j < len; ++j) {
4570 dst[j + dstIndex] = src[j + srcIndex];
4571 src[j + srcIndex] = void 0;
4572 }
4573}
4574
4575function Queue(capacity) {
4576 this._capacity = capacity;
4577 this._length = 0;
4578 this._front = 0;
4579}
4580
4581Queue.prototype._willBeOverCapacity = function (size) {
4582 return this._capacity < size;
4583};
4584
4585Queue.prototype._pushOne = function (arg) {
4586 var length = this.length();
4587 this._checkCapacity(length + 1);
4588 var i = (this._front + length) & (this._capacity - 1);
4589 this[i] = arg;
4590 this._length = length + 1;
4591};
4592
4593Queue.prototype._unshiftOne = function(value) {
4594 var capacity = this._capacity;
4595 this._checkCapacity(this.length() + 1);
4596 var front = this._front;
4597 var i = (((( front - 1 ) &
4598 ( capacity - 1) ) ^ capacity ) - capacity );
4599 this[i] = value;
4600 this._front = i;
4601 this._length = this.length() + 1;
4602};
4603
4604Queue.prototype.unshift = function(fn, receiver, arg) {
4605 this._unshiftOne(arg);
4606 this._unshiftOne(receiver);
4607 this._unshiftOne(fn);
4608};
4609
4610Queue.prototype.push = function (fn, receiver, arg) {
4611 var length = this.length() + 3;
4612 if (this._willBeOverCapacity(length)) {
4613 this._pushOne(fn);
4614 this._pushOne(receiver);
4615 this._pushOne(arg);
4616 return;
4617 }
4618 var j = this._front + length - 3;
4619 this._checkCapacity(length);
4620 var wrapMask = this._capacity - 1;
4621 this[(j + 0) & wrapMask] = fn;
4622 this[(j + 1) & wrapMask] = receiver;
4623 this[(j + 2) & wrapMask] = arg;
4624 this._length = length;
4625};
4626
4627Queue.prototype.shift = function () {
4628 var front = this._front,
4629 ret = this[front];
4630
4631 this[front] = undefined;
4632 this._front = (front + 1) & (this._capacity - 1);
4633 this._length--;
4634 return ret;
4635};
4636
4637Queue.prototype.length = function () {
4638 return this._length;
4639};
4640
4641Queue.prototype._checkCapacity = function (size) {
4642 if (this._capacity < size) {
4643 this._resizeTo(this._capacity << 1);
4644 }
4645};
4646
4647Queue.prototype._resizeTo = function (capacity) {
4648 var oldCapacity = this._capacity;
4649 this._capacity = capacity;
4650 var front = this._front;
4651 var length = this._length;
4652 var moveItemsCount = (front + length) & (oldCapacity - 1);
4653 arrayMove(this, 0, this, oldCapacity, moveItemsCount);
4654};
4655
4656module.exports = Queue;
4657
4658},{}],27:[function(_dereq_,module,exports){
4659"use strict";
4660module.exports = function(
4661 Promise, INTERNAL, tryConvertToPromise, apiRejection) {
4662var util = _dereq_("./util");
4663
4664var raceLater = function (promise) {
4665 return promise.then(function(array) {
4666 return race(array, promise);
4667 });
4668};
4669
4670function race(promises, parent) {
4671 var maybePromise = tryConvertToPromise(promises);
4672
4673 if (maybePromise instanceof Promise) {
4674 return raceLater(maybePromise);
4675 } else {
4676 promises = util.asArray(promises);
4677 if (promises === null)
4678 return apiRejection("expecting an array or an iterable object but got " + util.classString(promises));
4679 }
4680
4681 var ret = new Promise(INTERNAL);
4682 if (parent !== undefined) {
4683 ret._propagateFrom(parent, 3);
4684 }
4685 var fulfill = ret._fulfill;
4686 var reject = ret._reject;
4687 for (var i = 0, len = promises.length; i < len; ++i) {
4688 var val = promises[i];
4689
4690 if (val === undefined && !(i in promises)) {
4691 continue;
4692 }
4693
4694 Promise.cast(val)._then(fulfill, reject, undefined, ret, null);
4695 }
4696 return ret;
4697}
4698
4699Promise.race = function (promises) {
4700 return race(promises, undefined);
4701};
4702
4703Promise.prototype.race = function () {
4704 return race(this, undefined);
4705};
4706
4707};
4708
4709},{"./util":36}],28:[function(_dereq_,module,exports){
4710"use strict";
4711module.exports = function(Promise,
4712 PromiseArray,
4713 apiRejection,
4714 tryConvertToPromise,
4715 INTERNAL,
4716 debug) {
4717var getDomain = Promise._getDomain;
4718var util = _dereq_("./util");
4719var tryCatch = util.tryCatch;
4720
4721function ReductionPromiseArray(promises, fn, initialValue, _each) {
4722 this.constructor$(promises);
4723 var domain = getDomain();
4724 this._fn = domain === null ? fn : util.domainBind(domain, fn);
4725 if (initialValue !== undefined) {
4726 initialValue = Promise.resolve(initialValue);
4727 initialValue._attachCancellationCallback(this);
4728 }
4729 this._initialValue = initialValue;
4730 this._currentCancellable = null;
4731 if(_each === INTERNAL) {
4732 this._eachValues = Array(this._length);
4733 } else if (_each === 0) {
4734 this._eachValues = null;
4735 } else {
4736 this._eachValues = undefined;
4737 }
4738 this._promise._captureStackTrace();
4739 this._init$(undefined, -5);
4740}
4741util.inherits(ReductionPromiseArray, PromiseArray);
4742
4743ReductionPromiseArray.prototype._gotAccum = function(accum) {
4744 if (this._eachValues !== undefined &&
4745 this._eachValues !== null &&
4746 accum !== INTERNAL) {
4747 this._eachValues.push(accum);
4748 }
4749};
4750
4751ReductionPromiseArray.prototype._eachComplete = function(value) {
4752 if (this._eachValues !== null) {
4753 this._eachValues.push(value);
4754 }
4755 return this._eachValues;
4756};
4757
4758ReductionPromiseArray.prototype._init = function() {};
4759
4760ReductionPromiseArray.prototype._resolveEmptyArray = function() {
4761 this._resolve(this._eachValues !== undefined ? this._eachValues
4762 : this._initialValue);
4763};
4764
4765ReductionPromiseArray.prototype.shouldCopyValues = function () {
4766 return false;
4767};
4768
4769ReductionPromiseArray.prototype._resolve = function(value) {
4770 this._promise._resolveCallback(value);
4771 this._values = null;
4772};
4773
4774ReductionPromiseArray.prototype._resultCancelled = function(sender) {
4775 if (sender === this._initialValue) return this._cancel();
4776 if (this._isResolved()) return;
4777 this._resultCancelled$();
4778 if (this._currentCancellable instanceof Promise) {
4779 this._currentCancellable.cancel();
4780 }
4781 if (this._initialValue instanceof Promise) {
4782 this._initialValue.cancel();
4783 }
4784};
4785
4786ReductionPromiseArray.prototype._iterate = function (values) {
4787 this._values = values;
4788 var value;
4789 var i;
4790 var length = values.length;
4791 if (this._initialValue !== undefined) {
4792 value = this._initialValue;
4793 i = 0;
4794 } else {
4795 value = Promise.resolve(values[0]);
4796 i = 1;
4797 }
4798
4799 this._currentCancellable = value;
4800
4801 if (!value.isRejected()) {
4802 for (; i < length; ++i) {
4803 var ctx = {
4804 accum: null,
4805 value: values[i],
4806 index: i,
4807 length: length,
4808 array: this
4809 };
4810 value = value._then(gotAccum, undefined, undefined, ctx, undefined);
4811 }
4812 }
4813
4814 if (this._eachValues !== undefined) {
4815 value = value
4816 ._then(this._eachComplete, undefined, undefined, this, undefined);
4817 }
4818 value._then(completed, completed, undefined, value, this);
4819};
4820
4821Promise.prototype.reduce = function (fn, initialValue) {
4822 return reduce(this, fn, initialValue, null);
4823};
4824
4825Promise.reduce = function (promises, fn, initialValue, _each) {
4826 return reduce(promises, fn, initialValue, _each);
4827};
4828
4829function completed(valueOrReason, array) {
4830 if (this.isFulfilled()) {
4831 array._resolve(valueOrReason);
4832 } else {
4833 array._reject(valueOrReason);
4834 }
4835}
4836
4837function reduce(promises, fn, initialValue, _each) {
4838 if (typeof fn !== "function") {
4839 return apiRejection("expecting a function but got " + util.classString(fn));
4840 }
4841 var array = new ReductionPromiseArray(promises, fn, initialValue, _each);
4842 return array.promise();
4843}
4844
4845function gotAccum(accum) {
4846 this.accum = accum;
4847 this.array._gotAccum(accum);
4848 var value = tryConvertToPromise(this.value, this.array._promise);
4849 if (value instanceof Promise) {
4850 this.array._currentCancellable = value;
4851 return value._then(gotValue, undefined, undefined, this, undefined);
4852 } else {
4853 return gotValue.call(this, value);
4854 }
4855}
4856
4857function gotValue(value) {
4858 var array = this.array;
4859 var promise = array._promise;
4860 var fn = tryCatch(array._fn);
4861 promise._pushContext();
4862 var ret;
4863 if (array._eachValues !== undefined) {
4864 ret = fn.call(promise._boundValue(), value, this.index, this.length);
4865 } else {
4866 ret = fn.call(promise._boundValue(),
4867 this.accum, value, this.index, this.length);
4868 }
4869 if (ret instanceof Promise) {
4870 array._currentCancellable = ret;
4871 }
4872 var promiseCreated = promise._popContext();
4873 debug.checkForgottenReturns(
4874 ret,
4875 promiseCreated,
4876 array._eachValues !== undefined ? "Promise.each" : "Promise.reduce",
4877 promise
4878 );
4879 return ret;
4880}
4881};
4882
4883},{"./util":36}],29:[function(_dereq_,module,exports){
4884"use strict";
4885var util = _dereq_("./util");
4886var schedule;
4887var noAsyncScheduler = function() {
4888 throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/MqrFmX\u000a");
4889};
4890var NativePromise = util.getNativePromise();
4891if (util.isNode && typeof MutationObserver === "undefined") {
4892 var GlobalSetImmediate = global.setImmediate;
4893 var ProcessNextTick = process.nextTick;
4894 schedule = util.isRecentNode
4895 ? function(fn) { GlobalSetImmediate.call(global, fn); }
4896 : function(fn) { ProcessNextTick.call(process, fn); };
4897} else if (typeof NativePromise === "function" &&
4898 typeof NativePromise.resolve === "function") {
4899 var nativePromise = NativePromise.resolve();
4900 schedule = function(fn) {
4901 nativePromise.then(fn);
4902 };
4903} else if ((typeof MutationObserver !== "undefined") &&
4904 !(typeof window !== "undefined" &&
4905 window.navigator &&
4906 (window.navigator.standalone || window.cordova))) {
4907 schedule = (function() {
4908 var div = document.createElement("div");
4909 var opts = {attributes: true};
4910 var toggleScheduled = false;
4911 var div2 = document.createElement("div");
4912 var o2 = new MutationObserver(function() {
4913 div.classList.toggle("foo");
4914 toggleScheduled = false;
4915 });
4916 o2.observe(div2, opts);
4917
4918 var scheduleToggle = function() {
4919 if (toggleScheduled) return;
4920 toggleScheduled = true;
4921 div2.classList.toggle("foo");
4922 };
4923
4924 return function schedule(fn) {
4925 var o = new MutationObserver(function() {
4926 o.disconnect();
4927 fn();
4928 });
4929 o.observe(div, opts);
4930 scheduleToggle();
4931 };
4932 })();
4933} else if (typeof setImmediate !== "undefined") {
4934 schedule = function (fn) {
4935 setImmediate(fn);
4936 };
4937} else if (typeof setTimeout !== "undefined") {
4938 schedule = function (fn) {
4939 setTimeout(fn, 0);
4940 };
4941} else {
4942 schedule = noAsyncScheduler;
4943}
4944module.exports = schedule;
4945
4946},{"./util":36}],30:[function(_dereq_,module,exports){
4947"use strict";
4948module.exports =
4949 function(Promise, PromiseArray, debug) {
4950var PromiseInspection = Promise.PromiseInspection;
4951var util = _dereq_("./util");
4952
4953function SettledPromiseArray(values) {
4954 this.constructor$(values);
4955}
4956util.inherits(SettledPromiseArray, PromiseArray);
4957
4958SettledPromiseArray.prototype._promiseResolved = function (index, inspection) {
4959 this._values[index] = inspection;
4960 var totalResolved = ++this._totalResolved;
4961 if (totalResolved >= this._length) {
4962 this._resolve(this._values);
4963 return true;
4964 }
4965 return false;
4966};
4967
4968SettledPromiseArray.prototype._promiseFulfilled = function (value, index) {
4969 var ret = new PromiseInspection();
4970 ret._bitField = 33554432;
4971 ret._settledValueField = value;
4972 return this._promiseResolved(index, ret);
4973};
4974SettledPromiseArray.prototype._promiseRejected = function (reason, index) {
4975 var ret = new PromiseInspection();
4976 ret._bitField = 16777216;
4977 ret._settledValueField = reason;
4978 return this._promiseResolved(index, ret);
4979};
4980
4981Promise.settle = function (promises) {
4982 debug.deprecated(".settle()", ".reflect()");
4983 return new SettledPromiseArray(promises).promise();
4984};
4985
4986Promise.prototype.settle = function () {
4987 return Promise.settle(this);
4988};
4989};
4990
4991},{"./util":36}],31:[function(_dereq_,module,exports){
4992"use strict";
4993module.exports =
4994function(Promise, PromiseArray, apiRejection) {
4995var util = _dereq_("./util");
4996var RangeError = _dereq_("./errors").RangeError;
4997var AggregateError = _dereq_("./errors").AggregateError;
4998var isArray = util.isArray;
4999var CANCELLATION = {};
5000
5001
5002function SomePromiseArray(values) {
5003 this.constructor$(values);
5004 this._howMany = 0;
5005 this._unwrap = false;
5006 this._initialized = false;
5007}
5008util.inherits(SomePromiseArray, PromiseArray);
5009
5010SomePromiseArray.prototype._init = function () {
5011 if (!this._initialized) {
5012 return;
5013 }
5014 if (this._howMany === 0) {
5015 this._resolve([]);
5016 return;
5017 }
5018 this._init$(undefined, -5);
5019 var isArrayResolved = isArray(this._values);
5020 if (!this._isResolved() &&
5021 isArrayResolved &&
5022 this._howMany > this._canPossiblyFulfill()) {
5023 this._reject(this._getRangeError(this.length()));
5024 }
5025};
5026
5027SomePromiseArray.prototype.init = function () {
5028 this._initialized = true;
5029 this._init();
5030};
5031
5032SomePromiseArray.prototype.setUnwrap = function () {
5033 this._unwrap = true;
5034};
5035
5036SomePromiseArray.prototype.howMany = function () {
5037 return this._howMany;
5038};
5039
5040SomePromiseArray.prototype.setHowMany = function (count) {
5041 this._howMany = count;
5042};
5043
5044SomePromiseArray.prototype._promiseFulfilled = function (value) {
5045 this._addFulfilled(value);
5046 if (this._fulfilled() === this.howMany()) {
5047 this._values.length = this.howMany();
5048 if (this.howMany() === 1 && this._unwrap) {
5049 this._resolve(this._values[0]);
5050 } else {
5051 this._resolve(this._values);
5052 }
5053 return true;
5054 }
5055 return false;
5056
5057};
5058SomePromiseArray.prototype._promiseRejected = function (reason) {
5059 this._addRejected(reason);
5060 return this._checkOutcome();
5061};
5062
5063SomePromiseArray.prototype._promiseCancelled = function () {
5064 if (this._values instanceof Promise || this._values == null) {
5065 return this._cancel();
5066 }
5067 this._addRejected(CANCELLATION);
5068 return this._checkOutcome();
5069};
5070
5071SomePromiseArray.prototype._checkOutcome = function() {
5072 if (this.howMany() > this._canPossiblyFulfill()) {
5073 var e = new AggregateError();
5074 for (var i = this.length(); i < this._values.length; ++i) {
5075 if (this._values[i] !== CANCELLATION) {
5076 e.push(this._values[i]);
5077 }
5078 }
5079 if (e.length > 0) {
5080 this._reject(e);
5081 } else {
5082 this._cancel();
5083 }
5084 return true;
5085 }
5086 return false;
5087};
5088
5089SomePromiseArray.prototype._fulfilled = function () {
5090 return this._totalResolved;
5091};
5092
5093SomePromiseArray.prototype._rejected = function () {
5094 return this._values.length - this.length();
5095};
5096
5097SomePromiseArray.prototype._addRejected = function (reason) {
5098 this._values.push(reason);
5099};
5100
5101SomePromiseArray.prototype._addFulfilled = function (value) {
5102 this._values[this._totalResolved++] = value;
5103};
5104
5105SomePromiseArray.prototype._canPossiblyFulfill = function () {
5106 return this.length() - this._rejected();
5107};
5108
5109SomePromiseArray.prototype._getRangeError = function (count) {
5110 var message = "Input array must contain at least " +
5111 this._howMany + " items but contains only " + count + " items";
5112 return new RangeError(message);
5113};
5114
5115SomePromiseArray.prototype._resolveEmptyArray = function () {
5116 this._reject(this._getRangeError(0));
5117};
5118
5119function some(promises, howMany) {
5120 if ((howMany | 0) !== howMany || howMany < 0) {
5121 return apiRejection("expecting a positive integer\u000a\u000a See http://goo.gl/MqrFmX\u000a");
5122 }
5123 var ret = new SomePromiseArray(promises);
5124 var promise = ret.promise();
5125 ret.setHowMany(howMany);
5126 ret.init();
5127 return promise;
5128}
5129
5130Promise.some = function (promises, howMany) {
5131 return some(promises, howMany);
5132};
5133
5134Promise.prototype.some = function (howMany) {
5135 return some(this, howMany);
5136};
5137
5138Promise._SomePromiseArray = SomePromiseArray;
5139};
5140
5141},{"./errors":12,"./util":36}],32:[function(_dereq_,module,exports){
5142"use strict";
5143module.exports = function(Promise) {
5144function PromiseInspection(promise) {
5145 if (promise !== undefined) {
5146 promise = promise._target();
5147 this._bitField = promise._bitField;
5148 this._settledValueField = promise._isFateSealed()
5149 ? promise._settledValue() : undefined;
5150 }
5151 else {
5152 this._bitField = 0;
5153 this._settledValueField = undefined;
5154 }
5155}
5156
5157PromiseInspection.prototype._settledValue = function() {
5158 return this._settledValueField;
5159};
5160
5161var value = PromiseInspection.prototype.value = function () {
5162 if (!this.isFulfilled()) {
5163 throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\u000a\u000a See http://goo.gl/MqrFmX\u000a");
5164 }
5165 return this._settledValue();
5166};
5167
5168var reason = PromiseInspection.prototype.error =
5169PromiseInspection.prototype.reason = function () {
5170 if (!this.isRejected()) {
5171 throw new TypeError("cannot get rejection reason of a non-rejected promise\u000a\u000a See http://goo.gl/MqrFmX\u000a");
5172 }
5173 return this._settledValue();
5174};
5175
5176var isFulfilled = PromiseInspection.prototype.isFulfilled = function() {
5177 return (this._bitField & 33554432) !== 0;
5178};
5179
5180var isRejected = PromiseInspection.prototype.isRejected = function () {
5181 return (this._bitField & 16777216) !== 0;
5182};
5183
5184var isPending = PromiseInspection.prototype.isPending = function () {
5185 return (this._bitField & 50397184) === 0;
5186};
5187
5188var isResolved = PromiseInspection.prototype.isResolved = function () {
5189 return (this._bitField & 50331648) !== 0;
5190};
5191
5192PromiseInspection.prototype.isCancelled = function() {
5193 return (this._bitField & 8454144) !== 0;
5194};
5195
5196Promise.prototype.__isCancelled = function() {
5197 return (this._bitField & 65536) === 65536;
5198};
5199
5200Promise.prototype._isCancelled = function() {
5201 return this._target().__isCancelled();
5202};
5203
5204Promise.prototype.isCancelled = function() {
5205 return (this._target()._bitField & 8454144) !== 0;
5206};
5207
5208Promise.prototype.isPending = function() {
5209 return isPending.call(this._target());
5210};
5211
5212Promise.prototype.isRejected = function() {
5213 return isRejected.call(this._target());
5214};
5215
5216Promise.prototype.isFulfilled = function() {
5217 return isFulfilled.call(this._target());
5218};
5219
5220Promise.prototype.isResolved = function() {
5221 return isResolved.call(this._target());
5222};
5223
5224Promise.prototype.value = function() {
5225 return value.call(this._target());
5226};
5227
5228Promise.prototype.reason = function() {
5229 var target = this._target();
5230 target._unsetRejectionIsUnhandled();
5231 return reason.call(target);
5232};
5233
5234Promise.prototype._value = function() {
5235 return this._settledValue();
5236};
5237
5238Promise.prototype._reason = function() {
5239 this._unsetRejectionIsUnhandled();
5240 return this._settledValue();
5241};
5242
5243Promise.PromiseInspection = PromiseInspection;
5244};
5245
5246},{}],33:[function(_dereq_,module,exports){
5247"use strict";
5248module.exports = function(Promise, INTERNAL) {
5249var util = _dereq_("./util");
5250var errorObj = util.errorObj;
5251var isObject = util.isObject;
5252
5253function tryConvertToPromise(obj, context) {
5254 if (isObject(obj)) {
5255 if (obj instanceof Promise) return obj;
5256 var then = getThen(obj);
5257 if (then === errorObj) {
5258 if (context) context._pushContext();
5259 var ret = Promise.reject(then.e);
5260 if (context) context._popContext();
5261 return ret;
5262 } else if (typeof then === "function") {
5263 if (isAnyBluebirdPromise(obj)) {
5264 var ret = new Promise(INTERNAL);
5265 obj._then(
5266 ret._fulfill,
5267 ret._reject,
5268 undefined,
5269 ret,
5270 null
5271 );
5272 return ret;
5273 }
5274 return doThenable(obj, then, context);
5275 }
5276 }
5277 return obj;
5278}
5279
5280function doGetThen(obj) {
5281 return obj.then;
5282}
5283
5284function getThen(obj) {
5285 try {
5286 return doGetThen(obj);
5287 } catch (e) {
5288 errorObj.e = e;
5289 return errorObj;
5290 }
5291}
5292
5293var hasProp = {}.hasOwnProperty;
5294function isAnyBluebirdPromise(obj) {
5295 try {
5296 return hasProp.call(obj, "_promise0");
5297 } catch (e) {
5298 return false;
5299 }
5300}
5301
5302function doThenable(x, then, context) {
5303 var promise = new Promise(INTERNAL);
5304 var ret = promise;
5305 if (context) context._pushContext();
5306 promise._captureStackTrace();
5307 if (context) context._popContext();
5308 var synchronous = true;
5309 var result = util.tryCatch(then).call(x, resolve, reject);
5310 synchronous = false;
5311
5312 if (promise && result === errorObj) {
5313 promise._rejectCallback(result.e, true, true);
5314 promise = null;
5315 }
5316
5317 function resolve(value) {
5318 if (!promise) return;
5319 promise._resolveCallback(value);
5320 promise = null;
5321 }
5322
5323 function reject(reason) {
5324 if (!promise) return;
5325 promise._rejectCallback(reason, synchronous, true);
5326 promise = null;
5327 }
5328 return ret;
5329}
5330
5331return tryConvertToPromise;
5332};
5333
5334},{"./util":36}],34:[function(_dereq_,module,exports){
5335"use strict";
5336module.exports = function(Promise, INTERNAL, debug) {
5337var util = _dereq_("./util");
5338var TimeoutError = Promise.TimeoutError;
5339
5340function HandleWrapper(handle) {
5341 this.handle = handle;
5342}
5343
5344HandleWrapper.prototype._resultCancelled = function() {
5345 clearTimeout(this.handle);
5346};
5347
5348var afterValue = function(value) { return delay(+this).thenReturn(value); };
5349var delay = Promise.delay = function (ms, value) {
5350 var ret;
5351 var handle;
5352 if (value !== undefined) {
5353 ret = Promise.resolve(value)
5354 ._then(afterValue, null, null, ms, undefined);
5355 if (debug.cancellation() && value instanceof Promise) {
5356 ret._setOnCancel(value);
5357 }
5358 } else {
5359 ret = new Promise(INTERNAL);
5360 handle = setTimeout(function() { ret._fulfill(); }, +ms);
5361 if (debug.cancellation()) {
5362 ret._setOnCancel(new HandleWrapper(handle));
5363 }
5364 ret._captureStackTrace();
5365 }
5366 ret._setAsyncGuaranteed();
5367 return ret;
5368};
5369
5370Promise.prototype.delay = function (ms) {
5371 return delay(ms, this);
5372};
5373
5374var afterTimeout = function (promise, message, parent) {
5375 var err;
5376 if (typeof message !== "string") {
5377 if (message instanceof Error) {
5378 err = message;
5379 } else {
5380 err = new TimeoutError("operation timed out");
5381 }
5382 } else {
5383 err = new TimeoutError(message);
5384 }
5385 util.markAsOriginatingFromRejection(err);
5386 promise._attachExtraTrace(err);
5387 promise._reject(err);
5388
5389 if (parent != null) {
5390 parent.cancel();
5391 }
5392};
5393
5394function successClear(value) {
5395 clearTimeout(this.handle);
5396 return value;
5397}
5398
5399function failureClear(reason) {
5400 clearTimeout(this.handle);
5401 throw reason;
5402}
5403
5404Promise.prototype.timeout = function (ms, message) {
5405 ms = +ms;
5406 var ret, parent;
5407
5408 var handleWrapper = new HandleWrapper(setTimeout(function timeoutTimeout() {
5409 if (ret.isPending()) {
5410 afterTimeout(ret, message, parent);
5411 }
5412 }, ms));
5413
5414 if (debug.cancellation()) {
5415 parent = this.then();
5416 ret = parent._then(successClear, failureClear,
5417 undefined, handleWrapper, undefined);
5418 ret._setOnCancel(handleWrapper);
5419 } else {
5420 ret = this._then(successClear, failureClear,
5421 undefined, handleWrapper, undefined);
5422 }
5423
5424 return ret;
5425};
5426
5427};
5428
5429},{"./util":36}],35:[function(_dereq_,module,exports){
5430"use strict";
5431module.exports = function (Promise, apiRejection, tryConvertToPromise,
5432 createContext, INTERNAL, debug) {
5433 var util = _dereq_("./util");
5434 var TypeError = _dereq_("./errors").TypeError;
5435 var inherits = _dereq_("./util").inherits;
5436 var errorObj = util.errorObj;
5437 var tryCatch = util.tryCatch;
5438 var NULL = {};
5439
5440 function thrower(e) {
5441 setTimeout(function(){throw e;}, 0);
5442 }
5443
5444 function castPreservingDisposable(thenable) {
5445 var maybePromise = tryConvertToPromise(thenable);
5446 if (maybePromise !== thenable &&
5447 typeof thenable._isDisposable === "function" &&
5448 typeof thenable._getDisposer === "function" &&
5449 thenable._isDisposable()) {
5450 maybePromise._setDisposable(thenable._getDisposer());
5451 }
5452 return maybePromise;
5453 }
5454 function dispose(resources, inspection) {
5455 var i = 0;
5456 var len = resources.length;
5457 var ret = new Promise(INTERNAL);
5458 function iterator() {
5459 if (i >= len) return ret._fulfill();
5460 var maybePromise = castPreservingDisposable(resources[i++]);
5461 if (maybePromise instanceof Promise &&
5462 maybePromise._isDisposable()) {
5463 try {
5464 maybePromise = tryConvertToPromise(
5465 maybePromise._getDisposer().tryDispose(inspection),
5466 resources.promise);
5467 } catch (e) {
5468 return thrower(e);
5469 }
5470 if (maybePromise instanceof Promise) {
5471 return maybePromise._then(iterator, thrower,
5472 null, null, null);
5473 }
5474 }
5475 iterator();
5476 }
5477 iterator();
5478 return ret;
5479 }
5480
5481 function Disposer(data, promise, context) {
5482 this._data = data;
5483 this._promise = promise;
5484 this._context = context;
5485 }
5486
5487 Disposer.prototype.data = function () {
5488 return this._data;
5489 };
5490
5491 Disposer.prototype.promise = function () {
5492 return this._promise;
5493 };
5494
5495 Disposer.prototype.resource = function () {
5496 if (this.promise().isFulfilled()) {
5497 return this.promise().value();
5498 }
5499 return NULL;
5500 };
5501
5502 Disposer.prototype.tryDispose = function(inspection) {
5503 var resource = this.resource();
5504 var context = this._context;
5505 if (context !== undefined) context._pushContext();
5506 var ret = resource !== NULL
5507 ? this.doDispose(resource, inspection) : null;
5508 if (context !== undefined) context._popContext();
5509 this._promise._unsetDisposable();
5510 this._data = null;
5511 return ret;
5512 };
5513
5514 Disposer.isDisposer = function (d) {
5515 return (d != null &&
5516 typeof d.resource === "function" &&
5517 typeof d.tryDispose === "function");
5518 };
5519
5520 function FunctionDisposer(fn, promise, context) {
5521 this.constructor$(fn, promise, context);
5522 }
5523 inherits(FunctionDisposer, Disposer);
5524
5525 FunctionDisposer.prototype.doDispose = function (resource, inspection) {
5526 var fn = this.data();
5527 return fn.call(resource, resource, inspection);
5528 };
5529
5530 function maybeUnwrapDisposer(value) {
5531 if (Disposer.isDisposer(value)) {
5532 this.resources[this.index]._setDisposable(value);
5533 return value.promise();
5534 }
5535 return value;
5536 }
5537
5538 function ResourceList(length) {
5539 this.length = length;
5540 this.promise = null;
5541 this[length-1] = null;
5542 }
5543
5544 ResourceList.prototype._resultCancelled = function() {
5545 var len = this.length;
5546 for (var i = 0; i < len; ++i) {
5547 var item = this[i];
5548 if (item instanceof Promise) {
5549 item.cancel();
5550 }
5551 }
5552 };
5553
5554 Promise.using = function () {
5555 var len = arguments.length;
5556 if (len < 2) return apiRejection(
5557 "you must pass at least 2 arguments to Promise.using");
5558 var fn = arguments[len - 1];
5559 if (typeof fn !== "function") {
5560 return apiRejection("expecting a function but got " + util.classString(fn));
5561 }
5562 var input;
5563 var spreadArgs = true;
5564 if (len === 2 && Array.isArray(arguments[0])) {
5565 input = arguments[0];
5566 len = input.length;
5567 spreadArgs = false;
5568 } else {
5569 input = arguments;
5570 len--;
5571 }
5572 var resources = new ResourceList(len);
5573 for (var i = 0; i < len; ++i) {
5574 var resource = input[i];
5575 if (Disposer.isDisposer(resource)) {
5576 var disposer = resource;
5577 resource = resource.promise();
5578 resource._setDisposable(disposer);
5579 } else {
5580 var maybePromise = tryConvertToPromise(resource);
5581 if (maybePromise instanceof Promise) {
5582 resource =
5583 maybePromise._then(maybeUnwrapDisposer, null, null, {
5584 resources: resources,
5585 index: i
5586 }, undefined);
5587 }
5588 }
5589 resources[i] = resource;
5590 }
5591
5592 var reflectedResources = new Array(resources.length);
5593 for (var i = 0; i < reflectedResources.length; ++i) {
5594 reflectedResources[i] = Promise.resolve(resources[i]).reflect();
5595 }
5596
5597 var resultPromise = Promise.all(reflectedResources)
5598 .then(function(inspections) {
5599 for (var i = 0; i < inspections.length; ++i) {
5600 var inspection = inspections[i];
5601 if (inspection.isRejected()) {
5602 errorObj.e = inspection.error();
5603 return errorObj;
5604 } else if (!inspection.isFulfilled()) {
5605 resultPromise.cancel();
5606 return;
5607 }
5608 inspections[i] = inspection.value();
5609 }
5610 promise._pushContext();
5611
5612 fn = tryCatch(fn);
5613 var ret = spreadArgs
5614 ? fn.apply(undefined, inspections) : fn(inspections);
5615 var promiseCreated = promise._popContext();
5616 debug.checkForgottenReturns(
5617 ret, promiseCreated, "Promise.using", promise);
5618 return ret;
5619 });
5620
5621 var promise = resultPromise.lastly(function() {
5622 var inspection = new Promise.PromiseInspection(resultPromise);
5623 return dispose(resources, inspection);
5624 });
5625 resources.promise = promise;
5626 promise._setOnCancel(resources);
5627 return promise;
5628 };
5629
5630 Promise.prototype._setDisposable = function (disposer) {
5631 this._bitField = this._bitField | 131072;
5632 this._disposer = disposer;
5633 };
5634
5635 Promise.prototype._isDisposable = function () {
5636 return (this._bitField & 131072) > 0;
5637 };
5638
5639 Promise.prototype._getDisposer = function () {
5640 return this._disposer;
5641 };
5642
5643 Promise.prototype._unsetDisposable = function () {
5644 this._bitField = this._bitField & (~131072);
5645 this._disposer = undefined;
5646 };
5647
5648 Promise.prototype.disposer = function (fn) {
5649 if (typeof fn === "function") {
5650 return new FunctionDisposer(fn, this, createContext());
5651 }
5652 throw new TypeError();
5653 };
5654
5655};
5656
5657},{"./errors":12,"./util":36}],36:[function(_dereq_,module,exports){
5658"use strict";
5659var es5 = _dereq_("./es5");
5660var canEvaluate = typeof navigator == "undefined";
5661
5662var errorObj = {e: {}};
5663var tryCatchTarget;
5664var globalObject = typeof self !== "undefined" ? self :
5665 typeof window !== "undefined" ? window :
5666 typeof global !== "undefined" ? global :
5667 this !== undefined ? this : null;
5668
5669function tryCatcher() {
5670 try {
5671 var target = tryCatchTarget;
5672 tryCatchTarget = null;
5673 return target.apply(this, arguments);
5674 } catch (e) {
5675 errorObj.e = e;
5676 return errorObj;
5677 }
5678}
5679function tryCatch(fn) {
5680 tryCatchTarget = fn;
5681 return tryCatcher;
5682}
5683
5684var inherits = function(Child, Parent) {
5685 var hasProp = {}.hasOwnProperty;
5686
5687 function T() {
5688 this.constructor = Child;
5689 this.constructor$ = Parent;
5690 for (var propertyName in Parent.prototype) {
5691 if (hasProp.call(Parent.prototype, propertyName) &&
5692 propertyName.charAt(propertyName.length-1) !== "$"
5693 ) {
5694 this[propertyName + "$"] = Parent.prototype[propertyName];
5695 }
5696 }
5697 }
5698 T.prototype = Parent.prototype;
5699 Child.prototype = new T();
5700 return Child.prototype;
5701};
5702
5703
5704function isPrimitive(val) {
5705 return val == null || val === true || val === false ||
5706 typeof val === "string" || typeof val === "number";
5707
5708}
5709
5710function isObject(value) {
5711 return typeof value === "function" ||
5712 typeof value === "object" && value !== null;
5713}
5714
5715function maybeWrapAsError(maybeError) {
5716 if (!isPrimitive(maybeError)) return maybeError;
5717
5718 return new Error(safeToString(maybeError));
5719}
5720
5721function withAppended(target, appendee) {
5722 var len = target.length;
5723 var ret = new Array(len + 1);
5724 var i;
5725 for (i = 0; i < len; ++i) {
5726 ret[i] = target[i];
5727 }
5728 ret[i] = appendee;
5729 return ret;
5730}
5731
5732function getDataPropertyOrDefault(obj, key, defaultValue) {
5733 if (es5.isES5) {
5734 var desc = Object.getOwnPropertyDescriptor(obj, key);
5735
5736 if (desc != null) {
5737 return desc.get == null && desc.set == null
5738 ? desc.value
5739 : defaultValue;
5740 }
5741 } else {
5742 return {}.hasOwnProperty.call(obj, key) ? obj[key] : undefined;
5743 }
5744}
5745
5746function notEnumerableProp(obj, name, value) {
5747 if (isPrimitive(obj)) return obj;
5748 var descriptor = {
5749 value: value,
5750 configurable: true,
5751 enumerable: false,
5752 writable: true
5753 };
5754 es5.defineProperty(obj, name, descriptor);
5755 return obj;
5756}
5757
5758function thrower(r) {
5759 throw r;
5760}
5761
5762var inheritedDataKeys = (function() {
5763 var excludedPrototypes = [
5764 Array.prototype,
5765 Object.prototype,
5766 Function.prototype
5767 ];
5768
5769 var isExcludedProto = function(val) {
5770 for (var i = 0; i < excludedPrototypes.length; ++i) {
5771 if (excludedPrototypes[i] === val) {
5772 return true;
5773 }
5774 }
5775 return false;
5776 };
5777
5778 if (es5.isES5) {
5779 var getKeys = Object.getOwnPropertyNames;
5780 return function(obj) {
5781 var ret = [];
5782 var visitedKeys = Object.create(null);
5783 while (obj != null && !isExcludedProto(obj)) {
5784 var keys;
5785 try {
5786 keys = getKeys(obj);
5787 } catch (e) {
5788 return ret;
5789 }
5790 for (var i = 0; i < keys.length; ++i) {
5791 var key = keys[i];
5792 if (visitedKeys[key]) continue;
5793 visitedKeys[key] = true;
5794 var desc = Object.getOwnPropertyDescriptor(obj, key);
5795 if (desc != null && desc.get == null && desc.set == null) {
5796 ret.push(key);
5797 }
5798 }
5799 obj = es5.getPrototypeOf(obj);
5800 }
5801 return ret;
5802 };
5803 } else {
5804 var hasProp = {}.hasOwnProperty;
5805 return function(obj) {
5806 if (isExcludedProto(obj)) return [];
5807 var ret = [];
5808
5809 /*jshint forin:false */
5810 enumeration: for (var key in obj) {
5811 if (hasProp.call(obj, key)) {
5812 ret.push(key);
5813 } else {
5814 for (var i = 0; i < excludedPrototypes.length; ++i) {
5815 if (hasProp.call(excludedPrototypes[i], key)) {
5816 continue enumeration;
5817 }
5818 }
5819 ret.push(key);
5820 }
5821 }
5822 return ret;
5823 };
5824 }
5825
5826})();
5827
5828var thisAssignmentPattern = /this\s*\.\s*\S+\s*=/;
5829function isClass(fn) {
5830 try {
5831 if (typeof fn === "function") {
5832 var keys = es5.names(fn.prototype);
5833
5834 var hasMethods = es5.isES5 && keys.length > 1;
5835 var hasMethodsOtherThanConstructor = keys.length > 0 &&
5836 !(keys.length === 1 && keys[0] === "constructor");
5837 var hasThisAssignmentAndStaticMethods =
5838 thisAssignmentPattern.test(fn + "") && es5.names(fn).length > 0;
5839
5840 if (hasMethods || hasMethodsOtherThanConstructor ||
5841 hasThisAssignmentAndStaticMethods) {
5842 return true;
5843 }
5844 }
5845 return false;
5846 } catch (e) {
5847 return false;
5848 }
5849}
5850
5851function toFastProperties(obj) {
5852 /*jshint -W027,-W055,-W031*/
5853 function FakeConstructor() {}
5854 FakeConstructor.prototype = obj;
5855 var l = 8;
5856 while (l--) new FakeConstructor();
5857 return obj;
5858 eval(obj);
5859}
5860
5861var rident = /^[a-z$_][a-z$_0-9]*$/i;
5862function isIdentifier(str) {
5863 return rident.test(str);
5864}
5865
5866function filledRange(count, prefix, suffix) {
5867 var ret = new Array(count);
5868 for(var i = 0; i < count; ++i) {
5869 ret[i] = prefix + i + suffix;
5870 }
5871 return ret;
5872}
5873
5874function safeToString(obj) {
5875 try {
5876 return obj + "";
5877 } catch (e) {
5878 return "[no string representation]";
5879 }
5880}
5881
5882function isError(obj) {
5883 return obj !== null &&
5884 typeof obj === "object" &&
5885 typeof obj.message === "string" &&
5886 typeof obj.name === "string";
5887}
5888
5889function markAsOriginatingFromRejection(e) {
5890 try {
5891 notEnumerableProp(e, "isOperational", true);
5892 }
5893 catch(ignore) {}
5894}
5895
5896function originatesFromRejection(e) {
5897 if (e == null) return false;
5898 return ((e instanceof Error["__BluebirdErrorTypes__"].OperationalError) ||
5899 e["isOperational"] === true);
5900}
5901
5902function canAttachTrace(obj) {
5903 return isError(obj) && es5.propertyIsWritable(obj, "stack");
5904}
5905
5906var ensureErrorObject = (function() {
5907 if (!("stack" in new Error())) {
5908 return function(value) {
5909 if (canAttachTrace(value)) return value;
5910 try {throw new Error(safeToString(value));}
5911 catch(err) {return err;}
5912 };
5913 } else {
5914 return function(value) {
5915 if (canAttachTrace(value)) return value;
5916 return new Error(safeToString(value));
5917 };
5918 }
5919})();
5920
5921function classString(obj) {
5922 return {}.toString.call(obj);
5923}
5924
5925function copyDescriptors(from, to, filter) {
5926 var keys = es5.names(from);
5927 for (var i = 0; i < keys.length; ++i) {
5928 var key = keys[i];
5929 if (filter(key)) {
5930 try {
5931 es5.defineProperty(to, key, es5.getDescriptor(from, key));
5932 } catch (ignore) {}
5933 }
5934 }
5935}
5936
5937var asArray = function(v) {
5938 if (es5.isArray(v)) {
5939 return v;
5940 }
5941 return null;
5942};
5943
5944if (typeof Symbol !== "undefined" && Symbol.iterator) {
5945 var ArrayFrom = typeof Array.from === "function" ? function(v) {
5946 return Array.from(v);
5947 } : function(v) {
5948 var ret = [];
5949 var it = v[Symbol.iterator]();
5950 var itResult;
5951 while (!((itResult = it.next()).done)) {
5952 ret.push(itResult.value);
5953 }
5954 return ret;
5955 };
5956
5957 asArray = function(v) {
5958 if (es5.isArray(v)) {
5959 return v;
5960 } else if (v != null && typeof v[Symbol.iterator] === "function") {
5961 return ArrayFrom(v);
5962 }
5963 return null;
5964 };
5965}
5966
5967var isNode = typeof process !== "undefined" &&
5968 classString(process).toLowerCase() === "[object process]";
5969
5970function env(key, def) {
5971 return isNode ? process.env[key] : def;
5972}
5973
5974function getNativePromise() {
5975 if (typeof Promise === "function") {
5976 try {
5977 var promise = new Promise(function(){});
5978 if ({}.toString.call(promise) === "[object Promise]") {
5979 return Promise;
5980 }
5981 } catch (e) {}
5982 }
5983}
5984
5985function domainBind(self, cb) {
5986 return self.bind(cb);
5987}
5988
5989var ret = {
5990 isClass: isClass,
5991 isIdentifier: isIdentifier,
5992 inheritedDataKeys: inheritedDataKeys,
5993 getDataPropertyOrDefault: getDataPropertyOrDefault,
5994 thrower: thrower,
5995 isArray: es5.isArray,
5996 asArray: asArray,
5997 notEnumerableProp: notEnumerableProp,
5998 isPrimitive: isPrimitive,
5999 isObject: isObject,
6000 isError: isError,
6001 canEvaluate: canEvaluate,
6002 errorObj: errorObj,
6003 tryCatch: tryCatch,
6004 inherits: inherits,
6005 withAppended: withAppended,
6006 maybeWrapAsError: maybeWrapAsError,
6007 toFastProperties: toFastProperties,
6008 filledRange: filledRange,
6009 toString: safeToString,
6010 canAttachTrace: canAttachTrace,
6011 ensureErrorObject: ensureErrorObject,
6012 originatesFromRejection: originatesFromRejection,
6013 markAsOriginatingFromRejection: markAsOriginatingFromRejection,
6014 classString: classString,
6015 copyDescriptors: copyDescriptors,
6016 hasDevTools: typeof chrome !== "undefined" && chrome &&
6017 typeof chrome.loadTimes === "function",
6018 isNode: isNode,
6019 env: env,
6020 global: globalObject,
6021 getNativePromise: getNativePromise,
6022 domainBind: domainBind
6023};
6024ret.isRecentNode = ret.isNode && (function() {
6025 var version = process.versions.node.split(".").map(Number);
6026 return (version[0] === 0 && version[1] > 10) || (version[0] > 0);
6027})();
6028
6029if (ret.isNode) ret.toFastProperties(process);
6030
6031try {throw new Error(); } catch (e) {ret.lastLineError = e;}
6032module.exports = ret;
6033
6034},{"./es5":13}]},{},[4])(4)
6035}); ;if (typeof window !== 'undefined' && window !== null) { window.P = window.Promise; } else if (typeof self !== 'undefined' && self !== null) { self.P = self.Promise; }
6036}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
6037},{"_process":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/process/browser.js"}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/browser-request/index.js":[function(require,module,exports){
6038// Browser Request
6039//
6040// Licensed under the Apache License, Version 2.0 (the "License");
6041// you may not use this file except in compliance with the License.
6042// You may obtain a copy of the License at
6043//
6044// http://www.apache.org/licenses/LICENSE-2.0
6045//
6046// Unless required by applicable law or agreed to in writing, software
6047// distributed under the License is distributed on an "AS IS" BASIS,
6048// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
6049// See the License for the specific language governing permissions and
6050// limitations under the License.
6051
6052// UMD HEADER START
6053(function (root, factory) {
6054 if (typeof define === 'function' && define.amd) {
6055 // AMD. Register as an anonymous module.
6056 define([], factory);
6057 } else if (typeof exports === 'object') {
6058 // Node. Does not work with strict CommonJS, but
6059 // only CommonJS-like enviroments that support module.exports,
6060 // like Node.
6061 module.exports = factory();
6062 } else {
6063 // Browser globals (root is window)
6064 root.returnExports = factory();
6065 }
6066}(this, function () {
6067// UMD HEADER END
6068
6069var XHR = XMLHttpRequest
6070if (!XHR) throw new Error('missing XMLHttpRequest')
6071request.log = {
6072 'trace': noop, 'debug': noop, 'info': noop, 'warn': noop, 'error': noop
6073}
6074
6075var DEFAULT_TIMEOUT = 3 * 60 * 1000 // 3 minutes
6076
6077//
6078// request
6079//
6080
6081function request(options, callback) {
6082 // The entry-point to the API: prep the options object and pass the real work to run_xhr.
6083 if(typeof callback !== 'function')
6084 throw new Error('Bad callback given: ' + callback)
6085
6086 if(!options)
6087 throw new Error('No options given')
6088
6089 var options_onResponse = options.onResponse; // Save this for later.
6090
6091 if(typeof options === 'string')
6092 options = {'uri':options};
6093 else
6094 options = JSON.parse(JSON.stringify(options)); // Use a duplicate for mutating.
6095
6096 options.onResponse = options_onResponse // And put it back.
6097
6098 if (options.verbose) request.log = getLogger();
6099
6100 if(options.url) {
6101 options.uri = options.url;
6102 delete options.url;
6103 }
6104
6105 if(!options.uri && options.uri !== "")
6106 throw new Error("options.uri is a required argument");
6107
6108 if(typeof options.uri != "string")
6109 throw new Error("options.uri must be a string");
6110
6111 var unsupported_options = ['proxy', '_redirectsFollowed', 'maxRedirects', 'followRedirect']
6112 for (var i = 0; i < unsupported_options.length; i++)
6113 if(options[ unsupported_options[i] ])
6114 throw new Error("options." + unsupported_options[i] + " is not supported")
6115
6116 options.callback = callback
6117 options.method = options.method || 'GET';
6118 options.headers = options.headers || {};
6119 options.body = options.body || null
6120 options.timeout = options.timeout || request.DEFAULT_TIMEOUT
6121
6122 if(options.headers.host)
6123 throw new Error("Options.headers.host is not supported");
6124
6125 if(options.json) {
6126 options.headers.accept = options.headers.accept || 'application/json'
6127 if(options.method !== 'GET')
6128 options.headers['content-type'] = 'application/json'
6129
6130 if(typeof options.json !== 'boolean')
6131 options.body = JSON.stringify(options.json)
6132 else if(typeof options.body !== 'string')
6133 options.body = JSON.stringify(options.body)
6134 }
6135
6136 //BEGIN QS Hack
6137 var serialize = function(obj) {
6138 var str = [];
6139 for(var p in obj)
6140 if (obj.hasOwnProperty(p)) {
6141 str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
6142 }
6143 return str.join("&");
6144 }
6145
6146 if(options.qs){
6147 var qs = (typeof options.qs == 'string')? options.qs : serialize(options.qs);
6148 if(options.uri.indexOf('?') !== -1){ //no get params
6149 options.uri = options.uri+'&'+qs;
6150 }else{ //existing get params
6151 options.uri = options.uri+'?'+qs;
6152 }
6153 }
6154 //END QS Hack
6155
6156 //BEGIN FORM Hack
6157 var multipart = function(obj) {
6158 //todo: support file type (useful?)
6159 var result = {};
6160 result.boundry = '-------------------------------'+Math.floor(Math.random()*1000000000);
6161 var lines = [];
6162 for(var p in obj){
6163 if (obj.hasOwnProperty(p)) {
6164 lines.push(
6165 '--'+result.boundry+"\n"+
6166 'Content-Disposition: form-data; name="'+p+'"'+"\n"+
6167 "\n"+
6168 obj[p]+"\n"
6169 );
6170 }
6171 }
6172 lines.push( '--'+result.boundry+'--' );
6173 result.body = lines.join('');
6174 result.length = result.body.length;
6175 result.type = 'multipart/form-data; boundary='+result.boundry;
6176 return result;
6177 }
6178
6179 if(options.form){
6180 if(typeof options.form == 'string') throw('form name unsupported');
6181 if(options.method === 'POST'){
6182 var encoding = (options.encoding || 'application/x-www-form-urlencoded').toLowerCase();
6183 options.headers['content-type'] = encoding;
6184 switch(encoding){
6185 case 'application/x-www-form-urlencoded':
6186 options.body = serialize(options.form).replace(/%20/g, "+");
6187 break;
6188 case 'multipart/form-data':
6189 var multi = multipart(options.form);
6190 //options.headers['content-length'] = multi.length;
6191 options.body = multi.body;
6192 options.headers['content-type'] = multi.type;
6193 break;
6194 default : throw new Error('unsupported encoding:'+encoding);
6195 }
6196 }
6197 }
6198 //END FORM Hack
6199
6200 // If onResponse is boolean true, call back immediately when the response is known,
6201 // not when the full request is complete.
6202 options.onResponse = options.onResponse || noop
6203 if(options.onResponse === true) {
6204 options.onResponse = callback
6205 options.callback = noop
6206 }
6207
6208 // XXX Browsers do not like this.
6209 //if(options.body)
6210 // options.headers['content-length'] = options.body.length;
6211
6212 // HTTP basic authentication
6213 if(!options.headers.authorization && options.auth)
6214 options.headers.authorization = 'Basic ' + b64_enc(options.auth.username + ':' + options.auth.password);
6215
6216 return run_xhr(options)
6217}
6218
6219var req_seq = 0
6220function run_xhr(options) {
6221 var xhr = new XHR
6222 , timed_out = false
6223 , is_cors = is_crossDomain(options.uri)
6224 , supports_cors = ('withCredentials' in xhr)
6225
6226 req_seq += 1
6227 xhr.seq_id = req_seq
6228 xhr.id = req_seq + ': ' + options.method + ' ' + options.uri
6229 xhr._id = xhr.id // I know I will type "_id" from habit all the time.
6230
6231 if(is_cors && !supports_cors) {
6232 var cors_err = new Error('Browser does not support cross-origin request: ' + options.uri)
6233 cors_err.cors = 'unsupported'
6234 return options.callback(cors_err, xhr)
6235 }
6236
6237 xhr.timeoutTimer = setTimeout(too_late, options.timeout)
6238 function too_late() {
6239 timed_out = true
6240 var er = new Error('ETIMEDOUT')
6241 er.code = 'ETIMEDOUT'
6242 er.duration = options.timeout
6243
6244 request.log.error('Timeout', { 'id':xhr._id, 'milliseconds':options.timeout })
6245 return options.callback(er, xhr)
6246 }
6247
6248 // Some states can be skipped over, so remember what is still incomplete.
6249 var did = {'response':false, 'loading':false, 'end':false}
6250
6251 xhr.onreadystatechange = on_state_change
6252 xhr.open(options.method, options.uri, true) // asynchronous
6253 if(is_cors)
6254 xhr.withCredentials = !! options.withCredentials
6255 xhr.send(options.body)
6256 return xhr
6257
6258 function on_state_change(event) {
6259 if(timed_out)
6260 return request.log.debug('Ignoring timed out state change', {'state':xhr.readyState, 'id':xhr.id})
6261
6262 request.log.debug('State change', {'state':xhr.readyState, 'id':xhr.id, 'timed_out':timed_out})
6263
6264 if(xhr.readyState === XHR.OPENED) {
6265 request.log.debug('Request started', {'id':xhr.id})
6266 for (var key in options.headers)
6267 xhr.setRequestHeader(key, options.headers[key])
6268 }
6269
6270 else if(xhr.readyState === XHR.HEADERS_RECEIVED)
6271 on_response()
6272
6273 else if(xhr.readyState === XHR.LOADING) {
6274 on_response()
6275 on_loading()
6276 }
6277
6278 else if(xhr.readyState === XHR.DONE) {
6279 on_response()
6280 on_loading()
6281 on_end()
6282 }
6283 }
6284
6285 function on_response() {
6286 if(did.response)
6287 return
6288
6289 did.response = true
6290 request.log.debug('Got response', {'id':xhr.id, 'status':xhr.status})
6291 clearTimeout(xhr.timeoutTimer)
6292 xhr.statusCode = xhr.status // Node request compatibility
6293
6294 // Detect failed CORS requests.
6295 if(is_cors && xhr.statusCode == 0) {
6296 var cors_err = new Error('CORS request rejected: ' + options.uri)
6297 cors_err.cors = 'rejected'
6298
6299 // Do not process this request further.
6300 did.loading = true
6301 did.end = true
6302
6303 return options.callback(cors_err, xhr)
6304 }
6305
6306 options.onResponse(null, xhr)
6307 }
6308
6309 function on_loading() {
6310 if(did.loading)
6311 return
6312
6313 did.loading = true
6314 request.log.debug('Response body loading', {'id':xhr.id})
6315 // TODO: Maybe simulate "data" events by watching xhr.responseText
6316 }
6317
6318 function on_end() {
6319 if(did.end)
6320 return
6321
6322 did.end = true
6323 request.log.debug('Request done', {'id':xhr.id})
6324
6325 xhr.body = xhr.responseText
6326 if(options.json) {
6327 try { xhr.body = JSON.parse(xhr.responseText) }
6328 catch (er) { return options.callback(er, xhr) }
6329 }
6330
6331 options.callback(null, xhr, xhr.body)
6332 }
6333
6334} // request
6335
6336request.withCredentials = false;
6337request.DEFAULT_TIMEOUT = DEFAULT_TIMEOUT;
6338
6339//
6340// defaults
6341//
6342
6343request.defaults = function(options, requester) {
6344 var def = function (method) {
6345 var d = function (params, callback) {
6346 if(typeof params === 'string')
6347 params = {'uri': params};
6348 else {
6349 params = JSON.parse(JSON.stringify(params));
6350 }
6351 for (var i in options) {
6352 if (params[i] === undefined) params[i] = options[i]
6353 }
6354 return method(params, callback)
6355 }
6356 return d
6357 }
6358 var de = def(request)
6359 de.get = def(request.get)
6360 de.post = def(request.post)
6361 de.put = def(request.put)
6362 de.head = def(request.head)
6363 return de
6364}
6365
6366//
6367// HTTP method shortcuts
6368//
6369
6370var shortcuts = [ 'get', 'put', 'post', 'head' ];
6371shortcuts.forEach(function(shortcut) {
6372 var method = shortcut.toUpperCase();
6373 var func = shortcut.toLowerCase();
6374
6375 request[func] = function(opts) {
6376 if(typeof opts === 'string')
6377 opts = {'method':method, 'uri':opts};
6378 else {
6379 opts = JSON.parse(JSON.stringify(opts));
6380 opts.method = method;
6381 }
6382
6383 var args = [opts].concat(Array.prototype.slice.apply(arguments, [1]));
6384 return request.apply(this, args);
6385 }
6386})
6387
6388//
6389// CouchDB shortcut
6390//
6391
6392request.couch = function(options, callback) {
6393 if(typeof options === 'string')
6394 options = {'uri':options}
6395
6396 // Just use the request API to do JSON.
6397 options.json = true
6398 if(options.body)
6399 options.json = options.body
6400 delete options.body
6401
6402 callback = callback || noop
6403
6404 var xhr = request(options, couch_handler)
6405 return xhr
6406
6407 function couch_handler(er, resp, body) {
6408 if(er)
6409 return callback(er, resp, body)
6410
6411 if((resp.statusCode < 200 || resp.statusCode > 299) && body.error) {
6412 // The body is a Couch JSON object indicating the error.
6413 er = new Error('CouchDB error: ' + (body.error.reason || body.error.error))
6414 for (var key in body)
6415 er[key] = body[key]
6416 return callback(er, resp, body);
6417 }
6418
6419 return callback(er, resp, body);
6420 }
6421}
6422
6423//
6424// Utility
6425//
6426
6427function noop() {}
6428
6429function getLogger() {
6430 var logger = {}
6431 , levels = ['trace', 'debug', 'info', 'warn', 'error']
6432 , level, i
6433
6434 for(i = 0; i < levels.length; i++) {
6435 level = levels[i]
6436
6437 logger[level] = noop
6438 if(typeof console !== 'undefined' && console && console[level])
6439 logger[level] = formatted(console, level)
6440 }
6441
6442 return logger
6443}
6444
6445function formatted(obj, method) {
6446 return formatted_logger
6447
6448 function formatted_logger(str, context) {
6449 if(typeof context === 'object')
6450 str += ' ' + JSON.stringify(context)
6451
6452 return obj[method].call(obj, str)
6453 }
6454}
6455
6456// Return whether a URL is a cross-domain request.
6457function is_crossDomain(url) {
6458 var rurl = /^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/
6459
6460 // jQuery #8138, IE may throw an exception when accessing
6461 // a field from window.location if document.domain has been set
6462 var ajaxLocation
6463 try { ajaxLocation = location.href }
6464 catch (e) {
6465 // Use the href attribute of an A element since IE will modify it given document.location
6466 ajaxLocation = document.createElement( "a" );
6467 ajaxLocation.href = "";
6468 ajaxLocation = ajaxLocation.href;
6469 }
6470
6471 var ajaxLocParts = rurl.exec(ajaxLocation.toLowerCase()) || []
6472 , parts = rurl.exec(url.toLowerCase() )
6473
6474 var result = !!(
6475 parts &&
6476 ( parts[1] != ajaxLocParts[1]
6477 || parts[2] != ajaxLocParts[2]
6478 || (parts[3] || (parts[1] === "http:" ? 80 : 443)) != (ajaxLocParts[3] || (ajaxLocParts[1] === "http:" ? 80 : 443))
6479 )
6480 )
6481
6482 //console.debug('is_crossDomain('+url+') -> ' + result)
6483 return result
6484}
6485
6486// MIT License from http://phpjs.org/functions/base64_encode:358
6487function b64_enc (data) {
6488 // Encodes string using MIME base64 algorithm
6489 var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
6490 var o1, o2, o3, h1, h2, h3, h4, bits, i = 0, ac = 0, enc="", tmp_arr = [];
6491
6492 if (!data) {
6493 return data;
6494 }
6495
6496 // assume utf8 data
6497 // data = this.utf8_encode(data+'');
6498
6499 do { // pack three octets into four hexets
6500 o1 = data.charCodeAt(i++);
6501 o2 = data.charCodeAt(i++);
6502 o3 = data.charCodeAt(i++);
6503
6504 bits = o1<<16 | o2<<8 | o3;
6505
6506 h1 = bits>>18 & 0x3f;
6507 h2 = bits>>12 & 0x3f;
6508 h3 = bits>>6 & 0x3f;
6509 h4 = bits & 0x3f;
6510
6511 // use hexets to index into b64, and append result to encoded string
6512 tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
6513 } while (i < data.length);
6514
6515 enc = tmp_arr.join('');
6516
6517 switch (data.length % 3) {
6518 case 1:
6519 enc = enc.slice(0, -2) + '==';
6520 break;
6521 case 2:
6522 enc = enc.slice(0, -1) + '=';
6523 break;
6524 }
6525
6526 return enc;
6527}
6528 return request;
6529//UMD FOOTER START
6530}));
6531//UMD FOOTER END
6532
6533},{}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/browser-resolve/empty.js":[function(require,module,exports){
6534
6535},{}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/buffer/index.js":[function(require,module,exports){
6536(function (global){
6537/*!
6538 * The buffer module from node.js, for the browser.
6539 *
6540 * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
6541 * @license MIT
6542 */
6543/* eslint-disable no-proto */
6544
6545'use strict'
6546
6547var base64 = require('base64-js')
6548var ieee754 = require('ieee754')
6549var isArray = require('isarray')
6550
6551exports.Buffer = Buffer
6552exports.SlowBuffer = SlowBuffer
6553exports.INSPECT_MAX_BYTES = 50
6554Buffer.poolSize = 8192 // not used by this implementation
6555
6556var rootParent = {}
6557
6558/**
6559 * If `Buffer.TYPED_ARRAY_SUPPORT`:
6560 * === true Use Uint8Array implementation (fastest)
6561 * === false Use Object implementation (most compatible, even IE6)
6562 *
6563 * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
6564 * Opera 11.6+, iOS 4.2+.
6565 *
6566 * Due to various browser bugs, sometimes the Object implementation will be used even
6567 * when the browser supports typed arrays.
6568 *
6569 * Note:
6570 *
6571 * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
6572 * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
6573 *
6574 * - Safari 5-7 lacks support for changing the `Object.prototype.constructor` property
6575 * on objects.
6576 *
6577 * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
6578 *
6579 * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
6580 * incorrect length in some situations.
6581
6582 * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
6583 * get the Object implementation, which is slower but behaves correctly.
6584 */
6585Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined
6586 ? global.TYPED_ARRAY_SUPPORT
6587 : typedArraySupport()
6588
6589function typedArraySupport () {
6590 function Bar () {}
6591 try {
6592 var arr = new Uint8Array(1)
6593 arr.foo = function () { return 42 }
6594 arr.constructor = Bar
6595 return arr.foo() === 42 && // typed array instances can be augmented
6596 arr.constructor === Bar && // constructor can be set
6597 typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`
6598 arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`
6599 } catch (e) {
6600 return false
6601 }
6602}
6603
6604function kMaxLength () {
6605 return Buffer.TYPED_ARRAY_SUPPORT
6606 ? 0x7fffffff
6607 : 0x3fffffff
6608}
6609
6610/**
6611 * Class: Buffer
6612 * =============
6613 *
6614 * The Buffer constructor returns instances of `Uint8Array` that are augmented
6615 * with function properties for all the node `Buffer` API functions. We use
6616 * `Uint8Array` so that square bracket notation works as expected -- it returns
6617 * a single octet.
6618 *
6619 * By augmenting the instances, we can avoid modifying the `Uint8Array`
6620 * prototype.
6621 */
6622function Buffer (arg) {
6623 if (!(this instanceof Buffer)) {
6624 // Avoid going through an ArgumentsAdaptorTrampoline in the common case.
6625 if (arguments.length > 1) return new Buffer(arg, arguments[1])
6626 return new Buffer(arg)
6627 }
6628
6629 if (!Buffer.TYPED_ARRAY_SUPPORT) {
6630 this.length = 0
6631 this.parent = undefined
6632 }
6633
6634 // Common case.
6635 if (typeof arg === 'number') {
6636 return fromNumber(this, arg)
6637 }
6638
6639 // Slightly less common case.
6640 if (typeof arg === 'string') {
6641 return fromString(this, arg, arguments.length > 1 ? arguments[1] : 'utf8')
6642 }
6643
6644 // Unusual.
6645 return fromObject(this, arg)
6646}
6647
6648function fromNumber (that, length) {
6649 that = allocate(that, length < 0 ? 0 : checked(length) | 0)
6650 if (!Buffer.TYPED_ARRAY_SUPPORT) {
6651 for (var i = 0; i < length; i++) {
6652 that[i] = 0
6653 }
6654 }
6655 return that
6656}
6657
6658function fromString (that, string, encoding) {
6659 if (typeof encoding !== 'string' || encoding === '') encoding = 'utf8'
6660
6661 // Assumption: byteLength() return value is always < kMaxLength.
6662 var length = byteLength(string, encoding) | 0
6663 that = allocate(that, length)
6664
6665 that.write(string, encoding)
6666 return that
6667}
6668
6669function fromObject (that, object) {
6670 if (Buffer.isBuffer(object)) return fromBuffer(that, object)
6671
6672 if (isArray(object)) return fromArray(that, object)
6673
6674 if (object == null) {
6675 throw new TypeError('must start with number, buffer, array or string')
6676 }
6677
6678 if (typeof ArrayBuffer !== 'undefined') {
6679 if (object.buffer instanceof ArrayBuffer) {
6680 return fromTypedArray(that, object)
6681 }
6682 if (object instanceof ArrayBuffer) {
6683 return fromArrayBuffer(that, object)
6684 }
6685 }
6686
6687 if (object.length) return fromArrayLike(that, object)
6688
6689 return fromJsonObject(that, object)
6690}
6691
6692function fromBuffer (that, buffer) {
6693 var length = checked(buffer.length) | 0
6694 that = allocate(that, length)
6695 buffer.copy(that, 0, 0, length)
6696 return that
6697}
6698
6699function fromArray (that, array) {
6700 var length = checked(array.length) | 0
6701 that = allocate(that, length)
6702 for (var i = 0; i < length; i += 1) {
6703 that[i] = array[i] & 255
6704 }
6705 return that
6706}
6707
6708// Duplicate of fromArray() to keep fromArray() monomorphic.
6709function fromTypedArray (that, array) {
6710 var length = checked(array.length) | 0
6711 that = allocate(that, length)
6712 // Truncating the elements is probably not what people expect from typed
6713 // arrays with BYTES_PER_ELEMENT > 1 but it's compatible with the behavior
6714 // of the old Buffer constructor.
6715 for (var i = 0; i < length; i += 1) {
6716 that[i] = array[i] & 255
6717 }
6718 return that
6719}
6720
6721function fromArrayBuffer (that, array) {
6722 if (Buffer.TYPED_ARRAY_SUPPORT) {
6723 // Return an augmented `Uint8Array` instance, for best performance
6724 array.byteLength
6725 that = Buffer._augment(new Uint8Array(array))
6726 } else {
6727 // Fallback: Return an object instance of the Buffer class
6728 that = fromTypedArray(that, new Uint8Array(array))
6729 }
6730 return that
6731}
6732
6733function fromArrayLike (that, array) {
6734 var length = checked(array.length) | 0
6735 that = allocate(that, length)
6736 for (var i = 0; i < length; i += 1) {
6737 that[i] = array[i] & 255
6738 }
6739 return that
6740}
6741
6742// Deserialize { type: 'Buffer', data: [1,2,3,...] } into a Buffer object.
6743// Returns a zero-length buffer for inputs that don't conform to the spec.
6744function fromJsonObject (that, object) {
6745 var array
6746 var length = 0
6747
6748 if (object.type === 'Buffer' && isArray(object.data)) {
6749 array = object.data
6750 length = checked(array.length) | 0
6751 }
6752 that = allocate(that, length)
6753
6754 for (var i = 0; i < length; i += 1) {
6755 that[i] = array[i] & 255
6756 }
6757 return that
6758}
6759
6760if (Buffer.TYPED_ARRAY_SUPPORT) {
6761 Buffer.prototype.__proto__ = Uint8Array.prototype
6762 Buffer.__proto__ = Uint8Array
6763} else {
6764 // pre-set for values that may exist in the future
6765 Buffer.prototype.length = undefined
6766 Buffer.prototype.parent = undefined
6767}
6768
6769function allocate (that, length) {
6770 if (Buffer.TYPED_ARRAY_SUPPORT) {
6771 // Return an augmented `Uint8Array` instance, for best performance
6772 that = Buffer._augment(new Uint8Array(length))
6773 that.__proto__ = Buffer.prototype
6774 } else {
6775 // Fallback: Return an object instance of the Buffer class
6776 that.length = length
6777 that._isBuffer = true
6778 }
6779
6780 var fromPool = length !== 0 && length <= Buffer.poolSize >>> 1
6781 if (fromPool) that.parent = rootParent
6782
6783 return that
6784}
6785
6786function checked (length) {
6787 // Note: cannot use `length < kMaxLength` here because that fails when
6788 // length is NaN (which is otherwise coerced to zero.)
6789 if (length >= kMaxLength()) {
6790 throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
6791 'size: 0x' + kMaxLength().toString(16) + ' bytes')
6792 }
6793 return length | 0
6794}
6795
6796function SlowBuffer (subject, encoding) {
6797 if (!(this instanceof SlowBuffer)) return new SlowBuffer(subject, encoding)
6798
6799 var buf = new Buffer(subject, encoding)
6800 delete buf.parent
6801 return buf
6802}
6803
6804Buffer.isBuffer = function isBuffer (b) {
6805 return !!(b != null && b._isBuffer)
6806}
6807
6808Buffer.compare = function compare (a, b) {
6809 if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
6810 throw new TypeError('Arguments must be Buffers')
6811 }
6812
6813 if (a === b) return 0
6814
6815 var x = a.length
6816 var y = b.length
6817
6818 var i = 0
6819 var len = Math.min(x, y)
6820 while (i < len) {
6821 if (a[i] !== b[i]) break
6822
6823 ++i
6824 }
6825
6826 if (i !== len) {
6827 x = a[i]
6828 y = b[i]
6829 }
6830
6831 if (x < y) return -1
6832 if (y < x) return 1
6833 return 0
6834}
6835
6836Buffer.isEncoding = function isEncoding (encoding) {
6837 switch (String(encoding).toLowerCase()) {
6838 case 'hex':
6839 case 'utf8':
6840 case 'utf-8':
6841 case 'ascii':
6842 case 'binary':
6843 case 'base64':
6844 case 'raw':
6845 case 'ucs2':
6846 case 'ucs-2':
6847 case 'utf16le':
6848 case 'utf-16le':
6849 return true
6850 default:
6851 return false
6852 }
6853}
6854
6855Buffer.concat = function concat (list, length) {
6856 if (!isArray(list)) throw new TypeError('list argument must be an Array of Buffers.')
6857
6858 if (list.length === 0) {
6859 return new Buffer(0)
6860 }
6861
6862 var i
6863 if (length === undefined) {
6864 length = 0
6865 for (i = 0; i < list.length; i++) {
6866 length += list[i].length
6867 }
6868 }
6869
6870 var buf = new Buffer(length)
6871 var pos = 0
6872 for (i = 0; i < list.length; i++) {
6873 var item = list[i]
6874 item.copy(buf, pos)
6875 pos += item.length
6876 }
6877 return buf
6878}
6879
6880function byteLength (string, encoding) {
6881 if (typeof string !== 'string') string = '' + string
6882
6883 var len = string.length
6884 if (len === 0) return 0
6885
6886 // Use a for loop to avoid recursion
6887 var loweredCase = false
6888 for (;;) {
6889 switch (encoding) {
6890 case 'ascii':
6891 case 'binary':
6892 // Deprecated
6893 case 'raw':
6894 case 'raws':
6895 return len
6896 case 'utf8':
6897 case 'utf-8':
6898 return utf8ToBytes(string).length
6899 case 'ucs2':
6900 case 'ucs-2':
6901 case 'utf16le':
6902 case 'utf-16le':
6903 return len * 2
6904 case 'hex':
6905 return len >>> 1
6906 case 'base64':
6907 return base64ToBytes(string).length
6908 default:
6909 if (loweredCase) return utf8ToBytes(string).length // assume utf8
6910 encoding = ('' + encoding).toLowerCase()
6911 loweredCase = true
6912 }
6913 }
6914}
6915Buffer.byteLength = byteLength
6916
6917function slowToString (encoding, start, end) {
6918 var loweredCase = false
6919
6920 start = start | 0
6921 end = end === undefined || end === Infinity ? this.length : end | 0
6922
6923 if (!encoding) encoding = 'utf8'
6924 if (start < 0) start = 0
6925 if (end > this.length) end = this.length
6926 if (end <= start) return ''
6927
6928 while (true) {
6929 switch (encoding) {
6930 case 'hex':
6931 return hexSlice(this, start, end)
6932
6933 case 'utf8':
6934 case 'utf-8':
6935 return utf8Slice(this, start, end)
6936
6937 case 'ascii':
6938 return asciiSlice(this, start, end)
6939
6940 case 'binary':
6941 return binarySlice(this, start, end)
6942
6943 case 'base64':
6944 return base64Slice(this, start, end)
6945
6946 case 'ucs2':
6947 case 'ucs-2':
6948 case 'utf16le':
6949 case 'utf-16le':
6950 return utf16leSlice(this, start, end)
6951
6952 default:
6953 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
6954 encoding = (encoding + '').toLowerCase()
6955 loweredCase = true
6956 }
6957 }
6958}
6959
6960Buffer.prototype.toString = function toString () {
6961 var length = this.length | 0
6962 if (length === 0) return ''
6963 if (arguments.length === 0) return utf8Slice(this, 0, length)
6964 return slowToString.apply(this, arguments)
6965}
6966
6967Buffer.prototype.equals = function equals (b) {
6968 if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
6969 if (this === b) return true
6970 return Buffer.compare(this, b) === 0
6971}
6972
6973Buffer.prototype.inspect = function inspect () {
6974 var str = ''
6975 var max = exports.INSPECT_MAX_BYTES
6976 if (this.length > 0) {
6977 str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
6978 if (this.length > max) str += ' ... '
6979 }
6980 return '<Buffer ' + str + '>'
6981}
6982
6983Buffer.prototype.compare = function compare (b) {
6984 if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
6985 if (this === b) return 0
6986 return Buffer.compare(this, b)
6987}
6988
6989Buffer.prototype.indexOf = function indexOf (val, byteOffset) {
6990 if (byteOffset > 0x7fffffff) byteOffset = 0x7fffffff
6991 else if (byteOffset < -0x80000000) byteOffset = -0x80000000
6992 byteOffset >>= 0
6993
6994 if (this.length === 0) return -1
6995 if (byteOffset >= this.length) return -1
6996
6997 // Negative offsets start from the end of the buffer
6998 if (byteOffset < 0) byteOffset = Math.max(this.length + byteOffset, 0)
6999
7000 if (typeof val === 'string') {
7001 if (val.length === 0) return -1 // special case: looking for empty string always fails
7002 return String.prototype.indexOf.call(this, val, byteOffset)
7003 }
7004 if (Buffer.isBuffer(val)) {
7005 return arrayIndexOf(this, val, byteOffset)
7006 }
7007 if (typeof val === 'number') {
7008 if (Buffer.TYPED_ARRAY_SUPPORT && Uint8Array.prototype.indexOf === 'function') {
7009 return Uint8Array.prototype.indexOf.call(this, val, byteOffset)
7010 }
7011 return arrayIndexOf(this, [ val ], byteOffset)
7012 }
7013
7014 function arrayIndexOf (arr, val, byteOffset) {
7015 var foundIndex = -1
7016 for (var i = 0; byteOffset + i < arr.length; i++) {
7017 if (arr[byteOffset + i] === val[foundIndex === -1 ? 0 : i - foundIndex]) {
7018 if (foundIndex === -1) foundIndex = i
7019 if (i - foundIndex + 1 === val.length) return byteOffset + foundIndex
7020 } else {
7021 foundIndex = -1
7022 }
7023 }
7024 return -1
7025 }
7026
7027 throw new TypeError('val must be string, number or Buffer')
7028}
7029
7030// `get` is deprecated
7031Buffer.prototype.get = function get (offset) {
7032 console.log('.get() is deprecated. Access using array indexes instead.')
7033 return this.readUInt8(offset)
7034}
7035
7036// `set` is deprecated
7037Buffer.prototype.set = function set (v, offset) {
7038 console.log('.set() is deprecated. Access using array indexes instead.')
7039 return this.writeUInt8(v, offset)
7040}
7041
7042function hexWrite (buf, string, offset, length) {
7043 offset = Number(offset) || 0
7044 var remaining = buf.length - offset
7045 if (!length) {
7046 length = remaining
7047 } else {
7048 length = Number(length)
7049 if (length > remaining) {
7050 length = remaining
7051 }
7052 }
7053
7054 // must be an even number of digits
7055 var strLen = string.length
7056 if (strLen % 2 !== 0) throw new Error('Invalid hex string')
7057
7058 if (length > strLen / 2) {
7059 length = strLen / 2
7060 }
7061 for (var i = 0; i < length; i++) {
7062 var parsed = parseInt(string.substr(i * 2, 2), 16)
7063 if (isNaN(parsed)) throw new Error('Invalid hex string')
7064 buf[offset + i] = parsed
7065 }
7066 return i
7067}
7068
7069function utf8Write (buf, string, offset, length) {
7070 return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
7071}
7072
7073function asciiWrite (buf, string, offset, length) {
7074 return blitBuffer(asciiToBytes(string), buf, offset, length)
7075}
7076
7077function binaryWrite (buf, string, offset, length) {
7078 return asciiWrite(buf, string, offset, length)
7079}
7080
7081function base64Write (buf, string, offset, length) {
7082 return blitBuffer(base64ToBytes(string), buf, offset, length)
7083}
7084
7085function ucs2Write (buf, string, offset, length) {
7086 return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
7087}
7088
7089Buffer.prototype.write = function write (string, offset, length, encoding) {
7090 // Buffer#write(string)
7091 if (offset === undefined) {
7092 encoding = 'utf8'
7093 length = this.length
7094 offset = 0
7095 // Buffer#write(string, encoding)
7096 } else if (length === undefined && typeof offset === 'string') {
7097 encoding = offset
7098 length = this.length
7099 offset = 0
7100 // Buffer#write(string, offset[, length][, encoding])
7101 } else if (isFinite(offset)) {
7102 offset = offset | 0
7103 if (isFinite(length)) {
7104 length = length | 0
7105 if (encoding === undefined) encoding = 'utf8'
7106 } else {
7107 encoding = length
7108 length = undefined
7109 }
7110 // legacy write(string, encoding, offset, length) - remove in v0.13
7111 } else {
7112 var swap = encoding
7113 encoding = offset
7114 offset = length | 0
7115 length = swap
7116 }
7117
7118 var remaining = this.length - offset
7119 if (length === undefined || length > remaining) length = remaining
7120
7121 if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
7122 throw new RangeError('attempt to write outside buffer bounds')
7123 }
7124
7125 if (!encoding) encoding = 'utf8'
7126
7127 var loweredCase = false
7128 for (;;) {
7129 switch (encoding) {
7130 case 'hex':
7131 return hexWrite(this, string, offset, length)
7132
7133 case 'utf8':
7134 case 'utf-8':
7135 return utf8Write(this, string, offset, length)
7136
7137 case 'ascii':
7138 return asciiWrite(this, string, offset, length)
7139
7140 case 'binary':
7141 return binaryWrite(this, string, offset, length)
7142
7143 case 'base64':
7144 // Warning: maxLength not taken into account in base64Write
7145 return base64Write(this, string, offset, length)
7146
7147 case 'ucs2':
7148 case 'ucs-2':
7149 case 'utf16le':
7150 case 'utf-16le':
7151 return ucs2Write(this, string, offset, length)
7152
7153 default:
7154 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
7155 encoding = ('' + encoding).toLowerCase()
7156 loweredCase = true
7157 }
7158 }
7159}
7160
7161Buffer.prototype.toJSON = function toJSON () {
7162 return {
7163 type: 'Buffer',
7164 data: Array.prototype.slice.call(this._arr || this, 0)
7165 }
7166}
7167
7168function base64Slice (buf, start, end) {
7169 if (start === 0 && end === buf.length) {
7170 return base64.fromByteArray(buf)
7171 } else {
7172 return base64.fromByteArray(buf.slice(start, end))
7173 }
7174}
7175
7176function utf8Slice (buf, start, end) {
7177 end = Math.min(buf.length, end)
7178 var res = []
7179
7180 var i = start
7181 while (i < end) {
7182 var firstByte = buf[i]
7183 var codePoint = null
7184 var bytesPerSequence = (firstByte > 0xEF) ? 4
7185 : (firstByte > 0xDF) ? 3
7186 : (firstByte > 0xBF) ? 2
7187 : 1
7188
7189 if (i + bytesPerSequence <= end) {
7190 var secondByte, thirdByte, fourthByte, tempCodePoint
7191
7192 switch (bytesPerSequence) {
7193 case 1:
7194 if (firstByte < 0x80) {
7195 codePoint = firstByte
7196 }
7197 break
7198 case 2:
7199 secondByte = buf[i + 1]
7200 if ((secondByte & 0xC0) === 0x80) {
7201 tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
7202 if (tempCodePoint > 0x7F) {
7203 codePoint = tempCodePoint
7204 }
7205 }
7206 break
7207 case 3:
7208 secondByte = buf[i + 1]
7209 thirdByte = buf[i + 2]
7210 if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
7211 tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
7212 if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
7213 codePoint = tempCodePoint
7214 }
7215 }
7216 break
7217 case 4:
7218 secondByte = buf[i + 1]
7219 thirdByte = buf[i + 2]
7220 fourthByte = buf[i + 3]
7221 if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
7222 tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
7223 if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
7224 codePoint = tempCodePoint
7225 }
7226 }
7227 }
7228 }
7229
7230 if (codePoint === null) {
7231 // we did not generate a valid codePoint so insert a
7232 // replacement char (U+FFFD) and advance only 1 byte
7233 codePoint = 0xFFFD
7234 bytesPerSequence = 1
7235 } else if (codePoint > 0xFFFF) {
7236 // encode to utf16 (surrogate pair dance)
7237 codePoint -= 0x10000
7238 res.push(codePoint >>> 10 & 0x3FF | 0xD800)
7239 codePoint = 0xDC00 | codePoint & 0x3FF
7240 }
7241
7242 res.push(codePoint)
7243 i += bytesPerSequence
7244 }
7245
7246 return decodeCodePointsArray(res)
7247}
7248
7249// Based on http://stackoverflow.com/a/22747272/680742, the browser with
7250// the lowest limit is Chrome, with 0x10000 args.
7251// We go 1 magnitude less, for safety
7252var MAX_ARGUMENTS_LENGTH = 0x1000
7253
7254function decodeCodePointsArray (codePoints) {
7255 var len = codePoints.length
7256 if (len <= MAX_ARGUMENTS_LENGTH) {
7257 return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
7258 }
7259
7260 // Decode in chunks to avoid "call stack size exceeded".
7261 var res = ''
7262 var i = 0
7263 while (i < len) {
7264 res += String.fromCharCode.apply(
7265 String,
7266 codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
7267 )
7268 }
7269 return res
7270}
7271
7272function asciiSlice (buf, start, end) {
7273 var ret = ''
7274 end = Math.min(buf.length, end)
7275
7276 for (var i = start; i < end; i++) {
7277 ret += String.fromCharCode(buf[i] & 0x7F)
7278 }
7279 return ret
7280}
7281
7282function binarySlice (buf, start, end) {
7283 var ret = ''
7284 end = Math.min(buf.length, end)
7285
7286 for (var i = start; i < end; i++) {
7287 ret += String.fromCharCode(buf[i])
7288 }
7289 return ret
7290}
7291
7292function hexSlice (buf, start, end) {
7293 var len = buf.length
7294
7295 if (!start || start < 0) start = 0
7296 if (!end || end < 0 || end > len) end = len
7297
7298 var out = ''
7299 for (var i = start; i < end; i++) {
7300 out += toHex(buf[i])
7301 }
7302 return out
7303}
7304
7305function utf16leSlice (buf, start, end) {
7306 var bytes = buf.slice(start, end)
7307 var res = ''
7308 for (var i = 0; i < bytes.length; i += 2) {
7309 res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)
7310 }
7311 return res
7312}
7313
7314Buffer.prototype.slice = function slice (start, end) {
7315 var len = this.length
7316 start = ~~start
7317 end = end === undefined ? len : ~~end
7318
7319 if (start < 0) {
7320 start += len
7321 if (start < 0) start = 0
7322 } else if (start > len) {
7323 start = len
7324 }
7325
7326 if (end < 0) {
7327 end += len
7328 if (end < 0) end = 0
7329 } else if (end > len) {
7330 end = len
7331 }
7332
7333 if (end < start) end = start
7334
7335 var newBuf
7336 if (Buffer.TYPED_ARRAY_SUPPORT) {
7337 newBuf = Buffer._augment(this.subarray(start, end))
7338 } else {
7339 var sliceLen = end - start
7340 newBuf = new Buffer(sliceLen, undefined)
7341 for (var i = 0; i < sliceLen; i++) {
7342 newBuf[i] = this[i + start]
7343 }
7344 }
7345
7346 if (newBuf.length) newBuf.parent = this.parent || this
7347
7348 return newBuf
7349}
7350
7351/*
7352 * Need to make sure that buffer isn't trying to write out of bounds.
7353 */
7354function checkOffset (offset, ext, length) {
7355 if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
7356 if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
7357}
7358
7359Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
7360 offset = offset | 0
7361 byteLength = byteLength | 0
7362 if (!noAssert) checkOffset(offset, byteLength, this.length)
7363
7364 var val = this[offset]
7365 var mul = 1
7366 var i = 0
7367 while (++i < byteLength && (mul *= 0x100)) {
7368 val += this[offset + i] * mul
7369 }
7370
7371 return val
7372}
7373
7374Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
7375 offset = offset | 0
7376 byteLength = byteLength | 0
7377 if (!noAssert) {
7378 checkOffset(offset, byteLength, this.length)
7379 }
7380
7381 var val = this[offset + --byteLength]
7382 var mul = 1
7383 while (byteLength > 0 && (mul *= 0x100)) {
7384 val += this[offset + --byteLength] * mul
7385 }
7386
7387 return val
7388}
7389
7390Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
7391 if (!noAssert) checkOffset(offset, 1, this.length)
7392 return this[offset]
7393}
7394
7395Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
7396 if (!noAssert) checkOffset(offset, 2, this.length)
7397 return this[offset] | (this[offset + 1] << 8)
7398}
7399
7400Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
7401 if (!noAssert) checkOffset(offset, 2, this.length)
7402 return (this[offset] << 8) | this[offset + 1]
7403}
7404
7405Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
7406 if (!noAssert) checkOffset(offset, 4, this.length)
7407
7408 return ((this[offset]) |
7409 (this[offset + 1] << 8) |
7410 (this[offset + 2] << 16)) +
7411 (this[offset + 3] * 0x1000000)
7412}
7413
7414Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
7415 if (!noAssert) checkOffset(offset, 4, this.length)
7416
7417 return (this[offset] * 0x1000000) +
7418 ((this[offset + 1] << 16) |
7419 (this[offset + 2] << 8) |
7420 this[offset + 3])
7421}
7422
7423Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
7424 offset = offset | 0
7425 byteLength = byteLength | 0
7426 if (!noAssert) checkOffset(offset, byteLength, this.length)
7427
7428 var val = this[offset]
7429 var mul = 1
7430 var i = 0
7431 while (++i < byteLength && (mul *= 0x100)) {
7432 val += this[offset + i] * mul
7433 }
7434 mul *= 0x80
7435
7436 if (val >= mul) val -= Math.pow(2, 8 * byteLength)
7437
7438 return val
7439}
7440
7441Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
7442 offset = offset | 0
7443 byteLength = byteLength | 0
7444 if (!noAssert) checkOffset(offset, byteLength, this.length)
7445
7446 var i = byteLength
7447 var mul = 1
7448 var val = this[offset + --i]
7449 while (i > 0 && (mul *= 0x100)) {
7450 val += this[offset + --i] * mul
7451 }
7452 mul *= 0x80
7453
7454 if (val >= mul) val -= Math.pow(2, 8 * byteLength)
7455
7456 return val
7457}
7458
7459Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
7460 if (!noAssert) checkOffset(offset, 1, this.length)
7461 if (!(this[offset] & 0x80)) return (this[offset])
7462 return ((0xff - this[offset] + 1) * -1)
7463}
7464
7465Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
7466 if (!noAssert) checkOffset(offset, 2, this.length)
7467 var val = this[offset] | (this[offset + 1] << 8)
7468 return (val & 0x8000) ? val | 0xFFFF0000 : val
7469}
7470
7471Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
7472 if (!noAssert) checkOffset(offset, 2, this.length)
7473 var val = this[offset + 1] | (this[offset] << 8)
7474 return (val & 0x8000) ? val | 0xFFFF0000 : val
7475}
7476
7477Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
7478 if (!noAssert) checkOffset(offset, 4, this.length)
7479
7480 return (this[offset]) |
7481 (this[offset + 1] << 8) |
7482 (this[offset + 2] << 16) |
7483 (this[offset + 3] << 24)
7484}
7485
7486Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
7487 if (!noAssert) checkOffset(offset, 4, this.length)
7488
7489 return (this[offset] << 24) |
7490 (this[offset + 1] << 16) |
7491 (this[offset + 2] << 8) |
7492 (this[offset + 3])
7493}
7494
7495Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
7496 if (!noAssert) checkOffset(offset, 4, this.length)
7497 return ieee754.read(this, offset, true, 23, 4)
7498}
7499
7500Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
7501 if (!noAssert) checkOffset(offset, 4, this.length)
7502 return ieee754.read(this, offset, false, 23, 4)
7503}
7504
7505Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
7506 if (!noAssert) checkOffset(offset, 8, this.length)
7507 return ieee754.read(this, offset, true, 52, 8)
7508}
7509
7510Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
7511 if (!noAssert) checkOffset(offset, 8, this.length)
7512 return ieee754.read(this, offset, false, 52, 8)
7513}
7514
7515function checkInt (buf, value, offset, ext, max, min) {
7516 if (!Buffer.isBuffer(buf)) throw new TypeError('buffer must be a Buffer instance')
7517 if (value > max || value < min) throw new RangeError('value is out of bounds')
7518 if (offset + ext > buf.length) throw new RangeError('index out of range')
7519}
7520
7521Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
7522 value = +value
7523 offset = offset | 0
7524 byteLength = byteLength | 0
7525 if (!noAssert) checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0)
7526
7527 var mul = 1
7528 var i = 0
7529 this[offset] = value & 0xFF
7530 while (++i < byteLength && (mul *= 0x100)) {
7531 this[offset + i] = (value / mul) & 0xFF
7532 }
7533
7534 return offset + byteLength
7535}
7536
7537Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
7538 value = +value
7539 offset = offset | 0
7540 byteLength = byteLength | 0
7541 if (!noAssert) checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0)
7542
7543 var i = byteLength - 1
7544 var mul = 1
7545 this[offset + i] = value & 0xFF
7546 while (--i >= 0 && (mul *= 0x100)) {
7547 this[offset + i] = (value / mul) & 0xFF
7548 }
7549
7550 return offset + byteLength
7551}
7552
7553Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
7554 value = +value
7555 offset = offset | 0
7556 if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
7557 if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
7558 this[offset] = (value & 0xff)
7559 return offset + 1
7560}
7561
7562function objectWriteUInt16 (buf, value, offset, littleEndian) {
7563 if (value < 0) value = 0xffff + value + 1
7564 for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; i++) {
7565 buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
7566 (littleEndian ? i : 1 - i) * 8
7567 }
7568}
7569
7570Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
7571 value = +value
7572 offset = offset | 0
7573 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
7574 if (Buffer.TYPED_ARRAY_SUPPORT) {
7575 this[offset] = (value & 0xff)
7576 this[offset + 1] = (value >>> 8)
7577 } else {
7578 objectWriteUInt16(this, value, offset, true)
7579 }
7580 return offset + 2
7581}
7582
7583Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
7584 value = +value
7585 offset = offset | 0
7586 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
7587 if (Buffer.TYPED_ARRAY_SUPPORT) {
7588 this[offset] = (value >>> 8)
7589 this[offset + 1] = (value & 0xff)
7590 } else {
7591 objectWriteUInt16(this, value, offset, false)
7592 }
7593 return offset + 2
7594}
7595
7596function objectWriteUInt32 (buf, value, offset, littleEndian) {
7597 if (value < 0) value = 0xffffffff + value + 1
7598 for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; i++) {
7599 buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff
7600 }
7601}
7602
7603Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
7604 value = +value
7605 offset = offset | 0
7606 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
7607 if (Buffer.TYPED_ARRAY_SUPPORT) {
7608 this[offset + 3] = (value >>> 24)
7609 this[offset + 2] = (value >>> 16)
7610 this[offset + 1] = (value >>> 8)
7611 this[offset] = (value & 0xff)
7612 } else {
7613 objectWriteUInt32(this, value, offset, true)
7614 }
7615 return offset + 4
7616}
7617
7618Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
7619 value = +value
7620 offset = offset | 0
7621 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
7622 if (Buffer.TYPED_ARRAY_SUPPORT) {
7623 this[offset] = (value >>> 24)
7624 this[offset + 1] = (value >>> 16)
7625 this[offset + 2] = (value >>> 8)
7626 this[offset + 3] = (value & 0xff)
7627 } else {
7628 objectWriteUInt32(this, value, offset, false)
7629 }
7630 return offset + 4
7631}
7632
7633Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
7634 value = +value
7635 offset = offset | 0
7636 if (!noAssert) {
7637 var limit = Math.pow(2, 8 * byteLength - 1)
7638
7639 checkInt(this, value, offset, byteLength, limit - 1, -limit)
7640 }
7641
7642 var i = 0
7643 var mul = 1
7644 var sub = value < 0 ? 1 : 0
7645 this[offset] = value & 0xFF
7646 while (++i < byteLength && (mul *= 0x100)) {
7647 this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
7648 }
7649
7650 return offset + byteLength
7651}
7652
7653Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
7654 value = +value
7655 offset = offset | 0
7656 if (!noAssert) {
7657 var limit = Math.pow(2, 8 * byteLength - 1)
7658
7659 checkInt(this, value, offset, byteLength, limit - 1, -limit)
7660 }
7661
7662 var i = byteLength - 1
7663 var mul = 1
7664 var sub = value < 0 ? 1 : 0
7665 this[offset + i] = value & 0xFF
7666 while (--i >= 0 && (mul *= 0x100)) {
7667 this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
7668 }
7669
7670 return offset + byteLength
7671}
7672
7673Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
7674 value = +value
7675 offset = offset | 0
7676 if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
7677 if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
7678 if (value < 0) value = 0xff + value + 1
7679 this[offset] = (value & 0xff)
7680 return offset + 1
7681}
7682
7683Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
7684 value = +value
7685 offset = offset | 0
7686 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
7687 if (Buffer.TYPED_ARRAY_SUPPORT) {
7688 this[offset] = (value & 0xff)
7689 this[offset + 1] = (value >>> 8)
7690 } else {
7691 objectWriteUInt16(this, value, offset, true)
7692 }
7693 return offset + 2
7694}
7695
7696Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
7697 value = +value
7698 offset = offset | 0
7699 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
7700 if (Buffer.TYPED_ARRAY_SUPPORT) {
7701 this[offset] = (value >>> 8)
7702 this[offset + 1] = (value & 0xff)
7703 } else {
7704 objectWriteUInt16(this, value, offset, false)
7705 }
7706 return offset + 2
7707}
7708
7709Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
7710 value = +value
7711 offset = offset | 0
7712 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
7713 if (Buffer.TYPED_ARRAY_SUPPORT) {
7714 this[offset] = (value & 0xff)
7715 this[offset + 1] = (value >>> 8)
7716 this[offset + 2] = (value >>> 16)
7717 this[offset + 3] = (value >>> 24)
7718 } else {
7719 objectWriteUInt32(this, value, offset, true)
7720 }
7721 return offset + 4
7722}
7723
7724Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
7725 value = +value
7726 offset = offset | 0
7727 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
7728 if (value < 0) value = 0xffffffff + value + 1
7729 if (Buffer.TYPED_ARRAY_SUPPORT) {
7730 this[offset] = (value >>> 24)
7731 this[offset + 1] = (value >>> 16)
7732 this[offset + 2] = (value >>> 8)
7733 this[offset + 3] = (value & 0xff)
7734 } else {
7735 objectWriteUInt32(this, value, offset, false)
7736 }
7737 return offset + 4
7738}
7739
7740function checkIEEE754 (buf, value, offset, ext, max, min) {
7741 if (value > max || value < min) throw new RangeError('value is out of bounds')
7742 if (offset + ext > buf.length) throw new RangeError('index out of range')
7743 if (offset < 0) throw new RangeError('index out of range')
7744}
7745
7746function writeFloat (buf, value, offset, littleEndian, noAssert) {
7747 if (!noAssert) {
7748 checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
7749 }
7750 ieee754.write(buf, value, offset, littleEndian, 23, 4)
7751 return offset + 4
7752}
7753
7754Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
7755 return writeFloat(this, value, offset, true, noAssert)
7756}
7757
7758Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
7759 return writeFloat(this, value, offset, false, noAssert)
7760}
7761
7762function writeDouble (buf, value, offset, littleEndian, noAssert) {
7763 if (!noAssert) {
7764 checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
7765 }
7766 ieee754.write(buf, value, offset, littleEndian, 52, 8)
7767 return offset + 8
7768}
7769
7770Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
7771 return writeDouble(this, value, offset, true, noAssert)
7772}
7773
7774Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
7775 return writeDouble(this, value, offset, false, noAssert)
7776}
7777
7778// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
7779Buffer.prototype.copy = function copy (target, targetStart, start, end) {
7780 if (!start) start = 0
7781 if (!end && end !== 0) end = this.length
7782 if (targetStart >= target.length) targetStart = target.length
7783 if (!targetStart) targetStart = 0
7784 if (end > 0 && end < start) end = start
7785
7786 // Copy 0 bytes; we're done
7787 if (end === start) return 0
7788 if (target.length === 0 || this.length === 0) return 0
7789
7790 // Fatal error conditions
7791 if (targetStart < 0) {
7792 throw new RangeError('targetStart out of bounds')
7793 }
7794 if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
7795 if (end < 0) throw new RangeError('sourceEnd out of bounds')
7796
7797 // Are we oob?
7798 if (end > this.length) end = this.length
7799 if (target.length - targetStart < end - start) {
7800 end = target.length - targetStart + start
7801 }
7802
7803 var len = end - start
7804 var i
7805
7806 if (this === target && start < targetStart && targetStart < end) {
7807 // descending copy from end
7808 for (i = len - 1; i >= 0; i--) {
7809 target[i + targetStart] = this[i + start]
7810 }
7811 } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
7812 // ascending copy from start
7813 for (i = 0; i < len; i++) {
7814 target[i + targetStart] = this[i + start]
7815 }
7816 } else {
7817 target._set(this.subarray(start, start + len), targetStart)
7818 }
7819
7820 return len
7821}
7822
7823// fill(value, start=0, end=buffer.length)
7824Buffer.prototype.fill = function fill (value, start, end) {
7825 if (!value) value = 0
7826 if (!start) start = 0
7827 if (!end) end = this.length
7828
7829 if (end < start) throw new RangeError('end < start')
7830
7831 // Fill 0 bytes; we're done
7832 if (end === start) return
7833 if (this.length === 0) return
7834
7835 if (start < 0 || start >= this.length) throw new RangeError('start out of bounds')
7836 if (end < 0 || end > this.length) throw new RangeError('end out of bounds')
7837
7838 var i
7839 if (typeof value === 'number') {
7840 for (i = start; i < end; i++) {
7841 this[i] = value
7842 }
7843 } else {
7844 var bytes = utf8ToBytes(value.toString())
7845 var len = bytes.length
7846 for (i = start; i < end; i++) {
7847 this[i] = bytes[i % len]
7848 }
7849 }
7850
7851 return this
7852}
7853
7854/**
7855 * Creates a new `ArrayBuffer` with the *copied* memory of the buffer instance.
7856 * Added in Node 0.12. Only available in browsers that support ArrayBuffer.
7857 */
7858Buffer.prototype.toArrayBuffer = function toArrayBuffer () {
7859 if (typeof Uint8Array !== 'undefined') {
7860 if (Buffer.TYPED_ARRAY_SUPPORT) {
7861 return (new Buffer(this)).buffer
7862 } else {
7863 var buf = new Uint8Array(this.length)
7864 for (var i = 0, len = buf.length; i < len; i += 1) {
7865 buf[i] = this[i]
7866 }
7867 return buf.buffer
7868 }
7869 } else {
7870 throw new TypeError('Buffer.toArrayBuffer not supported in this browser')
7871 }
7872}
7873
7874// HELPER FUNCTIONS
7875// ================
7876
7877var BP = Buffer.prototype
7878
7879/**
7880 * Augment a Uint8Array *instance* (not the Uint8Array class!) with Buffer methods
7881 */
7882Buffer._augment = function _augment (arr) {
7883 arr.constructor = Buffer
7884 arr._isBuffer = true
7885
7886 // save reference to original Uint8Array set method before overwriting
7887 arr._set = arr.set
7888
7889 // deprecated
7890 arr.get = BP.get
7891 arr.set = BP.set
7892
7893 arr.write = BP.write
7894 arr.toString = BP.toString
7895 arr.toLocaleString = BP.toString
7896 arr.toJSON = BP.toJSON
7897 arr.equals = BP.equals
7898 arr.compare = BP.compare
7899 arr.indexOf = BP.indexOf
7900 arr.copy = BP.copy
7901 arr.slice = BP.slice
7902 arr.readUIntLE = BP.readUIntLE
7903 arr.readUIntBE = BP.readUIntBE
7904 arr.readUInt8 = BP.readUInt8
7905 arr.readUInt16LE = BP.readUInt16LE
7906 arr.readUInt16BE = BP.readUInt16BE
7907 arr.readUInt32LE = BP.readUInt32LE
7908 arr.readUInt32BE = BP.readUInt32BE
7909 arr.readIntLE = BP.readIntLE
7910 arr.readIntBE = BP.readIntBE
7911 arr.readInt8 = BP.readInt8
7912 arr.readInt16LE = BP.readInt16LE
7913 arr.readInt16BE = BP.readInt16BE
7914 arr.readInt32LE = BP.readInt32LE
7915 arr.readInt32BE = BP.readInt32BE
7916 arr.readFloatLE = BP.readFloatLE
7917 arr.readFloatBE = BP.readFloatBE
7918 arr.readDoubleLE = BP.readDoubleLE
7919 arr.readDoubleBE = BP.readDoubleBE
7920 arr.writeUInt8 = BP.writeUInt8
7921 arr.writeUIntLE = BP.writeUIntLE
7922 arr.writeUIntBE = BP.writeUIntBE
7923 arr.writeUInt16LE = BP.writeUInt16LE
7924 arr.writeUInt16BE = BP.writeUInt16BE
7925 arr.writeUInt32LE = BP.writeUInt32LE
7926 arr.writeUInt32BE = BP.writeUInt32BE
7927 arr.writeIntLE = BP.writeIntLE
7928 arr.writeIntBE = BP.writeIntBE
7929 arr.writeInt8 = BP.writeInt8
7930 arr.writeInt16LE = BP.writeInt16LE
7931 arr.writeInt16BE = BP.writeInt16BE
7932 arr.writeInt32LE = BP.writeInt32LE
7933 arr.writeInt32BE = BP.writeInt32BE
7934 arr.writeFloatLE = BP.writeFloatLE
7935 arr.writeFloatBE = BP.writeFloatBE
7936 arr.writeDoubleLE = BP.writeDoubleLE
7937 arr.writeDoubleBE = BP.writeDoubleBE
7938 arr.fill = BP.fill
7939 arr.inspect = BP.inspect
7940 arr.toArrayBuffer = BP.toArrayBuffer
7941
7942 return arr
7943}
7944
7945var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g
7946
7947function base64clean (str) {
7948 // Node strips out invalid characters like \n and \t from the string, base64-js does not
7949 str = stringtrim(str).replace(INVALID_BASE64_RE, '')
7950 // Node converts strings with length < 2 to ''
7951 if (str.length < 2) return ''
7952 // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
7953 while (str.length % 4 !== 0) {
7954 str = str + '='
7955 }
7956 return str
7957}
7958
7959function stringtrim (str) {
7960 if (str.trim) return str.trim()
7961 return str.replace(/^\s+|\s+$/g, '')
7962}
7963
7964function toHex (n) {
7965 if (n < 16) return '0' + n.toString(16)
7966 return n.toString(16)
7967}
7968
7969function utf8ToBytes (string, units) {
7970 units = units || Infinity
7971 var codePoint
7972 var length = string.length
7973 var leadSurrogate = null
7974 var bytes = []
7975
7976 for (var i = 0; i < length; i++) {
7977 codePoint = string.charCodeAt(i)
7978
7979 // is surrogate component
7980 if (codePoint > 0xD7FF && codePoint < 0xE000) {
7981 // last char was a lead
7982 if (!leadSurrogate) {
7983 // no lead yet
7984 if (codePoint > 0xDBFF) {
7985 // unexpected trail
7986 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
7987 continue
7988 } else if (i + 1 === length) {
7989 // unpaired lead
7990 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
7991 continue
7992 }
7993
7994 // valid lead
7995 leadSurrogate = codePoint
7996
7997 continue
7998 }
7999
8000 // 2 leads in a row
8001 if (codePoint < 0xDC00) {
8002 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
8003 leadSurrogate = codePoint
8004 continue
8005 }
8006
8007 // valid surrogate pair
8008 codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
8009 } else if (leadSurrogate) {
8010 // valid bmp char, but last char was a lead
8011 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
8012 }
8013
8014 leadSurrogate = null
8015
8016 // encode utf8
8017 if (codePoint < 0x80) {
8018 if ((units -= 1) < 0) break
8019 bytes.push(codePoint)
8020 } else if (codePoint < 0x800) {
8021 if ((units -= 2) < 0) break
8022 bytes.push(
8023 codePoint >> 0x6 | 0xC0,
8024 codePoint & 0x3F | 0x80
8025 )
8026 } else if (codePoint < 0x10000) {
8027 if ((units -= 3) < 0) break
8028 bytes.push(
8029 codePoint >> 0xC | 0xE0,
8030 codePoint >> 0x6 & 0x3F | 0x80,
8031 codePoint & 0x3F | 0x80
8032 )
8033 } else if (codePoint < 0x110000) {
8034 if ((units -= 4) < 0) break
8035 bytes.push(
8036 codePoint >> 0x12 | 0xF0,
8037 codePoint >> 0xC & 0x3F | 0x80,
8038 codePoint >> 0x6 & 0x3F | 0x80,
8039 codePoint & 0x3F | 0x80
8040 )
8041 } else {
8042 throw new Error('Invalid code point')
8043 }
8044 }
8045
8046 return bytes
8047}
8048
8049function asciiToBytes (str) {
8050 var byteArray = []
8051 for (var i = 0; i < str.length; i++) {
8052 // Node's code seems to be doing this and not & 0x7F..
8053 byteArray.push(str.charCodeAt(i) & 0xFF)
8054 }
8055 return byteArray
8056}
8057
8058function utf16leToBytes (str, units) {
8059 var c, hi, lo
8060 var byteArray = []
8061 for (var i = 0; i < str.length; i++) {
8062 if ((units -= 2) < 0) break
8063
8064 c = str.charCodeAt(i)
8065 hi = c >> 8
8066 lo = c % 256
8067 byteArray.push(lo)
8068 byteArray.push(hi)
8069 }
8070
8071 return byteArray
8072}
8073
8074function base64ToBytes (str) {
8075 return base64.toByteArray(base64clean(str))
8076}
8077
8078function blitBuffer (src, dst, offset, length) {
8079 for (var i = 0; i < length; i++) {
8080 if ((i + offset >= dst.length) || (i >= src.length)) break
8081 dst[i + offset] = src[i]
8082 }
8083 return i
8084}
8085
8086}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
8087},{"base64-js":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/base64-js/lib/b64.js","ieee754":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/ieee754/index.js","isarray":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/isarray/index.js"}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/component-bind/index.js":[function(require,module,exports){
8088/**
8089 * Slice reference.
8090 */
8091
8092var slice = [].slice;
8093
8094/**
8095 * Bind `obj` to `fn`.
8096 *
8097 * @param {Object} obj
8098 * @param {Function|String} fn or string
8099 * @return {Function}
8100 * @api public
8101 */
8102
8103module.exports = function(obj, fn){
8104 if ('string' == typeof fn) fn = obj[fn];
8105 if ('function' != typeof fn) throw new Error('bind() requires a function');
8106 var args = slice.call(arguments, 2);
8107 return function(){
8108 return fn.apply(obj, args.concat(slice.call(arguments)));
8109 }
8110};
8111
8112},{}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/component-emitter/index.js":[function(require,module,exports){
8113
8114/**
8115 * Expose `Emitter`.
8116 */
8117
8118module.exports = Emitter;
8119
8120/**
8121 * Initialize a new `Emitter`.
8122 *
8123 * @api public
8124 */
8125
8126function Emitter(obj) {
8127 if (obj) return mixin(obj);
8128};
8129
8130/**
8131 * Mixin the emitter properties.
8132 *
8133 * @param {Object} obj
8134 * @return {Object}
8135 * @api private
8136 */
8137
8138function mixin(obj) {
8139 for (var key in Emitter.prototype) {
8140 obj[key] = Emitter.prototype[key];
8141 }
8142 return obj;
8143}
8144
8145/**
8146 * Listen on the given `event` with `fn`.
8147 *
8148 * @param {String} event
8149 * @param {Function} fn
8150 * @return {Emitter}
8151 * @api public
8152 */
8153
8154Emitter.prototype.on =
8155Emitter.prototype.addEventListener = function(event, fn){
8156 this._callbacks = this._callbacks || {};
8157 (this._callbacks['$' + event] = this._callbacks['$' + event] || [])
8158 .push(fn);
8159 return this;
8160};
8161
8162/**
8163 * Adds an `event` listener that will be invoked a single
8164 * time then automatically removed.
8165 *
8166 * @param {String} event
8167 * @param {Function} fn
8168 * @return {Emitter}
8169 * @api public
8170 */
8171
8172Emitter.prototype.once = function(event, fn){
8173 function on() {
8174 this.off(event, on);
8175 fn.apply(this, arguments);
8176 }
8177
8178 on.fn = fn;
8179 this.on(event, on);
8180 return this;
8181};
8182
8183/**
8184 * Remove the given callback for `event` or all
8185 * registered callbacks.
8186 *
8187 * @param {String} event
8188 * @param {Function} fn
8189 * @return {Emitter}
8190 * @api public
8191 */
8192
8193Emitter.prototype.off =
8194Emitter.prototype.removeListener =
8195Emitter.prototype.removeAllListeners =
8196Emitter.prototype.removeEventListener = function(event, fn){
8197 this._callbacks = this._callbacks || {};
8198
8199 // all
8200 if (0 == arguments.length) {
8201 this._callbacks = {};
8202 return this;
8203 }
8204
8205 // specific event
8206 var callbacks = this._callbacks['$' + event];
8207 if (!callbacks) return this;
8208
8209 // remove all handlers
8210 if (1 == arguments.length) {
8211 delete this._callbacks['$' + event];
8212 return this;
8213 }
8214
8215 // remove specific handler
8216 var cb;
8217 for (var i = 0; i < callbacks.length; i++) {
8218 cb = callbacks[i];
8219 if (cb === fn || cb.fn === fn) {
8220 callbacks.splice(i, 1);
8221 break;
8222 }
8223 }
8224 return this;
8225};
8226
8227/**
8228 * Emit `event` with the given args.
8229 *
8230 * @param {String} event
8231 * @param {Mixed} ...
8232 * @return {Emitter}
8233 */
8234
8235Emitter.prototype.emit = function(event){
8236 this._callbacks = this._callbacks || {};
8237 var args = [].slice.call(arguments, 1)
8238 , callbacks = this._callbacks['$' + event];
8239
8240 if (callbacks) {
8241 callbacks = callbacks.slice(0);
8242 for (var i = 0, len = callbacks.length; i < len; ++i) {
8243 callbacks[i].apply(this, args);
8244 }
8245 }
8246
8247 return this;
8248};
8249
8250/**
8251 * Return array of callbacks for `event`.
8252 *
8253 * @param {String} event
8254 * @return {Array}
8255 * @api public
8256 */
8257
8258Emitter.prototype.listeners = function(event){
8259 this._callbacks = this._callbacks || {};
8260 return this._callbacks['$' + event] || [];
8261};
8262
8263/**
8264 * Check if this emitter has `event` handlers.
8265 *
8266 * @param {String} event
8267 * @return {Boolean}
8268 * @api public
8269 */
8270
8271Emitter.prototype.hasListeners = function(event){
8272 return !! this.listeners(event).length;
8273};
8274
8275},{}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/component-inherit/index.js":[function(require,module,exports){
8276
8277module.exports = function(a, b){
8278 var fn = function(){};
8279 fn.prototype = b.prototype;
8280 a.prototype = new fn;
8281 a.prototype.constructor = a;
8282};
8283},{}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/debug/browser.js":[function(require,module,exports){
8284
8285/**
8286 * This is the web browser implementation of `debug()`.
8287 *
8288 * Expose `debug()` as the module.
8289 */
8290
8291exports = module.exports = require('./debug');
8292exports.log = log;
8293exports.formatArgs = formatArgs;
8294exports.save = save;
8295exports.load = load;
8296exports.useColors = useColors;
8297exports.storage = 'undefined' != typeof chrome
8298 && 'undefined' != typeof chrome.storage
8299 ? chrome.storage.local
8300 : localstorage();
8301
8302/**
8303 * Colors.
8304 */
8305
8306exports.colors = [
8307 'lightseagreen',
8308 'forestgreen',
8309 'goldenrod',
8310 'dodgerblue',
8311 'darkorchid',
8312 'crimson'
8313];
8314
8315/**
8316 * Currently only WebKit-based Web Inspectors, Firefox >= v31,
8317 * and the Firebug extension (any Firefox version) are known
8318 * to support "%c" CSS customizations.
8319 *
8320 * TODO: add a `localStorage` variable to explicitly enable/disable colors
8321 */
8322
8323function useColors() {
8324 // is webkit? http://stackoverflow.com/a/16459606/376773
8325 return ('WebkitAppearance' in document.documentElement.style) ||
8326 // is firebug? http://stackoverflow.com/a/398120/376773
8327 (window.console && (console.firebug || (console.exception && console.table))) ||
8328 // is firefox >= v31?
8329 // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
8330 (navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31);
8331}
8332
8333/**
8334 * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
8335 */
8336
8337exports.formatters.j = function(v) {
8338 return JSON.stringify(v);
8339};
8340
8341
8342/**
8343 * Colorize log arguments if enabled.
8344 *
8345 * @api public
8346 */
8347
8348function formatArgs() {
8349 var args = arguments;
8350 var useColors = this.useColors;
8351
8352 args[0] = (useColors ? '%c' : '')
8353 + this.namespace
8354 + (useColors ? ' %c' : ' ')
8355 + args[0]
8356 + (useColors ? '%c ' : ' ')
8357 + '+' + exports.humanize(this.diff);
8358
8359 if (!useColors) return args;
8360
8361 var c = 'color: ' + this.color;
8362 args = [args[0], c, 'color: inherit'].concat(Array.prototype.slice.call(args, 1));
8363
8364 // the final "%c" is somewhat tricky, because there could be other
8365 // arguments passed either before or after the %c, so we need to
8366 // figure out the correct index to insert the CSS into
8367 var index = 0;
8368 var lastC = 0;
8369 args[0].replace(/%[a-z%]/g, function(match) {
8370 if ('%%' === match) return;
8371 index++;
8372 if ('%c' === match) {
8373 // we only are interested in the *last* %c
8374 // (the user may have provided their own)
8375 lastC = index;
8376 }
8377 });
8378
8379 args.splice(lastC, 0, c);
8380 return args;
8381}
8382
8383/**
8384 * Invokes `console.log()` when available.
8385 * No-op when `console.log` is not a "function".
8386 *
8387 * @api public
8388 */
8389
8390function log() {
8391 // this hackery is required for IE8/9, where
8392 // the `console.log` function doesn't have 'apply'
8393 return 'object' === typeof console
8394 && console.log
8395 && Function.prototype.apply.call(console.log, console, arguments);
8396}
8397
8398/**
8399 * Save `namespaces`.
8400 *
8401 * @param {String} namespaces
8402 * @api private
8403 */
8404
8405function save(namespaces) {
8406 try {
8407 if (null == namespaces) {
8408 exports.storage.removeItem('debug');
8409 } else {
8410 exports.storage.debug = namespaces;
8411 }
8412 } catch(e) {}
8413}
8414
8415/**
8416 * Load `namespaces`.
8417 *
8418 * @return {String} returns the previously persisted debug modes
8419 * @api private
8420 */
8421
8422function load() {
8423 var r;
8424 try {
8425 r = exports.storage.debug;
8426 } catch(e) {}
8427 return r;
8428}
8429
8430/**
8431 * Enable namespaces listed in `localStorage.debug` initially.
8432 */
8433
8434exports.enable(load());
8435
8436/**
8437 * Localstorage attempts to return the localstorage.
8438 *
8439 * This is necessary because safari throws
8440 * when a user disables cookies/localstorage
8441 * and you attempt to access it.
8442 *
8443 * @return {LocalStorage}
8444 * @api private
8445 */
8446
8447function localstorage(){
8448 try {
8449 return window.localStorage;
8450 } catch (e) {}
8451}
8452
8453},{"./debug":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/debug/debug.js"}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/debug/debug.js":[function(require,module,exports){
8454
8455/**
8456 * This is the common logic for both the Node.js and web browser
8457 * implementations of `debug()`.
8458 *
8459 * Expose `debug()` as the module.
8460 */
8461
8462exports = module.exports = debug;
8463exports.coerce = coerce;
8464exports.disable = disable;
8465exports.enable = enable;
8466exports.enabled = enabled;
8467exports.humanize = require('ms');
8468
8469/**
8470 * The currently active debug mode names, and names to skip.
8471 */
8472
8473exports.names = [];
8474exports.skips = [];
8475
8476/**
8477 * Map of special "%n" handling functions, for the debug "format" argument.
8478 *
8479 * Valid key names are a single, lowercased letter, i.e. "n".
8480 */
8481
8482exports.formatters = {};
8483
8484/**
8485 * Previously assigned color.
8486 */
8487
8488var prevColor = 0;
8489
8490/**
8491 * Previous log timestamp.
8492 */
8493
8494var prevTime;
8495
8496/**
8497 * Select a color.
8498 *
8499 * @return {Number}
8500 * @api private
8501 */
8502
8503function selectColor() {
8504 return exports.colors[prevColor++ % exports.colors.length];
8505}
8506
8507/**
8508 * Create a debugger with the given `namespace`.
8509 *
8510 * @param {String} namespace
8511 * @return {Function}
8512 * @api public
8513 */
8514
8515function debug(namespace) {
8516
8517 // define the `disabled` version
8518 function disabled() {
8519 }
8520 disabled.enabled = false;
8521
8522 // define the `enabled` version
8523 function enabled() {
8524
8525 var self = enabled;
8526
8527 // set `diff` timestamp
8528 var curr = +new Date();
8529 var ms = curr - (prevTime || curr);
8530 self.diff = ms;
8531 self.prev = prevTime;
8532 self.curr = curr;
8533 prevTime = curr;
8534
8535 // add the `color` if not set
8536 if (null == self.useColors) self.useColors = exports.useColors();
8537 if (null == self.color && self.useColors) self.color = selectColor();
8538
8539 var args = Array.prototype.slice.call(arguments);
8540
8541 args[0] = exports.coerce(args[0]);
8542
8543 if ('string' !== typeof args[0]) {
8544 // anything else let's inspect with %o
8545 args = ['%o'].concat(args);
8546 }
8547
8548 // apply any `formatters` transformations
8549 var index = 0;
8550 args[0] = args[0].replace(/%([a-z%])/g, function(match, format) {
8551 // if we encounter an escaped % then don't increase the array index
8552 if (match === '%%') return match;
8553 index++;
8554 var formatter = exports.formatters[format];
8555 if ('function' === typeof formatter) {
8556 var val = args[index];
8557 match = formatter.call(self, val);
8558
8559 // now we need to remove `args[index]` since it's inlined in the `format`
8560 args.splice(index, 1);
8561 index--;
8562 }
8563 return match;
8564 });
8565
8566 if ('function' === typeof exports.formatArgs) {
8567 args = exports.formatArgs.apply(self, args);
8568 }
8569 var logFn = enabled.log || exports.log || console.log.bind(console);
8570 logFn.apply(self, args);
8571 }
8572 enabled.enabled = true;
8573
8574 var fn = exports.enabled(namespace) ? enabled : disabled;
8575
8576 fn.namespace = namespace;
8577
8578 return fn;
8579}
8580
8581/**
8582 * Enables a debug mode by namespaces. This can include modes
8583 * separated by a colon and wildcards.
8584 *
8585 * @param {String} namespaces
8586 * @api public
8587 */
8588
8589function enable(namespaces) {
8590 exports.save(namespaces);
8591
8592 var split = (namespaces || '').split(/[\s,]+/);
8593 var len = split.length;
8594
8595 for (var i = 0; i < len; i++) {
8596 if (!split[i]) continue; // ignore empty strings
8597 namespaces = split[i].replace(/\*/g, '.*?');
8598 if (namespaces[0] === '-') {
8599 exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
8600 } else {
8601 exports.names.push(new RegExp('^' + namespaces + '$'));
8602 }
8603 }
8604}
8605
8606/**
8607 * Disable debug output.
8608 *
8609 * @api public
8610 */
8611
8612function disable() {
8613 exports.enable('');
8614}
8615
8616/**
8617 * Returns true if the given mode name is enabled, false otherwise.
8618 *
8619 * @param {String} name
8620 * @return {Boolean}
8621 * @api public
8622 */
8623
8624function enabled(name) {
8625 var i, len;
8626 for (i = 0, len = exports.skips.length; i < len; i++) {
8627 if (exports.skips[i].test(name)) {
8628 return false;
8629 }
8630 }
8631 for (i = 0, len = exports.names.length; i < len; i++) {
8632 if (exports.names[i].test(name)) {
8633 return true;
8634 }
8635 }
8636 return false;
8637}
8638
8639/**
8640 * Coerce `val`.
8641 *
8642 * @param {Mixed} val
8643 * @return {Mixed}
8644 * @api private
8645 */
8646
8647function coerce(val) {
8648 if (val instanceof Error) return val.stack || val.message;
8649 return val;
8650}
8651
8652},{"ms":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/ms/index.js"}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/engine.io-client/index.js":[function(require,module,exports){
8653
8654module.exports = require('./lib/');
8655
8656},{"./lib/":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/engine.io-client/lib/index.js"}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/engine.io-client/lib/index.js":[function(require,module,exports){
8657
8658module.exports = require('./socket');
8659
8660/**
8661 * Exports parser
8662 *
8663 * @api public
8664 *
8665 */
8666module.exports.parser = require('engine.io-parser');
8667
8668},{"./socket":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/engine.io-client/lib/socket.js","engine.io-parser":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/engine.io-parser/lib/browser.js"}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/engine.io-client/lib/socket.js":[function(require,module,exports){
8669(function (global){
8670/**
8671 * Module dependencies.
8672 */
8673
8674var transports = require('./transports');
8675var Emitter = require('component-emitter');
8676var debug = require('debug')('engine.io-client:socket');
8677var index = require('indexof');
8678var parser = require('engine.io-parser');
8679var parseuri = require('parseuri');
8680var parsejson = require('parsejson');
8681var parseqs = require('parseqs');
8682
8683/**
8684 * Module exports.
8685 */
8686
8687module.exports = Socket;
8688
8689/**
8690 * Noop function.
8691 *
8692 * @api private
8693 */
8694
8695function noop(){}
8696
8697/**
8698 * Socket constructor.
8699 *
8700 * @param {String|Object} uri or options
8701 * @param {Object} options
8702 * @api public
8703 */
8704
8705function Socket(uri, opts){
8706 if (!(this instanceof Socket)) return new Socket(uri, opts);
8707
8708 opts = opts || {};
8709
8710 if (uri && 'object' == typeof uri) {
8711 opts = uri;
8712 uri = null;
8713 }
8714
8715 if (uri) {
8716 uri = parseuri(uri);
8717 opts.hostname = uri.host;
8718 opts.secure = uri.protocol == 'https' || uri.protocol == 'wss';
8719 opts.port = uri.port;
8720 if (uri.query) opts.query = uri.query;
8721 } else if (opts.host) {
8722 opts.hostname = parseuri(opts.host).host;
8723 }
8724
8725 this.secure = null != opts.secure ? opts.secure :
8726 (global.location && 'https:' == location.protocol);
8727
8728 if (opts.hostname && !opts.port) {
8729 // if no port is specified manually, use the protocol default
8730 opts.port = this.secure ? '443' : '80';
8731 }
8732
8733 this.agent = opts.agent || false;
8734 this.hostname = opts.hostname ||
8735 (global.location ? location.hostname : 'localhost');
8736 this.port = opts.port || (global.location && location.port ?
8737 location.port :
8738 (this.secure ? 443 : 80));
8739 this.query = opts.query || {};
8740 if ('string' == typeof this.query) this.query = parseqs.decode(this.query);
8741 this.upgrade = false !== opts.upgrade;
8742 this.path = (opts.path || '/engine.io').replace(/\/$/, '') + '/';
8743 this.forceJSONP = !!opts.forceJSONP;
8744 this.jsonp = false !== opts.jsonp;
8745 this.forceBase64 = !!opts.forceBase64;
8746 this.enablesXDR = !!opts.enablesXDR;
8747 this.timestampParam = opts.timestampParam || 't';
8748 this.timestampRequests = opts.timestampRequests;
8749 this.transports = opts.transports || ['polling', 'websocket'];
8750 this.readyState = '';
8751 this.writeBuffer = [];
8752 this.policyPort = opts.policyPort || 843;
8753 this.rememberUpgrade = opts.rememberUpgrade || false;
8754 this.binaryType = null;
8755 this.onlyBinaryUpgrades = opts.onlyBinaryUpgrades;
8756 this.perMessageDeflate = false !== opts.perMessageDeflate ? (opts.perMessageDeflate || {}) : false;
8757
8758 if (true === this.perMessageDeflate) this.perMessageDeflate = {};
8759 if (this.perMessageDeflate && null == this.perMessageDeflate.threshold) {
8760 this.perMessageDeflate.threshold = 1024;
8761 }
8762
8763 // SSL options for Node.js client
8764 this.pfx = opts.pfx || null;
8765 this.key = opts.key || null;
8766 this.passphrase = opts.passphrase || null;
8767 this.cert = opts.cert || null;
8768 this.ca = opts.ca || null;
8769 this.ciphers = opts.ciphers || null;
8770 this.rejectUnauthorized = opts.rejectUnauthorized === undefined ? true : opts.rejectUnauthorized;
8771
8772 // other options for Node.js client
8773 var freeGlobal = typeof global == 'object' && global;
8774 if (freeGlobal.global === freeGlobal) {
8775 if (opts.extraHeaders && Object.keys(opts.extraHeaders).length > 0) {
8776 this.extraHeaders = opts.extraHeaders;
8777 }
8778 }
8779
8780 this.open();
8781}
8782
8783Socket.priorWebsocketSuccess = false;
8784
8785/**
8786 * Mix in `Emitter`.
8787 */
8788
8789Emitter(Socket.prototype);
8790
8791/**
8792 * Protocol version.
8793 *
8794 * @api public
8795 */
8796
8797Socket.protocol = parser.protocol; // this is an int
8798
8799/**
8800 * Expose deps for legacy compatibility
8801 * and standalone browser access.
8802 */
8803
8804Socket.Socket = Socket;
8805Socket.Transport = require('./transport');
8806Socket.transports = require('./transports');
8807Socket.parser = require('engine.io-parser');
8808
8809/**
8810 * Creates transport of the given type.
8811 *
8812 * @param {String} transport name
8813 * @return {Transport}
8814 * @api private
8815 */
8816
8817Socket.prototype.createTransport = function (name) {
8818 debug('creating transport "%s"', name);
8819 var query = clone(this.query);
8820
8821 // append engine.io protocol identifier
8822 query.EIO = parser.protocol;
8823
8824 // transport name
8825 query.transport = name;
8826
8827 // session id if we already have one
8828 if (this.id) query.sid = this.id;
8829
8830 var transport = new transports[name]({
8831 agent: this.agent,
8832 hostname: this.hostname,
8833 port: this.port,
8834 secure: this.secure,
8835 path: this.path,
8836 query: query,
8837 forceJSONP: this.forceJSONP,
8838 jsonp: this.jsonp,
8839 forceBase64: this.forceBase64,
8840 enablesXDR: this.enablesXDR,
8841 timestampRequests: this.timestampRequests,
8842 timestampParam: this.timestampParam,
8843 policyPort: this.policyPort,
8844 socket: this,
8845 pfx: this.pfx,
8846 key: this.key,
8847 passphrase: this.passphrase,
8848 cert: this.cert,
8849 ca: this.ca,
8850 ciphers: this.ciphers,
8851 rejectUnauthorized: this.rejectUnauthorized,
8852 perMessageDeflate: this.perMessageDeflate,
8853 extraHeaders: this.extraHeaders
8854 });
8855
8856 return transport;
8857};
8858
8859function clone (obj) {
8860 var o = {};
8861 for (var i in obj) {
8862 if (obj.hasOwnProperty(i)) {
8863 o[i] = obj[i];
8864 }
8865 }
8866 return o;
8867}
8868
8869/**
8870 * Initializes transport to use and starts probe.
8871 *
8872 * @api private
8873 */
8874Socket.prototype.open = function () {
8875 var transport;
8876 if (this.rememberUpgrade && Socket.priorWebsocketSuccess && this.transports.indexOf('websocket') != -1) {
8877 transport = 'websocket';
8878 } else if (0 === this.transports.length) {
8879 // Emit error on next tick so it can be listened to
8880 var self = this;
8881 setTimeout(function() {
8882 self.emit('error', 'No transports available');
8883 }, 0);
8884 return;
8885 } else {
8886 transport = this.transports[0];
8887 }
8888 this.readyState = 'opening';
8889
8890 // Retry with the next transport if the transport is disabled (jsonp: false)
8891 try {
8892 transport = this.createTransport(transport);
8893 } catch (e) {
8894 this.transports.shift();
8895 this.open();
8896 return;
8897 }
8898
8899 transport.open();
8900 this.setTransport(transport);
8901};
8902
8903/**
8904 * Sets the current transport. Disables the existing one (if any).
8905 *
8906 * @api private
8907 */
8908
8909Socket.prototype.setTransport = function(transport){
8910 debug('setting transport %s', transport.name);
8911 var self = this;
8912
8913 if (this.transport) {
8914 debug('clearing existing transport %s', this.transport.name);
8915 this.transport.removeAllListeners();
8916 }
8917
8918 // set up transport
8919 this.transport = transport;
8920
8921 // set up transport listeners
8922 transport
8923 .on('drain', function(){
8924 self.onDrain();
8925 })
8926 .on('packet', function(packet){
8927 self.onPacket(packet);
8928 })
8929 .on('error', function(e){
8930 self.onError(e);
8931 })
8932 .on('close', function(){
8933 self.onClose('transport close');
8934 });
8935};
8936
8937/**
8938 * Probes a transport.
8939 *
8940 * @param {String} transport name
8941 * @api private
8942 */
8943
8944Socket.prototype.probe = function (name) {
8945 debug('probing transport "%s"', name);
8946 var transport = this.createTransport(name, { probe: 1 })
8947 , failed = false
8948 , self = this;
8949
8950 Socket.priorWebsocketSuccess = false;
8951
8952 function onTransportOpen(){
8953 if (self.onlyBinaryUpgrades) {
8954 var upgradeLosesBinary = !this.supportsBinary && self.transport.supportsBinary;
8955 failed = failed || upgradeLosesBinary;
8956 }
8957 if (failed) return;
8958
8959 debug('probe transport "%s" opened', name);
8960 transport.send([{ type: 'ping', data: 'probe' }]);
8961 transport.once('packet', function (msg) {
8962 if (failed) return;
8963 if ('pong' == msg.type && 'probe' == msg.data) {
8964 debug('probe transport "%s" pong', name);
8965 self.upgrading = true;
8966 self.emit('upgrading', transport);
8967 if (!transport) return;
8968 Socket.priorWebsocketSuccess = 'websocket' == transport.name;
8969
8970 debug('pausing current transport "%s"', self.transport.name);
8971 self.transport.pause(function () {
8972 if (failed) return;
8973 if ('closed' == self.readyState) return;
8974 debug('changing transport and sending upgrade packet');
8975
8976 cleanup();
8977
8978 self.setTransport(transport);
8979 transport.send([{ type: 'upgrade' }]);
8980 self.emit('upgrade', transport);
8981 transport = null;
8982 self.upgrading = false;
8983 self.flush();
8984 });
8985 } else {
8986 debug('probe transport "%s" failed', name);
8987 var err = new Error('probe error');
8988 err.transport = transport.name;
8989 self.emit('upgradeError', err);
8990 }
8991 });
8992 }
8993
8994 function freezeTransport() {
8995 if (failed) return;
8996
8997 // Any callback called by transport should be ignored since now
8998 failed = true;
8999
9000 cleanup();
9001
9002 transport.close();
9003 transport = null;
9004 }
9005
9006 //Handle any error that happens while probing
9007 function onerror(err) {
9008 var error = new Error('probe error: ' + err);
9009 error.transport = transport.name;
9010
9011 freezeTransport();
9012
9013 debug('probe transport "%s" failed because of error: %s', name, err);
9014
9015 self.emit('upgradeError', error);
9016 }
9017
9018 function onTransportClose(){
9019 onerror("transport closed");
9020 }
9021
9022 //When the socket is closed while we're probing
9023 function onclose(){
9024 onerror("socket closed");
9025 }
9026
9027 //When the socket is upgraded while we're probing
9028 function onupgrade(to){
9029 if (transport && to.name != transport.name) {
9030 debug('"%s" works - aborting "%s"', to.name, transport.name);
9031 freezeTransport();
9032 }
9033 }
9034
9035 //Remove all listeners on the transport and on self
9036 function cleanup(){
9037 transport.removeListener('open', onTransportOpen);
9038 transport.removeListener('error', onerror);
9039 transport.removeListener('close', onTransportClose);
9040 self.removeListener('close', onclose);
9041 self.removeListener('upgrading', onupgrade);
9042 }
9043
9044 transport.once('open', onTransportOpen);
9045 transport.once('error', onerror);
9046 transport.once('close', onTransportClose);
9047
9048 this.once('close', onclose);
9049 this.once('upgrading', onupgrade);
9050
9051 transport.open();
9052
9053};
9054
9055/**
9056 * Called when connection is deemed open.
9057 *
9058 * @api public
9059 */
9060
9061Socket.prototype.onOpen = function () {
9062 debug('socket open');
9063 this.readyState = 'open';
9064 Socket.priorWebsocketSuccess = 'websocket' == this.transport.name;
9065 this.emit('open');
9066 this.flush();
9067
9068 // we check for `readyState` in case an `open`
9069 // listener already closed the socket
9070 if ('open' == this.readyState && this.upgrade && this.transport.pause) {
9071 debug('starting upgrade probes');
9072 for (var i = 0, l = this.upgrades.length; i < l; i++) {
9073 this.probe(this.upgrades[i]);
9074 }
9075 }
9076};
9077
9078/**
9079 * Handles a packet.
9080 *
9081 * @api private
9082 */
9083
9084Socket.prototype.onPacket = function (packet) {
9085 if ('opening' == this.readyState || 'open' == this.readyState) {
9086 debug('socket receive: type "%s", data "%s"', packet.type, packet.data);
9087
9088 this.emit('packet', packet);
9089
9090 // Socket is live - any packet counts
9091 this.emit('heartbeat');
9092
9093 switch (packet.type) {
9094 case 'open':
9095 this.onHandshake(parsejson(packet.data));
9096 break;
9097
9098 case 'pong':
9099 this.setPing();
9100 this.emit('pong');
9101 break;
9102
9103 case 'error':
9104 var err = new Error('server error');
9105 err.code = packet.data;
9106 this.onError(err);
9107 break;
9108
9109 case 'message':
9110 this.emit('data', packet.data);
9111 this.emit('message', packet.data);
9112 break;
9113 }
9114 } else {
9115 debug('packet received with socket readyState "%s"', this.readyState);
9116 }
9117};
9118
9119/**
9120 * Called upon handshake completion.
9121 *
9122 * @param {Object} handshake obj
9123 * @api private
9124 */
9125
9126Socket.prototype.onHandshake = function (data) {
9127 this.emit('handshake', data);
9128 this.id = data.sid;
9129 this.transport.query.sid = data.sid;
9130 this.upgrades = this.filterUpgrades(data.upgrades);
9131 this.pingInterval = data.pingInterval;
9132 this.pingTimeout = data.pingTimeout;
9133 this.onOpen();
9134 // In case open handler closes socket
9135 if ('closed' == this.readyState) return;
9136 this.setPing();
9137
9138 // Prolong liveness of socket on heartbeat
9139 this.removeListener('heartbeat', this.onHeartbeat);
9140 this.on('heartbeat', this.onHeartbeat);
9141};
9142
9143/**
9144 * Resets ping timeout.
9145 *
9146 * @api private
9147 */
9148
9149Socket.prototype.onHeartbeat = function (timeout) {
9150 clearTimeout(this.pingTimeoutTimer);
9151 var self = this;
9152 self.pingTimeoutTimer = setTimeout(function () {
9153 if ('closed' == self.readyState) return;
9154 self.onClose('ping timeout');
9155 }, timeout || (self.pingInterval + self.pingTimeout));
9156};
9157
9158/**
9159 * Pings server every `this.pingInterval` and expects response
9160 * within `this.pingTimeout` or closes connection.
9161 *
9162 * @api private
9163 */
9164
9165Socket.prototype.setPing = function () {
9166 var self = this;
9167 clearTimeout(self.pingIntervalTimer);
9168 self.pingIntervalTimer = setTimeout(function () {
9169 debug('writing ping packet - expecting pong within %sms', self.pingTimeout);
9170 self.ping();
9171 self.onHeartbeat(self.pingTimeout);
9172 }, self.pingInterval);
9173};
9174
9175/**
9176* Sends a ping packet.
9177*
9178* @api private
9179*/
9180
9181Socket.prototype.ping = function () {
9182 var self = this;
9183 this.sendPacket('ping', function(){
9184 self.emit('ping');
9185 });
9186};
9187
9188/**
9189 * Called on `drain` event
9190 *
9191 * @api private
9192 */
9193
9194Socket.prototype.onDrain = function() {
9195 this.writeBuffer.splice(0, this.prevBufferLen);
9196
9197 // setting prevBufferLen = 0 is very important
9198 // for example, when upgrading, upgrade packet is sent over,
9199 // and a nonzero prevBufferLen could cause problems on `drain`
9200 this.prevBufferLen = 0;
9201
9202 if (0 === this.writeBuffer.length) {
9203 this.emit('drain');
9204 } else {
9205 this.flush();
9206 }
9207};
9208
9209/**
9210 * Flush write buffers.
9211 *
9212 * @api private
9213 */
9214
9215Socket.prototype.flush = function () {
9216 if ('closed' != this.readyState && this.transport.writable &&
9217 !this.upgrading && this.writeBuffer.length) {
9218 debug('flushing %d packets in socket', this.writeBuffer.length);
9219 this.transport.send(this.writeBuffer);
9220 // keep track of current length of writeBuffer
9221 // splice writeBuffer and callbackBuffer on `drain`
9222 this.prevBufferLen = this.writeBuffer.length;
9223 this.emit('flush');
9224 }
9225};
9226
9227/**
9228 * Sends a message.
9229 *
9230 * @param {String} message.
9231 * @param {Function} callback function.
9232 * @param {Object} options.
9233 * @return {Socket} for chaining.
9234 * @api public
9235 */
9236
9237Socket.prototype.write =
9238Socket.prototype.send = function (msg, options, fn) {
9239 this.sendPacket('message', msg, options, fn);
9240 return this;
9241};
9242
9243/**
9244 * Sends a packet.
9245 *
9246 * @param {String} packet type.
9247 * @param {String} data.
9248 * @param {Object} options.
9249 * @param {Function} callback function.
9250 * @api private
9251 */
9252
9253Socket.prototype.sendPacket = function (type, data, options, fn) {
9254 if('function' == typeof data) {
9255 fn = data;
9256 data = undefined;
9257 }
9258
9259 if ('function' == typeof options) {
9260 fn = options;
9261 options = null;
9262 }
9263
9264 if ('closing' == this.readyState || 'closed' == this.readyState) {
9265 return;
9266 }
9267
9268 options = options || {};
9269 options.compress = false !== options.compress;
9270
9271 var packet = {
9272 type: type,
9273 data: data,
9274 options: options
9275 };
9276 this.emit('packetCreate', packet);
9277 this.writeBuffer.push(packet);
9278 if (fn) this.once('flush', fn);
9279 this.flush();
9280};
9281
9282/**
9283 * Closes the connection.
9284 *
9285 * @api private
9286 */
9287
9288Socket.prototype.close = function () {
9289 if ('opening' == this.readyState || 'open' == this.readyState) {
9290 this.readyState = 'closing';
9291
9292 var self = this;
9293
9294 if (this.writeBuffer.length) {
9295 this.once('drain', function() {
9296 if (this.upgrading) {
9297 waitForUpgrade();
9298 } else {
9299 close();
9300 }
9301 });
9302 } else if (this.upgrading) {
9303 waitForUpgrade();
9304 } else {
9305 close();
9306 }
9307 }
9308
9309 function close() {
9310 self.onClose('forced close');
9311 debug('socket closing - telling transport to close');
9312 self.transport.close();
9313 }
9314
9315 function cleanupAndClose() {
9316 self.removeListener('upgrade', cleanupAndClose);
9317 self.removeListener('upgradeError', cleanupAndClose);
9318 close();
9319 }
9320
9321 function waitForUpgrade() {
9322 // wait for upgrade to finish since we can't send packets while pausing a transport
9323 self.once('upgrade', cleanupAndClose);
9324 self.once('upgradeError', cleanupAndClose);
9325 }
9326
9327 return this;
9328};
9329
9330/**
9331 * Called upon transport error
9332 *
9333 * @api private
9334 */
9335
9336Socket.prototype.onError = function (err) {
9337 debug('socket error %j', err);
9338 Socket.priorWebsocketSuccess = false;
9339 this.emit('error', err);
9340 this.onClose('transport error', err);
9341};
9342
9343/**
9344 * Called upon transport close.
9345 *
9346 * @api private
9347 */
9348
9349Socket.prototype.onClose = function (reason, desc) {
9350 if ('opening' == this.readyState || 'open' == this.readyState || 'closing' == this.readyState) {
9351 debug('socket close with reason: "%s"', reason);
9352 var self = this;
9353
9354 // clear timers
9355 clearTimeout(this.pingIntervalTimer);
9356 clearTimeout(this.pingTimeoutTimer);
9357
9358 // stop event from firing again for transport
9359 this.transport.removeAllListeners('close');
9360
9361 // ensure transport won't stay open
9362 this.transport.close();
9363
9364 // ignore further transport communication
9365 this.transport.removeAllListeners();
9366
9367 // set ready state
9368 this.readyState = 'closed';
9369
9370 // clear session id
9371 this.id = null;
9372
9373 // emit close event
9374 this.emit('close', reason, desc);
9375
9376 // clean buffers after, so users can still
9377 // grab the buffers on `close` event
9378 self.writeBuffer = [];
9379 self.prevBufferLen = 0;
9380 }
9381};
9382
9383/**
9384 * Filters upgrades, returning only those matching client transports.
9385 *
9386 * @param {Array} server upgrades
9387 * @api private
9388 *
9389 */
9390
9391Socket.prototype.filterUpgrades = function (upgrades) {
9392 var filteredUpgrades = [];
9393 for (var i = 0, j = upgrades.length; i<j; i++) {
9394 if (~index(this.transports, upgrades[i])) filteredUpgrades.push(upgrades[i]);
9395 }
9396 return filteredUpgrades;
9397};
9398
9399}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
9400},{"./transport":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/engine.io-client/lib/transport.js","./transports":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/engine.io-client/lib/transports/index.js","component-emitter":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/engine.io-client/node_modules/component-emitter/index.js","debug":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/debug/browser.js","engine.io-parser":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/engine.io-parser/lib/browser.js","indexof":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/indexof/index.js","parsejson":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/parsejson/index.js","parseqs":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/parseqs/index.js","parseuri":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/parseuri/index.js"}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/engine.io-client/lib/transport.js":[function(require,module,exports){
9401/**
9402 * Module dependencies.
9403 */
9404
9405var parser = require('engine.io-parser');
9406var Emitter = require('component-emitter');
9407
9408/**
9409 * Module exports.
9410 */
9411
9412module.exports = Transport;
9413
9414/**
9415 * Transport abstract constructor.
9416 *
9417 * @param {Object} options.
9418 * @api private
9419 */
9420
9421function Transport (opts) {
9422 this.path = opts.path;
9423 this.hostname = opts.hostname;
9424 this.port = opts.port;
9425 this.secure = opts.secure;
9426 this.query = opts.query;
9427 this.timestampParam = opts.timestampParam;
9428 this.timestampRequests = opts.timestampRequests;
9429 this.readyState = '';
9430 this.agent = opts.agent || false;
9431 this.socket = opts.socket;
9432 this.enablesXDR = opts.enablesXDR;
9433
9434 // SSL options for Node.js client
9435 this.pfx = opts.pfx;
9436 this.key = opts.key;
9437 this.passphrase = opts.passphrase;
9438 this.cert = opts.cert;
9439 this.ca = opts.ca;
9440 this.ciphers = opts.ciphers;
9441 this.rejectUnauthorized = opts.rejectUnauthorized;
9442
9443 // other options for Node.js client
9444 this.extraHeaders = opts.extraHeaders;
9445}
9446
9447/**
9448 * Mix in `Emitter`.
9449 */
9450
9451Emitter(Transport.prototype);
9452
9453/**
9454 * Emits an error.
9455 *
9456 * @param {String} str
9457 * @return {Transport} for chaining
9458 * @api public
9459 */
9460
9461Transport.prototype.onError = function (msg, desc) {
9462 var err = new Error(msg);
9463 err.type = 'TransportError';
9464 err.description = desc;
9465 this.emit('error', err);
9466 return this;
9467};
9468
9469/**
9470 * Opens the transport.
9471 *
9472 * @api public
9473 */
9474
9475Transport.prototype.open = function () {
9476 if ('closed' == this.readyState || '' == this.readyState) {
9477 this.readyState = 'opening';
9478 this.doOpen();
9479 }
9480
9481 return this;
9482};
9483
9484/**
9485 * Closes the transport.
9486 *
9487 * @api private
9488 */
9489
9490Transport.prototype.close = function () {
9491 if ('opening' == this.readyState || 'open' == this.readyState) {
9492 this.doClose();
9493 this.onClose();
9494 }
9495
9496 return this;
9497};
9498
9499/**
9500 * Sends multiple packets.
9501 *
9502 * @param {Array} packets
9503 * @api private
9504 */
9505
9506Transport.prototype.send = function(packets){
9507 if ('open' == this.readyState) {
9508 this.write(packets);
9509 } else {
9510 throw new Error('Transport not open');
9511 }
9512};
9513
9514/**
9515 * Called upon open
9516 *
9517 * @api private
9518 */
9519
9520Transport.prototype.onOpen = function () {
9521 this.readyState = 'open';
9522 this.writable = true;
9523 this.emit('open');
9524};
9525
9526/**
9527 * Called with data.
9528 *
9529 * @param {String} data
9530 * @api private
9531 */
9532
9533Transport.prototype.onData = function(data){
9534 var packet = parser.decodePacket(data, this.socket.binaryType);
9535 this.onPacket(packet);
9536};
9537
9538/**
9539 * Called with a decoded packet.
9540 */
9541
9542Transport.prototype.onPacket = function (packet) {
9543 this.emit('packet', packet);
9544};
9545
9546/**
9547 * Called upon close.
9548 *
9549 * @api private
9550 */
9551
9552Transport.prototype.onClose = function () {
9553 this.readyState = 'closed';
9554 this.emit('close');
9555};
9556
9557},{"component-emitter":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/engine.io-client/node_modules/component-emitter/index.js","engine.io-parser":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/engine.io-parser/lib/browser.js"}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/engine.io-client/lib/transports/index.js":[function(require,module,exports){
9558(function (global){
9559/**
9560 * Module dependencies
9561 */
9562
9563var XMLHttpRequest = require('xmlhttprequest-ssl');
9564var XHR = require('./polling-xhr');
9565var JSONP = require('./polling-jsonp');
9566var websocket = require('./websocket');
9567
9568/**
9569 * Export transports.
9570 */
9571
9572exports.polling = polling;
9573exports.websocket = websocket;
9574
9575/**
9576 * Polling transport polymorphic constructor.
9577 * Decides on xhr vs jsonp based on feature detection.
9578 *
9579 * @api private
9580 */
9581
9582function polling(opts){
9583 var xhr;
9584 var xd = false;
9585 var xs = false;
9586 var jsonp = false !== opts.jsonp;
9587
9588 if (global.location) {
9589 var isSSL = 'https:' == location.protocol;
9590 var port = location.port;
9591
9592 // some user agents have empty `location.port`
9593 if (!port) {
9594 port = isSSL ? 443 : 80;
9595 }
9596
9597 xd = opts.hostname != location.hostname || port != opts.port;
9598 xs = opts.secure != isSSL;
9599 }
9600
9601 opts.xdomain = xd;
9602 opts.xscheme = xs;
9603 xhr = new XMLHttpRequest(opts);
9604
9605 if ('open' in xhr && !opts.forceJSONP) {
9606 return new XHR(opts);
9607 } else {
9608 if (!jsonp) throw new Error('JSONP disabled');
9609 return new JSONP(opts);
9610 }
9611}
9612
9613}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
9614},{"./polling-jsonp":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/engine.io-client/lib/transports/polling-jsonp.js","./polling-xhr":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/engine.io-client/lib/transports/polling-xhr.js","./websocket":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/engine.io-client/lib/transports/websocket.js","xmlhttprequest-ssl":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/engine.io-client/lib/xmlhttprequest.js"}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/engine.io-client/lib/transports/polling-jsonp.js":[function(require,module,exports){
9615(function (global){
9616
9617/**
9618 * Module requirements.
9619 */
9620
9621var Polling = require('./polling');
9622var inherit = require('component-inherit');
9623
9624/**
9625 * Module exports.
9626 */
9627
9628module.exports = JSONPPolling;
9629
9630/**
9631 * Cached regular expressions.
9632 */
9633
9634var rNewline = /\n/g;
9635var rEscapedNewline = /\\n/g;
9636
9637/**
9638 * Global JSONP callbacks.
9639 */
9640
9641var callbacks;
9642
9643/**
9644 * Callbacks count.
9645 */
9646
9647var index = 0;
9648
9649/**
9650 * Noop.
9651 */
9652
9653function empty () { }
9654
9655/**
9656 * JSONP Polling constructor.
9657 *
9658 * @param {Object} opts.
9659 * @api public
9660 */
9661
9662function JSONPPolling (opts) {
9663 Polling.call(this, opts);
9664
9665 this.query = this.query || {};
9666
9667 // define global callbacks array if not present
9668 // we do this here (lazily) to avoid unneeded global pollution
9669 if (!callbacks) {
9670 // we need to consider multiple engines in the same page
9671 if (!global.___eio) global.___eio = [];
9672 callbacks = global.___eio;
9673 }
9674
9675 // callback identifier
9676 this.index = callbacks.length;
9677
9678 // add callback to jsonp global
9679 var self = this;
9680 callbacks.push(function (msg) {
9681 self.onData(msg);
9682 });
9683
9684 // append to query string
9685 this.query.j = this.index;
9686
9687 // prevent spurious errors from being emitted when the window is unloaded
9688 if (global.document && global.addEventListener) {
9689 global.addEventListener('beforeunload', function () {
9690 if (self.script) self.script.onerror = empty;
9691 }, false);
9692 }
9693}
9694
9695/**
9696 * Inherits from Polling.
9697 */
9698
9699inherit(JSONPPolling, Polling);
9700
9701/*
9702 * JSONP only supports binary as base64 encoded strings
9703 */
9704
9705JSONPPolling.prototype.supportsBinary = false;
9706
9707/**
9708 * Closes the socket.
9709 *
9710 * @api private
9711 */
9712
9713JSONPPolling.prototype.doClose = function () {
9714 if (this.script) {
9715 this.script.parentNode.removeChild(this.script);
9716 this.script = null;
9717 }
9718
9719 if (this.form) {
9720 this.form.parentNode.removeChild(this.form);
9721 this.form = null;
9722 this.iframe = null;
9723 }
9724
9725 Polling.prototype.doClose.call(this);
9726};
9727
9728/**
9729 * Starts a poll cycle.
9730 *
9731 * @api private
9732 */
9733
9734JSONPPolling.prototype.doPoll = function () {
9735 var self = this;
9736 var script = document.createElement('script');
9737
9738 if (this.script) {
9739 this.script.parentNode.removeChild(this.script);
9740 this.script = null;
9741 }
9742
9743 script.async = true;
9744 script.src = this.uri();
9745 script.onerror = function(e){
9746 self.onError('jsonp poll error',e);
9747 };
9748
9749 var insertAt = document.getElementsByTagName('script')[0];
9750 if (insertAt) {
9751 insertAt.parentNode.insertBefore(script, insertAt);
9752 }
9753 else {
9754 (document.head || document.body).appendChild(script);
9755 }
9756 this.script = script;
9757
9758 var isUAgecko = 'undefined' != typeof navigator && /gecko/i.test(navigator.userAgent);
9759
9760 if (isUAgecko) {
9761 setTimeout(function () {
9762 var iframe = document.createElement('iframe');
9763 document.body.appendChild(iframe);
9764 document.body.removeChild(iframe);
9765 }, 100);
9766 }
9767};
9768
9769/**
9770 * Writes with a hidden iframe.
9771 *
9772 * @param {String} data to send
9773 * @param {Function} called upon flush.
9774 * @api private
9775 */
9776
9777JSONPPolling.prototype.doWrite = function (data, fn) {
9778 var self = this;
9779
9780 if (!this.form) {
9781 var form = document.createElement('form');
9782 var area = document.createElement('textarea');
9783 var id = this.iframeId = 'eio_iframe_' + this.index;
9784 var iframe;
9785
9786 form.className = 'socketio';
9787 form.style.position = 'absolute';
9788 form.style.top = '-1000px';
9789 form.style.left = '-1000px';
9790 form.target = id;
9791 form.method = 'POST';
9792 form.setAttribute('accept-charset', 'utf-8');
9793 area.name = 'd';
9794 form.appendChild(area);
9795 document.body.appendChild(form);
9796
9797 this.form = form;
9798 this.area = area;
9799 }
9800
9801 this.form.action = this.uri();
9802
9803 function complete () {
9804 initIframe();
9805 fn();
9806 }
9807
9808 function initIframe () {
9809 if (self.iframe) {
9810 try {
9811 self.form.removeChild(self.iframe);
9812 } catch (e) {
9813 self.onError('jsonp polling iframe removal error', e);
9814 }
9815 }
9816
9817 try {
9818 // ie6 dynamic iframes with target="" support (thanks Chris Lambacher)
9819 var html = '<iframe src="javascript:0" name="'+ self.iframeId +'">';
9820 iframe = document.createElement(html);
9821 } catch (e) {
9822 iframe = document.createElement('iframe');
9823 iframe.name = self.iframeId;
9824 iframe.src = 'javascript:0';
9825 }
9826
9827 iframe.id = self.iframeId;
9828
9829 self.form.appendChild(iframe);
9830 self.iframe = iframe;
9831 }
9832
9833 initIframe();
9834
9835 // escape \n to prevent it from being converted into \r\n by some UAs
9836 // double escaping is required for escaped new lines because unescaping of new lines can be done safely on server-side
9837 data = data.replace(rEscapedNewline, '\\\n');
9838 this.area.value = data.replace(rNewline, '\\n');
9839
9840 try {
9841 this.form.submit();
9842 } catch(e) {}
9843
9844 if (this.iframe.attachEvent) {
9845 this.iframe.onreadystatechange = function(){
9846 if (self.iframe.readyState == 'complete') {
9847 complete();
9848 }
9849 };
9850 } else {
9851 this.iframe.onload = complete;
9852 }
9853};
9854
9855}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
9856},{"./polling":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/engine.io-client/lib/transports/polling.js","component-inherit":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/component-inherit/index.js"}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/engine.io-client/lib/transports/polling-xhr.js":[function(require,module,exports){
9857(function (global){
9858/**
9859 * Module requirements.
9860 */
9861
9862var XMLHttpRequest = require('xmlhttprequest-ssl');
9863var Polling = require('./polling');
9864var Emitter = require('component-emitter');
9865var inherit = require('component-inherit');
9866var debug = require('debug')('engine.io-client:polling-xhr');
9867
9868/**
9869 * Module exports.
9870 */
9871
9872module.exports = XHR;
9873module.exports.Request = Request;
9874
9875/**
9876 * Empty function
9877 */
9878
9879function empty(){}
9880
9881/**
9882 * XHR Polling constructor.
9883 *
9884 * @param {Object} opts
9885 * @api public
9886 */
9887
9888function XHR(opts){
9889 Polling.call(this, opts);
9890
9891 if (global.location) {
9892 var isSSL = 'https:' == location.protocol;
9893 var port = location.port;
9894
9895 // some user agents have empty `location.port`
9896 if (!port) {
9897 port = isSSL ? 443 : 80;
9898 }
9899
9900 this.xd = opts.hostname != global.location.hostname ||
9901 port != opts.port;
9902 this.xs = opts.secure != isSSL;
9903 } else {
9904 this.extraHeaders = opts.extraHeaders;
9905 }
9906}
9907
9908/**
9909 * Inherits from Polling.
9910 */
9911
9912inherit(XHR, Polling);
9913
9914/**
9915 * XHR supports binary
9916 */
9917
9918XHR.prototype.supportsBinary = true;
9919
9920/**
9921 * Creates a request.
9922 *
9923 * @param {String} method
9924 * @api private
9925 */
9926
9927XHR.prototype.request = function(opts){
9928 opts = opts || {};
9929 opts.uri = this.uri();
9930 opts.xd = this.xd;
9931 opts.xs = this.xs;
9932 opts.agent = this.agent || false;
9933 opts.supportsBinary = this.supportsBinary;
9934 opts.enablesXDR = this.enablesXDR;
9935
9936 // SSL options for Node.js client
9937 opts.pfx = this.pfx;
9938 opts.key = this.key;
9939 opts.passphrase = this.passphrase;
9940 opts.cert = this.cert;
9941 opts.ca = this.ca;
9942 opts.ciphers = this.ciphers;
9943 opts.rejectUnauthorized = this.rejectUnauthorized;
9944
9945 // other options for Node.js client
9946 opts.extraHeaders = this.extraHeaders;
9947
9948 return new Request(opts);
9949};
9950
9951/**
9952 * Sends data.
9953 *
9954 * @param {String} data to send.
9955 * @param {Function} called upon flush.
9956 * @api private
9957 */
9958
9959XHR.prototype.doWrite = function(data, fn){
9960 var isBinary = typeof data !== 'string' && data !== undefined;
9961 var req = this.request({ method: 'POST', data: data, isBinary: isBinary });
9962 var self = this;
9963 req.on('success', fn);
9964 req.on('error', function(err){
9965 self.onError('xhr post error', err);
9966 });
9967 this.sendXhr = req;
9968};
9969
9970/**
9971 * Starts a poll cycle.
9972 *
9973 * @api private
9974 */
9975
9976XHR.prototype.doPoll = function(){
9977 debug('xhr poll');
9978 var req = this.request();
9979 var self = this;
9980 req.on('data', function(data){
9981 self.onData(data);
9982 });
9983 req.on('error', function(err){
9984 self.onError('xhr poll error', err);
9985 });
9986 this.pollXhr = req;
9987};
9988
9989/**
9990 * Request constructor
9991 *
9992 * @param {Object} options
9993 * @api public
9994 */
9995
9996function Request(opts){
9997 this.method = opts.method || 'GET';
9998 this.uri = opts.uri;
9999 this.xd = !!opts.xd;
10000 this.xs = !!opts.xs;
10001 this.async = false !== opts.async;
10002 this.data = undefined != opts.data ? opts.data : null;
10003 this.agent = opts.agent;
10004 this.isBinary = opts.isBinary;
10005 this.supportsBinary = opts.supportsBinary;
10006 this.enablesXDR = opts.enablesXDR;
10007
10008 // SSL options for Node.js client
10009 this.pfx = opts.pfx;
10010 this.key = opts.key;
10011 this.passphrase = opts.passphrase;
10012 this.cert = opts.cert;
10013 this.ca = opts.ca;
10014 this.ciphers = opts.ciphers;
10015 this.rejectUnauthorized = opts.rejectUnauthorized;
10016
10017 // other options for Node.js client
10018 this.extraHeaders = opts.extraHeaders;
10019
10020 this.create();
10021}
10022
10023/**
10024 * Mix in `Emitter`.
10025 */
10026
10027Emitter(Request.prototype);
10028
10029/**
10030 * Creates the XHR object and sends the request.
10031 *
10032 * @api private
10033 */
10034
10035Request.prototype.create = function(){
10036 var opts = { agent: this.agent, xdomain: this.xd, xscheme: this.xs, enablesXDR: this.enablesXDR };
10037
10038 // SSL options for Node.js client
10039 opts.pfx = this.pfx;
10040 opts.key = this.key;
10041 opts.passphrase = this.passphrase;
10042 opts.cert = this.cert;
10043 opts.ca = this.ca;
10044 opts.ciphers = this.ciphers;
10045 opts.rejectUnauthorized = this.rejectUnauthorized;
10046
10047 var xhr = this.xhr = new XMLHttpRequest(opts);
10048 var self = this;
10049
10050 try {
10051 debug('xhr open %s: %s', this.method, this.uri);
10052 xhr.open(this.method, this.uri, this.async);
10053 try {
10054 if (this.extraHeaders) {
10055 xhr.setDisableHeaderCheck(true);
10056 for (var i in this.extraHeaders) {
10057 if (this.extraHeaders.hasOwnProperty(i)) {
10058 xhr.setRequestHeader(i, this.extraHeaders[i]);
10059 }
10060 }
10061 }
10062 } catch (e) {}
10063 if (this.supportsBinary) {
10064 // This has to be done after open because Firefox is stupid
10065 // http://stackoverflow.com/questions/13216903/get-binary-data-with-xmlhttprequest-in-a-firefox-extension
10066 xhr.responseType = 'arraybuffer';
10067 }
10068
10069 if ('POST' == this.method) {
10070 try {
10071 if (this.isBinary) {
10072 xhr.setRequestHeader('Content-type', 'application/octet-stream');
10073 } else {
10074 xhr.setRequestHeader('Content-type', 'text/plain;charset=UTF-8');
10075 }
10076 } catch (e) {}
10077 }
10078
10079 // ie6 check
10080 if ('withCredentials' in xhr) {
10081 xhr.withCredentials = true;
10082 }
10083
10084 if (this.hasXDR()) {
10085 xhr.onload = function(){
10086 self.onLoad();
10087 };
10088 xhr.onerror = function(){
10089 self.onError(xhr.responseText);
10090 };
10091 } else {
10092 xhr.onreadystatechange = function(){
10093 if (4 != xhr.readyState) return;
10094 if (200 == xhr.status || 1223 == xhr.status) {
10095 self.onLoad();
10096 } else {
10097 // make sure the `error` event handler that's user-set
10098 // does not throw in the same tick and gets caught here
10099 setTimeout(function(){
10100 self.onError(xhr.status);
10101 }, 0);
10102 }
10103 };
10104 }
10105
10106 debug('xhr data %s', this.data);
10107 xhr.send(this.data);
10108 } catch (e) {
10109 // Need to defer since .create() is called directly fhrom the constructor
10110 // and thus the 'error' event can only be only bound *after* this exception
10111 // occurs. Therefore, also, we cannot throw here at all.
10112 setTimeout(function() {
10113 self.onError(e);
10114 }, 0);
10115 return;
10116 }
10117
10118 if (global.document) {
10119 this.index = Request.requestsCount++;
10120 Request.requests[this.index] = this;
10121 }
10122};
10123
10124/**
10125 * Called upon successful response.
10126 *
10127 * @api private
10128 */
10129
10130Request.prototype.onSuccess = function(){
10131 this.emit('success');
10132 this.cleanup();
10133};
10134
10135/**
10136 * Called if we have data.
10137 *
10138 * @api private
10139 */
10140
10141Request.prototype.onData = function(data){
10142 this.emit('data', data);
10143 this.onSuccess();
10144};
10145
10146/**
10147 * Called upon error.
10148 *
10149 * @api private
10150 */
10151
10152Request.prototype.onError = function(err){
10153 this.emit('error', err);
10154 this.cleanup(true);
10155};
10156
10157/**
10158 * Cleans up house.
10159 *
10160 * @api private
10161 */
10162
10163Request.prototype.cleanup = function(fromError){
10164 if ('undefined' == typeof this.xhr || null === this.xhr) {
10165 return;
10166 }
10167 // xmlhttprequest
10168 if (this.hasXDR()) {
10169 this.xhr.onload = this.xhr.onerror = empty;
10170 } else {
10171 this.xhr.onreadystatechange = empty;
10172 }
10173
10174 if (fromError) {
10175 try {
10176 this.xhr.abort();
10177 } catch(e) {}
10178 }
10179
10180 if (global.document) {
10181 delete Request.requests[this.index];
10182 }
10183
10184 this.xhr = null;
10185};
10186
10187/**
10188 * Called upon load.
10189 *
10190 * @api private
10191 */
10192
10193Request.prototype.onLoad = function(){
10194 var data;
10195 try {
10196 var contentType;
10197 try {
10198 contentType = this.xhr.getResponseHeader('Content-Type').split(';')[0];
10199 } catch (e) {}
10200 if (contentType === 'application/octet-stream') {
10201 data = this.xhr.response;
10202 } else {
10203 if (!this.supportsBinary) {
10204 data = this.xhr.responseText;
10205 } else {
10206 try {
10207 data = String.fromCharCode.apply(null, new Uint8Array(this.xhr.response));
10208 } catch (e) {
10209 var ui8Arr = new Uint8Array(this.xhr.response);
10210 var dataArray = [];
10211 for (var idx = 0, length = ui8Arr.length; idx < length; idx++) {
10212 dataArray.push(ui8Arr[idx]);
10213 }
10214
10215 data = String.fromCharCode.apply(null, dataArray);
10216 }
10217 }
10218 }
10219 } catch (e) {
10220 this.onError(e);
10221 }
10222 if (null != data) {
10223 this.onData(data);
10224 }
10225};
10226
10227/**
10228 * Check if it has XDomainRequest.
10229 *
10230 * @api private
10231 */
10232
10233Request.prototype.hasXDR = function(){
10234 return 'undefined' !== typeof global.XDomainRequest && !this.xs && this.enablesXDR;
10235};
10236
10237/**
10238 * Aborts the request.
10239 *
10240 * @api public
10241 */
10242
10243Request.prototype.abort = function(){
10244 this.cleanup();
10245};
10246
10247/**
10248 * Aborts pending requests when unloading the window. This is needed to prevent
10249 * memory leaks (e.g. when using IE) and to ensure that no spurious error is
10250 * emitted.
10251 */
10252
10253if (global.document) {
10254 Request.requestsCount = 0;
10255 Request.requests = {};
10256 if (global.attachEvent) {
10257 global.attachEvent('onunload', unloadHandler);
10258 } else if (global.addEventListener) {
10259 global.addEventListener('beforeunload', unloadHandler, false);
10260 }
10261}
10262
10263function unloadHandler() {
10264 for (var i in Request.requests) {
10265 if (Request.requests.hasOwnProperty(i)) {
10266 Request.requests[i].abort();
10267 }
10268 }
10269}
10270
10271}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
10272},{"./polling":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/engine.io-client/lib/transports/polling.js","component-emitter":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/engine.io-client/node_modules/component-emitter/index.js","component-inherit":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/component-inherit/index.js","debug":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/debug/browser.js","xmlhttprequest-ssl":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/engine.io-client/lib/xmlhttprequest.js"}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/engine.io-client/lib/transports/polling.js":[function(require,module,exports){
10273/**
10274 * Module dependencies.
10275 */
10276
10277var Transport = require('../transport');
10278var parseqs = require('parseqs');
10279var parser = require('engine.io-parser');
10280var inherit = require('component-inherit');
10281var yeast = require('yeast');
10282var debug = require('debug')('engine.io-client:polling');
10283
10284/**
10285 * Module exports.
10286 */
10287
10288module.exports = Polling;
10289
10290/**
10291 * Is XHR2 supported?
10292 */
10293
10294var hasXHR2 = (function() {
10295 var XMLHttpRequest = require('xmlhttprequest-ssl');
10296 var xhr = new XMLHttpRequest({ xdomain: false });
10297 return null != xhr.responseType;
10298})();
10299
10300/**
10301 * Polling interface.
10302 *
10303 * @param {Object} opts
10304 * @api private
10305 */
10306
10307function Polling(opts){
10308 var forceBase64 = (opts && opts.forceBase64);
10309 if (!hasXHR2 || forceBase64) {
10310 this.supportsBinary = false;
10311 }
10312 Transport.call(this, opts);
10313}
10314
10315/**
10316 * Inherits from Transport.
10317 */
10318
10319inherit(Polling, Transport);
10320
10321/**
10322 * Transport name.
10323 */
10324
10325Polling.prototype.name = 'polling';
10326
10327/**
10328 * Opens the socket (triggers polling). We write a PING message to determine
10329 * when the transport is open.
10330 *
10331 * @api private
10332 */
10333
10334Polling.prototype.doOpen = function(){
10335 this.poll();
10336};
10337
10338/**
10339 * Pauses polling.
10340 *
10341 * @param {Function} callback upon buffers are flushed and transport is paused
10342 * @api private
10343 */
10344
10345Polling.prototype.pause = function(onPause){
10346 var pending = 0;
10347 var self = this;
10348
10349 this.readyState = 'pausing';
10350
10351 function pause(){
10352 debug('paused');
10353 self.readyState = 'paused';
10354 onPause();
10355 }
10356
10357 if (this.polling || !this.writable) {
10358 var total = 0;
10359
10360 if (this.polling) {
10361 debug('we are currently polling - waiting to pause');
10362 total++;
10363 this.once('pollComplete', function(){
10364 debug('pre-pause polling complete');
10365 --total || pause();
10366 });
10367 }
10368
10369 if (!this.writable) {
10370 debug('we are currently writing - waiting to pause');
10371 total++;
10372 this.once('drain', function(){
10373 debug('pre-pause writing complete');
10374 --total || pause();
10375 });
10376 }
10377 } else {
10378 pause();
10379 }
10380};
10381
10382/**
10383 * Starts polling cycle.
10384 *
10385 * @api public
10386 */
10387
10388Polling.prototype.poll = function(){
10389 debug('polling');
10390 this.polling = true;
10391 this.doPoll();
10392 this.emit('poll');
10393};
10394
10395/**
10396 * Overloads onData to detect payloads.
10397 *
10398 * @api private
10399 */
10400
10401Polling.prototype.onData = function(data){
10402 var self = this;
10403 debug('polling got data %s', data);
10404 var callback = function(packet, index, total) {
10405 // if its the first message we consider the transport open
10406 if ('opening' == self.readyState) {
10407 self.onOpen();
10408 }
10409
10410 // if its a close packet, we close the ongoing requests
10411 if ('close' == packet.type) {
10412 self.onClose();
10413 return false;
10414 }
10415
10416 // otherwise bypass onData and handle the message
10417 self.onPacket(packet);
10418 };
10419
10420 // decode payload
10421 parser.decodePayload(data, this.socket.binaryType, callback);
10422
10423 // if an event did not trigger closing
10424 if ('closed' != this.readyState) {
10425 // if we got data we're not polling
10426 this.polling = false;
10427 this.emit('pollComplete');
10428
10429 if ('open' == this.readyState) {
10430 this.poll();
10431 } else {
10432 debug('ignoring poll - transport state "%s"', this.readyState);
10433 }
10434 }
10435};
10436
10437/**
10438 * For polling, send a close packet.
10439 *
10440 * @api private
10441 */
10442
10443Polling.prototype.doClose = function(){
10444 var self = this;
10445
10446 function close(){
10447 debug('writing close packet');
10448 self.write([{ type: 'close' }]);
10449 }
10450
10451 if ('open' == this.readyState) {
10452 debug('transport open - closing');
10453 close();
10454 } else {
10455 // in case we're trying to close while
10456 // handshaking is in progress (GH-164)
10457 debug('transport not open - deferring close');
10458 this.once('open', close);
10459 }
10460};
10461
10462/**
10463 * Writes a packets payload.
10464 *
10465 * @param {Array} data packets
10466 * @param {Function} drain callback
10467 * @api private
10468 */
10469
10470Polling.prototype.write = function(packets){
10471 var self = this;
10472 this.writable = false;
10473 var callbackfn = function() {
10474 self.writable = true;
10475 self.emit('drain');
10476 };
10477
10478 var self = this;
10479 parser.encodePayload(packets, this.supportsBinary, function(data) {
10480 self.doWrite(data, callbackfn);
10481 });
10482};
10483
10484/**
10485 * Generates uri for connection.
10486 *
10487 * @api private
10488 */
10489
10490Polling.prototype.uri = function(){
10491 var query = this.query || {};
10492 var schema = this.secure ? 'https' : 'http';
10493 var port = '';
10494
10495 // cache busting is forced
10496 if (false !== this.timestampRequests) {
10497 query[this.timestampParam] = yeast();
10498 }
10499
10500 if (!this.supportsBinary && !query.sid) {
10501 query.b64 = 1;
10502 }
10503
10504 query = parseqs.encode(query);
10505
10506 // avoid port if default for schema
10507 if (this.port && (('https' == schema && this.port != 443) ||
10508 ('http' == schema && this.port != 80))) {
10509 port = ':' + this.port;
10510 }
10511
10512 // prepend ? to query
10513 if (query.length) {
10514 query = '?' + query;
10515 }
10516
10517 var ipv6 = this.hostname.indexOf(':') !== -1;
10518 return schema + '://' + (ipv6 ? '[' + this.hostname + ']' : this.hostname) + port + this.path + query;
10519};
10520
10521},{"../transport":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/engine.io-client/lib/transport.js","component-inherit":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/component-inherit/index.js","debug":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/debug/browser.js","engine.io-parser":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/engine.io-parser/lib/browser.js","parseqs":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/parseqs/index.js","xmlhttprequest-ssl":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/engine.io-client/lib/xmlhttprequest.js","yeast":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/yeast/index.js"}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/engine.io-client/lib/transports/websocket.js":[function(require,module,exports){
10522(function (global){
10523/**
10524 * Module dependencies.
10525 */
10526
10527var Transport = require('../transport');
10528var parser = require('engine.io-parser');
10529var parseqs = require('parseqs');
10530var inherit = require('component-inherit');
10531var yeast = require('yeast');
10532var debug = require('debug')('engine.io-client:websocket');
10533var BrowserWebSocket = global.WebSocket || global.MozWebSocket;
10534
10535/**
10536 * Get either the `WebSocket` or `MozWebSocket` globals
10537 * in the browser or try to resolve WebSocket-compatible
10538 * interface exposed by `ws` for Node-like environment.
10539 */
10540
10541var WebSocket = BrowserWebSocket;
10542if (!WebSocket && typeof window === 'undefined') {
10543 try {
10544 WebSocket = require('ws');
10545 } catch (e) { }
10546}
10547
10548/**
10549 * Module exports.
10550 */
10551
10552module.exports = WS;
10553
10554/**
10555 * WebSocket transport constructor.
10556 *
10557 * @api {Object} connection options
10558 * @api public
10559 */
10560
10561function WS(opts){
10562 var forceBase64 = (opts && opts.forceBase64);
10563 if (forceBase64) {
10564 this.supportsBinary = false;
10565 }
10566 this.perMessageDeflate = opts.perMessageDeflate;
10567 Transport.call(this, opts);
10568}
10569
10570/**
10571 * Inherits from Transport.
10572 */
10573
10574inherit(WS, Transport);
10575
10576/**
10577 * Transport name.
10578 *
10579 * @api public
10580 */
10581
10582WS.prototype.name = 'websocket';
10583
10584/*
10585 * WebSockets support binary
10586 */
10587
10588WS.prototype.supportsBinary = true;
10589
10590/**
10591 * Opens socket.
10592 *
10593 * @api private
10594 */
10595
10596WS.prototype.doOpen = function(){
10597 if (!this.check()) {
10598 // let probe timeout
10599 return;
10600 }
10601
10602 var self = this;
10603 var uri = this.uri();
10604 var protocols = void(0);
10605 var opts = {
10606 agent: this.agent,
10607 perMessageDeflate: this.perMessageDeflate
10608 };
10609
10610 // SSL options for Node.js client
10611 opts.pfx = this.pfx;
10612 opts.key = this.key;
10613 opts.passphrase = this.passphrase;
10614 opts.cert = this.cert;
10615 opts.ca = this.ca;
10616 opts.ciphers = this.ciphers;
10617 opts.rejectUnauthorized = this.rejectUnauthorized;
10618 if (this.extraHeaders) {
10619 opts.headers = this.extraHeaders;
10620 }
10621
10622 this.ws = BrowserWebSocket ? new WebSocket(uri) : new WebSocket(uri, protocols, opts);
10623
10624 if (this.ws.binaryType === undefined) {
10625 this.supportsBinary = false;
10626 }
10627
10628 if (this.ws.supports && this.ws.supports.binary) {
10629 this.supportsBinary = true;
10630 this.ws.binaryType = 'buffer';
10631 } else {
10632 this.ws.binaryType = 'arraybuffer';
10633 }
10634
10635 this.addEventListeners();
10636};
10637
10638/**
10639 * Adds event listeners to the socket
10640 *
10641 * @api private
10642 */
10643
10644WS.prototype.addEventListeners = function(){
10645 var self = this;
10646
10647 this.ws.onopen = function(){
10648 self.onOpen();
10649 };
10650 this.ws.onclose = function(){
10651 self.onClose();
10652 };
10653 this.ws.onmessage = function(ev){
10654 self.onData(ev.data);
10655 };
10656 this.ws.onerror = function(e){
10657 self.onError('websocket error', e);
10658 };
10659};
10660
10661/**
10662 * Override `onData` to use a timer on iOS.
10663 * See: https://gist.github.com/mloughran/2052006
10664 *
10665 * @api private
10666 */
10667
10668if ('undefined' != typeof navigator
10669 && /iPad|iPhone|iPod/i.test(navigator.userAgent)) {
10670 WS.prototype.onData = function(data){
10671 var self = this;
10672 setTimeout(function(){
10673 Transport.prototype.onData.call(self, data);
10674 }, 0);
10675 };
10676}
10677
10678/**
10679 * Writes data to socket.
10680 *
10681 * @param {Array} array of packets.
10682 * @api private
10683 */
10684
10685WS.prototype.write = function(packets){
10686 var self = this;
10687 this.writable = false;
10688
10689 // encodePacket efficient as it uses WS framing
10690 // no need for encodePayload
10691 var total = packets.length;
10692 for (var i = 0, l = total; i < l; i++) {
10693 (function(packet) {
10694 parser.encodePacket(packet, self.supportsBinary, function(data) {
10695 if (!BrowserWebSocket) {
10696 // always create a new object (GH-437)
10697 var opts = {};
10698 if (packet.options) {
10699 opts.compress = packet.options.compress;
10700 }
10701
10702 if (self.perMessageDeflate) {
10703 var len = 'string' == typeof data ? global.Buffer.byteLength(data) : data.length;
10704 if (len < self.perMessageDeflate.threshold) {
10705 opts.compress = false;
10706 }
10707 }
10708 }
10709
10710 //Sometimes the websocket has already been closed but the browser didn't
10711 //have a chance of informing us about it yet, in that case send will
10712 //throw an error
10713 try {
10714 if (BrowserWebSocket) {
10715 // TypeError is thrown when passing the second argument on Safari
10716 self.ws.send(data);
10717 } else {
10718 self.ws.send(data, opts);
10719 }
10720 } catch (e){
10721 debug('websocket closed before onclose event');
10722 }
10723
10724 --total || done();
10725 });
10726 })(packets[i]);
10727 }
10728
10729 function done(){
10730 self.emit('flush');
10731
10732 // fake drain
10733 // defer to next tick to allow Socket to clear writeBuffer
10734 setTimeout(function(){
10735 self.writable = true;
10736 self.emit('drain');
10737 }, 0);
10738 }
10739};
10740
10741/**
10742 * Called upon close
10743 *
10744 * @api private
10745 */
10746
10747WS.prototype.onClose = function(){
10748 Transport.prototype.onClose.call(this);
10749};
10750
10751/**
10752 * Closes socket.
10753 *
10754 * @api private
10755 */
10756
10757WS.prototype.doClose = function(){
10758 if (typeof this.ws !== 'undefined') {
10759 this.ws.close();
10760 }
10761};
10762
10763/**
10764 * Generates uri for connection.
10765 *
10766 * @api private
10767 */
10768
10769WS.prototype.uri = function(){
10770 var query = this.query || {};
10771 var schema = this.secure ? 'wss' : 'ws';
10772 var port = '';
10773
10774 // avoid port if default for schema
10775 if (this.port && (('wss' == schema && this.port != 443)
10776 || ('ws' == schema && this.port != 80))) {
10777 port = ':' + this.port;
10778 }
10779
10780 // append timestamp to URI
10781 if (this.timestampRequests) {
10782 query[this.timestampParam] = yeast();
10783 }
10784
10785 // communicate binary support capabilities
10786 if (!this.supportsBinary) {
10787 query.b64 = 1;
10788 }
10789
10790 query = parseqs.encode(query);
10791
10792 // prepend ? to query
10793 if (query.length) {
10794 query = '?' + query;
10795 }
10796
10797 var ipv6 = this.hostname.indexOf(':') !== -1;
10798 return schema + '://' + (ipv6 ? '[' + this.hostname + ']' : this.hostname) + port + this.path + query;
10799};
10800
10801/**
10802 * Feature detection for WebSocket.
10803 *
10804 * @return {Boolean} whether this transport is available.
10805 * @api public
10806 */
10807
10808WS.prototype.check = function(){
10809 return !!WebSocket && !('__initialize' in WebSocket && this.name === WS.prototype.name);
10810};
10811
10812}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
10813},{"../transport":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/engine.io-client/lib/transport.js","component-inherit":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/component-inherit/index.js","debug":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/debug/browser.js","engine.io-parser":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/engine.io-parser/lib/browser.js","parseqs":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/parseqs/index.js","ws":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/browser-resolve/empty.js","yeast":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/yeast/index.js"}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/engine.io-client/lib/xmlhttprequest.js":[function(require,module,exports){
10814// browser shim for xmlhttprequest module
10815var hasCORS = require('has-cors');
10816
10817module.exports = function(opts) {
10818 var xdomain = opts.xdomain;
10819
10820 // scheme must be same when usign XDomainRequest
10821 // http://blogs.msdn.com/b/ieinternals/archive/2010/05/13/xdomainrequest-restrictions-limitations-and-workarounds.aspx
10822 var xscheme = opts.xscheme;
10823
10824 // XDomainRequest has a flow of not sending cookie, therefore it should be disabled as a default.
10825 // https://github.com/Automattic/engine.io-client/pull/217
10826 var enablesXDR = opts.enablesXDR;
10827
10828 // XMLHttpRequest can be disabled on IE
10829 try {
10830 if ('undefined' != typeof XMLHttpRequest && (!xdomain || hasCORS)) {
10831 return new XMLHttpRequest();
10832 }
10833 } catch (e) { }
10834
10835 // Use XDomainRequest for IE8 if enablesXDR is true
10836 // because loading bar keeps flashing when using jsonp-polling
10837 // https://github.com/yujiosaka/socke.io-ie8-loading-example
10838 try {
10839 if ('undefined' != typeof XDomainRequest && !xscheme && enablesXDR) {
10840 return new XDomainRequest();
10841 }
10842 } catch (e) { }
10843
10844 if (!xdomain) {
10845 try {
10846 return new ActiveXObject('Microsoft.XMLHTTP');
10847 } catch(e) { }
10848 }
10849}
10850
10851},{"has-cors":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/has-cors/index.js"}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/engine.io-client/node_modules/component-emitter/index.js":[function(require,module,exports){
10852
10853/**
10854 * Expose `Emitter`.
10855 */
10856
10857module.exports = Emitter;
10858
10859/**
10860 * Initialize a new `Emitter`.
10861 *
10862 * @api public
10863 */
10864
10865function Emitter(obj) {
10866 if (obj) return mixin(obj);
10867};
10868
10869/**
10870 * Mixin the emitter properties.
10871 *
10872 * @param {Object} obj
10873 * @return {Object}
10874 * @api private
10875 */
10876
10877function mixin(obj) {
10878 for (var key in Emitter.prototype) {
10879 obj[key] = Emitter.prototype[key];
10880 }
10881 return obj;
10882}
10883
10884/**
10885 * Listen on the given `event` with `fn`.
10886 *
10887 * @param {String} event
10888 * @param {Function} fn
10889 * @return {Emitter}
10890 * @api public
10891 */
10892
10893Emitter.prototype.on =
10894Emitter.prototype.addEventListener = function(event, fn){
10895 this._callbacks = this._callbacks || {};
10896 (this._callbacks[event] = this._callbacks[event] || [])
10897 .push(fn);
10898 return this;
10899};
10900
10901/**
10902 * Adds an `event` listener that will be invoked a single
10903 * time then automatically removed.
10904 *
10905 * @param {String} event
10906 * @param {Function} fn
10907 * @return {Emitter}
10908 * @api public
10909 */
10910
10911Emitter.prototype.once = function(event, fn){
10912 var self = this;
10913 this._callbacks = this._callbacks || {};
10914
10915 function on() {
10916 self.off(event, on);
10917 fn.apply(this, arguments);
10918 }
10919
10920 on.fn = fn;
10921 this.on(event, on);
10922 return this;
10923};
10924
10925/**
10926 * Remove the given callback for `event` or all
10927 * registered callbacks.
10928 *
10929 * @param {String} event
10930 * @param {Function} fn
10931 * @return {Emitter}
10932 * @api public
10933 */
10934
10935Emitter.prototype.off =
10936Emitter.prototype.removeListener =
10937Emitter.prototype.removeAllListeners =
10938Emitter.prototype.removeEventListener = function(event, fn){
10939 this._callbacks = this._callbacks || {};
10940
10941 // all
10942 if (0 == arguments.length) {
10943 this._callbacks = {};
10944 return this;
10945 }
10946
10947 // specific event
10948 var callbacks = this._callbacks[event];
10949 if (!callbacks) return this;
10950
10951 // remove all handlers
10952 if (1 == arguments.length) {
10953 delete this._callbacks[event];
10954 return this;
10955 }
10956
10957 // remove specific handler
10958 var cb;
10959 for (var i = 0; i < callbacks.length; i++) {
10960 cb = callbacks[i];
10961 if (cb === fn || cb.fn === fn) {
10962 callbacks.splice(i, 1);
10963 break;
10964 }
10965 }
10966 return this;
10967};
10968
10969/**
10970 * Emit `event` with the given args.
10971 *
10972 * @param {String} event
10973 * @param {Mixed} ...
10974 * @return {Emitter}
10975 */
10976
10977Emitter.prototype.emit = function(event){
10978 this._callbacks = this._callbacks || {};
10979 var args = [].slice.call(arguments, 1)
10980 , callbacks = this._callbacks[event];
10981
10982 if (callbacks) {
10983 callbacks = callbacks.slice(0);
10984 for (var i = 0, len = callbacks.length; i < len; ++i) {
10985 callbacks[i].apply(this, args);
10986 }
10987 }
10988
10989 return this;
10990};
10991
10992/**
10993 * Return array of callbacks for `event`.
10994 *
10995 * @param {String} event
10996 * @return {Array}
10997 * @api public
10998 */
10999
11000Emitter.prototype.listeners = function(event){
11001 this._callbacks = this._callbacks || {};
11002 return this._callbacks[event] || [];
11003};
11004
11005/**
11006 * Check if this emitter has `event` handlers.
11007 *
11008 * @param {String} event
11009 * @return {Boolean}
11010 * @api public
11011 */
11012
11013Emitter.prototype.hasListeners = function(event){
11014 return !! this.listeners(event).length;
11015};
11016
11017},{}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/engine.io-parser/lib/browser.js":[function(require,module,exports){
11018(function (global){
11019/**
11020 * Module dependencies.
11021 */
11022
11023var keys = require('./keys');
11024var hasBinary = require('has-binary');
11025var sliceBuffer = require('arraybuffer.slice');
11026var base64encoder = require('base64-arraybuffer');
11027var after = require('after');
11028var utf8 = require('utf8');
11029
11030/**
11031 * Check if we are running an android browser. That requires us to use
11032 * ArrayBuffer with polling transports...
11033 *
11034 * http://ghinda.net/jpeg-blob-ajax-android/
11035 */
11036
11037var isAndroid = navigator.userAgent.match(/Android/i);
11038
11039/**
11040 * Check if we are running in PhantomJS.
11041 * Uploading a Blob with PhantomJS does not work correctly, as reported here:
11042 * https://github.com/ariya/phantomjs/issues/11395
11043 * @type boolean
11044 */
11045var isPhantomJS = /PhantomJS/i.test(navigator.userAgent);
11046
11047/**
11048 * When true, avoids using Blobs to encode payloads.
11049 * @type boolean
11050 */
11051var dontSendBlobs = isAndroid || isPhantomJS;
11052
11053/**
11054 * Current protocol version.
11055 */
11056
11057exports.protocol = 3;
11058
11059/**
11060 * Packet types.
11061 */
11062
11063var packets = exports.packets = {
11064 open: 0 // non-ws
11065 , close: 1 // non-ws
11066 , ping: 2
11067 , pong: 3
11068 , message: 4
11069 , upgrade: 5
11070 , noop: 6
11071};
11072
11073var packetslist = keys(packets);
11074
11075/**
11076 * Premade error packet.
11077 */
11078
11079var err = { type: 'error', data: 'parser error' };
11080
11081/**
11082 * Create a blob api even for blob builder when vendor prefixes exist
11083 */
11084
11085var Blob = require('blob');
11086
11087/**
11088 * Encodes a packet.
11089 *
11090 * <packet type id> [ <data> ]
11091 *
11092 * Example:
11093 *
11094 * 5hello world
11095 * 3
11096 * 4
11097 *
11098 * Binary is encoded in an identical principle
11099 *
11100 * @api private
11101 */
11102
11103exports.encodePacket = function (packet, supportsBinary, utf8encode, callback) {
11104 if ('function' == typeof supportsBinary) {
11105 callback = supportsBinary;
11106 supportsBinary = false;
11107 }
11108
11109 if ('function' == typeof utf8encode) {
11110 callback = utf8encode;
11111 utf8encode = null;
11112 }
11113
11114 var data = (packet.data === undefined)
11115 ? undefined
11116 : packet.data.buffer || packet.data;
11117
11118 if (global.ArrayBuffer && data instanceof ArrayBuffer) {
11119 return encodeArrayBuffer(packet, supportsBinary, callback);
11120 } else if (Blob && data instanceof global.Blob) {
11121 return encodeBlob(packet, supportsBinary, callback);
11122 }
11123
11124 // might be an object with { base64: true, data: dataAsBase64String }
11125 if (data && data.base64) {
11126 return encodeBase64Object(packet, callback);
11127 }
11128
11129 // Sending data as a utf-8 string
11130 var encoded = packets[packet.type];
11131
11132 // data fragment is optional
11133 if (undefined !== packet.data) {
11134 encoded += utf8encode ? utf8.encode(String(packet.data)) : String(packet.data);
11135 }
11136
11137 return callback('' + encoded);
11138
11139};
11140
11141function encodeBase64Object(packet, callback) {
11142 // packet data is an object { base64: true, data: dataAsBase64String }
11143 var message = 'b' + exports.packets[packet.type] + packet.data.data;
11144 return callback(message);
11145}
11146
11147/**
11148 * Encode packet helpers for binary types
11149 */
11150
11151function encodeArrayBuffer(packet, supportsBinary, callback) {
11152 if (!supportsBinary) {
11153 return exports.encodeBase64Packet(packet, callback);
11154 }
11155
11156 var data = packet.data;
11157 var contentArray = new Uint8Array(data);
11158 var resultBuffer = new Uint8Array(1 + data.byteLength);
11159
11160 resultBuffer[0] = packets[packet.type];
11161 for (var i = 0; i < contentArray.length; i++) {
11162 resultBuffer[i+1] = contentArray[i];
11163 }
11164
11165 return callback(resultBuffer.buffer);
11166}
11167
11168function encodeBlobAsArrayBuffer(packet, supportsBinary, callback) {
11169 if (!supportsBinary) {
11170 return exports.encodeBase64Packet(packet, callback);
11171 }
11172
11173 var fr = new FileReader();
11174 fr.onload = function() {
11175 packet.data = fr.result;
11176 exports.encodePacket(packet, supportsBinary, true, callback);
11177 };
11178 return fr.readAsArrayBuffer(packet.data);
11179}
11180
11181function encodeBlob(packet, supportsBinary, callback) {
11182 if (!supportsBinary) {
11183 return exports.encodeBase64Packet(packet, callback);
11184 }
11185
11186 if (dontSendBlobs) {
11187 return encodeBlobAsArrayBuffer(packet, supportsBinary, callback);
11188 }
11189
11190 var length = new Uint8Array(1);
11191 length[0] = packets[packet.type];
11192 var blob = new Blob([length.buffer, packet.data]);
11193
11194 return callback(blob);
11195}
11196
11197/**
11198 * Encodes a packet with binary data in a base64 string
11199 *
11200 * @param {Object} packet, has `type` and `data`
11201 * @return {String} base64 encoded message
11202 */
11203
11204exports.encodeBase64Packet = function(packet, callback) {
11205 var message = 'b' + exports.packets[packet.type];
11206 if (Blob && packet.data instanceof global.Blob) {
11207 var fr = new FileReader();
11208 fr.onload = function() {
11209 var b64 = fr.result.split(',')[1];
11210 callback(message + b64);
11211 };
11212 return fr.readAsDataURL(packet.data);
11213 }
11214
11215 var b64data;
11216 try {
11217 b64data = String.fromCharCode.apply(null, new Uint8Array(packet.data));
11218 } catch (e) {
11219 // iPhone Safari doesn't let you apply with typed arrays
11220 var typed = new Uint8Array(packet.data);
11221 var basic = new Array(typed.length);
11222 for (var i = 0; i < typed.length; i++) {
11223 basic[i] = typed[i];
11224 }
11225 b64data = String.fromCharCode.apply(null, basic);
11226 }
11227 message += global.btoa(b64data);
11228 return callback(message);
11229};
11230
11231/**
11232 * Decodes a packet. Changes format to Blob if requested.
11233 *
11234 * @return {Object} with `type` and `data` (if any)
11235 * @api private
11236 */
11237
11238exports.decodePacket = function (data, binaryType, utf8decode) {
11239 // String data
11240 if (typeof data == 'string' || data === undefined) {
11241 if (data.charAt(0) == 'b') {
11242 return exports.decodeBase64Packet(data.substr(1), binaryType);
11243 }
11244
11245 if (utf8decode) {
11246 try {
11247 data = utf8.decode(data);
11248 } catch (e) {
11249 return err;
11250 }
11251 }
11252 var type = data.charAt(0);
11253
11254 if (Number(type) != type || !packetslist[type]) {
11255 return err;
11256 }
11257
11258 if (data.length > 1) {
11259 return { type: packetslist[type], data: data.substring(1) };
11260 } else {
11261 return { type: packetslist[type] };
11262 }
11263 }
11264
11265 var asArray = new Uint8Array(data);
11266 var type = asArray[0];
11267 var rest = sliceBuffer(data, 1);
11268 if (Blob && binaryType === 'blob') {
11269 rest = new Blob([rest]);
11270 }
11271 return { type: packetslist[type], data: rest };
11272};
11273
11274/**
11275 * Decodes a packet encoded in a base64 string
11276 *
11277 * @param {String} base64 encoded message
11278 * @return {Object} with `type` and `data` (if any)
11279 */
11280
11281exports.decodeBase64Packet = function(msg, binaryType) {
11282 var type = packetslist[msg.charAt(0)];
11283 if (!global.ArrayBuffer) {
11284 return { type: type, data: { base64: true, data: msg.substr(1) } };
11285 }
11286
11287 var data = base64encoder.decode(msg.substr(1));
11288
11289 if (binaryType === 'blob' && Blob) {
11290 data = new Blob([data]);
11291 }
11292
11293 return { type: type, data: data };
11294};
11295
11296/**
11297 * Encodes multiple messages (payload).
11298 *
11299 * <length>:data
11300 *
11301 * Example:
11302 *
11303 * 11:hello world2:hi
11304 *
11305 * If any contents are binary, they will be encoded as base64 strings. Base64
11306 * encoded strings are marked with a b before the length specifier
11307 *
11308 * @param {Array} packets
11309 * @api private
11310 */
11311
11312exports.encodePayload = function (packets, supportsBinary, callback) {
11313 if (typeof supportsBinary == 'function') {
11314 callback = supportsBinary;
11315 supportsBinary = null;
11316 }
11317
11318 var isBinary = hasBinary(packets);
11319
11320 if (supportsBinary && isBinary) {
11321 if (Blob && !dontSendBlobs) {
11322 return exports.encodePayloadAsBlob(packets, callback);
11323 }
11324
11325 return exports.encodePayloadAsArrayBuffer(packets, callback);
11326 }
11327
11328 if (!packets.length) {
11329 return callback('0:');
11330 }
11331
11332 function setLengthHeader(message) {
11333 return message.length + ':' + message;
11334 }
11335
11336 function encodeOne(packet, doneCallback) {
11337 exports.encodePacket(packet, !isBinary ? false : supportsBinary, true, function(message) {
11338 doneCallback(null, setLengthHeader(message));
11339 });
11340 }
11341
11342 map(packets, encodeOne, function(err, results) {
11343 return callback(results.join(''));
11344 });
11345};
11346
11347/**
11348 * Async array map using after
11349 */
11350
11351function map(ary, each, done) {
11352 var result = new Array(ary.length);
11353 var next = after(ary.length, done);
11354
11355 var eachWithIndex = function(i, el, cb) {
11356 each(el, function(error, msg) {
11357 result[i] = msg;
11358 cb(error, result);
11359 });
11360 };
11361
11362 for (var i = 0; i < ary.length; i++) {
11363 eachWithIndex(i, ary[i], next);
11364 }
11365}
11366
11367/*
11368 * Decodes data when a payload is maybe expected. Possible binary contents are
11369 * decoded from their base64 representation
11370 *
11371 * @param {String} data, callback method
11372 * @api public
11373 */
11374
11375exports.decodePayload = function (data, binaryType, callback) {
11376 if (typeof data != 'string') {
11377 return exports.decodePayloadAsBinary(data, binaryType, callback);
11378 }
11379
11380 if (typeof binaryType === 'function') {
11381 callback = binaryType;
11382 binaryType = null;
11383 }
11384
11385 var packet;
11386 if (data == '') {
11387 // parser error - ignoring payload
11388 return callback(err, 0, 1);
11389 }
11390
11391 var length = ''
11392 , n, msg;
11393
11394 for (var i = 0, l = data.length; i < l; i++) {
11395 var chr = data.charAt(i);
11396
11397 if (':' != chr) {
11398 length += chr;
11399 } else {
11400 if ('' == length || (length != (n = Number(length)))) {
11401 // parser error - ignoring payload
11402 return callback(err, 0, 1);
11403 }
11404
11405 msg = data.substr(i + 1, n);
11406
11407 if (length != msg.length) {
11408 // parser error - ignoring payload
11409 return callback(err, 0, 1);
11410 }
11411
11412 if (msg.length) {
11413 packet = exports.decodePacket(msg, binaryType, true);
11414
11415 if (err.type == packet.type && err.data == packet.data) {
11416 // parser error in individual packet - ignoring payload
11417 return callback(err, 0, 1);
11418 }
11419
11420 var ret = callback(packet, i + n, l);
11421 if (false === ret) return;
11422 }
11423
11424 // advance cursor
11425 i += n;
11426 length = '';
11427 }
11428 }
11429
11430 if (length != '') {
11431 // parser error - ignoring payload
11432 return callback(err, 0, 1);
11433 }
11434
11435};
11436
11437/**
11438 * Encodes multiple messages (payload) as binary.
11439 *
11440 * <1 = binary, 0 = string><number from 0-9><number from 0-9>[...]<number
11441 * 255><data>
11442 *
11443 * Example:
11444 * 1 3 255 1 2 3, if the binary contents are interpreted as 8 bit integers
11445 *
11446 * @param {Array} packets
11447 * @return {ArrayBuffer} encoded payload
11448 * @api private
11449 */
11450
11451exports.encodePayloadAsArrayBuffer = function(packets, callback) {
11452 if (!packets.length) {
11453 return callback(new ArrayBuffer(0));
11454 }
11455
11456 function encodeOne(packet, doneCallback) {
11457 exports.encodePacket(packet, true, true, function(data) {
11458 return doneCallback(null, data);
11459 });
11460 }
11461
11462 map(packets, encodeOne, function(err, encodedPackets) {
11463 var totalLength = encodedPackets.reduce(function(acc, p) {
11464 var len;
11465 if (typeof p === 'string'){
11466 len = p.length;
11467 } else {
11468 len = p.byteLength;
11469 }
11470 return acc + len.toString().length + len + 2; // string/binary identifier + separator = 2
11471 }, 0);
11472
11473 var resultArray = new Uint8Array(totalLength);
11474
11475 var bufferIndex = 0;
11476 encodedPackets.forEach(function(p) {
11477 var isString = typeof p === 'string';
11478 var ab = p;
11479 if (isString) {
11480 var view = new Uint8Array(p.length);
11481 for (var i = 0; i < p.length; i++) {
11482 view[i] = p.charCodeAt(i);
11483 }
11484 ab = view.buffer;
11485 }
11486
11487 if (isString) { // not true binary
11488 resultArray[bufferIndex++] = 0;
11489 } else { // true binary
11490 resultArray[bufferIndex++] = 1;
11491 }
11492
11493 var lenStr = ab.byteLength.toString();
11494 for (var i = 0; i < lenStr.length; i++) {
11495 resultArray[bufferIndex++] = parseInt(lenStr[i]);
11496 }
11497 resultArray[bufferIndex++] = 255;
11498
11499 var view = new Uint8Array(ab);
11500 for (var i = 0; i < view.length; i++) {
11501 resultArray[bufferIndex++] = view[i];
11502 }
11503 });
11504
11505 return callback(resultArray.buffer);
11506 });
11507};
11508
11509/**
11510 * Encode as Blob
11511 */
11512
11513exports.encodePayloadAsBlob = function(packets, callback) {
11514 function encodeOne(packet, doneCallback) {
11515 exports.encodePacket(packet, true, true, function(encoded) {
11516 var binaryIdentifier = new Uint8Array(1);
11517 binaryIdentifier[0] = 1;
11518 if (typeof encoded === 'string') {
11519 var view = new Uint8Array(encoded.length);
11520 for (var i = 0; i < encoded.length; i++) {
11521 view[i] = encoded.charCodeAt(i);
11522 }
11523 encoded = view.buffer;
11524 binaryIdentifier[0] = 0;
11525 }
11526
11527 var len = (encoded instanceof ArrayBuffer)
11528 ? encoded.byteLength
11529 : encoded.size;
11530
11531 var lenStr = len.toString();
11532 var lengthAry = new Uint8Array(lenStr.length + 1);
11533 for (var i = 0; i < lenStr.length; i++) {
11534 lengthAry[i] = parseInt(lenStr[i]);
11535 }
11536 lengthAry[lenStr.length] = 255;
11537
11538 if (Blob) {
11539 var blob = new Blob([binaryIdentifier.buffer, lengthAry.buffer, encoded]);
11540 doneCallback(null, blob);
11541 }
11542 });
11543 }
11544
11545 map(packets, encodeOne, function(err, results) {
11546 return callback(new Blob(results));
11547 });
11548};
11549
11550/*
11551 * Decodes data when a payload is maybe expected. Strings are decoded by
11552 * interpreting each byte as a key code for entries marked to start with 0. See
11553 * description of encodePayloadAsBinary
11554 *
11555 * @param {ArrayBuffer} data, callback method
11556 * @api public
11557 */
11558
11559exports.decodePayloadAsBinary = function (data, binaryType, callback) {
11560 if (typeof binaryType === 'function') {
11561 callback = binaryType;
11562 binaryType = null;
11563 }
11564
11565 var bufferTail = data;
11566 var buffers = [];
11567
11568 var numberTooLong = false;
11569 while (bufferTail.byteLength > 0) {
11570 var tailArray = new Uint8Array(bufferTail);
11571 var isString = tailArray[0] === 0;
11572 var msgLength = '';
11573
11574 for (var i = 1; ; i++) {
11575 if (tailArray[i] == 255) break;
11576
11577 if (msgLength.length > 310) {
11578 numberTooLong = true;
11579 break;
11580 }
11581
11582 msgLength += tailArray[i];
11583 }
11584
11585 if(numberTooLong) return callback(err, 0, 1);
11586
11587 bufferTail = sliceBuffer(bufferTail, 2 + msgLength.length);
11588 msgLength = parseInt(msgLength);
11589
11590 var msg = sliceBuffer(bufferTail, 0, msgLength);
11591 if (isString) {
11592 try {
11593 msg = String.fromCharCode.apply(null, new Uint8Array(msg));
11594 } catch (e) {
11595 // iPhone Safari doesn't let you apply to typed arrays
11596 var typed = new Uint8Array(msg);
11597 msg = '';
11598 for (var i = 0; i < typed.length; i++) {
11599 msg += String.fromCharCode(typed[i]);
11600 }
11601 }
11602 }
11603
11604 buffers.push(msg);
11605 bufferTail = sliceBuffer(bufferTail, msgLength);
11606 }
11607
11608 var total = buffers.length;
11609 buffers.forEach(function(buffer, i) {
11610 callback(exports.decodePacket(buffer, binaryType, true), i, total);
11611 });
11612};
11613
11614}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
11615},{"./keys":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/engine.io-parser/lib/keys.js","after":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/after/index.js","arraybuffer.slice":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/arraybuffer.slice/index.js","base64-arraybuffer":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/base64-arraybuffer/lib/base64-arraybuffer.js","blob":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/blob/index.js","has-binary":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/engine.io-parser/node_modules/has-binary/index.js","utf8":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/utf8/utf8.js"}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/engine.io-parser/lib/keys.js":[function(require,module,exports){
11616
11617/**
11618 * Gets the keys for an object.
11619 *
11620 * @return {Array} keys
11621 * @api private
11622 */
11623
11624module.exports = Object.keys || function keys (obj){
11625 var arr = [];
11626 var has = Object.prototype.hasOwnProperty;
11627
11628 for (var i in obj) {
11629 if (has.call(obj, i)) {
11630 arr.push(i);
11631 }
11632 }
11633 return arr;
11634};
11635
11636},{}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/engine.io-parser/node_modules/has-binary/index.js":[function(require,module,exports){
11637(function (global){
11638
11639/*
11640 * Module requirements.
11641 */
11642
11643var isArray = require('isarray');
11644
11645/**
11646 * Module exports.
11647 */
11648
11649module.exports = hasBinary;
11650
11651/**
11652 * Checks for binary data.
11653 *
11654 * Right now only Buffer and ArrayBuffer are supported..
11655 *
11656 * @param {Object} anything
11657 * @api public
11658 */
11659
11660function hasBinary(data) {
11661
11662 function _hasBinary(obj) {
11663 if (!obj) return false;
11664
11665 if ( (global.Buffer && global.Buffer.isBuffer(obj)) ||
11666 (global.ArrayBuffer && obj instanceof ArrayBuffer) ||
11667 (global.Blob && obj instanceof Blob) ||
11668 (global.File && obj instanceof File)
11669 ) {
11670 return true;
11671 }
11672
11673 if (isArray(obj)) {
11674 for (var i = 0; i < obj.length; i++) {
11675 if (_hasBinary(obj[i])) {
11676 return true;
11677 }
11678 }
11679 } else if (obj && 'object' == typeof obj) {
11680 if (obj.toJSON) {
11681 obj = obj.toJSON();
11682 }
11683
11684 for (var key in obj) {
11685 if (Object.prototype.hasOwnProperty.call(obj, key) && _hasBinary(obj[key])) {
11686 return true;
11687 }
11688 }
11689 }
11690
11691 return false;
11692 }
11693
11694 return _hasBinary(data);
11695}
11696
11697}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
11698},{"isarray":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/engine.io-parser/node_modules/isarray/index.js"}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/engine.io-parser/node_modules/isarray/index.js":[function(require,module,exports){
11699module.exports = Array.isArray || function (arr) {
11700 return Object.prototype.toString.call(arr) == '[object Array]';
11701};
11702
11703},{}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/events/events.js":[function(require,module,exports){
11704// Copyright Joyent, Inc. and other Node contributors.
11705//
11706// Permission is hereby granted, free of charge, to any person obtaining a
11707// copy of this software and associated documentation files (the
11708// "Software"), to deal in the Software without restriction, including
11709// without limitation the rights to use, copy, modify, merge, publish,
11710// distribute, sublicense, and/or sell copies of the Software, and to permit
11711// persons to whom the Software is furnished to do so, subject to the
11712// following conditions:
11713//
11714// The above copyright notice and this permission notice shall be included
11715// in all copies or substantial portions of the Software.
11716//
11717// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
11718// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
11719// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
11720// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
11721// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
11722// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
11723// USE OR OTHER DEALINGS IN THE SOFTWARE.
11724
11725function EventEmitter() {
11726 this._events = this._events || {};
11727 this._maxListeners = this._maxListeners || undefined;
11728}
11729module.exports = EventEmitter;
11730
11731// Backwards-compat with node 0.10.x
11732EventEmitter.EventEmitter = EventEmitter;
11733
11734EventEmitter.prototype._events = undefined;
11735EventEmitter.prototype._maxListeners = undefined;
11736
11737// By default EventEmitters will print a warning if more than 10 listeners are
11738// added to it. This is a useful default which helps finding memory leaks.
11739EventEmitter.defaultMaxListeners = 10;
11740
11741// Obviously not all Emitters should be limited to 10. This function allows
11742// that to be increased. Set to zero for unlimited.
11743EventEmitter.prototype.setMaxListeners = function(n) {
11744 if (!isNumber(n) || n < 0 || isNaN(n))
11745 throw TypeError('n must be a positive number');
11746 this._maxListeners = n;
11747 return this;
11748};
11749
11750EventEmitter.prototype.emit = function(type) {
11751 var er, handler, len, args, i, listeners;
11752
11753 if (!this._events)
11754 this._events = {};
11755
11756 // If there is no 'error' event listener then throw.
11757 if (type === 'error') {
11758 if (!this._events.error ||
11759 (isObject(this._events.error) && !this._events.error.length)) {
11760 er = arguments[1];
11761 if (er instanceof Error) {
11762 throw er; // Unhandled 'error' event
11763 }
11764 throw TypeError('Uncaught, unspecified "error" event.');
11765 }
11766 }
11767
11768 handler = this._events[type];
11769
11770 if (isUndefined(handler))
11771 return false;
11772
11773 if (isFunction(handler)) {
11774 switch (arguments.length) {
11775 // fast cases
11776 case 1:
11777 handler.call(this);
11778 break;
11779 case 2:
11780 handler.call(this, arguments[1]);
11781 break;
11782 case 3:
11783 handler.call(this, arguments[1], arguments[2]);
11784 break;
11785 // slower
11786 default:
11787 len = arguments.length;
11788 args = new Array(len - 1);
11789 for (i = 1; i < len; i++)
11790 args[i - 1] = arguments[i];
11791 handler.apply(this, args);
11792 }
11793 } else if (isObject(handler)) {
11794 len = arguments.length;
11795 args = new Array(len - 1);
11796 for (i = 1; i < len; i++)
11797 args[i - 1] = arguments[i];
11798
11799 listeners = handler.slice();
11800 len = listeners.length;
11801 for (i = 0; i < len; i++)
11802 listeners[i].apply(this, args);
11803 }
11804
11805 return true;
11806};
11807
11808EventEmitter.prototype.addListener = function(type, listener) {
11809 var m;
11810
11811 if (!isFunction(listener))
11812 throw TypeError('listener must be a function');
11813
11814 if (!this._events)
11815 this._events = {};
11816
11817 // To avoid recursion in the case that type === "newListener"! Before
11818 // adding it to the listeners, first emit "newListener".
11819 if (this._events.newListener)
11820 this.emit('newListener', type,
11821 isFunction(listener.listener) ?
11822 listener.listener : listener);
11823
11824 if (!this._events[type])
11825 // Optimize the case of one listener. Don't need the extra array object.
11826 this._events[type] = listener;
11827 else if (isObject(this._events[type]))
11828 // If we've already got an array, just append.
11829 this._events[type].push(listener);
11830 else
11831 // Adding the second element, need to change to array.
11832 this._events[type] = [this._events[type], listener];
11833
11834 // Check for listener leak
11835 if (isObject(this._events[type]) && !this._events[type].warned) {
11836 var m;
11837 if (!isUndefined(this._maxListeners)) {
11838 m = this._maxListeners;
11839 } else {
11840 m = EventEmitter.defaultMaxListeners;
11841 }
11842
11843 if (m && m > 0 && this._events[type].length > m) {
11844 this._events[type].warned = true;
11845 console.error('(node) warning: possible EventEmitter memory ' +
11846 'leak detected. %d listeners added. ' +
11847 'Use emitter.setMaxListeners() to increase limit.',
11848 this._events[type].length);
11849 if (typeof console.trace === 'function') {
11850 // not supported in IE 10
11851 console.trace();
11852 }
11853 }
11854 }
11855
11856 return this;
11857};
11858
11859EventEmitter.prototype.on = EventEmitter.prototype.addListener;
11860
11861EventEmitter.prototype.once = function(type, listener) {
11862 if (!isFunction(listener))
11863 throw TypeError('listener must be a function');
11864
11865 var fired = false;
11866
11867 function g() {
11868 this.removeListener(type, g);
11869
11870 if (!fired) {
11871 fired = true;
11872 listener.apply(this, arguments);
11873 }
11874 }
11875
11876 g.listener = listener;
11877 this.on(type, g);
11878
11879 return this;
11880};
11881
11882// emits a 'removeListener' event iff the listener was removed
11883EventEmitter.prototype.removeListener = function(type, listener) {
11884 var list, position, length, i;
11885
11886 if (!isFunction(listener))
11887 throw TypeError('listener must be a function');
11888
11889 if (!this._events || !this._events[type])
11890 return this;
11891
11892 list = this._events[type];
11893 length = list.length;
11894 position = -1;
11895
11896 if (list === listener ||
11897 (isFunction(list.listener) && list.listener === listener)) {
11898 delete this._events[type];
11899 if (this._events.removeListener)
11900 this.emit('removeListener', type, listener);
11901
11902 } else if (isObject(list)) {
11903 for (i = length; i-- > 0;) {
11904 if (list[i] === listener ||
11905 (list[i].listener && list[i].listener === listener)) {
11906 position = i;
11907 break;
11908 }
11909 }
11910
11911 if (position < 0)
11912 return this;
11913
11914 if (list.length === 1) {
11915 list.length = 0;
11916 delete this._events[type];
11917 } else {
11918 list.splice(position, 1);
11919 }
11920
11921 if (this._events.removeListener)
11922 this.emit('removeListener', type, listener);
11923 }
11924
11925 return this;
11926};
11927
11928EventEmitter.prototype.removeAllListeners = function(type) {
11929 var key, listeners;
11930
11931 if (!this._events)
11932 return this;
11933
11934 // not listening for removeListener, no need to emit
11935 if (!this._events.removeListener) {
11936 if (arguments.length === 0)
11937 this._events = {};
11938 else if (this._events[type])
11939 delete this._events[type];
11940 return this;
11941 }
11942
11943 // emit removeListener for all listeners on all events
11944 if (arguments.length === 0) {
11945 for (key in this._events) {
11946 if (key === 'removeListener') continue;
11947 this.removeAllListeners(key);
11948 }
11949 this.removeAllListeners('removeListener');
11950 this._events = {};
11951 return this;
11952 }
11953
11954 listeners = this._events[type];
11955
11956 if (isFunction(listeners)) {
11957 this.removeListener(type, listeners);
11958 } else {
11959 // LIFO order
11960 while (listeners.length)
11961 this.removeListener(type, listeners[listeners.length - 1]);
11962 }
11963 delete this._events[type];
11964
11965 return this;
11966};
11967
11968EventEmitter.prototype.listeners = function(type) {
11969 var ret;
11970 if (!this._events || !this._events[type])
11971 ret = [];
11972 else if (isFunction(this._events[type]))
11973 ret = [this._events[type]];
11974 else
11975 ret = this._events[type].slice();
11976 return ret;
11977};
11978
11979EventEmitter.listenerCount = function(emitter, type) {
11980 var ret;
11981 if (!emitter._events || !emitter._events[type])
11982 ret = 0;
11983 else if (isFunction(emitter._events[type]))
11984 ret = 1;
11985 else
11986 ret = emitter._events[type].length;
11987 return ret;
11988};
11989
11990function isFunction(arg) {
11991 return typeof arg === 'function';
11992}
11993
11994function isNumber(arg) {
11995 return typeof arg === 'number';
11996}
11997
11998function isObject(arg) {
11999 return typeof arg === 'object' && arg !== null;
12000}
12001
12002function isUndefined(arg) {
12003 return arg === void 0;
12004}
12005
12006},{}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/has-binary/index.js":[function(require,module,exports){
12007(function (global){
12008
12009/*
12010 * Module requirements.
12011 */
12012
12013var isArray = require('isarray');
12014
12015/**
12016 * Module exports.
12017 */
12018
12019module.exports = hasBinary;
12020
12021/**
12022 * Checks for binary data.
12023 *
12024 * Right now only Buffer and ArrayBuffer are supported..
12025 *
12026 * @param {Object} anything
12027 * @api public
12028 */
12029
12030function hasBinary(data) {
12031
12032 function _hasBinary(obj) {
12033 if (!obj) return false;
12034
12035 if ( (global.Buffer && global.Buffer.isBuffer && global.Buffer.isBuffer(obj)) ||
12036 (global.ArrayBuffer && obj instanceof ArrayBuffer) ||
12037 (global.Blob && obj instanceof Blob) ||
12038 (global.File && obj instanceof File)
12039 ) {
12040 return true;
12041 }
12042
12043 if (isArray(obj)) {
12044 for (var i = 0; i < obj.length; i++) {
12045 if (_hasBinary(obj[i])) {
12046 return true;
12047 }
12048 }
12049 } else if (obj && 'object' == typeof obj) {
12050 // see: https://github.com/Automattic/has-binary/pull/4
12051 if (obj.toJSON && 'function' == typeof obj.toJSON) {
12052 obj = obj.toJSON();
12053 }
12054
12055 for (var key in obj) {
12056 if (Object.prototype.hasOwnProperty.call(obj, key) && _hasBinary(obj[key])) {
12057 return true;
12058 }
12059 }
12060 }
12061
12062 return false;
12063 }
12064
12065 return _hasBinary(data);
12066}
12067
12068}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
12069},{"isarray":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/has-binary/node_modules/isarray/index.js"}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/has-binary/node_modules/isarray/index.js":[function(require,module,exports){
12070arguments[4]["/home/employee-2klic/projects/2klic_io-sdk/node_modules/engine.io-parser/node_modules/isarray/index.js"][0].apply(exports,arguments)
12071},{}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/has-cors/index.js":[function(require,module,exports){
12072
12073/**
12074 * Module exports.
12075 *
12076 * Logic borrowed from Modernizr:
12077 *
12078 * - https://github.com/Modernizr/Modernizr/blob/master/feature-detects/cors.js
12079 */
12080
12081try {
12082 module.exports = typeof XMLHttpRequest !== 'undefined' &&
12083 'withCredentials' in new XMLHttpRequest();
12084} catch (err) {
12085 // if XMLHttp support is disabled in IE then it will throw
12086 // when trying to create
12087 module.exports = false;
12088}
12089
12090},{}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/ieee754/index.js":[function(require,module,exports){
12091exports.read = function (buffer, offset, isLE, mLen, nBytes) {
12092 var e, m
12093 var eLen = nBytes * 8 - mLen - 1
12094 var eMax = (1 << eLen) - 1
12095 var eBias = eMax >> 1
12096 var nBits = -7
12097 var i = isLE ? (nBytes - 1) : 0
12098 var d = isLE ? -1 : 1
12099 var s = buffer[offset + i]
12100
12101 i += d
12102
12103 e = s & ((1 << (-nBits)) - 1)
12104 s >>= (-nBits)
12105 nBits += eLen
12106 for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
12107
12108 m = e & ((1 << (-nBits)) - 1)
12109 e >>= (-nBits)
12110 nBits += mLen
12111 for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
12112
12113 if (e === 0) {
12114 e = 1 - eBias
12115 } else if (e === eMax) {
12116 return m ? NaN : ((s ? -1 : 1) * Infinity)
12117 } else {
12118 m = m + Math.pow(2, mLen)
12119 e = e - eBias
12120 }
12121 return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
12122}
12123
12124exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
12125 var e, m, c
12126 var eLen = nBytes * 8 - mLen - 1
12127 var eMax = (1 << eLen) - 1
12128 var eBias = eMax >> 1
12129 var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
12130 var i = isLE ? 0 : (nBytes - 1)
12131 var d = isLE ? 1 : -1
12132 var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
12133
12134 value = Math.abs(value)
12135
12136 if (isNaN(value) || value === Infinity) {
12137 m = isNaN(value) ? 1 : 0
12138 e = eMax
12139 } else {
12140 e = Math.floor(Math.log(value) / Math.LN2)
12141 if (value * (c = Math.pow(2, -e)) < 1) {
12142 e--
12143 c *= 2
12144 }
12145 if (e + eBias >= 1) {
12146 value += rt / c
12147 } else {
12148 value += rt * Math.pow(2, 1 - eBias)
12149 }
12150 if (value * c >= 2) {
12151 e++
12152 c /= 2
12153 }
12154
12155 if (e + eBias >= eMax) {
12156 m = 0
12157 e = eMax
12158 } else if (e + eBias >= 1) {
12159 m = (value * c - 1) * Math.pow(2, mLen)
12160 e = e + eBias
12161 } else {
12162 m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
12163 e = 0
12164 }
12165 }
12166
12167 for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
12168
12169 e = (e << mLen) | m
12170 eLen += mLen
12171 for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
12172
12173 buffer[offset + i - d] |= s * 128
12174}
12175
12176},{}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/indexof/index.js":[function(require,module,exports){
12177
12178var indexOf = [].indexOf;
12179
12180module.exports = function(arr, obj){
12181 if (indexOf) return arr.indexOf(obj);
12182 for (var i = 0; i < arr.length; ++i) {
12183 if (arr[i] === obj) return i;
12184 }
12185 return -1;
12186};
12187},{}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/inherits/inherits_browser.js":[function(require,module,exports){
12188if (typeof Object.create === 'function') {
12189 // implementation from standard node.js 'util' module
12190 module.exports = function inherits(ctor, superCtor) {
12191 ctor.super_ = superCtor
12192 ctor.prototype = Object.create(superCtor.prototype, {
12193 constructor: {
12194 value: ctor,
12195 enumerable: false,
12196 writable: true,
12197 configurable: true
12198 }
12199 });
12200 };
12201} else {
12202 // old school shim for old browsers
12203 module.exports = function inherits(ctor, superCtor) {
12204 ctor.super_ = superCtor
12205 var TempCtor = function () {}
12206 TempCtor.prototype = superCtor.prototype
12207 ctor.prototype = new TempCtor()
12208 ctor.prototype.constructor = ctor
12209 }
12210}
12211
12212},{}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/isarray/index.js":[function(require,module,exports){
12213var toString = {}.toString;
12214
12215module.exports = Array.isArray || function (arr) {
12216 return toString.call(arr) == '[object Array]';
12217};
12218
12219},{}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/json3/lib/json3.js":[function(require,module,exports){
12220(function (global){
12221/*! JSON v3.3.2 | http://bestiejs.github.io/json3 | Copyright 2012-2014, Kit Cambridge | http://kit.mit-license.org */
12222;(function () {
12223 // Detect the `define` function exposed by asynchronous module loaders. The
12224 // strict `define` check is necessary for compatibility with `r.js`.
12225 var isLoader = typeof define === "function" && define.amd;
12226
12227 // A set of types used to distinguish objects from primitives.
12228 var objectTypes = {
12229 "function": true,
12230 "object": true
12231 };
12232
12233 // Detect the `exports` object exposed by CommonJS implementations.
12234 var freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports;
12235
12236 // Use the `global` object exposed by Node (including Browserify via
12237 // `insert-module-globals`), Narwhal, and Ringo as the default context,
12238 // and the `window` object in browsers. Rhino exports a `global` function
12239 // instead.
12240 var root = objectTypes[typeof window] && window || this,
12241 freeGlobal = freeExports && objectTypes[typeof module] && module && !module.nodeType && typeof global == "object" && global;
12242
12243 if (freeGlobal && (freeGlobal["global"] === freeGlobal || freeGlobal["window"] === freeGlobal || freeGlobal["self"] === freeGlobal)) {
12244 root = freeGlobal;
12245 }
12246
12247 // Public: Initializes JSON 3 using the given `context` object, attaching the
12248 // `stringify` and `parse` functions to the specified `exports` object.
12249 function runInContext(context, exports) {
12250 context || (context = root["Object"]());
12251 exports || (exports = root["Object"]());
12252
12253 // Native constructor aliases.
12254 var Number = context["Number"] || root["Number"],
12255 String = context["String"] || root["String"],
12256 Object = context["Object"] || root["Object"],
12257 Date = context["Date"] || root["Date"],
12258 SyntaxError = context["SyntaxError"] || root["SyntaxError"],
12259 TypeError = context["TypeError"] || root["TypeError"],
12260 Math = context["Math"] || root["Math"],
12261 nativeJSON = context["JSON"] || root["JSON"];
12262
12263 // Delegate to the native `stringify` and `parse` implementations.
12264 if (typeof nativeJSON == "object" && nativeJSON) {
12265 exports.stringify = nativeJSON.stringify;
12266 exports.parse = nativeJSON.parse;
12267 }
12268
12269 // Convenience aliases.
12270 var objectProto = Object.prototype,
12271 getClass = objectProto.toString,
12272 isProperty, forEach, undef;
12273
12274 // Test the `Date#getUTC*` methods. Based on work by @Yaffle.
12275 var isExtended = new Date(-3509827334573292);
12276 try {
12277 // The `getUTCFullYear`, `Month`, and `Date` methods return nonsensical
12278 // results for certain dates in Opera >= 10.53.
12279 isExtended = isExtended.getUTCFullYear() == -109252 && isExtended.getUTCMonth() === 0 && isExtended.getUTCDate() === 1 &&
12280 // Safari < 2.0.2 stores the internal millisecond time value correctly,
12281 // but clips the values returned by the date methods to the range of
12282 // signed 32-bit integers ([-2 ** 31, 2 ** 31 - 1]).
12283 isExtended.getUTCHours() == 10 && isExtended.getUTCMinutes() == 37 && isExtended.getUTCSeconds() == 6 && isExtended.getUTCMilliseconds() == 708;
12284 } catch (exception) {}
12285
12286 // Internal: Determines whether the native `JSON.stringify` and `parse`
12287 // implementations are spec-compliant. Based on work by Ken Snyder.
12288 function has(name) {
12289 if (has[name] !== undef) {
12290 // Return cached feature test result.
12291 return has[name];
12292 }
12293 var isSupported;
12294 if (name == "bug-string-char-index") {
12295 // IE <= 7 doesn't support accessing string characters using square
12296 // bracket notation. IE 8 only supports this for primitives.
12297 isSupported = "a"[0] != "a";
12298 } else if (name == "json") {
12299 // Indicates whether both `JSON.stringify` and `JSON.parse` are
12300 // supported.
12301 isSupported = has("json-stringify") && has("json-parse");
12302 } else {
12303 var value, serialized = '{"a":[1,true,false,null,"\\u0000\\b\\n\\f\\r\\t"]}';
12304 // Test `JSON.stringify`.
12305 if (name == "json-stringify") {
12306 var stringify = exports.stringify, stringifySupported = typeof stringify == "function" && isExtended;
12307 if (stringifySupported) {
12308 // A test function object with a custom `toJSON` method.
12309 (value = function () {
12310 return 1;
12311 }).toJSON = value;
12312 try {
12313 stringifySupported =
12314 // Firefox 3.1b1 and b2 serialize string, number, and boolean
12315 // primitives as object literals.
12316 stringify(0) === "0" &&
12317 // FF 3.1b1, b2, and JSON 2 serialize wrapped primitives as object
12318 // literals.
12319 stringify(new Number()) === "0" &&
12320 stringify(new String()) == '""' &&
12321 // FF 3.1b1, 2 throw an error if the value is `null`, `undefined`, or
12322 // does not define a canonical JSON representation (this applies to
12323 // objects with `toJSON` properties as well, *unless* they are nested
12324 // within an object or array).
12325 stringify(getClass) === undef &&
12326 // IE 8 serializes `undefined` as `"undefined"`. Safari <= 5.1.7 and
12327 // FF 3.1b3 pass this test.
12328 stringify(undef) === undef &&
12329 // Safari <= 5.1.7 and FF 3.1b3 throw `Error`s and `TypeError`s,
12330 // respectively, if the value is omitted entirely.
12331 stringify() === undef &&
12332 // FF 3.1b1, 2 throw an error if the given value is not a number,
12333 // string, array, object, Boolean, or `null` literal. This applies to
12334 // objects with custom `toJSON` methods as well, unless they are nested
12335 // inside object or array literals. YUI 3.0.0b1 ignores custom `toJSON`
12336 // methods entirely.
12337 stringify(value) === "1" &&
12338 stringify([value]) == "[1]" &&
12339 // Prototype <= 1.6.1 serializes `[undefined]` as `"[]"` instead of
12340 // `"[null]"`.
12341 stringify([undef]) == "[null]" &&
12342 // YUI 3.0.0b1 fails to serialize `null` literals.
12343 stringify(null) == "null" &&
12344 // FF 3.1b1, 2 halts serialization if an array contains a function:
12345 // `[1, true, getClass, 1]` serializes as "[1,true,],". FF 3.1b3
12346 // elides non-JSON values from objects and arrays, unless they
12347 // define custom `toJSON` methods.
12348 stringify([undef, getClass, null]) == "[null,null,null]" &&
12349 // Simple serialization test. FF 3.1b1 uses Unicode escape sequences
12350 // where character escape codes are expected (e.g., `\b` => `\u0008`).
12351 stringify({ "a": [value, true, false, null, "\x00\b\n\f\r\t"] }) == serialized &&
12352 // FF 3.1b1 and b2 ignore the `filter` and `width` arguments.
12353 stringify(null, value) === "1" &&
12354 stringify([1, 2], null, 1) == "[\n 1,\n 2\n]" &&
12355 // JSON 2, Prototype <= 1.7, and older WebKit builds incorrectly
12356 // serialize extended years.
12357 stringify(new Date(-8.64e15)) == '"-271821-04-20T00:00:00.000Z"' &&
12358 // The milliseconds are optional in ES 5, but required in 5.1.
12359 stringify(new Date(8.64e15)) == '"+275760-09-13T00:00:00.000Z"' &&
12360 // Firefox <= 11.0 incorrectly serializes years prior to 0 as negative
12361 // four-digit years instead of six-digit years. Credits: @Yaffle.
12362 stringify(new Date(-621987552e5)) == '"-000001-01-01T00:00:00.000Z"' &&
12363 // Safari <= 5.1.5 and Opera >= 10.53 incorrectly serialize millisecond
12364 // values less than 1000. Credits: @Yaffle.
12365 stringify(new Date(-1)) == '"1969-12-31T23:59:59.999Z"';
12366 } catch (exception) {
12367 stringifySupported = false;
12368 }
12369 }
12370 isSupported = stringifySupported;
12371 }
12372 // Test `JSON.parse`.
12373 if (name == "json-parse") {
12374 var parse = exports.parse;
12375 if (typeof parse == "function") {
12376 try {
12377 // FF 3.1b1, b2 will throw an exception if a bare literal is provided.
12378 // Conforming implementations should also coerce the initial argument to
12379 // a string prior to parsing.
12380 if (parse("0") === 0 && !parse(false)) {
12381 // Simple parsing test.
12382 value = parse(serialized);
12383 var parseSupported = value["a"].length == 5 && value["a"][0] === 1;
12384 if (parseSupported) {
12385 try {
12386 // Safari <= 5.1.2 and FF 3.1b1 allow unescaped tabs in strings.
12387 parseSupported = !parse('"\t"');
12388 } catch (exception) {}
12389 if (parseSupported) {
12390 try {
12391 // FF 4.0 and 4.0.1 allow leading `+` signs and leading
12392 // decimal points. FF 4.0, 4.0.1, and IE 9-10 also allow
12393 // certain octal literals.
12394 parseSupported = parse("01") !== 1;
12395 } catch (exception) {}
12396 }
12397 if (parseSupported) {
12398 try {
12399 // FF 4.0, 4.0.1, and Rhino 1.7R3-R4 allow trailing decimal
12400 // points. These environments, along with FF 3.1b1 and 2,
12401 // also allow trailing commas in JSON objects and arrays.
12402 parseSupported = parse("1.") !== 1;
12403 } catch (exception) {}
12404 }
12405 }
12406 }
12407 } catch (exception) {
12408 parseSupported = false;
12409 }
12410 }
12411 isSupported = parseSupported;
12412 }
12413 }
12414 return has[name] = !!isSupported;
12415 }
12416
12417 if (!has("json")) {
12418 // Common `[[Class]]` name aliases.
12419 var functionClass = "[object Function]",
12420 dateClass = "[object Date]",
12421 numberClass = "[object Number]",
12422 stringClass = "[object String]",
12423 arrayClass = "[object Array]",
12424 booleanClass = "[object Boolean]";
12425
12426 // Detect incomplete support for accessing string characters by index.
12427 var charIndexBuggy = has("bug-string-char-index");
12428
12429 // Define additional utility methods if the `Date` methods are buggy.
12430 if (!isExtended) {
12431 var floor = Math.floor;
12432 // A mapping between the months of the year and the number of days between
12433 // January 1st and the first of the respective month.
12434 var Months = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
12435 // Internal: Calculates the number of days between the Unix epoch and the
12436 // first day of the given month.
12437 var getDay = function (year, month) {
12438 return Months[month] + 365 * (year - 1970) + floor((year - 1969 + (month = +(month > 1))) / 4) - floor((year - 1901 + month) / 100) + floor((year - 1601 + month) / 400);
12439 };
12440 }
12441
12442 // Internal: Determines if a property is a direct property of the given
12443 // object. Delegates to the native `Object#hasOwnProperty` method.
12444 if (!(isProperty = objectProto.hasOwnProperty)) {
12445 isProperty = function (property) {
12446 var members = {}, constructor;
12447 if ((members.__proto__ = null, members.__proto__ = {
12448 // The *proto* property cannot be set multiple times in recent
12449 // versions of Firefox and SeaMonkey.
12450 "toString": 1
12451 }, members).toString != getClass) {
12452 // Safari <= 2.0.3 doesn't implement `Object#hasOwnProperty`, but
12453 // supports the mutable *proto* property.
12454 isProperty = function (property) {
12455 // Capture and break the object's prototype chain (see section 8.6.2
12456 // of the ES 5.1 spec). The parenthesized expression prevents an
12457 // unsafe transformation by the Closure Compiler.
12458 var original = this.__proto__, result = property in (this.__proto__ = null, this);
12459 // Restore the original prototype chain.
12460 this.__proto__ = original;
12461 return result;
12462 };
12463 } else {
12464 // Capture a reference to the top-level `Object` constructor.
12465 constructor = members.constructor;
12466 // Use the `constructor` property to simulate `Object#hasOwnProperty` in
12467 // other environments.
12468 isProperty = function (property) {
12469 var parent = (this.constructor || constructor).prototype;
12470 return property in this && !(property in parent && this[property] === parent[property]);
12471 };
12472 }
12473 members = null;
12474 return isProperty.call(this, property);
12475 };
12476 }
12477
12478 // Internal: Normalizes the `for...in` iteration algorithm across
12479 // environments. Each enumerated key is yielded to a `callback` function.
12480 forEach = function (object, callback) {
12481 var size = 0, Properties, members, property;
12482
12483 // Tests for bugs in the current environment's `for...in` algorithm. The
12484 // `valueOf` property inherits the non-enumerable flag from
12485 // `Object.prototype` in older versions of IE, Netscape, and Mozilla.
12486 (Properties = function () {
12487 this.valueOf = 0;
12488 }).prototype.valueOf = 0;
12489
12490 // Iterate over a new instance of the `Properties` class.
12491 members = new Properties();
12492 for (property in members) {
12493 // Ignore all properties inherited from `Object.prototype`.
12494 if (isProperty.call(members, property)) {
12495 size++;
12496 }
12497 }
12498 Properties = members = null;
12499
12500 // Normalize the iteration algorithm.
12501 if (!size) {
12502 // A list of non-enumerable properties inherited from `Object.prototype`.
12503 members = ["valueOf", "toString", "toLocaleString", "propertyIsEnumerable", "isPrototypeOf", "hasOwnProperty", "constructor"];
12504 // IE <= 8, Mozilla 1.0, and Netscape 6.2 ignore shadowed non-enumerable
12505 // properties.
12506 forEach = function (object, callback) {
12507 var isFunction = getClass.call(object) == functionClass, property, length;
12508 var hasProperty = !isFunction && typeof object.constructor != "function" && objectTypes[typeof object.hasOwnProperty] && object.hasOwnProperty || isProperty;
12509 for (property in object) {
12510 // Gecko <= 1.0 enumerates the `prototype` property of functions under
12511 // certain conditions; IE does not.
12512 if (!(isFunction && property == "prototype") && hasProperty.call(object, property)) {
12513 callback(property);
12514 }
12515 }
12516 // Manually invoke the callback for each non-enumerable property.
12517 for (length = members.length; property = members[--length]; hasProperty.call(object, property) && callback(property));
12518 };
12519 } else if (size == 2) {
12520 // Safari <= 2.0.4 enumerates shadowed properties twice.
12521 forEach = function (object, callback) {
12522 // Create a set of iterated properties.
12523 var members = {}, isFunction = getClass.call(object) == functionClass, property;
12524 for (property in object) {
12525 // Store each property name to prevent double enumeration. The
12526 // `prototype` property of functions is not enumerated due to cross-
12527 // environment inconsistencies.
12528 if (!(isFunction && property == "prototype") && !isProperty.call(members, property) && (members[property] = 1) && isProperty.call(object, property)) {
12529 callback(property);
12530 }
12531 }
12532 };
12533 } else {
12534 // No bugs detected; use the standard `for...in` algorithm.
12535 forEach = function (object, callback) {
12536 var isFunction = getClass.call(object) == functionClass, property, isConstructor;
12537 for (property in object) {
12538 if (!(isFunction && property == "prototype") && isProperty.call(object, property) && !(isConstructor = property === "constructor")) {
12539 callback(property);
12540 }
12541 }
12542 // Manually invoke the callback for the `constructor` property due to
12543 // cross-environment inconsistencies.
12544 if (isConstructor || isProperty.call(object, (property = "constructor"))) {
12545 callback(property);
12546 }
12547 };
12548 }
12549 return forEach(object, callback);
12550 };
12551
12552 // Public: Serializes a JavaScript `value` as a JSON string. The optional
12553 // `filter` argument may specify either a function that alters how object and
12554 // array members are serialized, or an array of strings and numbers that
12555 // indicates which properties should be serialized. The optional `width`
12556 // argument may be either a string or number that specifies the indentation
12557 // level of the output.
12558 if (!has("json-stringify")) {
12559 // Internal: A map of control characters and their escaped equivalents.
12560 var Escapes = {
12561 92: "\\\\",
12562 34: '\\"',
12563 8: "\\b",
12564 12: "\\f",
12565 10: "\\n",
12566 13: "\\r",
12567 9: "\\t"
12568 };
12569
12570 // Internal: Converts `value` into a zero-padded string such that its
12571 // length is at least equal to `width`. The `width` must be <= 6.
12572 var leadingZeroes = "000000";
12573 var toPaddedString = function (width, value) {
12574 // The `|| 0` expression is necessary to work around a bug in
12575 // Opera <= 7.54u2 where `0 == -0`, but `String(-0) !== "0"`.
12576 return (leadingZeroes + (value || 0)).slice(-width);
12577 };
12578
12579 // Internal: Double-quotes a string `value`, replacing all ASCII control
12580 // characters (characters with code unit values between 0 and 31) with
12581 // their escaped equivalents. This is an implementation of the
12582 // `Quote(value)` operation defined in ES 5.1 section 15.12.3.
12583 var unicodePrefix = "\\u00";
12584 var quote = function (value) {
12585 var result = '"', index = 0, length = value.length, useCharIndex = !charIndexBuggy || length > 10;
12586 var symbols = useCharIndex && (charIndexBuggy ? value.split("") : value);
12587 for (; index < length; index++) {
12588 var charCode = value.charCodeAt(index);
12589 // If the character is a control character, append its Unicode or
12590 // shorthand escape sequence; otherwise, append the character as-is.
12591 switch (charCode) {
12592 case 8: case 9: case 10: case 12: case 13: case 34: case 92:
12593 result += Escapes[charCode];
12594 break;
12595 default:
12596 if (charCode < 32) {
12597 result += unicodePrefix + toPaddedString(2, charCode.toString(16));
12598 break;
12599 }
12600 result += useCharIndex ? symbols[index] : value.charAt(index);
12601 }
12602 }
12603 return result + '"';
12604 };
12605
12606 // Internal: Recursively serializes an object. Implements the
12607 // `Str(key, holder)`, `JO(value)`, and `JA(value)` operations.
12608 var serialize = function (property, object, callback, properties, whitespace, indentation, stack) {
12609 var value, className, year, month, date, time, hours, minutes, seconds, milliseconds, results, element, index, length, prefix, result;
12610 try {
12611 // Necessary for host object support.
12612 value = object[property];
12613 } catch (exception) {}
12614 if (typeof value == "object" && value) {
12615 className = getClass.call(value);
12616 if (className == dateClass && !isProperty.call(value, "toJSON")) {
12617 if (value > -1 / 0 && value < 1 / 0) {
12618 // Dates are serialized according to the `Date#toJSON` method
12619 // specified in ES 5.1 section 15.9.5.44. See section 15.9.1.15
12620 // for the ISO 8601 date time string format.
12621 if (getDay) {
12622 // Manually compute the year, month, date, hours, minutes,
12623 // seconds, and milliseconds if the `getUTC*` methods are
12624 // buggy. Adapted from @Yaffle's `date-shim` project.
12625 date = floor(value / 864e5);
12626 for (year = floor(date / 365.2425) + 1970 - 1; getDay(year + 1, 0) <= date; year++);
12627 for (month = floor((date - getDay(year, 0)) / 30.42); getDay(year, month + 1) <= date; month++);
12628 date = 1 + date - getDay(year, month);
12629 // The `time` value specifies the time within the day (see ES
12630 // 5.1 section 15.9.1.2). The formula `(A % B + B) % B` is used
12631 // to compute `A modulo B`, as the `%` operator does not
12632 // correspond to the `modulo` operation for negative numbers.
12633 time = (value % 864e5 + 864e5) % 864e5;
12634 // The hours, minutes, seconds, and milliseconds are obtained by
12635 // decomposing the time within the day. See section 15.9.1.10.
12636 hours = floor(time / 36e5) % 24;
12637 minutes = floor(time / 6e4) % 60;
12638 seconds = floor(time / 1e3) % 60;
12639 milliseconds = time % 1e3;
12640 } else {
12641 year = value.getUTCFullYear();
12642 month = value.getUTCMonth();
12643 date = value.getUTCDate();
12644 hours = value.getUTCHours();
12645 minutes = value.getUTCMinutes();
12646 seconds = value.getUTCSeconds();
12647 milliseconds = value.getUTCMilliseconds();
12648 }
12649 // Serialize extended years correctly.
12650 value = (year <= 0 || year >= 1e4 ? (year < 0 ? "-" : "+") + toPaddedString(6, year < 0 ? -year : year) : toPaddedString(4, year)) +
12651 "-" + toPaddedString(2, month + 1) + "-" + toPaddedString(2, date) +
12652 // Months, dates, hours, minutes, and seconds should have two
12653 // digits; milliseconds should have three.
12654 "T" + toPaddedString(2, hours) + ":" + toPaddedString(2, minutes) + ":" + toPaddedString(2, seconds) +
12655 // Milliseconds are optional in ES 5.0, but required in 5.1.
12656 "." + toPaddedString(3, milliseconds) + "Z";
12657 } else {
12658 value = null;
12659 }
12660 } else if (typeof value.toJSON == "function" && ((className != numberClass && className != stringClass && className != arrayClass) || isProperty.call(value, "toJSON"))) {
12661 // Prototype <= 1.6.1 adds non-standard `toJSON` methods to the
12662 // `Number`, `String`, `Date`, and `Array` prototypes. JSON 3
12663 // ignores all `toJSON` methods on these objects unless they are
12664 // defined directly on an instance.
12665 value = value.toJSON(property);
12666 }
12667 }
12668 if (callback) {
12669 // If a replacement function was provided, call it to obtain the value
12670 // for serialization.
12671 value = callback.call(object, property, value);
12672 }
12673 if (value === null) {
12674 return "null";
12675 }
12676 className = getClass.call(value);
12677 if (className == booleanClass) {
12678 // Booleans are represented literally.
12679 return "" + value;
12680 } else if (className == numberClass) {
12681 // JSON numbers must be finite. `Infinity` and `NaN` are serialized as
12682 // `"null"`.
12683 return value > -1 / 0 && value < 1 / 0 ? "" + value : "null";
12684 } else if (className == stringClass) {
12685 // Strings are double-quoted and escaped.
12686 return quote("" + value);
12687 }
12688 // Recursively serialize objects and arrays.
12689 if (typeof value == "object") {
12690 // Check for cyclic structures. This is a linear search; performance
12691 // is inversely proportional to the number of unique nested objects.
12692 for (length = stack.length; length--;) {
12693 if (stack[length] === value) {
12694 // Cyclic structures cannot be serialized by `JSON.stringify`.
12695 throw TypeError();
12696 }
12697 }
12698 // Add the object to the stack of traversed objects.
12699 stack.push(value);
12700 results = [];
12701 // Save the current indentation level and indent one additional level.
12702 prefix = indentation;
12703 indentation += whitespace;
12704 if (className == arrayClass) {
12705 // Recursively serialize array elements.
12706 for (index = 0, length = value.length; index < length; index++) {
12707 element = serialize(index, value, callback, properties, whitespace, indentation, stack);
12708 results.push(element === undef ? "null" : element);
12709 }
12710 result = results.length ? (whitespace ? "[\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "]" : ("[" + results.join(",") + "]")) : "[]";
12711 } else {
12712 // Recursively serialize object members. Members are selected from
12713 // either a user-specified list of property names, or the object
12714 // itself.
12715 forEach(properties || value, function (property) {
12716 var element = serialize(property, value, callback, properties, whitespace, indentation, stack);
12717 if (element !== undef) {
12718 // According to ES 5.1 section 15.12.3: "If `gap` {whitespace}
12719 // is not the empty string, let `member` {quote(property) + ":"}
12720 // be the concatenation of `member` and the `space` character."
12721 // The "`space` character" refers to the literal space
12722 // character, not the `space` {width} argument provided to
12723 // `JSON.stringify`.
12724 results.push(quote(property) + ":" + (whitespace ? " " : "") + element);
12725 }
12726 });
12727 result = results.length ? (whitespace ? "{\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "}" : ("{" + results.join(",") + "}")) : "{}";
12728 }
12729 // Remove the object from the traversed object stack.
12730 stack.pop();
12731 return result;
12732 }
12733 };
12734
12735 // Public: `JSON.stringify`. See ES 5.1 section 15.12.3.
12736 exports.stringify = function (source, filter, width) {
12737 var whitespace, callback, properties, className;
12738 if (objectTypes[typeof filter] && filter) {
12739 if ((className = getClass.call(filter)) == functionClass) {
12740 callback = filter;
12741 } else if (className == arrayClass) {
12742 // Convert the property names array into a makeshift set.
12743 properties = {};
12744 for (var index = 0, length = filter.length, value; index < length; value = filter[index++], ((className = getClass.call(value)), className == stringClass || className == numberClass) && (properties[value] = 1));
12745 }
12746 }
12747 if (width) {
12748 if ((className = getClass.call(width)) == numberClass) {
12749 // Convert the `width` to an integer and create a string containing
12750 // `width` number of space characters.
12751 if ((width -= width % 1) > 0) {
12752 for (whitespace = "", width > 10 && (width = 10); whitespace.length < width; whitespace += " ");
12753 }
12754 } else if (className == stringClass) {
12755 whitespace = width.length <= 10 ? width : width.slice(0, 10);
12756 }
12757 }
12758 // Opera <= 7.54u2 discards the values associated with empty string keys
12759 // (`""`) only if they are used directly within an object member list
12760 // (e.g., `!("" in { "": 1})`).
12761 return serialize("", (value = {}, value[""] = source, value), callback, properties, whitespace, "", []);
12762 };
12763 }
12764
12765 // Public: Parses a JSON source string.
12766 if (!has("json-parse")) {
12767 var fromCharCode = String.fromCharCode;
12768
12769 // Internal: A map of escaped control characters and their unescaped
12770 // equivalents.
12771 var Unescapes = {
12772 92: "\\",
12773 34: '"',
12774 47: "/",
12775 98: "\b",
12776 116: "\t",
12777 110: "\n",
12778 102: "\f",
12779 114: "\r"
12780 };
12781
12782 // Internal: Stores the parser state.
12783 var Index, Source;
12784
12785 // Internal: Resets the parser state and throws a `SyntaxError`.
12786 var abort = function () {
12787 Index = Source = null;
12788 throw SyntaxError();
12789 };
12790
12791 // Internal: Returns the next token, or `"$"` if the parser has reached
12792 // the end of the source string. A token may be a string, number, `null`
12793 // literal, or Boolean literal.
12794 var lex = function () {
12795 var source = Source, length = source.length, value, begin, position, isSigned, charCode;
12796 while (Index < length) {
12797 charCode = source.charCodeAt(Index);
12798 switch (charCode) {
12799 case 9: case 10: case 13: case 32:
12800 // Skip whitespace tokens, including tabs, carriage returns, line
12801 // feeds, and space characters.
12802 Index++;
12803 break;
12804 case 123: case 125: case 91: case 93: case 58: case 44:
12805 // Parse a punctuator token (`{`, `}`, `[`, `]`, `:`, or `,`) at
12806 // the current position.
12807 value = charIndexBuggy ? source.charAt(Index) : source[Index];
12808 Index++;
12809 return value;
12810 case 34:
12811 // `"` delimits a JSON string; advance to the next character and
12812 // begin parsing the string. String tokens are prefixed with the
12813 // sentinel `@` character to distinguish them from punctuators and
12814 // end-of-string tokens.
12815 for (value = "@", Index++; Index < length;) {
12816 charCode = source.charCodeAt(Index);
12817 if (charCode < 32) {
12818 // Unescaped ASCII control characters (those with a code unit
12819 // less than the space character) are not permitted.
12820 abort();
12821 } else if (charCode == 92) {
12822 // A reverse solidus (`\`) marks the beginning of an escaped
12823 // control character (including `"`, `\`, and `/`) or Unicode
12824 // escape sequence.
12825 charCode = source.charCodeAt(++Index);
12826 switch (charCode) {
12827 case 92: case 34: case 47: case 98: case 116: case 110: case 102: case 114:
12828 // Revive escaped control characters.
12829 value += Unescapes[charCode];
12830 Index++;
12831 break;
12832 case 117:
12833 // `\u` marks the beginning of a Unicode escape sequence.
12834 // Advance to the first character and validate the
12835 // four-digit code point.
12836 begin = ++Index;
12837 for (position = Index + 4; Index < position; Index++) {
12838 charCode = source.charCodeAt(Index);
12839 // A valid sequence comprises four hexdigits (case-
12840 // insensitive) that form a single hexadecimal value.
12841 if (!(charCode >= 48 && charCode <= 57 || charCode >= 97 && charCode <= 102 || charCode >= 65 && charCode <= 70)) {
12842 // Invalid Unicode escape sequence.
12843 abort();
12844 }
12845 }
12846 // Revive the escaped character.
12847 value += fromCharCode("0x" + source.slice(begin, Index));
12848 break;
12849 default:
12850 // Invalid escape sequence.
12851 abort();
12852 }
12853 } else {
12854 if (charCode == 34) {
12855 // An unescaped double-quote character marks the end of the
12856 // string.
12857 break;
12858 }
12859 charCode = source.charCodeAt(Index);
12860 begin = Index;
12861 // Optimize for the common case where a string is valid.
12862 while (charCode >= 32 && charCode != 92 && charCode != 34) {
12863 charCode = source.charCodeAt(++Index);
12864 }
12865 // Append the string as-is.
12866 value += source.slice(begin, Index);
12867 }
12868 }
12869 if (source.charCodeAt(Index) == 34) {
12870 // Advance to the next character and return the revived string.
12871 Index++;
12872 return value;
12873 }
12874 // Unterminated string.
12875 abort();
12876 default:
12877 // Parse numbers and literals.
12878 begin = Index;
12879 // Advance past the negative sign, if one is specified.
12880 if (charCode == 45) {
12881 isSigned = true;
12882 charCode = source.charCodeAt(++Index);
12883 }
12884 // Parse an integer or floating-point value.
12885 if (charCode >= 48 && charCode <= 57) {
12886 // Leading zeroes are interpreted as octal literals.
12887 if (charCode == 48 && ((charCode = source.charCodeAt(Index + 1)), charCode >= 48 && charCode <= 57)) {
12888 // Illegal octal literal.
12889 abort();
12890 }
12891 isSigned = false;
12892 // Parse the integer component.
12893 for (; Index < length && ((charCode = source.charCodeAt(Index)), charCode >= 48 && charCode <= 57); Index++);
12894 // Floats cannot contain a leading decimal point; however, this
12895 // case is already accounted for by the parser.
12896 if (source.charCodeAt(Index) == 46) {
12897 position = ++Index;
12898 // Parse the decimal component.
12899 for (; position < length && ((charCode = source.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++);
12900 if (position == Index) {
12901 // Illegal trailing decimal.
12902 abort();
12903 }
12904 Index = position;
12905 }
12906 // Parse exponents. The `e` denoting the exponent is
12907 // case-insensitive.
12908 charCode = source.charCodeAt(Index);
12909 if (charCode == 101 || charCode == 69) {
12910 charCode = source.charCodeAt(++Index);
12911 // Skip past the sign following the exponent, if one is
12912 // specified.
12913 if (charCode == 43 || charCode == 45) {
12914 Index++;
12915 }
12916 // Parse the exponential component.
12917 for (position = Index; position < length && ((charCode = source.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++);
12918 if (position == Index) {
12919 // Illegal empty exponent.
12920 abort();
12921 }
12922 Index = position;
12923 }
12924 // Coerce the parsed value to a JavaScript number.
12925 return +source.slice(begin, Index);
12926 }
12927 // A negative sign may only precede numbers.
12928 if (isSigned) {
12929 abort();
12930 }
12931 // `true`, `false`, and `null` literals.
12932 if (source.slice(Index, Index + 4) == "true") {
12933 Index += 4;
12934 return true;
12935 } else if (source.slice(Index, Index + 5) == "false") {
12936 Index += 5;
12937 return false;
12938 } else if (source.slice(Index, Index + 4) == "null") {
12939 Index += 4;
12940 return null;
12941 }
12942 // Unrecognized token.
12943 abort();
12944 }
12945 }
12946 // Return the sentinel `$` character if the parser has reached the end
12947 // of the source string.
12948 return "$";
12949 };
12950
12951 // Internal: Parses a JSON `value` token.
12952 var get = function (value) {
12953 var results, hasMembers;
12954 if (value == "$") {
12955 // Unexpected end of input.
12956 abort();
12957 }
12958 if (typeof value == "string") {
12959 if ((charIndexBuggy ? value.charAt(0) : value[0]) == "@") {
12960 // Remove the sentinel `@` character.
12961 return value.slice(1);
12962 }
12963 // Parse object and array literals.
12964 if (value == "[") {
12965 // Parses a JSON array, returning a new JavaScript array.
12966 results = [];
12967 for (;; hasMembers || (hasMembers = true)) {
12968 value = lex();
12969 // A closing square bracket marks the end of the array literal.
12970 if (value == "]") {
12971 break;
12972 }
12973 // If the array literal contains elements, the current token
12974 // should be a comma separating the previous element from the
12975 // next.
12976 if (hasMembers) {
12977 if (value == ",") {
12978 value = lex();
12979 if (value == "]") {
12980 // Unexpected trailing `,` in array literal.
12981 abort();
12982 }
12983 } else {
12984 // A `,` must separate each array element.
12985 abort();
12986 }
12987 }
12988 // Elisions and leading commas are not permitted.
12989 if (value == ",") {
12990 abort();
12991 }
12992 results.push(get(value));
12993 }
12994 return results;
12995 } else if (value == "{") {
12996 // Parses a JSON object, returning a new JavaScript object.
12997 results = {};
12998 for (;; hasMembers || (hasMembers = true)) {
12999 value = lex();
13000 // A closing curly brace marks the end of the object literal.
13001 if (value == "}") {
13002 break;
13003 }
13004 // If the object literal contains members, the current token
13005 // should be a comma separator.
13006 if (hasMembers) {
13007 if (value == ",") {
13008 value = lex();
13009 if (value == "}") {
13010 // Unexpected trailing `,` in object literal.
13011 abort();
13012 }
13013 } else {
13014 // A `,` must separate each object member.
13015 abort();
13016 }
13017 }
13018 // Leading commas are not permitted, object property names must be
13019 // double-quoted strings, and a `:` must separate each property
13020 // name and value.
13021 if (value == "," || typeof value != "string" || (charIndexBuggy ? value.charAt(0) : value[0]) != "@" || lex() != ":") {
13022 abort();
13023 }
13024 results[value.slice(1)] = get(lex());
13025 }
13026 return results;
13027 }
13028 // Unexpected token encountered.
13029 abort();
13030 }
13031 return value;
13032 };
13033
13034 // Internal: Updates a traversed object member.
13035 var update = function (source, property, callback) {
13036 var element = walk(source, property, callback);
13037 if (element === undef) {
13038 delete source[property];
13039 } else {
13040 source[property] = element;
13041 }
13042 };
13043
13044 // Internal: Recursively traverses a parsed JSON object, invoking the
13045 // `callback` function for each value. This is an implementation of the
13046 // `Walk(holder, name)` operation defined in ES 5.1 section 15.12.2.
13047 var walk = function (source, property, callback) {
13048 var value = source[property], length;
13049 if (typeof value == "object" && value) {
13050 // `forEach` can't be used to traverse an array in Opera <= 8.54
13051 // because its `Object#hasOwnProperty` implementation returns `false`
13052 // for array indices (e.g., `![1, 2, 3].hasOwnProperty("0")`).
13053 if (getClass.call(value) == arrayClass) {
13054 for (length = value.length; length--;) {
13055 update(value, length, callback);
13056 }
13057 } else {
13058 forEach(value, function (property) {
13059 update(value, property, callback);
13060 });
13061 }
13062 }
13063 return callback.call(source, property, value);
13064 };
13065
13066 // Public: `JSON.parse`. See ES 5.1 section 15.12.2.
13067 exports.parse = function (source, callback) {
13068 var result, value;
13069 Index = 0;
13070 Source = "" + source;
13071 result = get(lex());
13072 // If a JSON string contains multiple tokens, it is invalid.
13073 if (lex() != "$") {
13074 abort();
13075 }
13076 // Reset the parser state.
13077 Index = Source = null;
13078 return callback && getClass.call(callback) == functionClass ? walk((value = {}, value[""] = result, value), "", callback) : result;
13079 };
13080 }
13081 }
13082
13083 exports["runInContext"] = runInContext;
13084 return exports;
13085 }
13086
13087 if (freeExports && !isLoader) {
13088 // Export for CommonJS environments.
13089 runInContext(root, freeExports);
13090 } else {
13091 // Export for web browsers and JavaScript engines.
13092 var nativeJSON = root.JSON,
13093 previousJSON = root["JSON3"],
13094 isRestored = false;
13095
13096 var JSON3 = runInContext(root, (root["JSON3"] = {
13097 // Public: Restores the original value of the global `JSON` object and
13098 // returns a reference to the `JSON3` object.
13099 "noConflict": function () {
13100 if (!isRestored) {
13101 isRestored = true;
13102 root.JSON = nativeJSON;
13103 root["JSON3"] = previousJSON;
13104 nativeJSON = previousJSON = null;
13105 }
13106 return JSON3;
13107 }
13108 }));
13109
13110 root.JSON = {
13111 "parse": JSON3.parse,
13112 "stringify": JSON3.stringify
13113 };
13114 }
13115
13116 // Export for asynchronous module loaders.
13117 if (isLoader) {
13118 define(function () {
13119 return JSON3;
13120 });
13121 }
13122}).call(this);
13123
13124}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
13125},{}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/lodash/index.js":[function(require,module,exports){
13126(function (global){
13127/**
13128 * @license
13129 * lodash 3.10.1 (Custom Build) <https://lodash.com/>
13130 * Build: `lodash modern -d -o ./index.js`
13131 * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
13132 * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
13133 * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
13134 * Available under MIT license <https://lodash.com/license>
13135 */
13136;(function() {
13137
13138 /** Used as a safe reference for `undefined` in pre-ES5 environments. */
13139 var undefined;
13140
13141 /** Used as the semantic version number. */
13142 var VERSION = '3.10.1';
13143
13144 /** Used to compose bitmasks for wrapper metadata. */
13145 var BIND_FLAG = 1,
13146 BIND_KEY_FLAG = 2,
13147 CURRY_BOUND_FLAG = 4,
13148 CURRY_FLAG = 8,
13149 CURRY_RIGHT_FLAG = 16,
13150 PARTIAL_FLAG = 32,
13151 PARTIAL_RIGHT_FLAG = 64,
13152 ARY_FLAG = 128,
13153 REARG_FLAG = 256;
13154
13155 /** Used as default options for `_.trunc`. */
13156 var DEFAULT_TRUNC_LENGTH = 30,
13157 DEFAULT_TRUNC_OMISSION = '...';
13158
13159 /** Used to detect when a function becomes hot. */
13160 var HOT_COUNT = 150,
13161 HOT_SPAN = 16;
13162
13163 /** Used as the size to enable large array optimizations. */
13164 var LARGE_ARRAY_SIZE = 200;
13165
13166 /** Used to indicate the type of lazy iteratees. */
13167 var LAZY_FILTER_FLAG = 1,
13168 LAZY_MAP_FLAG = 2;
13169
13170 /** Used as the `TypeError` message for "Functions" methods. */
13171 var FUNC_ERROR_TEXT = 'Expected a function';
13172
13173 /** Used as the internal argument placeholder. */
13174 var PLACEHOLDER = '__lodash_placeholder__';
13175
13176 /** `Object#toString` result references. */
13177 var argsTag = '[object Arguments]',
13178 arrayTag = '[object Array]',
13179 boolTag = '[object Boolean]',
13180 dateTag = '[object Date]',
13181 errorTag = '[object Error]',
13182 funcTag = '[object Function]',
13183 mapTag = '[object Map]',
13184 numberTag = '[object Number]',
13185 objectTag = '[object Object]',
13186 regexpTag = '[object RegExp]',
13187 setTag = '[object Set]',
13188 stringTag = '[object String]',
13189 weakMapTag = '[object WeakMap]';
13190
13191 var arrayBufferTag = '[object ArrayBuffer]',
13192 float32Tag = '[object Float32Array]',
13193 float64Tag = '[object Float64Array]',
13194 int8Tag = '[object Int8Array]',
13195 int16Tag = '[object Int16Array]',
13196 int32Tag = '[object Int32Array]',
13197 uint8Tag = '[object Uint8Array]',
13198 uint8ClampedTag = '[object Uint8ClampedArray]',
13199 uint16Tag = '[object Uint16Array]',
13200 uint32Tag = '[object Uint32Array]';
13201
13202 /** Used to match empty string literals in compiled template source. */
13203 var reEmptyStringLeading = /\b__p \+= '';/g,
13204 reEmptyStringMiddle = /\b(__p \+=) '' \+/g,
13205 reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g;
13206
13207 /** Used to match HTML entities and HTML characters. */
13208 var reEscapedHtml = /&(?:amp|lt|gt|quot|#39|#96);/g,
13209 reUnescapedHtml = /[&<>"'`]/g,
13210 reHasEscapedHtml = RegExp(reEscapedHtml.source),
13211 reHasUnescapedHtml = RegExp(reUnescapedHtml.source);
13212
13213 /** Used to match template delimiters. */
13214 var reEscape = /<%-([\s\S]+?)%>/g,
13215 reEvaluate = /<%([\s\S]+?)%>/g,
13216 reInterpolate = /<%=([\s\S]+?)%>/g;
13217
13218 /** Used to match property names within property paths. */
13219 var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\n\\]|\\.)*?\1)\]/,
13220 reIsPlainProp = /^\w*$/,
13221 rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\n\\]|\\.)*?)\2)\]/g;
13222
13223 /**
13224 * Used to match `RegExp` [syntax characters](http://ecma-international.org/ecma-262/6.0/#sec-patterns)
13225 * and those outlined by [`EscapeRegExpPattern`](http://ecma-international.org/ecma-262/6.0/#sec-escaperegexppattern).
13226 */
13227 var reRegExpChars = /^[:!,]|[\\^$.*+?()[\]{}|\/]|(^[0-9a-fA-Fnrtuvx])|([\n\r\u2028\u2029])/g,
13228 reHasRegExpChars = RegExp(reRegExpChars.source);
13229
13230 /** Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks). */
13231 var reComboMark = /[\u0300-\u036f\ufe20-\ufe23]/g;
13232
13233 /** Used to match backslashes in property paths. */
13234 var reEscapeChar = /\\(\\)?/g;
13235
13236 /** Used to match [ES template delimiters](http://ecma-international.org/ecma-262/6.0/#sec-template-literal-lexical-components). */
13237 var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g;
13238
13239 /** Used to match `RegExp` flags from their coerced string values. */
13240 var reFlags = /\w*$/;
13241
13242 /** Used to detect hexadecimal string values. */
13243 var reHasHexPrefix = /^0[xX]/;
13244
13245 /** Used to detect host constructors (Safari > 5). */
13246 var reIsHostCtor = /^\[object .+?Constructor\]$/;
13247
13248 /** Used to detect unsigned integer values. */
13249 var reIsUint = /^\d+$/;
13250
13251 /** Used to match latin-1 supplementary letters (excluding mathematical operators). */
13252 var reLatin1 = /[\xc0-\xd6\xd8-\xde\xdf-\xf6\xf8-\xff]/g;
13253
13254 /** Used to ensure capturing order of template delimiters. */
13255 var reNoMatch = /($^)/;
13256
13257 /** Used to match unescaped characters in compiled string literals. */
13258 var reUnescapedString = /['\n\r\u2028\u2029\\]/g;
13259
13260 /** Used to match words to create compound words. */
13261 var reWords = (function() {
13262 var upper = '[A-Z\\xc0-\\xd6\\xd8-\\xde]',
13263 lower = '[a-z\\xdf-\\xf6\\xf8-\\xff]+';
13264
13265 return RegExp(upper + '+(?=' + upper + lower + ')|' + upper + '?' + lower + '|' + upper + '+|[0-9]+', 'g');
13266 }());
13267
13268 /** Used to assign default `context` object properties. */
13269 var contextProps = [
13270 'Array', 'ArrayBuffer', 'Date', 'Error', 'Float32Array', 'Float64Array',
13271 'Function', 'Int8Array', 'Int16Array', 'Int32Array', 'Math', 'Number',
13272 'Object', 'RegExp', 'Set', 'String', '_', 'clearTimeout', 'isFinite',
13273 'parseFloat', 'parseInt', 'setTimeout', 'TypeError', 'Uint8Array',
13274 'Uint8ClampedArray', 'Uint16Array', 'Uint32Array', 'WeakMap'
13275 ];
13276
13277 /** Used to make template sourceURLs easier to identify. */
13278 var templateCounter = -1;
13279
13280 /** Used to identify `toStringTag` values of typed arrays. */
13281 var typedArrayTags = {};
13282 typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =
13283 typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =
13284 typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =
13285 typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =
13286 typedArrayTags[uint32Tag] = true;
13287 typedArrayTags[argsTag] = typedArrayTags[arrayTag] =
13288 typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =
13289 typedArrayTags[dateTag] = typedArrayTags[errorTag] =
13290 typedArrayTags[funcTag] = typedArrayTags[mapTag] =
13291 typedArrayTags[numberTag] = typedArrayTags[objectTag] =
13292 typedArrayTags[regexpTag] = typedArrayTags[setTag] =
13293 typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false;
13294
13295 /** Used to identify `toStringTag` values supported by `_.clone`. */
13296 var cloneableTags = {};
13297 cloneableTags[argsTag] = cloneableTags[arrayTag] =
13298 cloneableTags[arrayBufferTag] = cloneableTags[boolTag] =
13299 cloneableTags[dateTag] = cloneableTags[float32Tag] =
13300 cloneableTags[float64Tag] = cloneableTags[int8Tag] =
13301 cloneableTags[int16Tag] = cloneableTags[int32Tag] =
13302 cloneableTags[numberTag] = cloneableTags[objectTag] =
13303 cloneableTags[regexpTag] = cloneableTags[stringTag] =
13304 cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] =
13305 cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true;
13306 cloneableTags[errorTag] = cloneableTags[funcTag] =
13307 cloneableTags[mapTag] = cloneableTags[setTag] =
13308 cloneableTags[weakMapTag] = false;
13309
13310 /** Used to map latin-1 supplementary letters to basic latin letters. */
13311 var deburredLetters = {
13312 '\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A',
13313 '\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a',
13314 '\xc7': 'C', '\xe7': 'c',
13315 '\xd0': 'D', '\xf0': 'd',
13316 '\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E',
13317 '\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e',
13318 '\xcC': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I',
13319 '\xeC': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i',
13320 '\xd1': 'N', '\xf1': 'n',
13321 '\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O',
13322 '\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o',
13323 '\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U',
13324 '\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u',
13325 '\xdd': 'Y', '\xfd': 'y', '\xff': 'y',
13326 '\xc6': 'Ae', '\xe6': 'ae',
13327 '\xde': 'Th', '\xfe': 'th',
13328 '\xdf': 'ss'
13329 };
13330
13331 /** Used to map characters to HTML entities. */
13332 var htmlEscapes = {
13333 '&': '&amp;',
13334 '<': '&lt;',
13335 '>': '&gt;',
13336 '"': '&quot;',
13337 "'": '&#39;',
13338 '`': '&#96;'
13339 };
13340
13341 /** Used to map HTML entities to characters. */
13342 var htmlUnescapes = {
13343 '&amp;': '&',
13344 '&lt;': '<',
13345 '&gt;': '>',
13346 '&quot;': '"',
13347 '&#39;': "'",
13348 '&#96;': '`'
13349 };
13350
13351 /** Used to determine if values are of the language type `Object`. */
13352 var objectTypes = {
13353 'function': true,
13354 'object': true
13355 };
13356
13357 /** Used to escape characters for inclusion in compiled regexes. */
13358 var regexpEscapes = {
13359 '0': 'x30', '1': 'x31', '2': 'x32', '3': 'x33', '4': 'x34',
13360 '5': 'x35', '6': 'x36', '7': 'x37', '8': 'x38', '9': 'x39',
13361 'A': 'x41', 'B': 'x42', 'C': 'x43', 'D': 'x44', 'E': 'x45', 'F': 'x46',
13362 'a': 'x61', 'b': 'x62', 'c': 'x63', 'd': 'x64', 'e': 'x65', 'f': 'x66',
13363 'n': 'x6e', 'r': 'x72', 't': 'x74', 'u': 'x75', 'v': 'x76', 'x': 'x78'
13364 };
13365
13366 /** Used to escape characters for inclusion in compiled string literals. */
13367 var stringEscapes = {
13368 '\\': '\\',
13369 "'": "'",
13370 '\n': 'n',
13371 '\r': 'r',
13372 '\u2028': 'u2028',
13373 '\u2029': 'u2029'
13374 };
13375
13376 /** Detect free variable `exports`. */
13377 var freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports;
13378
13379 /** Detect free variable `module`. */
13380 var freeModule = objectTypes[typeof module] && module && !module.nodeType && module;
13381
13382 /** Detect free variable `global` from Node.js. */
13383 var freeGlobal = freeExports && freeModule && typeof global == 'object' && global && global.Object && global;
13384
13385 /** Detect free variable `self`. */
13386 var freeSelf = objectTypes[typeof self] && self && self.Object && self;
13387
13388 /** Detect free variable `window`. */
13389 var freeWindow = objectTypes[typeof window] && window && window.Object && window;
13390
13391 /** Detect the popular CommonJS extension `module.exports`. */
13392 var moduleExports = freeModule && freeModule.exports === freeExports && freeExports;
13393
13394 /**
13395 * Used as a reference to the global object.
13396 *
13397 * The `this` value is used if it's the global object to avoid Greasemonkey's
13398 * restricted `window` object, otherwise the `window` object is used.
13399 */
13400 var root = freeGlobal || ((freeWindow !== (this && this.window)) && freeWindow) || freeSelf || this;
13401
13402 /*--------------------------------------------------------------------------*/
13403
13404 /**
13405 * The base implementation of `compareAscending` which compares values and
13406 * sorts them in ascending order without guaranteeing a stable sort.
13407 *
13408 * @private
13409 * @param {*} value The value to compare.
13410 * @param {*} other The other value to compare.
13411 * @returns {number} Returns the sort order indicator for `value`.
13412 */
13413 function baseCompareAscending(value, other) {
13414 if (value !== other) {
13415 var valIsNull = value === null,
13416 valIsUndef = value === undefined,
13417 valIsReflexive = value === value;
13418
13419 var othIsNull = other === null,
13420 othIsUndef = other === undefined,
13421 othIsReflexive = other === other;
13422
13423 if ((value > other && !othIsNull) || !valIsReflexive ||
13424 (valIsNull && !othIsUndef && othIsReflexive) ||
13425 (valIsUndef && othIsReflexive)) {
13426 return 1;
13427 }
13428 if ((value < other && !valIsNull) || !othIsReflexive ||
13429 (othIsNull && !valIsUndef && valIsReflexive) ||
13430 (othIsUndef && valIsReflexive)) {
13431 return -1;
13432 }
13433 }
13434 return 0;
13435 }
13436
13437 /**
13438 * The base implementation of `_.findIndex` and `_.findLastIndex` without
13439 * support for callback shorthands and `this` binding.
13440 *
13441 * @private
13442 * @param {Array} array The array to search.
13443 * @param {Function} predicate The function invoked per iteration.
13444 * @param {boolean} [fromRight] Specify iterating from right to left.
13445 * @returns {number} Returns the index of the matched value, else `-1`.
13446 */
13447 function baseFindIndex(array, predicate, fromRight) {
13448 var length = array.length,
13449 index = fromRight ? length : -1;
13450
13451 while ((fromRight ? index-- : ++index < length)) {
13452 if (predicate(array[index], index, array)) {
13453 return index;
13454 }
13455 }
13456 return -1;
13457 }
13458
13459 /**
13460 * The base implementation of `_.indexOf` without support for binary searches.
13461 *
13462 * @private
13463 * @param {Array} array The array to search.
13464 * @param {*} value The value to search for.
13465 * @param {number} fromIndex The index to search from.
13466 * @returns {number} Returns the index of the matched value, else `-1`.
13467 */
13468 function baseIndexOf(array, value, fromIndex) {
13469 if (value !== value) {
13470 return indexOfNaN(array, fromIndex);
13471 }
13472 var index = fromIndex - 1,
13473 length = array.length;
13474
13475 while (++index < length) {
13476 if (array[index] === value) {
13477 return index;
13478 }
13479 }
13480 return -1;
13481 }
13482
13483 /**
13484 * The base implementation of `_.isFunction` without support for environments
13485 * with incorrect `typeof` results.
13486 *
13487 * @private
13488 * @param {*} value The value to check.
13489 * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
13490 */
13491 function baseIsFunction(value) {
13492 // Avoid a Chakra JIT bug in compatibility modes of IE 11.
13493 // See https://github.com/jashkenas/underscore/issues/1621 for more details.
13494 return typeof value == 'function' || false;
13495 }
13496
13497 /**
13498 * Converts `value` to a string if it's not one. An empty string is returned
13499 * for `null` or `undefined` values.
13500 *
13501 * @private
13502 * @param {*} value The value to process.
13503 * @returns {string} Returns the string.
13504 */
13505 function baseToString(value) {
13506 return value == null ? '' : (value + '');
13507 }
13508
13509 /**
13510 * Used by `_.trim` and `_.trimLeft` to get the index of the first character
13511 * of `string` that is not found in `chars`.
13512 *
13513 * @private
13514 * @param {string} string The string to inspect.
13515 * @param {string} chars The characters to find.
13516 * @returns {number} Returns the index of the first character not found in `chars`.
13517 */
13518 function charsLeftIndex(string, chars) {
13519 var index = -1,
13520 length = string.length;
13521
13522 while (++index < length && chars.indexOf(string.charAt(index)) > -1) {}
13523 return index;
13524 }
13525
13526 /**
13527 * Used by `_.trim` and `_.trimRight` to get the index of the last character
13528 * of `string` that is not found in `chars`.
13529 *
13530 * @private
13531 * @param {string} string The string to inspect.
13532 * @param {string} chars The characters to find.
13533 * @returns {number} Returns the index of the last character not found in `chars`.
13534 */
13535 function charsRightIndex(string, chars) {
13536 var index = string.length;
13537
13538 while (index-- && chars.indexOf(string.charAt(index)) > -1) {}
13539 return index;
13540 }
13541
13542 /**
13543 * Used by `_.sortBy` to compare transformed elements of a collection and stable
13544 * sort them in ascending order.
13545 *
13546 * @private
13547 * @param {Object} object The object to compare.
13548 * @param {Object} other The other object to compare.
13549 * @returns {number} Returns the sort order indicator for `object`.
13550 */
13551 function compareAscending(object, other) {
13552 return baseCompareAscending(object.criteria, other.criteria) || (object.index - other.index);
13553 }
13554
13555 /**
13556 * Used by `_.sortByOrder` to compare multiple properties of a value to another
13557 * and stable sort them.
13558 *
13559 * If `orders` is unspecified, all valuess are sorted in ascending order. Otherwise,
13560 * a value is sorted in ascending order if its corresponding order is "asc", and
13561 * descending if "desc".
13562 *
13563 * @private
13564 * @param {Object} object The object to compare.
13565 * @param {Object} other The other object to compare.
13566 * @param {boolean[]} orders The order to sort by for each property.
13567 * @returns {number} Returns the sort order indicator for `object`.
13568 */
13569 function compareMultiple(object, other, orders) {
13570 var index = -1,
13571 objCriteria = object.criteria,
13572 othCriteria = other.criteria,
13573 length = objCriteria.length,
13574 ordersLength = orders.length;
13575
13576 while (++index < length) {
13577 var result = baseCompareAscending(objCriteria[index], othCriteria[index]);
13578 if (result) {
13579 if (index >= ordersLength) {
13580 return result;
13581 }
13582 var order = orders[index];
13583 return result * ((order === 'asc' || order === true) ? 1 : -1);
13584 }
13585 }
13586 // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications
13587 // that causes it, under certain circumstances, to provide the same value for
13588 // `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247
13589 // for more details.
13590 //
13591 // This also ensures a stable sort in V8 and other engines.
13592 // See https://code.google.com/p/v8/issues/detail?id=90 for more details.
13593 return object.index - other.index;
13594 }
13595
13596 /**
13597 * Used by `_.deburr` to convert latin-1 supplementary letters to basic latin letters.
13598 *
13599 * @private
13600 * @param {string} letter The matched letter to deburr.
13601 * @returns {string} Returns the deburred letter.
13602 */
13603 function deburrLetter(letter) {
13604 return deburredLetters[letter];
13605 }
13606
13607 /**
13608 * Used by `_.escape` to convert characters to HTML entities.
13609 *
13610 * @private
13611 * @param {string} chr The matched character to escape.
13612 * @returns {string} Returns the escaped character.
13613 */
13614 function escapeHtmlChar(chr) {
13615 return htmlEscapes[chr];
13616 }
13617
13618 /**
13619 * Used by `_.escapeRegExp` to escape characters for inclusion in compiled regexes.
13620 *
13621 * @private
13622 * @param {string} chr The matched character to escape.
13623 * @param {string} leadingChar The capture group for a leading character.
13624 * @param {string} whitespaceChar The capture group for a whitespace character.
13625 * @returns {string} Returns the escaped character.
13626 */
13627 function escapeRegExpChar(chr, leadingChar, whitespaceChar) {
13628 if (leadingChar) {
13629 chr = regexpEscapes[chr];
13630 } else if (whitespaceChar) {
13631 chr = stringEscapes[chr];
13632 }
13633 return '\\' + chr;
13634 }
13635
13636 /**
13637 * Used by `_.template` to escape characters for inclusion in compiled string literals.
13638 *
13639 * @private
13640 * @param {string} chr The matched character to escape.
13641 * @returns {string} Returns the escaped character.
13642 */
13643 function escapeStringChar(chr) {
13644 return '\\' + stringEscapes[chr];
13645 }
13646
13647 /**
13648 * Gets the index at which the first occurrence of `NaN` is found in `array`.
13649 *
13650 * @private
13651 * @param {Array} array The array to search.
13652 * @param {number} fromIndex The index to search from.
13653 * @param {boolean} [fromRight] Specify iterating from right to left.
13654 * @returns {number} Returns the index of the matched `NaN`, else `-1`.
13655 */
13656 function indexOfNaN(array, fromIndex, fromRight) {
13657 var length = array.length,
13658 index = fromIndex + (fromRight ? 0 : -1);
13659
13660 while ((fromRight ? index-- : ++index < length)) {
13661 var other = array[index];
13662 if (other !== other) {
13663 return index;
13664 }
13665 }
13666 return -1;
13667 }
13668
13669 /**
13670 * Checks if `value` is object-like.
13671 *
13672 * @private
13673 * @param {*} value The value to check.
13674 * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
13675 */
13676 function isObjectLike(value) {
13677 return !!value && typeof value == 'object';
13678 }
13679
13680 /**
13681 * Used by `trimmedLeftIndex` and `trimmedRightIndex` to determine if a
13682 * character code is whitespace.
13683 *
13684 * @private
13685 * @param {number} charCode The character code to inspect.
13686 * @returns {boolean} Returns `true` if `charCode` is whitespace, else `false`.
13687 */
13688 function isSpace(charCode) {
13689 return ((charCode <= 160 && (charCode >= 9 && charCode <= 13) || charCode == 32 || charCode == 160) || charCode == 5760 || charCode == 6158 ||
13690 (charCode >= 8192 && (charCode <= 8202 || charCode == 8232 || charCode == 8233 || charCode == 8239 || charCode == 8287 || charCode == 12288 || charCode == 65279)));
13691 }
13692
13693 /**
13694 * Replaces all `placeholder` elements in `array` with an internal placeholder
13695 * and returns an array of their indexes.
13696 *
13697 * @private
13698 * @param {Array} array The array to modify.
13699 * @param {*} placeholder The placeholder to replace.
13700 * @returns {Array} Returns the new array of placeholder indexes.
13701 */
13702 function replaceHolders(array, placeholder) {
13703 var index = -1,
13704 length = array.length,
13705 resIndex = -1,
13706 result = [];
13707
13708 while (++index < length) {
13709 if (array[index] === placeholder) {
13710 array[index] = PLACEHOLDER;
13711 result[++resIndex] = index;
13712 }
13713 }
13714 return result;
13715 }
13716
13717 /**
13718 * An implementation of `_.uniq` optimized for sorted arrays without support
13719 * for callback shorthands and `this` binding.
13720 *
13721 * @private
13722 * @param {Array} array The array to inspect.
13723 * @param {Function} [iteratee] The function invoked per iteration.
13724 * @returns {Array} Returns the new duplicate-value-free array.
13725 */
13726 function sortedUniq(array, iteratee) {
13727 var seen,
13728 index = -1,
13729 length = array.length,
13730 resIndex = -1,
13731 result = [];
13732
13733 while (++index < length) {
13734 var value = array[index],
13735 computed = iteratee ? iteratee(value, index, array) : value;
13736
13737 if (!index || seen !== computed) {
13738 seen = computed;
13739 result[++resIndex] = value;
13740 }
13741 }
13742 return result;
13743 }
13744
13745 /**
13746 * Used by `_.trim` and `_.trimLeft` to get the index of the first non-whitespace
13747 * character of `string`.
13748 *
13749 * @private
13750 * @param {string} string The string to inspect.
13751 * @returns {number} Returns the index of the first non-whitespace character.
13752 */
13753 function trimmedLeftIndex(string) {
13754 var index = -1,
13755 length = string.length;
13756
13757 while (++index < length && isSpace(string.charCodeAt(index))) {}
13758 return index;
13759 }
13760
13761 /**
13762 * Used by `_.trim` and `_.trimRight` to get the index of the last non-whitespace
13763 * character of `string`.
13764 *
13765 * @private
13766 * @param {string} string The string to inspect.
13767 * @returns {number} Returns the index of the last non-whitespace character.
13768 */
13769 function trimmedRightIndex(string) {
13770 var index = string.length;
13771
13772 while (index-- && isSpace(string.charCodeAt(index))) {}
13773 return index;
13774 }
13775
13776 /**
13777 * Used by `_.unescape` to convert HTML entities to characters.
13778 *
13779 * @private
13780 * @param {string} chr The matched character to unescape.
13781 * @returns {string} Returns the unescaped character.
13782 */
13783 function unescapeHtmlChar(chr) {
13784 return htmlUnescapes[chr];
13785 }
13786
13787 /*--------------------------------------------------------------------------*/
13788
13789 /**
13790 * Create a new pristine `lodash` function using the given `context` object.
13791 *
13792 * @static
13793 * @memberOf _
13794 * @category Utility
13795 * @param {Object} [context=root] The context object.
13796 * @returns {Function} Returns a new `lodash` function.
13797 * @example
13798 *
13799 * _.mixin({ 'foo': _.constant('foo') });
13800 *
13801 * var lodash = _.runInContext();
13802 * lodash.mixin({ 'bar': lodash.constant('bar') });
13803 *
13804 * _.isFunction(_.foo);
13805 * // => true
13806 * _.isFunction(_.bar);
13807 * // => false
13808 *
13809 * lodash.isFunction(lodash.foo);
13810 * // => false
13811 * lodash.isFunction(lodash.bar);
13812 * // => true
13813 *
13814 * // using `context` to mock `Date#getTime` use in `_.now`
13815 * var mock = _.runInContext({
13816 * 'Date': function() {
13817 * return { 'getTime': getTimeMock };
13818 * }
13819 * });
13820 *
13821 * // or creating a suped-up `defer` in Node.js
13822 * var defer = _.runInContext({ 'setTimeout': setImmediate }).defer;
13823 */
13824 function runInContext(context) {
13825 // Avoid issues with some ES3 environments that attempt to use values, named
13826 // after built-in constructors like `Object`, for the creation of literals.
13827 // ES5 clears this up by stating that literals must use built-in constructors.
13828 // See https://es5.github.io/#x11.1.5 for more details.
13829 context = context ? _.defaults(root.Object(), context, _.pick(root, contextProps)) : root;
13830
13831 /** Native constructor references. */
13832 var Array = context.Array,
13833 Date = context.Date,
13834 Error = context.Error,
13835 Function = context.Function,
13836 Math = context.Math,
13837 Number = context.Number,
13838 Object = context.Object,
13839 RegExp = context.RegExp,
13840 String = context.String,
13841 TypeError = context.TypeError;
13842
13843 /** Used for native method references. */
13844 var arrayProto = Array.prototype,
13845 objectProto = Object.prototype,
13846 stringProto = String.prototype;
13847
13848 /** Used to resolve the decompiled source of functions. */
13849 var fnToString = Function.prototype.toString;
13850
13851 /** Used to check objects for own properties. */
13852 var hasOwnProperty = objectProto.hasOwnProperty;
13853
13854 /** Used to generate unique IDs. */
13855 var idCounter = 0;
13856
13857 /**
13858 * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
13859 * of values.
13860 */
13861 var objToString = objectProto.toString;
13862
13863 /** Used to restore the original `_` reference in `_.noConflict`. */
13864 var oldDash = root._;
13865
13866 /** Used to detect if a method is native. */
13867 var reIsNative = RegExp('^' +
13868 fnToString.call(hasOwnProperty).replace(/[\\^$.*+?()[\]{}|]/g, '\\$&')
13869 .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
13870 );
13871
13872 /** Native method references. */
13873 var ArrayBuffer = context.ArrayBuffer,
13874 clearTimeout = context.clearTimeout,
13875 parseFloat = context.parseFloat,
13876 pow = Math.pow,
13877 propertyIsEnumerable = objectProto.propertyIsEnumerable,
13878 Set = getNative(context, 'Set'),
13879 setTimeout = context.setTimeout,
13880 splice = arrayProto.splice,
13881 Uint8Array = context.Uint8Array,
13882 WeakMap = getNative(context, 'WeakMap');
13883
13884 /* Native method references for those with the same name as other `lodash` methods. */
13885 var nativeCeil = Math.ceil,
13886 nativeCreate = getNative(Object, 'create'),
13887 nativeFloor = Math.floor,
13888 nativeIsArray = getNative(Array, 'isArray'),
13889 nativeIsFinite = context.isFinite,
13890 nativeKeys = getNative(Object, 'keys'),
13891 nativeMax = Math.max,
13892 nativeMin = Math.min,
13893 nativeNow = getNative(Date, 'now'),
13894 nativeParseInt = context.parseInt,
13895 nativeRandom = Math.random;
13896
13897 /** Used as references for `-Infinity` and `Infinity`. */
13898 var NEGATIVE_INFINITY = Number.NEGATIVE_INFINITY,
13899 POSITIVE_INFINITY = Number.POSITIVE_INFINITY;
13900
13901 /** Used as references for the maximum length and index of an array. */
13902 var MAX_ARRAY_LENGTH = 4294967295,
13903 MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1,
13904 HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1;
13905
13906 /**
13907 * Used as the [maximum length](http://ecma-international.org/ecma-262/6.0/#sec-number.max_safe_integer)
13908 * of an array-like value.
13909 */
13910 var MAX_SAFE_INTEGER = 9007199254740991;
13911
13912 /** Used to store function metadata. */
13913 var metaMap = WeakMap && new WeakMap;
13914
13915 /** Used to lookup unminified function names. */
13916 var realNames = {};
13917
13918 /*------------------------------------------------------------------------*/
13919
13920 /**
13921 * Creates a `lodash` object which wraps `value` to enable implicit chaining.
13922 * Methods that operate on and return arrays, collections, and functions can
13923 * be chained together. Methods that retrieve a single value or may return a
13924 * primitive value will automatically end the chain returning the unwrapped
13925 * value. Explicit chaining may be enabled using `_.chain`. The execution of
13926 * chained methods is lazy, that is, execution is deferred until `_#value`
13927 * is implicitly or explicitly called.
13928 *
13929 * Lazy evaluation allows several methods to support shortcut fusion. Shortcut
13930 * fusion is an optimization strategy which merge iteratee calls; this can help
13931 * to avoid the creation of intermediate data structures and greatly reduce the
13932 * number of iteratee executions.
13933 *
13934 * Chaining is supported in custom builds as long as the `_#value` method is
13935 * directly or indirectly included in the build.
13936 *
13937 * In addition to lodash methods, wrappers have `Array` and `String` methods.
13938 *
13939 * The wrapper `Array` methods are:
13940 * `concat`, `join`, `pop`, `push`, `reverse`, `shift`, `slice`, `sort`,
13941 * `splice`, and `unshift`
13942 *
13943 * The wrapper `String` methods are:
13944 * `replace` and `split`
13945 *
13946 * The wrapper methods that support shortcut fusion are:
13947 * `compact`, `drop`, `dropRight`, `dropRightWhile`, `dropWhile`, `filter`,
13948 * `first`, `initial`, `last`, `map`, `pluck`, `reject`, `rest`, `reverse`,
13949 * `slice`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, `toArray`,
13950 * and `where`
13951 *
13952 * The chainable wrapper methods are:
13953 * `after`, `ary`, `assign`, `at`, `before`, `bind`, `bindAll`, `bindKey`,
13954 * `callback`, `chain`, `chunk`, `commit`, `compact`, `concat`, `constant`,
13955 * `countBy`, `create`, `curry`, `debounce`, `defaults`, `defaultsDeep`,
13956 * `defer`, `delay`, `difference`, `drop`, `dropRight`, `dropRightWhile`,
13957 * `dropWhile`, `fill`, `filter`, `flatten`, `flattenDeep`, `flow`, `flowRight`,
13958 * `forEach`, `forEachRight`, `forIn`, `forInRight`, `forOwn`, `forOwnRight`,
13959 * `functions`, `groupBy`, `indexBy`, `initial`, `intersection`, `invert`,
13960 * `invoke`, `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`,
13961 * `matchesProperty`, `memoize`, `merge`, `method`, `methodOf`, `mixin`,
13962 * `modArgs`, `negate`, `omit`, `once`, `pairs`, `partial`, `partialRight`,
13963 * `partition`, `pick`, `plant`, `pluck`, `property`, `propertyOf`, `pull`,
13964 * `pullAt`, `push`, `range`, `rearg`, `reject`, `remove`, `rest`, `restParam`,
13965 * `reverse`, `set`, `shuffle`, `slice`, `sort`, `sortBy`, `sortByAll`,
13966 * `sortByOrder`, `splice`, `spread`, `take`, `takeRight`, `takeRightWhile`,
13967 * `takeWhile`, `tap`, `throttle`, `thru`, `times`, `toArray`, `toPlainObject`,
13968 * `transform`, `union`, `uniq`, `unshift`, `unzip`, `unzipWith`, `values`,
13969 * `valuesIn`, `where`, `without`, `wrap`, `xor`, `zip`, `zipObject`, `zipWith`
13970 *
13971 * The wrapper methods that are **not** chainable by default are:
13972 * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clone`, `cloneDeep`,
13973 * `deburr`, `endsWith`, `escape`, `escapeRegExp`, `every`, `find`, `findIndex`,
13974 * `findKey`, `findLast`, `findLastIndex`, `findLastKey`, `findWhere`, `first`,
13975 * `floor`, `get`, `gt`, `gte`, `has`, `identity`, `includes`, `indexOf`,
13976 * `inRange`, `isArguments`, `isArray`, `isBoolean`, `isDate`, `isElement`,
13977 * `isEmpty`, `isEqual`, `isError`, `isFinite` `isFunction`, `isMatch`,
13978 * `isNative`, `isNaN`, `isNull`, `isNumber`, `isObject`, `isPlainObject`,
13979 * `isRegExp`, `isString`, `isUndefined`, `isTypedArray`, `join`, `kebabCase`,
13980 * `last`, `lastIndexOf`, `lt`, `lte`, `max`, `min`, `noConflict`, `noop`,
13981 * `now`, `pad`, `padLeft`, `padRight`, `parseInt`, `pop`, `random`, `reduce`,
13982 * `reduceRight`, `repeat`, `result`, `round`, `runInContext`, `shift`, `size`,
13983 * `snakeCase`, `some`, `sortedIndex`, `sortedLastIndex`, `startCase`,
13984 * `startsWith`, `sum`, `template`, `trim`, `trimLeft`, `trimRight`, `trunc`,
13985 * `unescape`, `uniqueId`, `value`, and `words`
13986 *
13987 * The wrapper method `sample` will return a wrapped value when `n` is provided,
13988 * otherwise an unwrapped value is returned.
13989 *
13990 * @name _
13991 * @constructor
13992 * @category Chain
13993 * @param {*} value The value to wrap in a `lodash` instance.
13994 * @returns {Object} Returns the new `lodash` wrapper instance.
13995 * @example
13996 *
13997 * var wrapped = _([1, 2, 3]);
13998 *
13999 * // returns an unwrapped value
14000 * wrapped.reduce(function(total, n) {
14001 * return total + n;
14002 * });
14003 * // => 6
14004 *
14005 * // returns a wrapped value
14006 * var squares = wrapped.map(function(n) {
14007 * return n * n;
14008 * });
14009 *
14010 * _.isArray(squares);
14011 * // => false
14012 *
14013 * _.isArray(squares.value());
14014 * // => true
14015 */
14016 function lodash(value) {
14017 if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) {
14018 if (value instanceof LodashWrapper) {
14019 return value;
14020 }
14021 if (hasOwnProperty.call(value, '__chain__') && hasOwnProperty.call(value, '__wrapped__')) {
14022 return wrapperClone(value);
14023 }
14024 }
14025 return new LodashWrapper(value);
14026 }
14027
14028 /**
14029 * The function whose prototype all chaining wrappers inherit from.
14030 *
14031 * @private
14032 */
14033 function baseLodash() {
14034 // No operation performed.
14035 }
14036
14037 /**
14038 * The base constructor for creating `lodash` wrapper objects.
14039 *
14040 * @private
14041 * @param {*} value The value to wrap.
14042 * @param {boolean} [chainAll] Enable chaining for all wrapper methods.
14043 * @param {Array} [actions=[]] Actions to peform to resolve the unwrapped value.
14044 */
14045 function LodashWrapper(value, chainAll, actions) {
14046 this.__wrapped__ = value;
14047 this.__actions__ = actions || [];
14048 this.__chain__ = !!chainAll;
14049 }
14050
14051 /**
14052 * An object environment feature flags.
14053 *
14054 * @static
14055 * @memberOf _
14056 * @type Object
14057 */
14058 var support = lodash.support = {};
14059
14060 /**
14061 * By default, the template delimiters used by lodash are like those in
14062 * embedded Ruby (ERB). Change the following template settings to use
14063 * alternative delimiters.
14064 *
14065 * @static
14066 * @memberOf _
14067 * @type Object
14068 */
14069 lodash.templateSettings = {
14070
14071 /**
14072 * Used to detect `data` property values to be HTML-escaped.
14073 *
14074 * @memberOf _.templateSettings
14075 * @type RegExp
14076 */
14077 'escape': reEscape,
14078
14079 /**
14080 * Used to detect code to be evaluated.
14081 *
14082 * @memberOf _.templateSettings
14083 * @type RegExp
14084 */
14085 'evaluate': reEvaluate,
14086
14087 /**
14088 * Used to detect `data` property values to inject.
14089 *
14090 * @memberOf _.templateSettings
14091 * @type RegExp
14092 */
14093 'interpolate': reInterpolate,
14094
14095 /**
14096 * Used to reference the data object in the template text.
14097 *
14098 * @memberOf _.templateSettings
14099 * @type string
14100 */
14101 'variable': '',
14102
14103 /**
14104 * Used to import variables into the compiled template.
14105 *
14106 * @memberOf _.templateSettings
14107 * @type Object
14108 */
14109 'imports': {
14110
14111 /**
14112 * A reference to the `lodash` function.
14113 *
14114 * @memberOf _.templateSettings.imports
14115 * @type Function
14116 */
14117 '_': lodash
14118 }
14119 };
14120
14121 /*------------------------------------------------------------------------*/
14122
14123 /**
14124 * Creates a lazy wrapper object which wraps `value` to enable lazy evaluation.
14125 *
14126 * @private
14127 * @param {*} value The value to wrap.
14128 */
14129 function LazyWrapper(value) {
14130 this.__wrapped__ = value;
14131 this.__actions__ = [];
14132 this.__dir__ = 1;
14133 this.__filtered__ = false;
14134 this.__iteratees__ = [];
14135 this.__takeCount__ = POSITIVE_INFINITY;
14136 this.__views__ = [];
14137 }
14138
14139 /**
14140 * Creates a clone of the lazy wrapper object.
14141 *
14142 * @private
14143 * @name clone
14144 * @memberOf LazyWrapper
14145 * @returns {Object} Returns the cloned `LazyWrapper` object.
14146 */
14147 function lazyClone() {
14148 var result = new LazyWrapper(this.__wrapped__);
14149 result.__actions__ = arrayCopy(this.__actions__);
14150 result.__dir__ = this.__dir__;
14151 result.__filtered__ = this.__filtered__;
14152 result.__iteratees__ = arrayCopy(this.__iteratees__);
14153 result.__takeCount__ = this.__takeCount__;
14154 result.__views__ = arrayCopy(this.__views__);
14155 return result;
14156 }
14157
14158 /**
14159 * Reverses the direction of lazy iteration.
14160 *
14161 * @private
14162 * @name reverse
14163 * @memberOf LazyWrapper
14164 * @returns {Object} Returns the new reversed `LazyWrapper` object.
14165 */
14166 function lazyReverse() {
14167 if (this.__filtered__) {
14168 var result = new LazyWrapper(this);
14169 result.__dir__ = -1;
14170 result.__filtered__ = true;
14171 } else {
14172 result = this.clone();
14173 result.__dir__ *= -1;
14174 }
14175 return result;
14176 }
14177
14178 /**
14179 * Extracts the unwrapped value from its lazy wrapper.
14180 *
14181 * @private
14182 * @name value
14183 * @memberOf LazyWrapper
14184 * @returns {*} Returns the unwrapped value.
14185 */
14186 function lazyValue() {
14187 var array = this.__wrapped__.value(),
14188 dir = this.__dir__,
14189 isArr = isArray(array),
14190 isRight = dir < 0,
14191 arrLength = isArr ? array.length : 0,
14192 view = getView(0, arrLength, this.__views__),
14193 start = view.start,
14194 end = view.end,
14195 length = end - start,
14196 index = isRight ? end : (start - 1),
14197 iteratees = this.__iteratees__,
14198 iterLength = iteratees.length,
14199 resIndex = 0,
14200 takeCount = nativeMin(length, this.__takeCount__);
14201
14202 if (!isArr || arrLength < LARGE_ARRAY_SIZE || (arrLength == length && takeCount == length)) {
14203 return baseWrapperValue((isRight && isArr) ? array.reverse() : array, this.__actions__);
14204 }
14205 var result = [];
14206
14207 outer:
14208 while (length-- && resIndex < takeCount) {
14209 index += dir;
14210
14211 var iterIndex = -1,
14212 value = array[index];
14213
14214 while (++iterIndex < iterLength) {
14215 var data = iteratees[iterIndex],
14216 iteratee = data.iteratee,
14217 type = data.type,
14218 computed = iteratee(value);
14219
14220 if (type == LAZY_MAP_FLAG) {
14221 value = computed;
14222 } else if (!computed) {
14223 if (type == LAZY_FILTER_FLAG) {
14224 continue outer;
14225 } else {
14226 break outer;
14227 }
14228 }
14229 }
14230 result[resIndex++] = value;
14231 }
14232 return result;
14233 }
14234
14235 /*------------------------------------------------------------------------*/
14236
14237 /**
14238 * Creates a cache object to store key/value pairs.
14239 *
14240 * @private
14241 * @static
14242 * @name Cache
14243 * @memberOf _.memoize
14244 */
14245 function MapCache() {
14246 this.__data__ = {};
14247 }
14248
14249 /**
14250 * Removes `key` and its value from the cache.
14251 *
14252 * @private
14253 * @name delete
14254 * @memberOf _.memoize.Cache
14255 * @param {string} key The key of the value to remove.
14256 * @returns {boolean} Returns `true` if the entry was removed successfully, else `false`.
14257 */
14258 function mapDelete(key) {
14259 return this.has(key) && delete this.__data__[key];
14260 }
14261
14262 /**
14263 * Gets the cached value for `key`.
14264 *
14265 * @private
14266 * @name get
14267 * @memberOf _.memoize.Cache
14268 * @param {string} key The key of the value to get.
14269 * @returns {*} Returns the cached value.
14270 */
14271 function mapGet(key) {
14272 return key == '__proto__' ? undefined : this.__data__[key];
14273 }
14274
14275 /**
14276 * Checks if a cached value for `key` exists.
14277 *
14278 * @private
14279 * @name has
14280 * @memberOf _.memoize.Cache
14281 * @param {string} key The key of the entry to check.
14282 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
14283 */
14284 function mapHas(key) {
14285 return key != '__proto__' && hasOwnProperty.call(this.__data__, key);
14286 }
14287
14288 /**
14289 * Sets `value` to `key` of the cache.
14290 *
14291 * @private
14292 * @name set
14293 * @memberOf _.memoize.Cache
14294 * @param {string} key The key of the value to cache.
14295 * @param {*} value The value to cache.
14296 * @returns {Object} Returns the cache object.
14297 */
14298 function mapSet(key, value) {
14299 if (key != '__proto__') {
14300 this.__data__[key] = value;
14301 }
14302 return this;
14303 }
14304
14305 /*------------------------------------------------------------------------*/
14306
14307 /**
14308 *
14309 * Creates a cache object to store unique values.
14310 *
14311 * @private
14312 * @param {Array} [values] The values to cache.
14313 */
14314 function SetCache(values) {
14315 var length = values ? values.length : 0;
14316
14317 this.data = { 'hash': nativeCreate(null), 'set': new Set };
14318 while (length--) {
14319 this.push(values[length]);
14320 }
14321 }
14322
14323 /**
14324 * Checks if `value` is in `cache` mimicking the return signature of
14325 * `_.indexOf` by returning `0` if the value is found, else `-1`.
14326 *
14327 * @private
14328 * @param {Object} cache The cache to search.
14329 * @param {*} value The value to search for.
14330 * @returns {number} Returns `0` if `value` is found, else `-1`.
14331 */
14332 function cacheIndexOf(cache, value) {
14333 var data = cache.data,
14334 result = (typeof value == 'string' || isObject(value)) ? data.set.has(value) : data.hash[value];
14335
14336 return result ? 0 : -1;
14337 }
14338
14339 /**
14340 * Adds `value` to the cache.
14341 *
14342 * @private
14343 * @name push
14344 * @memberOf SetCache
14345 * @param {*} value The value to cache.
14346 */
14347 function cachePush(value) {
14348 var data = this.data;
14349 if (typeof value == 'string' || isObject(value)) {
14350 data.set.add(value);
14351 } else {
14352 data.hash[value] = true;
14353 }
14354 }
14355
14356 /*------------------------------------------------------------------------*/
14357
14358 /**
14359 * Creates a new array joining `array` with `other`.
14360 *
14361 * @private
14362 * @param {Array} array The array to join.
14363 * @param {Array} other The other array to join.
14364 * @returns {Array} Returns the new concatenated array.
14365 */
14366 function arrayConcat(array, other) {
14367 var index = -1,
14368 length = array.length,
14369 othIndex = -1,
14370 othLength = other.length,
14371 result = Array(length + othLength);
14372
14373 while (++index < length) {
14374 result[index] = array[index];
14375 }
14376 while (++othIndex < othLength) {
14377 result[index++] = other[othIndex];
14378 }
14379 return result;
14380 }
14381
14382 /**
14383 * Copies the values of `source` to `array`.
14384 *
14385 * @private
14386 * @param {Array} source The array to copy values from.
14387 * @param {Array} [array=[]] The array to copy values to.
14388 * @returns {Array} Returns `array`.
14389 */
14390 function arrayCopy(source, array) {
14391 var index = -1,
14392 length = source.length;
14393
14394 array || (array = Array(length));
14395 while (++index < length) {
14396 array[index] = source[index];
14397 }
14398 return array;
14399 }
14400
14401 /**
14402 * A specialized version of `_.forEach` for arrays without support for callback
14403 * shorthands and `this` binding.
14404 *
14405 * @private
14406 * @param {Array} array The array to iterate over.
14407 * @param {Function} iteratee The function invoked per iteration.
14408 * @returns {Array} Returns `array`.
14409 */
14410 function arrayEach(array, iteratee) {
14411 var index = -1,
14412 length = array.length;
14413
14414 while (++index < length) {
14415 if (iteratee(array[index], index, array) === false) {
14416 break;
14417 }
14418 }
14419 return array;
14420 }
14421
14422 /**
14423 * A specialized version of `_.forEachRight` for arrays without support for
14424 * callback shorthands and `this` binding.
14425 *
14426 * @private
14427 * @param {Array} array The array to iterate over.
14428 * @param {Function} iteratee The function invoked per iteration.
14429 * @returns {Array} Returns `array`.
14430 */
14431 function arrayEachRight(array, iteratee) {
14432 var length = array.length;
14433
14434 while (length--) {
14435 if (iteratee(array[length], length, array) === false) {
14436 break;
14437 }
14438 }
14439 return array;
14440 }
14441
14442 /**
14443 * A specialized version of `_.every` for arrays without support for callback
14444 * shorthands and `this` binding.
14445 *
14446 * @private
14447 * @param {Array} array The array to iterate over.
14448 * @param {Function} predicate The function invoked per iteration.
14449 * @returns {boolean} Returns `true` if all elements pass the predicate check,
14450 * else `false`.
14451 */
14452 function arrayEvery(array, predicate) {
14453 var index = -1,
14454 length = array.length;
14455
14456 while (++index < length) {
14457 if (!predicate(array[index], index, array)) {
14458 return false;
14459 }
14460 }
14461 return true;
14462 }
14463
14464 /**
14465 * A specialized version of `baseExtremum` for arrays which invokes `iteratee`
14466 * with one argument: (value).
14467 *
14468 * @private
14469 * @param {Array} array The array to iterate over.
14470 * @param {Function} iteratee The function invoked per iteration.
14471 * @param {Function} comparator The function used to compare values.
14472 * @param {*} exValue The initial extremum value.
14473 * @returns {*} Returns the extremum value.
14474 */
14475 function arrayExtremum(array, iteratee, comparator, exValue) {
14476 var index = -1,
14477 length = array.length,
14478 computed = exValue,
14479 result = computed;
14480
14481 while (++index < length) {
14482 var value = array[index],
14483 current = +iteratee(value);
14484
14485 if (comparator(current, computed)) {
14486 computed = current;
14487 result = value;
14488 }
14489 }
14490 return result;
14491 }
14492
14493 /**
14494 * A specialized version of `_.filter` for arrays without support for callback
14495 * shorthands and `this` binding.
14496 *
14497 * @private
14498 * @param {Array} array The array to iterate over.
14499 * @param {Function} predicate The function invoked per iteration.
14500 * @returns {Array} Returns the new filtered array.
14501 */
14502 function arrayFilter(array, predicate) {
14503 var index = -1,
14504 length = array.length,
14505 resIndex = -1,
14506 result = [];
14507
14508 while (++index < length) {
14509 var value = array[index];
14510 if (predicate(value, index, array)) {
14511 result[++resIndex] = value;
14512 }
14513 }
14514 return result;
14515 }
14516
14517 /**
14518 * A specialized version of `_.map` for arrays without support for callback
14519 * shorthands and `this` binding.
14520 *
14521 * @private
14522 * @param {Array} array The array to iterate over.
14523 * @param {Function} iteratee The function invoked per iteration.
14524 * @returns {Array} Returns the new mapped array.
14525 */
14526 function arrayMap(array, iteratee) {
14527 var index = -1,
14528 length = array.length,
14529 result = Array(length);
14530
14531 while (++index < length) {
14532 result[index] = iteratee(array[index], index, array);
14533 }
14534 return result;
14535 }
14536
14537 /**
14538 * Appends the elements of `values` to `array`.
14539 *
14540 * @private
14541 * @param {Array} array The array to modify.
14542 * @param {Array} values The values to append.
14543 * @returns {Array} Returns `array`.
14544 */
14545 function arrayPush(array, values) {
14546 var index = -1,
14547 length = values.length,
14548 offset = array.length;
14549
14550 while (++index < length) {
14551 array[offset + index] = values[index];
14552 }
14553 return array;
14554 }
14555
14556 /**
14557 * A specialized version of `_.reduce` for arrays without support for callback
14558 * shorthands and `this` binding.
14559 *
14560 * @private
14561 * @param {Array} array The array to iterate over.
14562 * @param {Function} iteratee The function invoked per iteration.
14563 * @param {*} [accumulator] The initial value.
14564 * @param {boolean} [initFromArray] Specify using the first element of `array`
14565 * as the initial value.
14566 * @returns {*} Returns the accumulated value.
14567 */
14568 function arrayReduce(array, iteratee, accumulator, initFromArray) {
14569 var index = -1,
14570 length = array.length;
14571
14572 if (initFromArray && length) {
14573 accumulator = array[++index];
14574 }
14575 while (++index < length) {
14576 accumulator = iteratee(accumulator, array[index], index, array);
14577 }
14578 return accumulator;
14579 }
14580
14581 /**
14582 * A specialized version of `_.reduceRight` for arrays without support for
14583 * callback shorthands and `this` binding.
14584 *
14585 * @private
14586 * @param {Array} array The array to iterate over.
14587 * @param {Function} iteratee The function invoked per iteration.
14588 * @param {*} [accumulator] The initial value.
14589 * @param {boolean} [initFromArray] Specify using the last element of `array`
14590 * as the initial value.
14591 * @returns {*} Returns the accumulated value.
14592 */
14593 function arrayReduceRight(array, iteratee, accumulator, initFromArray) {
14594 var length = array.length;
14595 if (initFromArray && length) {
14596 accumulator = array[--length];
14597 }
14598 while (length--) {
14599 accumulator = iteratee(accumulator, array[length], length, array);
14600 }
14601 return accumulator;
14602 }
14603
14604 /**
14605 * A specialized version of `_.some` for arrays without support for callback
14606 * shorthands and `this` binding.
14607 *
14608 * @private
14609 * @param {Array} array The array to iterate over.
14610 * @param {Function} predicate The function invoked per iteration.
14611 * @returns {boolean} Returns `true` if any element passes the predicate check,
14612 * else `false`.
14613 */
14614 function arraySome(array, predicate) {
14615 var index = -1,
14616 length = array.length;
14617
14618 while (++index < length) {
14619 if (predicate(array[index], index, array)) {
14620 return true;
14621 }
14622 }
14623 return false;
14624 }
14625
14626 /**
14627 * A specialized version of `_.sum` for arrays without support for callback
14628 * shorthands and `this` binding..
14629 *
14630 * @private
14631 * @param {Array} array The array to iterate over.
14632 * @param {Function} iteratee The function invoked per iteration.
14633 * @returns {number} Returns the sum.
14634 */
14635 function arraySum(array, iteratee) {
14636 var length = array.length,
14637 result = 0;
14638
14639 while (length--) {
14640 result += +iteratee(array[length]) || 0;
14641 }
14642 return result;
14643 }
14644
14645 /**
14646 * Used by `_.defaults` to customize its `_.assign` use.
14647 *
14648 * @private
14649 * @param {*} objectValue The destination object property value.
14650 * @param {*} sourceValue The source object property value.
14651 * @returns {*} Returns the value to assign to the destination object.
14652 */
14653 function assignDefaults(objectValue, sourceValue) {
14654 return objectValue === undefined ? sourceValue : objectValue;
14655 }
14656
14657 /**
14658 * Used by `_.template` to customize its `_.assign` use.
14659 *
14660 * **Note:** This function is like `assignDefaults` except that it ignores
14661 * inherited property values when checking if a property is `undefined`.
14662 *
14663 * @private
14664 * @param {*} objectValue The destination object property value.
14665 * @param {*} sourceValue The source object property value.
14666 * @param {string} key The key associated with the object and source values.
14667 * @param {Object} object The destination object.
14668 * @returns {*} Returns the value to assign to the destination object.
14669 */
14670 function assignOwnDefaults(objectValue, sourceValue, key, object) {
14671 return (objectValue === undefined || !hasOwnProperty.call(object, key))
14672 ? sourceValue
14673 : objectValue;
14674 }
14675
14676 /**
14677 * A specialized version of `_.assign` for customizing assigned values without
14678 * support for argument juggling, multiple sources, and `this` binding `customizer`
14679 * functions.
14680 *
14681 * @private
14682 * @param {Object} object The destination object.
14683 * @param {Object} source The source object.
14684 * @param {Function} customizer The function to customize assigned values.
14685 * @returns {Object} Returns `object`.
14686 */
14687 function assignWith(object, source, customizer) {
14688 var index = -1,
14689 props = keys(source),
14690 length = props.length;
14691
14692 while (++index < length) {
14693 var key = props[index],
14694 value = object[key],
14695 result = customizer(value, source[key], key, object, source);
14696
14697 if ((result === result ? (result !== value) : (value === value)) ||
14698 (value === undefined && !(key in object))) {
14699 object[key] = result;
14700 }
14701 }
14702 return object;
14703 }
14704
14705 /**
14706 * The base implementation of `_.assign` without support for argument juggling,
14707 * multiple sources, and `customizer` functions.
14708 *
14709 * @private
14710 * @param {Object} object The destination object.
14711 * @param {Object} source The source object.
14712 * @returns {Object} Returns `object`.
14713 */
14714 function baseAssign(object, source) {
14715 return source == null
14716 ? object
14717 : baseCopy(source, keys(source), object);
14718 }
14719
14720 /**
14721 * The base implementation of `_.at` without support for string collections
14722 * and individual key arguments.
14723 *
14724 * @private
14725 * @param {Array|Object} collection The collection to iterate over.
14726 * @param {number[]|string[]} props The property names or indexes of elements to pick.
14727 * @returns {Array} Returns the new array of picked elements.
14728 */
14729 function baseAt(collection, props) {
14730 var index = -1,
14731 isNil = collection == null,
14732 isArr = !isNil && isArrayLike(collection),
14733 length = isArr ? collection.length : 0,
14734 propsLength = props.length,
14735 result = Array(propsLength);
14736
14737 while(++index < propsLength) {
14738 var key = props[index];
14739 if (isArr) {
14740 result[index] = isIndex(key, length) ? collection[key] : undefined;
14741 } else {
14742 result[index] = isNil ? undefined : collection[key];
14743 }
14744 }
14745 return result;
14746 }
14747
14748 /**
14749 * Copies properties of `source` to `object`.
14750 *
14751 * @private
14752 * @param {Object} source The object to copy properties from.
14753 * @param {Array} props The property names to copy.
14754 * @param {Object} [object={}] The object to copy properties to.
14755 * @returns {Object} Returns `object`.
14756 */
14757 function baseCopy(source, props, object) {
14758 object || (object = {});
14759
14760 var index = -1,
14761 length = props.length;
14762
14763 while (++index < length) {
14764 var key = props[index];
14765 object[key] = source[key];
14766 }
14767 return object;
14768 }
14769
14770 /**
14771 * The base implementation of `_.callback` which supports specifying the
14772 * number of arguments to provide to `func`.
14773 *
14774 * @private
14775 * @param {*} [func=_.identity] The value to convert to a callback.
14776 * @param {*} [thisArg] The `this` binding of `func`.
14777 * @param {number} [argCount] The number of arguments to provide to `func`.
14778 * @returns {Function} Returns the callback.
14779 */
14780 function baseCallback(func, thisArg, argCount) {
14781 var type = typeof func;
14782 if (type == 'function') {
14783 return thisArg === undefined
14784 ? func
14785 : bindCallback(func, thisArg, argCount);
14786 }
14787 if (func == null) {
14788 return identity;
14789 }
14790 if (type == 'object') {
14791 return baseMatches(func);
14792 }
14793 return thisArg === undefined
14794 ? property(func)
14795 : baseMatchesProperty(func, thisArg);
14796 }
14797
14798 /**
14799 * The base implementation of `_.clone` without support for argument juggling
14800 * and `this` binding `customizer` functions.
14801 *
14802 * @private
14803 * @param {*} value The value to clone.
14804 * @param {boolean} [isDeep] Specify a deep clone.
14805 * @param {Function} [customizer] The function to customize cloning values.
14806 * @param {string} [key] The key of `value`.
14807 * @param {Object} [object] The object `value` belongs to.
14808 * @param {Array} [stackA=[]] Tracks traversed source objects.
14809 * @param {Array} [stackB=[]] Associates clones with source counterparts.
14810 * @returns {*} Returns the cloned value.
14811 */
14812 function baseClone(value, isDeep, customizer, key, object, stackA, stackB) {
14813 var result;
14814 if (customizer) {
14815 result = object ? customizer(value, key, object) : customizer(value);
14816 }
14817 if (result !== undefined) {
14818 return result;
14819 }
14820 if (!isObject(value)) {
14821 return value;
14822 }
14823 var isArr = isArray(value);
14824 if (isArr) {
14825 result = initCloneArray(value);
14826 if (!isDeep) {
14827 return arrayCopy(value, result);
14828 }
14829 } else {
14830 var tag = objToString.call(value),
14831 isFunc = tag == funcTag;
14832
14833 if (tag == objectTag || tag == argsTag || (isFunc && !object)) {
14834 result = initCloneObject(isFunc ? {} : value);
14835 if (!isDeep) {
14836 return baseAssign(result, value);
14837 }
14838 } else {
14839 return cloneableTags[tag]
14840 ? initCloneByTag(value, tag, isDeep)
14841 : (object ? value : {});
14842 }
14843 }
14844 // Check for circular references and return its corresponding clone.
14845 stackA || (stackA = []);
14846 stackB || (stackB = []);
14847
14848 var length = stackA.length;
14849 while (length--) {
14850 if (stackA[length] == value) {
14851 return stackB[length];
14852 }
14853 }
14854 // Add the source value to the stack of traversed objects and associate it with its clone.
14855 stackA.push(value);
14856 stackB.push(result);
14857
14858 // Recursively populate clone (susceptible to call stack limits).
14859 (isArr ? arrayEach : baseForOwn)(value, function(subValue, key) {
14860 result[key] = baseClone(subValue, isDeep, customizer, key, value, stackA, stackB);
14861 });
14862 return result;
14863 }
14864
14865 /**
14866 * The base implementation of `_.create` without support for assigning
14867 * properties to the created object.
14868 *
14869 * @private
14870 * @param {Object} prototype The object to inherit from.
14871 * @returns {Object} Returns the new object.
14872 */
14873 var baseCreate = (function() {
14874 function object() {}
14875 return function(prototype) {
14876 if (isObject(prototype)) {
14877 object.prototype = prototype;
14878 var result = new object;
14879 object.prototype = undefined;
14880 }
14881 return result || {};
14882 };
14883 }());
14884
14885 /**
14886 * The base implementation of `_.delay` and `_.defer` which accepts an index
14887 * of where to slice the arguments to provide to `func`.
14888 *
14889 * @private
14890 * @param {Function} func The function to delay.
14891 * @param {number} wait The number of milliseconds to delay invocation.
14892 * @param {Object} args The arguments provide to `func`.
14893 * @returns {number} Returns the timer id.
14894 */
14895 function baseDelay(func, wait, args) {
14896 if (typeof func != 'function') {
14897 throw new TypeError(FUNC_ERROR_TEXT);
14898 }
14899 return setTimeout(function() { func.apply(undefined, args); }, wait);
14900 }
14901
14902 /**
14903 * The base implementation of `_.difference` which accepts a single array
14904 * of values to exclude.
14905 *
14906 * @private
14907 * @param {Array} array The array to inspect.
14908 * @param {Array} values The values to exclude.
14909 * @returns {Array} Returns the new array of filtered values.
14910 */
14911 function baseDifference(array, values) {
14912 var length = array ? array.length : 0,
14913 result = [];
14914
14915 if (!length) {
14916 return result;
14917 }
14918 var index = -1,
14919 indexOf = getIndexOf(),
14920 isCommon = indexOf == baseIndexOf,
14921 cache = (isCommon && values.length >= LARGE_ARRAY_SIZE) ? createCache(values) : null,
14922 valuesLength = values.length;
14923
14924 if (cache) {
14925 indexOf = cacheIndexOf;
14926 isCommon = false;
14927 values = cache;
14928 }
14929 outer:
14930 while (++index < length) {
14931 var value = array[index];
14932
14933 if (isCommon && value === value) {
14934 var valuesIndex = valuesLength;
14935 while (valuesIndex--) {
14936 if (values[valuesIndex] === value) {
14937 continue outer;
14938 }
14939 }
14940 result.push(value);
14941 }
14942 else if (indexOf(values, value, 0) < 0) {
14943 result.push(value);
14944 }
14945 }
14946 return result;
14947 }
14948
14949 /**
14950 * The base implementation of `_.forEach` without support for callback
14951 * shorthands and `this` binding.
14952 *
14953 * @private
14954 * @param {Array|Object|string} collection The collection to iterate over.
14955 * @param {Function} iteratee The function invoked per iteration.
14956 * @returns {Array|Object|string} Returns `collection`.
14957 */
14958 var baseEach = createBaseEach(baseForOwn);
14959
14960 /**
14961 * The base implementation of `_.forEachRight` without support for callback
14962 * shorthands and `this` binding.
14963 *
14964 * @private
14965 * @param {Array|Object|string} collection The collection to iterate over.
14966 * @param {Function} iteratee The function invoked per iteration.
14967 * @returns {Array|Object|string} Returns `collection`.
14968 */
14969 var baseEachRight = createBaseEach(baseForOwnRight, true);
14970
14971 /**
14972 * The base implementation of `_.every` without support for callback
14973 * shorthands and `this` binding.
14974 *
14975 * @private
14976 * @param {Array|Object|string} collection The collection to iterate over.
14977 * @param {Function} predicate The function invoked per iteration.
14978 * @returns {boolean} Returns `true` if all elements pass the predicate check,
14979 * else `false`
14980 */
14981 function baseEvery(collection, predicate) {
14982 var result = true;
14983 baseEach(collection, function(value, index, collection) {
14984 result = !!predicate(value, index, collection);
14985 return result;
14986 });
14987 return result;
14988 }
14989
14990 /**
14991 * Gets the extremum value of `collection` invoking `iteratee` for each value
14992 * in `collection` to generate the criterion by which the value is ranked.
14993 * The `iteratee` is invoked with three arguments: (value, index|key, collection).
14994 *
14995 * @private
14996 * @param {Array|Object|string} collection The collection to iterate over.
14997 * @param {Function} iteratee The function invoked per iteration.
14998 * @param {Function} comparator The function used to compare values.
14999 * @param {*} exValue The initial extremum value.
15000 * @returns {*} Returns the extremum value.
15001 */
15002 function baseExtremum(collection, iteratee, comparator, exValue) {
15003 var computed = exValue,
15004 result = computed;
15005
15006 baseEach(collection, function(value, index, collection) {
15007 var current = +iteratee(value, index, collection);
15008 if (comparator(current, computed) || (current === exValue && current === result)) {
15009 computed = current;
15010 result = value;
15011 }
15012 });
15013 return result;
15014 }
15015
15016 /**
15017 * The base implementation of `_.fill` without an iteratee call guard.
15018 *
15019 * @private
15020 * @param {Array} array The array to fill.
15021 * @param {*} value The value to fill `array` with.
15022 * @param {number} [start=0] The start position.
15023 * @param {number} [end=array.length] The end position.
15024 * @returns {Array} Returns `array`.
15025 */
15026 function baseFill(array, value, start, end) {
15027 var length = array.length;
15028
15029 start = start == null ? 0 : (+start || 0);
15030 if (start < 0) {
15031 start = -start > length ? 0 : (length + start);
15032 }
15033 end = (end === undefined || end > length) ? length : (+end || 0);
15034 if (end < 0) {
15035 end += length;
15036 }
15037 length = start > end ? 0 : (end >>> 0);
15038 start >>>= 0;
15039
15040 while (start < length) {
15041 array[start++] = value;
15042 }
15043 return array;
15044 }
15045
15046 /**
15047 * The base implementation of `_.filter` without support for callback
15048 * shorthands and `this` binding.
15049 *
15050 * @private
15051 * @param {Array|Object|string} collection The collection to iterate over.
15052 * @param {Function} predicate The function invoked per iteration.
15053 * @returns {Array} Returns the new filtered array.
15054 */
15055 function baseFilter(collection, predicate) {
15056 var result = [];
15057 baseEach(collection, function(value, index, collection) {
15058 if (predicate(value, index, collection)) {
15059 result.push(value);
15060 }
15061 });
15062 return result;
15063 }
15064
15065 /**
15066 * The base implementation of `_.find`, `_.findLast`, `_.findKey`, and `_.findLastKey`,
15067 * without support for callback shorthands and `this` binding, which iterates
15068 * over `collection` using the provided `eachFunc`.
15069 *
15070 * @private
15071 * @param {Array|Object|string} collection The collection to search.
15072 * @param {Function} predicate The function invoked per iteration.
15073 * @param {Function} eachFunc The function to iterate over `collection`.
15074 * @param {boolean} [retKey] Specify returning the key of the found element
15075 * instead of the element itself.
15076 * @returns {*} Returns the found element or its key, else `undefined`.
15077 */
15078 function baseFind(collection, predicate, eachFunc, retKey) {
15079 var result;
15080 eachFunc(collection, function(value, key, collection) {
15081 if (predicate(value, key, collection)) {
15082 result = retKey ? key : value;
15083 return false;
15084 }
15085 });
15086 return result;
15087 }
15088
15089 /**
15090 * The base implementation of `_.flatten` with added support for restricting
15091 * flattening and specifying the start index.
15092 *
15093 * @private
15094 * @param {Array} array The array to flatten.
15095 * @param {boolean} [isDeep] Specify a deep flatten.
15096 * @param {boolean} [isStrict] Restrict flattening to arrays-like objects.
15097 * @param {Array} [result=[]] The initial result value.
15098 * @returns {Array} Returns the new flattened array.
15099 */
15100 function baseFlatten(array, isDeep, isStrict, result) {
15101 result || (result = []);
15102
15103 var index = -1,
15104 length = array.length;
15105
15106 while (++index < length) {
15107 var value = array[index];
15108 if (isObjectLike(value) && isArrayLike(value) &&
15109 (isStrict || isArray(value) || isArguments(value))) {
15110 if (isDeep) {
15111 // Recursively flatten arrays (susceptible to call stack limits).
15112 baseFlatten(value, isDeep, isStrict, result);
15113 } else {
15114 arrayPush(result, value);
15115 }
15116 } else if (!isStrict) {
15117 result[result.length] = value;
15118 }
15119 }
15120 return result;
15121 }
15122
15123 /**
15124 * The base implementation of `baseForIn` and `baseForOwn` which iterates
15125 * over `object` properties returned by `keysFunc` invoking `iteratee` for
15126 * each property. Iteratee functions may exit iteration early by explicitly
15127 * returning `false`.
15128 *
15129 * @private
15130 * @param {Object} object The object to iterate over.
15131 * @param {Function} iteratee The function invoked per iteration.
15132 * @param {Function} keysFunc The function to get the keys of `object`.
15133 * @returns {Object} Returns `object`.
15134 */
15135 var baseFor = createBaseFor();
15136
15137 /**
15138 * This function is like `baseFor` except that it iterates over properties
15139 * in the opposite order.
15140 *
15141 * @private
15142 * @param {Object} object The object to iterate over.
15143 * @param {Function} iteratee The function invoked per iteration.
15144 * @param {Function} keysFunc The function to get the keys of `object`.
15145 * @returns {Object} Returns `object`.
15146 */
15147 var baseForRight = createBaseFor(true);
15148
15149 /**
15150 * The base implementation of `_.forIn` without support for callback
15151 * shorthands and `this` binding.
15152 *
15153 * @private
15154 * @param {Object} object The object to iterate over.
15155 * @param {Function} iteratee The function invoked per iteration.
15156 * @returns {Object} Returns `object`.
15157 */
15158 function baseForIn(object, iteratee) {
15159 return baseFor(object, iteratee, keysIn);
15160 }
15161
15162 /**
15163 * The base implementation of `_.forOwn` without support for callback
15164 * shorthands and `this` binding.
15165 *
15166 * @private
15167 * @param {Object} object The object to iterate over.
15168 * @param {Function} iteratee The function invoked per iteration.
15169 * @returns {Object} Returns `object`.
15170 */
15171 function baseForOwn(object, iteratee) {
15172 return baseFor(object, iteratee, keys);
15173 }
15174
15175 /**
15176 * The base implementation of `_.forOwnRight` without support for callback
15177 * shorthands and `this` binding.
15178 *
15179 * @private
15180 * @param {Object} object The object to iterate over.
15181 * @param {Function} iteratee The function invoked per iteration.
15182 * @returns {Object} Returns `object`.
15183 */
15184 function baseForOwnRight(object, iteratee) {
15185 return baseForRight(object, iteratee, keys);
15186 }
15187
15188 /**
15189 * The base implementation of `_.functions` which creates an array of
15190 * `object` function property names filtered from those provided.
15191 *
15192 * @private
15193 * @param {Object} object The object to inspect.
15194 * @param {Array} props The property names to filter.
15195 * @returns {Array} Returns the new array of filtered property names.
15196 */
15197 function baseFunctions(object, props) {
15198 var index = -1,
15199 length = props.length,
15200 resIndex = -1,
15201 result = [];
15202
15203 while (++index < length) {
15204 var key = props[index];
15205 if (isFunction(object[key])) {
15206 result[++resIndex] = key;
15207 }
15208 }
15209 return result;
15210 }
15211
15212 /**
15213 * The base implementation of `get` without support for string paths
15214 * and default values.
15215 *
15216 * @private
15217 * @param {Object} object The object to query.
15218 * @param {Array} path The path of the property to get.
15219 * @param {string} [pathKey] The key representation of path.
15220 * @returns {*} Returns the resolved value.
15221 */
15222 function baseGet(object, path, pathKey) {
15223 if (object == null) {
15224 return;
15225 }
15226 if (pathKey !== undefined && pathKey in toObject(object)) {
15227 path = [pathKey];
15228 }
15229 var index = 0,
15230 length = path.length;
15231
15232 while (object != null && index < length) {
15233 object = object[path[index++]];
15234 }
15235 return (index && index == length) ? object : undefined;
15236 }
15237
15238 /**
15239 * The base implementation of `_.isEqual` without support for `this` binding
15240 * `customizer` functions.
15241 *
15242 * @private
15243 * @param {*} value The value to compare.
15244 * @param {*} other The other value to compare.
15245 * @param {Function} [customizer] The function to customize comparing values.
15246 * @param {boolean} [isLoose] Specify performing partial comparisons.
15247 * @param {Array} [stackA] Tracks traversed `value` objects.
15248 * @param {Array} [stackB] Tracks traversed `other` objects.
15249 * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
15250 */
15251 function baseIsEqual(value, other, customizer, isLoose, stackA, stackB) {
15252 if (value === other) {
15253 return true;
15254 }
15255 if (value == null || other == null || (!isObject(value) && !isObjectLike(other))) {
15256 return value !== value && other !== other;
15257 }
15258 return baseIsEqualDeep(value, other, baseIsEqual, customizer, isLoose, stackA, stackB);
15259 }
15260
15261 /**
15262 * A specialized version of `baseIsEqual` for arrays and objects which performs
15263 * deep comparisons and tracks traversed objects enabling objects with circular
15264 * references to be compared.
15265 *
15266 * @private
15267 * @param {Object} object The object to compare.
15268 * @param {Object} other The other object to compare.
15269 * @param {Function} equalFunc The function to determine equivalents of values.
15270 * @param {Function} [customizer] The function to customize comparing objects.
15271 * @param {boolean} [isLoose] Specify performing partial comparisons.
15272 * @param {Array} [stackA=[]] Tracks traversed `value` objects.
15273 * @param {Array} [stackB=[]] Tracks traversed `other` objects.
15274 * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
15275 */
15276 function baseIsEqualDeep(object, other, equalFunc, customizer, isLoose, stackA, stackB) {
15277 var objIsArr = isArray(object),
15278 othIsArr = isArray(other),
15279 objTag = arrayTag,
15280 othTag = arrayTag;
15281
15282 if (!objIsArr) {
15283 objTag = objToString.call(object);
15284 if (objTag == argsTag) {
15285 objTag = objectTag;
15286 } else if (objTag != objectTag) {
15287 objIsArr = isTypedArray(object);
15288 }
15289 }
15290 if (!othIsArr) {
15291 othTag = objToString.call(other);
15292 if (othTag == argsTag) {
15293 othTag = objectTag;
15294 } else if (othTag != objectTag) {
15295 othIsArr = isTypedArray(other);
15296 }
15297 }
15298 var objIsObj = objTag == objectTag,
15299 othIsObj = othTag == objectTag,
15300 isSameTag = objTag == othTag;
15301
15302 if (isSameTag && !(objIsArr || objIsObj)) {
15303 return equalByTag(object, other, objTag);
15304 }
15305 if (!isLoose) {
15306 var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),
15307 othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');
15308
15309 if (objIsWrapped || othIsWrapped) {
15310 return equalFunc(objIsWrapped ? object.value() : object, othIsWrapped ? other.value() : other, customizer, isLoose, stackA, stackB);
15311 }
15312 }
15313 if (!isSameTag) {
15314 return false;
15315 }
15316 // Assume cyclic values are equal.
15317 // For more information on detecting circular references see https://es5.github.io/#JO.
15318 stackA || (stackA = []);
15319 stackB || (stackB = []);
15320
15321 var length = stackA.length;
15322 while (length--) {
15323 if (stackA[length] == object) {
15324 return stackB[length] == other;
15325 }
15326 }
15327 // Add `object` and `other` to the stack of traversed objects.
15328 stackA.push(object);
15329 stackB.push(other);
15330
15331 var result = (objIsArr ? equalArrays : equalObjects)(object, other, equalFunc, customizer, isLoose, stackA, stackB);
15332
15333 stackA.pop();
15334 stackB.pop();
15335
15336 return result;
15337 }
15338
15339 /**
15340 * The base implementation of `_.isMatch` without support for callback
15341 * shorthands and `this` binding.
15342 *
15343 * @private
15344 * @param {Object} object The object to inspect.
15345 * @param {Array} matchData The propery names, values, and compare flags to match.
15346 * @param {Function} [customizer] The function to customize comparing objects.
15347 * @returns {boolean} Returns `true` if `object` is a match, else `false`.
15348 */
15349 function baseIsMatch(object, matchData, customizer) {
15350 var index = matchData.length,
15351 length = index,
15352 noCustomizer = !customizer;
15353
15354 if (object == null) {
15355 return !length;
15356 }
15357 object = toObject(object);
15358 while (index--) {
15359 var data = matchData[index];
15360 if ((noCustomizer && data[2])
15361 ? data[1] !== object[data[0]]
15362 : !(data[0] in object)
15363 ) {
15364 return false;
15365 }
15366 }
15367 while (++index < length) {
15368 data = matchData[index];
15369 var key = data[0],
15370 objValue = object[key],
15371 srcValue = data[1];
15372
15373 if (noCustomizer && data[2]) {
15374 if (objValue === undefined && !(key in object)) {
15375 return false;
15376 }
15377 } else {
15378 var result = customizer ? customizer(objValue, srcValue, key) : undefined;
15379 if (!(result === undefined ? baseIsEqual(srcValue, objValue, customizer, true) : result)) {
15380 return false;
15381 }
15382 }
15383 }
15384 return true;
15385 }
15386
15387 /**
15388 * The base implementation of `_.map` without support for callback shorthands
15389 * and `this` binding.
15390 *
15391 * @private
15392 * @param {Array|Object|string} collection The collection to iterate over.
15393 * @param {Function} iteratee The function invoked per iteration.
15394 * @returns {Array} Returns the new mapped array.
15395 */
15396 function baseMap(collection, iteratee) {
15397 var index = -1,
15398 result = isArrayLike(collection) ? Array(collection.length) : [];
15399
15400 baseEach(collection, function(value, key, collection) {
15401 result[++index] = iteratee(value, key, collection);
15402 });
15403 return result;
15404 }
15405
15406 /**
15407 * The base implementation of `_.matches` which does not clone `source`.
15408 *
15409 * @private
15410 * @param {Object} source The object of property values to match.
15411 * @returns {Function} Returns the new function.
15412 */
15413 function baseMatches(source) {
15414 var matchData = getMatchData(source);
15415 if (matchData.length == 1 && matchData[0][2]) {
15416 var key = matchData[0][0],
15417 value = matchData[0][1];
15418
15419 return function(object) {
15420 if (object == null) {
15421 return false;
15422 }
15423 return object[key] === value && (value !== undefined || (key in toObject(object)));
15424 };
15425 }
15426 return function(object) {
15427 return baseIsMatch(object, matchData);
15428 };
15429 }
15430
15431 /**
15432 * The base implementation of `_.matchesProperty` which does not clone `srcValue`.
15433 *
15434 * @private
15435 * @param {string} path The path of the property to get.
15436 * @param {*} srcValue The value to compare.
15437 * @returns {Function} Returns the new function.
15438 */
15439 function baseMatchesProperty(path, srcValue) {
15440 var isArr = isArray(path),
15441 isCommon = isKey(path) && isStrictComparable(srcValue),
15442 pathKey = (path + '');
15443
15444 path = toPath(path);
15445 return function(object) {
15446 if (object == null) {
15447 return false;
15448 }
15449 var key = pathKey;
15450 object = toObject(object);
15451 if ((isArr || !isCommon) && !(key in object)) {
15452 object = path.length == 1 ? object : baseGet(object, baseSlice(path, 0, -1));
15453 if (object == null) {
15454 return false;
15455 }
15456 key = last(path);
15457 object = toObject(object);
15458 }
15459 return object[key] === srcValue
15460 ? (srcValue !== undefined || (key in object))
15461 : baseIsEqual(srcValue, object[key], undefined, true);
15462 };
15463 }
15464
15465 /**
15466 * The base implementation of `_.merge` without support for argument juggling,
15467 * multiple sources, and `this` binding `customizer` functions.
15468 *
15469 * @private
15470 * @param {Object} object The destination object.
15471 * @param {Object} source The source object.
15472 * @param {Function} [customizer] The function to customize merged values.
15473 * @param {Array} [stackA=[]] Tracks traversed source objects.
15474 * @param {Array} [stackB=[]] Associates values with source counterparts.
15475 * @returns {Object} Returns `object`.
15476 */
15477 function baseMerge(object, source, customizer, stackA, stackB) {
15478 if (!isObject(object)) {
15479 return object;
15480 }
15481 var isSrcArr = isArrayLike(source) && (isArray(source) || isTypedArray(source)),
15482 props = isSrcArr ? undefined : keys(source);
15483
15484 arrayEach(props || source, function(srcValue, key) {
15485 if (props) {
15486 key = srcValue;
15487 srcValue = source[key];
15488 }
15489 if (isObjectLike(srcValue)) {
15490 stackA || (stackA = []);
15491 stackB || (stackB = []);
15492 baseMergeDeep(object, source, key, baseMerge, customizer, stackA, stackB);
15493 }
15494 else {
15495 var value = object[key],
15496 result = customizer ? customizer(value, srcValue, key, object, source) : undefined,
15497 isCommon = result === undefined;
15498
15499 if (isCommon) {
15500 result = srcValue;
15501 }
15502 if ((result !== undefined || (isSrcArr && !(key in object))) &&
15503 (isCommon || (result === result ? (result !== value) : (value === value)))) {
15504 object[key] = result;
15505 }
15506 }
15507 });
15508 return object;
15509 }
15510
15511 /**
15512 * A specialized version of `baseMerge` for arrays and objects which performs
15513 * deep merges and tracks traversed objects enabling objects with circular
15514 * references to be merged.
15515 *
15516 * @private
15517 * @param {Object} object The destination object.
15518 * @param {Object} source The source object.
15519 * @param {string} key The key of the value to merge.
15520 * @param {Function} mergeFunc The function to merge values.
15521 * @param {Function} [customizer] The function to customize merged values.
15522 * @param {Array} [stackA=[]] Tracks traversed source objects.
15523 * @param {Array} [stackB=[]] Associates values with source counterparts.
15524 * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
15525 */
15526 function baseMergeDeep(object, source, key, mergeFunc, customizer, stackA, stackB) {
15527 var length = stackA.length,
15528 srcValue = source[key];
15529
15530 while (length--) {
15531 if (stackA[length] == srcValue) {
15532 object[key] = stackB[length];
15533 return;
15534 }
15535 }
15536 var value = object[key],
15537 result = customizer ? customizer(value, srcValue, key, object, source) : undefined,
15538 isCommon = result === undefined;
15539
15540 if (isCommon) {
15541 result = srcValue;
15542 if (isArrayLike(srcValue) && (isArray(srcValue) || isTypedArray(srcValue))) {
15543 result = isArray(value)
15544 ? value
15545 : (isArrayLike(value) ? arrayCopy(value) : []);
15546 }
15547 else if (isPlainObject(srcValue) || isArguments(srcValue)) {
15548 result = isArguments(value)
15549 ? toPlainObject(value)
15550 : (isPlainObject(value) ? value : {});
15551 }
15552 else {
15553 isCommon = false;
15554 }
15555 }
15556 // Add the source value to the stack of traversed objects and associate
15557 // it with its merged value.
15558 stackA.push(srcValue);
15559 stackB.push(result);
15560
15561 if (isCommon) {
15562 // Recursively merge objects and arrays (susceptible to call stack limits).
15563 object[key] = mergeFunc(result, srcValue, customizer, stackA, stackB);
15564 } else if (result === result ? (result !== value) : (value === value)) {
15565 object[key] = result;
15566 }
15567 }
15568
15569 /**
15570 * The base implementation of `_.property` without support for deep paths.
15571 *
15572 * @private
15573 * @param {string} key The key of the property to get.
15574 * @returns {Function} Returns the new function.
15575 */
15576 function baseProperty(key) {
15577 return function(object) {
15578 return object == null ? undefined : object[key];
15579 };
15580 }
15581
15582 /**
15583 * A specialized version of `baseProperty` which supports deep paths.
15584 *
15585 * @private
15586 * @param {Array|string} path The path of the property to get.
15587 * @returns {Function} Returns the new function.
15588 */
15589 function basePropertyDeep(path) {
15590 var pathKey = (path + '');
15591 path = toPath(path);
15592 return function(object) {
15593 return baseGet(object, path, pathKey);
15594 };
15595 }
15596
15597 /**
15598 * The base implementation of `_.pullAt` without support for individual
15599 * index arguments and capturing the removed elements.
15600 *
15601 * @private
15602 * @param {Array} array The array to modify.
15603 * @param {number[]} indexes The indexes of elements to remove.
15604 * @returns {Array} Returns `array`.
15605 */
15606 function basePullAt(array, indexes) {
15607 var length = array ? indexes.length : 0;
15608 while (length--) {
15609 var index = indexes[length];
15610 if (index != previous && isIndex(index)) {
15611 var previous = index;
15612 splice.call(array, index, 1);
15613 }
15614 }
15615 return array;
15616 }
15617
15618 /**
15619 * The base implementation of `_.random` without support for argument juggling
15620 * and returning floating-point numbers.
15621 *
15622 * @private
15623 * @param {number} min The minimum possible value.
15624 * @param {number} max The maximum possible value.
15625 * @returns {number} Returns the random number.
15626 */
15627 function baseRandom(min, max) {
15628 return min + nativeFloor(nativeRandom() * (max - min + 1));
15629 }
15630
15631 /**
15632 * The base implementation of `_.reduce` and `_.reduceRight` without support
15633 * for callback shorthands and `this` binding, which iterates over `collection`
15634 * using the provided `eachFunc`.
15635 *
15636 * @private
15637 * @param {Array|Object|string} collection The collection to iterate over.
15638 * @param {Function} iteratee The function invoked per iteration.
15639 * @param {*} accumulator The initial value.
15640 * @param {boolean} initFromCollection Specify using the first or last element
15641 * of `collection` as the initial value.
15642 * @param {Function} eachFunc The function to iterate over `collection`.
15643 * @returns {*} Returns the accumulated value.
15644 */
15645 function baseReduce(collection, iteratee, accumulator, initFromCollection, eachFunc) {
15646 eachFunc(collection, function(value, index, collection) {
15647 accumulator = initFromCollection
15648 ? (initFromCollection = false, value)
15649 : iteratee(accumulator, value, index, collection);
15650 });
15651 return accumulator;
15652 }
15653
15654 /**
15655 * The base implementation of `setData` without support for hot loop detection.
15656 *
15657 * @private
15658 * @param {Function} func The function to associate metadata with.
15659 * @param {*} data The metadata.
15660 * @returns {Function} Returns `func`.
15661 */
15662 var baseSetData = !metaMap ? identity : function(func, data) {
15663 metaMap.set(func, data);
15664 return func;
15665 };
15666
15667 /**
15668 * The base implementation of `_.slice` without an iteratee call guard.
15669 *
15670 * @private
15671 * @param {Array} array The array to slice.
15672 * @param {number} [start=0] The start position.
15673 * @param {number} [end=array.length] The end position.
15674 * @returns {Array} Returns the slice of `array`.
15675 */
15676 function baseSlice(array, start, end) {
15677 var index = -1,
15678 length = array.length;
15679
15680 start = start == null ? 0 : (+start || 0);
15681 if (start < 0) {
15682 start = -start > length ? 0 : (length + start);
15683 }
15684 end = (end === undefined || end > length) ? length : (+end || 0);
15685 if (end < 0) {
15686 end += length;
15687 }
15688 length = start > end ? 0 : ((end - start) >>> 0);
15689 start >>>= 0;
15690
15691 var result = Array(length);
15692 while (++index < length) {
15693 result[index] = array[index + start];
15694 }
15695 return result;
15696 }
15697
15698 /**
15699 * The base implementation of `_.some` without support for callback shorthands
15700 * and `this` binding.
15701 *
15702 * @private
15703 * @param {Array|Object|string} collection The collection to iterate over.
15704 * @param {Function} predicate The function invoked per iteration.
15705 * @returns {boolean} Returns `true` if any element passes the predicate check,
15706 * else `false`.
15707 */
15708 function baseSome(collection, predicate) {
15709 var result;
15710
15711 baseEach(collection, function(value, index, collection) {
15712 result = predicate(value, index, collection);
15713 return !result;
15714 });
15715 return !!result;
15716 }
15717
15718 /**
15719 * The base implementation of `_.sortBy` which uses `comparer` to define
15720 * the sort order of `array` and replaces criteria objects with their
15721 * corresponding values.
15722 *
15723 * @private
15724 * @param {Array} array The array to sort.
15725 * @param {Function} comparer The function to define sort order.
15726 * @returns {Array} Returns `array`.
15727 */
15728 function baseSortBy(array, comparer) {
15729 var length = array.length;
15730
15731 array.sort(comparer);
15732 while (length--) {
15733 array[length] = array[length].value;
15734 }
15735 return array;
15736 }
15737
15738 /**
15739 * The base implementation of `_.sortByOrder` without param guards.
15740 *
15741 * @private
15742 * @param {Array|Object|string} collection The collection to iterate over.
15743 * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by.
15744 * @param {boolean[]} orders The sort orders of `iteratees`.
15745 * @returns {Array} Returns the new sorted array.
15746 */
15747 function baseSortByOrder(collection, iteratees, orders) {
15748 var callback = getCallback(),
15749 index = -1;
15750
15751 iteratees = arrayMap(iteratees, function(iteratee) { return callback(iteratee); });
15752
15753 var result = baseMap(collection, function(value) {
15754 var criteria = arrayMap(iteratees, function(iteratee) { return iteratee(value); });
15755 return { 'criteria': criteria, 'index': ++index, 'value': value };
15756 });
15757
15758 return baseSortBy(result, function(object, other) {
15759 return compareMultiple(object, other, orders);
15760 });
15761 }
15762
15763 /**
15764 * The base implementation of `_.sum` without support for callback shorthands
15765 * and `this` binding.
15766 *
15767 * @private
15768 * @param {Array|Object|string} collection The collection to iterate over.
15769 * @param {Function} iteratee The function invoked per iteration.
15770 * @returns {number} Returns the sum.
15771 */
15772 function baseSum(collection, iteratee) {
15773 var result = 0;
15774 baseEach(collection, function(value, index, collection) {
15775 result += +iteratee(value, index, collection) || 0;
15776 });
15777 return result;
15778 }
15779
15780 /**
15781 * The base implementation of `_.uniq` without support for callback shorthands
15782 * and `this` binding.
15783 *
15784 * @private
15785 * @param {Array} array The array to inspect.
15786 * @param {Function} [iteratee] The function invoked per iteration.
15787 * @returns {Array} Returns the new duplicate-value-free array.
15788 */
15789 function baseUniq(array, iteratee) {
15790 var index = -1,
15791 indexOf = getIndexOf(),
15792 length = array.length,
15793 isCommon = indexOf == baseIndexOf,
15794 isLarge = isCommon && length >= LARGE_ARRAY_SIZE,
15795 seen = isLarge ? createCache() : null,
15796 result = [];
15797
15798 if (seen) {
15799 indexOf = cacheIndexOf;
15800 isCommon = false;
15801 } else {
15802 isLarge = false;
15803 seen = iteratee ? [] : result;
15804 }
15805 outer:
15806 while (++index < length) {
15807 var value = array[index],
15808 computed = iteratee ? iteratee(value, index, array) : value;
15809
15810 if (isCommon && value === value) {
15811 var seenIndex = seen.length;
15812 while (seenIndex--) {
15813 if (seen[seenIndex] === computed) {
15814 continue outer;
15815 }
15816 }
15817 if (iteratee) {
15818 seen.push(computed);
15819 }
15820 result.push(value);
15821 }
15822 else if (indexOf(seen, computed, 0) < 0) {
15823 if (iteratee || isLarge) {
15824 seen.push(computed);
15825 }
15826 result.push(value);
15827 }
15828 }
15829 return result;
15830 }
15831
15832 /**
15833 * The base implementation of `_.values` and `_.valuesIn` which creates an
15834 * array of `object` property values corresponding to the property names
15835 * of `props`.
15836 *
15837 * @private
15838 * @param {Object} object The object to query.
15839 * @param {Array} props The property names to get values for.
15840 * @returns {Object} Returns the array of property values.
15841 */
15842 function baseValues(object, props) {
15843 var index = -1,
15844 length = props.length,
15845 result = Array(length);
15846
15847 while (++index < length) {
15848 result[index] = object[props[index]];
15849 }
15850 return result;
15851 }
15852
15853 /**
15854 * The base implementation of `_.dropRightWhile`, `_.dropWhile`, `_.takeRightWhile`,
15855 * and `_.takeWhile` without support for callback shorthands and `this` binding.
15856 *
15857 * @private
15858 * @param {Array} array The array to query.
15859 * @param {Function} predicate The function invoked per iteration.
15860 * @param {boolean} [isDrop] Specify dropping elements instead of taking them.
15861 * @param {boolean} [fromRight] Specify iterating from right to left.
15862 * @returns {Array} Returns the slice of `array`.
15863 */
15864 function baseWhile(array, predicate, isDrop, fromRight) {
15865 var length = array.length,
15866 index = fromRight ? length : -1;
15867
15868 while ((fromRight ? index-- : ++index < length) && predicate(array[index], index, array)) {}
15869 return isDrop
15870 ? baseSlice(array, (fromRight ? 0 : index), (fromRight ? index + 1 : length))
15871 : baseSlice(array, (fromRight ? index + 1 : 0), (fromRight ? length : index));
15872 }
15873
15874 /**
15875 * The base implementation of `wrapperValue` which returns the result of
15876 * performing a sequence of actions on the unwrapped `value`, where each
15877 * successive action is supplied the return value of the previous.
15878 *
15879 * @private
15880 * @param {*} value The unwrapped value.
15881 * @param {Array} actions Actions to peform to resolve the unwrapped value.
15882 * @returns {*} Returns the resolved value.
15883 */
15884 function baseWrapperValue(value, actions) {
15885 var result = value;
15886 if (result instanceof LazyWrapper) {
15887 result = result.value();
15888 }
15889 var index = -1,
15890 length = actions.length;
15891
15892 while (++index < length) {
15893 var action = actions[index];
15894 result = action.func.apply(action.thisArg, arrayPush([result], action.args));
15895 }
15896 return result;
15897 }
15898
15899 /**
15900 * Performs a binary search of `array` to determine the index at which `value`
15901 * should be inserted into `array` in order to maintain its sort order.
15902 *
15903 * @private
15904 * @param {Array} array The sorted array to inspect.
15905 * @param {*} value The value to evaluate.
15906 * @param {boolean} [retHighest] Specify returning the highest qualified index.
15907 * @returns {number} Returns the index at which `value` should be inserted
15908 * into `array`.
15909 */
15910 function binaryIndex(array, value, retHighest) {
15911 var low = 0,
15912 high = array ? array.length : low;
15913
15914 if (typeof value == 'number' && value === value && high <= HALF_MAX_ARRAY_LENGTH) {
15915 while (low < high) {
15916 var mid = (low + high) >>> 1,
15917 computed = array[mid];
15918
15919 if ((retHighest ? (computed <= value) : (computed < value)) && computed !== null) {
15920 low = mid + 1;
15921 } else {
15922 high = mid;
15923 }
15924 }
15925 return high;
15926 }
15927 return binaryIndexBy(array, value, identity, retHighest);
15928 }
15929
15930 /**
15931 * This function is like `binaryIndex` except that it invokes `iteratee` for
15932 * `value` and each element of `array` to compute their sort ranking. The
15933 * iteratee is invoked with one argument; (value).
15934 *
15935 * @private
15936 * @param {Array} array The sorted array to inspect.
15937 * @param {*} value The value to evaluate.
15938 * @param {Function} iteratee The function invoked per iteration.
15939 * @param {boolean} [retHighest] Specify returning the highest qualified index.
15940 * @returns {number} Returns the index at which `value` should be inserted
15941 * into `array`.
15942 */
15943 function binaryIndexBy(array, value, iteratee, retHighest) {
15944 value = iteratee(value);
15945
15946 var low = 0,
15947 high = array ? array.length : 0,
15948 valIsNaN = value !== value,
15949 valIsNull = value === null,
15950 valIsUndef = value === undefined;
15951
15952 while (low < high) {
15953 var mid = nativeFloor((low + high) / 2),
15954 computed = iteratee(array[mid]),
15955 isDef = computed !== undefined,
15956 isReflexive = computed === computed;
15957
15958 if (valIsNaN) {
15959 var setLow = isReflexive || retHighest;
15960 } else if (valIsNull) {
15961 setLow = isReflexive && isDef && (retHighest || computed != null);
15962 } else if (valIsUndef) {
15963 setLow = isReflexive && (retHighest || isDef);
15964 } else if (computed == null) {
15965 setLow = false;
15966 } else {
15967 setLow = retHighest ? (computed <= value) : (computed < value);
15968 }
15969 if (setLow) {
15970 low = mid + 1;
15971 } else {
15972 high = mid;
15973 }
15974 }
15975 return nativeMin(high, MAX_ARRAY_INDEX);
15976 }
15977
15978 /**
15979 * A specialized version of `baseCallback` which only supports `this` binding
15980 * and specifying the number of arguments to provide to `func`.
15981 *
15982 * @private
15983 * @param {Function} func The function to bind.
15984 * @param {*} thisArg The `this` binding of `func`.
15985 * @param {number} [argCount] The number of arguments to provide to `func`.
15986 * @returns {Function} Returns the callback.
15987 */
15988 function bindCallback(func, thisArg, argCount) {
15989 if (typeof func != 'function') {
15990 return identity;
15991 }
15992 if (thisArg === undefined) {
15993 return func;
15994 }
15995 switch (argCount) {
15996 case 1: return function(value) {
15997 return func.call(thisArg, value);
15998 };
15999 case 3: return function(value, index, collection) {
16000 return func.call(thisArg, value, index, collection);
16001 };
16002 case 4: return function(accumulator, value, index, collection) {
16003 return func.call(thisArg, accumulator, value, index, collection);
16004 };
16005 case 5: return function(value, other, key, object, source) {
16006 return func.call(thisArg, value, other, key, object, source);
16007 };
16008 }
16009 return function() {
16010 return func.apply(thisArg, arguments);
16011 };
16012 }
16013
16014 /**
16015 * Creates a clone of the given array buffer.
16016 *
16017 * @private
16018 * @param {ArrayBuffer} buffer The array buffer to clone.
16019 * @returns {ArrayBuffer} Returns the cloned array buffer.
16020 */
16021 function bufferClone(buffer) {
16022 var result = new ArrayBuffer(buffer.byteLength),
16023 view = new Uint8Array(result);
16024
16025 view.set(new Uint8Array(buffer));
16026 return result;
16027 }
16028
16029 /**
16030 * Creates an array that is the composition of partially applied arguments,
16031 * placeholders, and provided arguments into a single array of arguments.
16032 *
16033 * @private
16034 * @param {Array|Object} args The provided arguments.
16035 * @param {Array} partials The arguments to prepend to those provided.
16036 * @param {Array} holders The `partials` placeholder indexes.
16037 * @returns {Array} Returns the new array of composed arguments.
16038 */
16039 function composeArgs(args, partials, holders) {
16040 var holdersLength = holders.length,
16041 argsIndex = -1,
16042 argsLength = nativeMax(args.length - holdersLength, 0),
16043 leftIndex = -1,
16044 leftLength = partials.length,
16045 result = Array(leftLength + argsLength);
16046
16047 while (++leftIndex < leftLength) {
16048 result[leftIndex] = partials[leftIndex];
16049 }
16050 while (++argsIndex < holdersLength) {
16051 result[holders[argsIndex]] = args[argsIndex];
16052 }
16053 while (argsLength--) {
16054 result[leftIndex++] = args[argsIndex++];
16055 }
16056 return result;
16057 }
16058
16059 /**
16060 * This function is like `composeArgs` except that the arguments composition
16061 * is tailored for `_.partialRight`.
16062 *
16063 * @private
16064 * @param {Array|Object} args The provided arguments.
16065 * @param {Array} partials The arguments to append to those provided.
16066 * @param {Array} holders The `partials` placeholder indexes.
16067 * @returns {Array} Returns the new array of composed arguments.
16068 */
16069 function composeArgsRight(args, partials, holders) {
16070 var holdersIndex = -1,
16071 holdersLength = holders.length,
16072 argsIndex = -1,
16073 argsLength = nativeMax(args.length - holdersLength, 0),
16074 rightIndex = -1,
16075 rightLength = partials.length,
16076 result = Array(argsLength + rightLength);
16077
16078 while (++argsIndex < argsLength) {
16079 result[argsIndex] = args[argsIndex];
16080 }
16081 var offset = argsIndex;
16082 while (++rightIndex < rightLength) {
16083 result[offset + rightIndex] = partials[rightIndex];
16084 }
16085 while (++holdersIndex < holdersLength) {
16086 result[offset + holders[holdersIndex]] = args[argsIndex++];
16087 }
16088 return result;
16089 }
16090
16091 /**
16092 * Creates a `_.countBy`, `_.groupBy`, `_.indexBy`, or `_.partition` function.
16093 *
16094 * @private
16095 * @param {Function} setter The function to set keys and values of the accumulator object.
16096 * @param {Function} [initializer] The function to initialize the accumulator object.
16097 * @returns {Function} Returns the new aggregator function.
16098 */
16099 function createAggregator(setter, initializer) {
16100 return function(collection, iteratee, thisArg) {
16101 var result = initializer ? initializer() : {};
16102 iteratee = getCallback(iteratee, thisArg, 3);
16103
16104 if (isArray(collection)) {
16105 var index = -1,
16106 length = collection.length;
16107
16108 while (++index < length) {
16109 var value = collection[index];
16110 setter(result, value, iteratee(value, index, collection), collection);
16111 }
16112 } else {
16113 baseEach(collection, function(value, key, collection) {
16114 setter(result, value, iteratee(value, key, collection), collection);
16115 });
16116 }
16117 return result;
16118 };
16119 }
16120
16121 /**
16122 * Creates a `_.assign`, `_.defaults`, or `_.merge` function.
16123 *
16124 * @private
16125 * @param {Function} assigner The function to assign values.
16126 * @returns {Function} Returns the new assigner function.
16127 */
16128 function createAssigner(assigner) {
16129 return restParam(function(object, sources) {
16130 var index = -1,
16131 length = object == null ? 0 : sources.length,
16132 customizer = length > 2 ? sources[length - 2] : undefined,
16133 guard = length > 2 ? sources[2] : undefined,
16134 thisArg = length > 1 ? sources[length - 1] : undefined;
16135
16136 if (typeof customizer == 'function') {
16137 customizer = bindCallback(customizer, thisArg, 5);
16138 length -= 2;
16139 } else {
16140 customizer = typeof thisArg == 'function' ? thisArg : undefined;
16141 length -= (customizer ? 1 : 0);
16142 }
16143 if (guard && isIterateeCall(sources[0], sources[1], guard)) {
16144 customizer = length < 3 ? undefined : customizer;
16145 length = 1;
16146 }
16147 while (++index < length) {
16148 var source = sources[index];
16149 if (source) {
16150 assigner(object, source, customizer);
16151 }
16152 }
16153 return object;
16154 });
16155 }
16156
16157 /**
16158 * Creates a `baseEach` or `baseEachRight` function.
16159 *
16160 * @private
16161 * @param {Function} eachFunc The function to iterate over a collection.
16162 * @param {boolean} [fromRight] Specify iterating from right to left.
16163 * @returns {Function} Returns the new base function.
16164 */
16165 function createBaseEach(eachFunc, fromRight) {
16166 return function(collection, iteratee) {
16167 var length = collection ? getLength(collection) : 0;
16168 if (!isLength(length)) {
16169 return eachFunc(collection, iteratee);
16170 }
16171 var index = fromRight ? length : -1,
16172 iterable = toObject(collection);
16173
16174 while ((fromRight ? index-- : ++index < length)) {
16175 if (iteratee(iterable[index], index, iterable) === false) {
16176 break;
16177 }
16178 }
16179 return collection;
16180 };
16181 }
16182
16183 /**
16184 * Creates a base function for `_.forIn` or `_.forInRight`.
16185 *
16186 * @private
16187 * @param {boolean} [fromRight] Specify iterating from right to left.
16188 * @returns {Function} Returns the new base function.
16189 */
16190 function createBaseFor(fromRight) {
16191 return function(object, iteratee, keysFunc) {
16192 var iterable = toObject(object),
16193 props = keysFunc(object),
16194 length = props.length,
16195 index = fromRight ? length : -1;
16196
16197 while ((fromRight ? index-- : ++index < length)) {
16198 var key = props[index];
16199 if (iteratee(iterable[key], key, iterable) === false) {
16200 break;
16201 }
16202 }
16203 return object;
16204 };
16205 }
16206
16207 /**
16208 * Creates a function that wraps `func` and invokes it with the `this`
16209 * binding of `thisArg`.
16210 *
16211 * @private
16212 * @param {Function} func The function to bind.
16213 * @param {*} [thisArg] The `this` binding of `func`.
16214 * @returns {Function} Returns the new bound function.
16215 */
16216 function createBindWrapper(func, thisArg) {
16217 var Ctor = createCtorWrapper(func);
16218
16219 function wrapper() {
16220 var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;
16221 return fn.apply(thisArg, arguments);
16222 }
16223 return wrapper;
16224 }
16225
16226 /**
16227 * Creates a `Set` cache object to optimize linear searches of large arrays.
16228 *
16229 * @private
16230 * @param {Array} [values] The values to cache.
16231 * @returns {null|Object} Returns the new cache object if `Set` is supported, else `null`.
16232 */
16233 function createCache(values) {
16234 return (nativeCreate && Set) ? new SetCache(values) : null;
16235 }
16236
16237 /**
16238 * Creates a function that produces compound words out of the words in a
16239 * given string.
16240 *
16241 * @private
16242 * @param {Function} callback The function to combine each word.
16243 * @returns {Function} Returns the new compounder function.
16244 */
16245 function createCompounder(callback) {
16246 return function(string) {
16247 var index = -1,
16248 array = words(deburr(string)),
16249 length = array.length,
16250 result = '';
16251
16252 while (++index < length) {
16253 result = callback(result, array[index], index);
16254 }
16255 return result;
16256 };
16257 }
16258
16259 /**
16260 * Creates a function that produces an instance of `Ctor` regardless of
16261 * whether it was invoked as part of a `new` expression or by `call` or `apply`.
16262 *
16263 * @private
16264 * @param {Function} Ctor The constructor to wrap.
16265 * @returns {Function} Returns the new wrapped function.
16266 */
16267 function createCtorWrapper(Ctor) {
16268 return function() {
16269 // Use a `switch` statement to work with class constructors.
16270 // See http://ecma-international.org/ecma-262/6.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist
16271 // for more details.
16272 var args = arguments;
16273 switch (args.length) {
16274 case 0: return new Ctor;
16275 case 1: return new Ctor(args[0]);
16276 case 2: return new Ctor(args[0], args[1]);
16277 case 3: return new Ctor(args[0], args[1], args[2]);
16278 case 4: return new Ctor(args[0], args[1], args[2], args[3]);
16279 case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]);
16280 case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]);
16281 case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]);
16282 }
16283 var thisBinding = baseCreate(Ctor.prototype),
16284 result = Ctor.apply(thisBinding, args);
16285
16286 // Mimic the constructor's `return` behavior.
16287 // See https://es5.github.io/#x13.2.2 for more details.
16288 return isObject(result) ? result : thisBinding;
16289 };
16290 }
16291
16292 /**
16293 * Creates a `_.curry` or `_.curryRight` function.
16294 *
16295 * @private
16296 * @param {boolean} flag The curry bit flag.
16297 * @returns {Function} Returns the new curry function.
16298 */
16299 function createCurry(flag) {
16300 function curryFunc(func, arity, guard) {
16301 if (guard && isIterateeCall(func, arity, guard)) {
16302 arity = undefined;
16303 }
16304 var result = createWrapper(func, flag, undefined, undefined, undefined, undefined, undefined, arity);
16305 result.placeholder = curryFunc.placeholder;
16306 return result;
16307 }
16308 return curryFunc;
16309 }
16310
16311 /**
16312 * Creates a `_.defaults` or `_.defaultsDeep` function.
16313 *
16314 * @private
16315 * @param {Function} assigner The function to assign values.
16316 * @param {Function} customizer The function to customize assigned values.
16317 * @returns {Function} Returns the new defaults function.
16318 */
16319 function createDefaults(assigner, customizer) {
16320 return restParam(function(args) {
16321 var object = args[0];
16322 if (object == null) {
16323 return object;
16324 }
16325 args.push(customizer);
16326 return assigner.apply(undefined, args);
16327 });
16328 }
16329
16330 /**
16331 * Creates a `_.max` or `_.min` function.
16332 *
16333 * @private
16334 * @param {Function} comparator The function used to compare values.
16335 * @param {*} exValue The initial extremum value.
16336 * @returns {Function} Returns the new extremum function.
16337 */
16338 function createExtremum(comparator, exValue) {
16339 return function(collection, iteratee, thisArg) {
16340 if (thisArg && isIterateeCall(collection, iteratee, thisArg)) {
16341 iteratee = undefined;
16342 }
16343 iteratee = getCallback(iteratee, thisArg, 3);
16344 if (iteratee.length == 1) {
16345 collection = isArray(collection) ? collection : toIterable(collection);
16346 var result = arrayExtremum(collection, iteratee, comparator, exValue);
16347 if (!(collection.length && result === exValue)) {
16348 return result;
16349 }
16350 }
16351 return baseExtremum(collection, iteratee, comparator, exValue);
16352 };
16353 }
16354
16355 /**
16356 * Creates a `_.find` or `_.findLast` function.
16357 *
16358 * @private
16359 * @param {Function} eachFunc The function to iterate over a collection.
16360 * @param {boolean} [fromRight] Specify iterating from right to left.
16361 * @returns {Function} Returns the new find function.
16362 */
16363 function createFind(eachFunc, fromRight) {
16364 return function(collection, predicate, thisArg) {
16365 predicate = getCallback(predicate, thisArg, 3);
16366 if (isArray(collection)) {
16367 var index = baseFindIndex(collection, predicate, fromRight);
16368 return index > -1 ? collection[index] : undefined;
16369 }
16370 return baseFind(collection, predicate, eachFunc);
16371 };
16372 }
16373
16374 /**
16375 * Creates a `_.findIndex` or `_.findLastIndex` function.
16376 *
16377 * @private
16378 * @param {boolean} [fromRight] Specify iterating from right to left.
16379 * @returns {Function} Returns the new find function.
16380 */
16381 function createFindIndex(fromRight) {
16382 return function(array, predicate, thisArg) {
16383 if (!(array && array.length)) {
16384 return -1;
16385 }
16386 predicate = getCallback(predicate, thisArg, 3);
16387 return baseFindIndex(array, predicate, fromRight);
16388 };
16389 }
16390
16391 /**
16392 * Creates a `_.findKey` or `_.findLastKey` function.
16393 *
16394 * @private
16395 * @param {Function} objectFunc The function to iterate over an object.
16396 * @returns {Function} Returns the new find function.
16397 */
16398 function createFindKey(objectFunc) {
16399 return function(object, predicate, thisArg) {
16400 predicate = getCallback(predicate, thisArg, 3);
16401 return baseFind(object, predicate, objectFunc, true);
16402 };
16403 }
16404
16405 /**
16406 * Creates a `_.flow` or `_.flowRight` function.
16407 *
16408 * @private
16409 * @param {boolean} [fromRight] Specify iterating from right to left.
16410 * @returns {Function} Returns the new flow function.
16411 */
16412 function createFlow(fromRight) {
16413 return function() {
16414 var wrapper,
16415 length = arguments.length,
16416 index = fromRight ? length : -1,
16417 leftIndex = 0,
16418 funcs = Array(length);
16419
16420 while ((fromRight ? index-- : ++index < length)) {
16421 var func = funcs[leftIndex++] = arguments[index];
16422 if (typeof func != 'function') {
16423 throw new TypeError(FUNC_ERROR_TEXT);
16424 }
16425 if (!wrapper && LodashWrapper.prototype.thru && getFuncName(func) == 'wrapper') {
16426 wrapper = new LodashWrapper([], true);
16427 }
16428 }
16429 index = wrapper ? -1 : length;
16430 while (++index < length) {
16431 func = funcs[index];
16432
16433 var funcName = getFuncName(func),
16434 data = funcName == 'wrapper' ? getData(func) : undefined;
16435
16436 if (data && isLaziable(data[0]) && data[1] == (ARY_FLAG | CURRY_FLAG | PARTIAL_FLAG | REARG_FLAG) && !data[4].length && data[9] == 1) {
16437 wrapper = wrapper[getFuncName(data[0])].apply(wrapper, data[3]);
16438 } else {
16439 wrapper = (func.length == 1 && isLaziable(func)) ? wrapper[funcName]() : wrapper.thru(func);
16440 }
16441 }
16442 return function() {
16443 var args = arguments,
16444 value = args[0];
16445
16446 if (wrapper && args.length == 1 && isArray(value) && value.length >= LARGE_ARRAY_SIZE) {
16447 return wrapper.plant(value).value();
16448 }
16449 var index = 0,
16450 result = length ? funcs[index].apply(this, args) : value;
16451
16452 while (++index < length) {
16453 result = funcs[index].call(this, result);
16454 }
16455 return result;
16456 };
16457 };
16458 }
16459
16460 /**
16461 * Creates a function for `_.forEach` or `_.forEachRight`.
16462 *
16463 * @private
16464 * @param {Function} arrayFunc The function to iterate over an array.
16465 * @param {Function} eachFunc The function to iterate over a collection.
16466 * @returns {Function} Returns the new each function.
16467 */
16468 function createForEach(arrayFunc, eachFunc) {
16469 return function(collection, iteratee, thisArg) {
16470 return (typeof iteratee == 'function' && thisArg === undefined && isArray(collection))
16471 ? arrayFunc(collection, iteratee)
16472 : eachFunc(collection, bindCallback(iteratee, thisArg, 3));
16473 };
16474 }
16475
16476 /**
16477 * Creates a function for `_.forIn` or `_.forInRight`.
16478 *
16479 * @private
16480 * @param {Function} objectFunc The function to iterate over an object.
16481 * @returns {Function} Returns the new each function.
16482 */
16483 function createForIn(objectFunc) {
16484 return function(object, iteratee, thisArg) {
16485 if (typeof iteratee != 'function' || thisArg !== undefined) {
16486 iteratee = bindCallback(iteratee, thisArg, 3);
16487 }
16488 return objectFunc(object, iteratee, keysIn);
16489 };
16490 }
16491
16492 /**
16493 * Creates a function for `_.forOwn` or `_.forOwnRight`.
16494 *
16495 * @private
16496 * @param {Function} objectFunc The function to iterate over an object.
16497 * @returns {Function} Returns the new each function.
16498 */
16499 function createForOwn(objectFunc) {
16500 return function(object, iteratee, thisArg) {
16501 if (typeof iteratee != 'function' || thisArg !== undefined) {
16502 iteratee = bindCallback(iteratee, thisArg, 3);
16503 }
16504 return objectFunc(object, iteratee);
16505 };
16506 }
16507
16508 /**
16509 * Creates a function for `_.mapKeys` or `_.mapValues`.
16510 *
16511 * @private
16512 * @param {boolean} [isMapKeys] Specify mapping keys instead of values.
16513 * @returns {Function} Returns the new map function.
16514 */
16515 function createObjectMapper(isMapKeys) {
16516 return function(object, iteratee, thisArg) {
16517 var result = {};
16518 iteratee = getCallback(iteratee, thisArg, 3);
16519
16520 baseForOwn(object, function(value, key, object) {
16521 var mapped = iteratee(value, key, object);
16522 key = isMapKeys ? mapped : key;
16523 value = isMapKeys ? value : mapped;
16524 result[key] = value;
16525 });
16526 return result;
16527 };
16528 }
16529
16530 /**
16531 * Creates a function for `_.padLeft` or `_.padRight`.
16532 *
16533 * @private
16534 * @param {boolean} [fromRight] Specify padding from the right.
16535 * @returns {Function} Returns the new pad function.
16536 */
16537 function createPadDir(fromRight) {
16538 return function(string, length, chars) {
16539 string = baseToString(string);
16540 return (fromRight ? string : '') + createPadding(string, length, chars) + (fromRight ? '' : string);
16541 };
16542 }
16543
16544 /**
16545 * Creates a `_.partial` or `_.partialRight` function.
16546 *
16547 * @private
16548 * @param {boolean} flag The partial bit flag.
16549 * @returns {Function} Returns the new partial function.
16550 */
16551 function createPartial(flag) {
16552 var partialFunc = restParam(function(func, partials) {
16553 var holders = replaceHolders(partials, partialFunc.placeholder);
16554 return createWrapper(func, flag, undefined, partials, holders);
16555 });
16556 return partialFunc;
16557 }
16558
16559 /**
16560 * Creates a function for `_.reduce` or `_.reduceRight`.
16561 *
16562 * @private
16563 * @param {Function} arrayFunc The function to iterate over an array.
16564 * @param {Function} eachFunc The function to iterate over a collection.
16565 * @returns {Function} Returns the new each function.
16566 */
16567 function createReduce(arrayFunc, eachFunc) {
16568 return function(collection, iteratee, accumulator, thisArg) {
16569 var initFromArray = arguments.length < 3;
16570 return (typeof iteratee == 'function' && thisArg === undefined && isArray(collection))
16571 ? arrayFunc(collection, iteratee, accumulator, initFromArray)
16572 : baseReduce(collection, getCallback(iteratee, thisArg, 4), accumulator, initFromArray, eachFunc);
16573 };
16574 }
16575
16576 /**
16577 * Creates a function that wraps `func` and invokes it with optional `this`
16578 * binding of, partial application, and currying.
16579 *
16580 * @private
16581 * @param {Function|string} func The function or method name to reference.
16582 * @param {number} bitmask The bitmask of flags. See `createWrapper` for more details.
16583 * @param {*} [thisArg] The `this` binding of `func`.
16584 * @param {Array} [partials] The arguments to prepend to those provided to the new function.
16585 * @param {Array} [holders] The `partials` placeholder indexes.
16586 * @param {Array} [partialsRight] The arguments to append to those provided to the new function.
16587 * @param {Array} [holdersRight] The `partialsRight` placeholder indexes.
16588 * @param {Array} [argPos] The argument positions of the new function.
16589 * @param {number} [ary] The arity cap of `func`.
16590 * @param {number} [arity] The arity of `func`.
16591 * @returns {Function} Returns the new wrapped function.
16592 */
16593 function createHybridWrapper(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) {
16594 var isAry = bitmask & ARY_FLAG,
16595 isBind = bitmask & BIND_FLAG,
16596 isBindKey = bitmask & BIND_KEY_FLAG,
16597 isCurry = bitmask & CURRY_FLAG,
16598 isCurryBound = bitmask & CURRY_BOUND_FLAG,
16599 isCurryRight = bitmask & CURRY_RIGHT_FLAG,
16600 Ctor = isBindKey ? undefined : createCtorWrapper(func);
16601
16602 function wrapper() {
16603 // Avoid `arguments` object use disqualifying optimizations by
16604 // converting it to an array before providing it to other functions.
16605 var length = arguments.length,
16606 index = length,
16607 args = Array(length);
16608
16609 while (index--) {
16610 args[index] = arguments[index];
16611 }
16612 if (partials) {
16613 args = composeArgs(args, partials, holders);
16614 }
16615 if (partialsRight) {
16616 args = composeArgsRight(args, partialsRight, holdersRight);
16617 }
16618 if (isCurry || isCurryRight) {
16619 var placeholder = wrapper.placeholder,
16620 argsHolders = replaceHolders(args, placeholder);
16621
16622 length -= argsHolders.length;
16623 if (length < arity) {
16624 var newArgPos = argPos ? arrayCopy(argPos) : undefined,
16625 newArity = nativeMax(arity - length, 0),
16626 newsHolders = isCurry ? argsHolders : undefined,
16627 newHoldersRight = isCurry ? undefined : argsHolders,
16628 newPartials = isCurry ? args : undefined,
16629 newPartialsRight = isCurry ? undefined : args;
16630
16631 bitmask |= (isCurry ? PARTIAL_FLAG : PARTIAL_RIGHT_FLAG);
16632 bitmask &= ~(isCurry ? PARTIAL_RIGHT_FLAG : PARTIAL_FLAG);
16633
16634 if (!isCurryBound) {
16635 bitmask &= ~(BIND_FLAG | BIND_KEY_FLAG);
16636 }
16637 var newData = [func, bitmask, thisArg, newPartials, newsHolders, newPartialsRight, newHoldersRight, newArgPos, ary, newArity],
16638 result = createHybridWrapper.apply(undefined, newData);
16639
16640 if (isLaziable(func)) {
16641 setData(result, newData);
16642 }
16643 result.placeholder = placeholder;
16644 return result;
16645 }
16646 }
16647 var thisBinding = isBind ? thisArg : this,
16648 fn = isBindKey ? thisBinding[func] : func;
16649
16650 if (argPos) {
16651 args = reorder(args, argPos);
16652 }
16653 if (isAry && ary < args.length) {
16654 args.length = ary;
16655 }
16656 if (this && this !== root && this instanceof wrapper) {
16657 fn = Ctor || createCtorWrapper(func);
16658 }
16659 return fn.apply(thisBinding, args);
16660 }
16661 return wrapper;
16662 }
16663
16664 /**
16665 * Creates the padding required for `string` based on the given `length`.
16666 * The `chars` string is truncated if the number of characters exceeds `length`.
16667 *
16668 * @private
16669 * @param {string} string The string to create padding for.
16670 * @param {number} [length=0] The padding length.
16671 * @param {string} [chars=' '] The string used as padding.
16672 * @returns {string} Returns the pad for `string`.
16673 */
16674 function createPadding(string, length, chars) {
16675 var strLength = string.length;
16676 length = +length;
16677
16678 if (strLength >= length || !nativeIsFinite(length)) {
16679 return '';
16680 }
16681 var padLength = length - strLength;
16682 chars = chars == null ? ' ' : (chars + '');
16683 return repeat(chars, nativeCeil(padLength / chars.length)).slice(0, padLength);
16684 }
16685
16686 /**
16687 * Creates a function that wraps `func` and invokes it with the optional `this`
16688 * binding of `thisArg` and the `partials` prepended to those provided to
16689 * the wrapper.
16690 *
16691 * @private
16692 * @param {Function} func The function to partially apply arguments to.
16693 * @param {number} bitmask The bitmask of flags. See `createWrapper` for more details.
16694 * @param {*} thisArg The `this` binding of `func`.
16695 * @param {Array} partials The arguments to prepend to those provided to the new function.
16696 * @returns {Function} Returns the new bound function.
16697 */
16698 function createPartialWrapper(func, bitmask, thisArg, partials) {
16699 var isBind = bitmask & BIND_FLAG,
16700 Ctor = createCtorWrapper(func);
16701
16702 function wrapper() {
16703 // Avoid `arguments` object use disqualifying optimizations by
16704 // converting it to an array before providing it `func`.
16705 var argsIndex = -1,
16706 argsLength = arguments.length,
16707 leftIndex = -1,
16708 leftLength = partials.length,
16709 args = Array(leftLength + argsLength);
16710
16711 while (++leftIndex < leftLength) {
16712 args[leftIndex] = partials[leftIndex];
16713 }
16714 while (argsLength--) {
16715 args[leftIndex++] = arguments[++argsIndex];
16716 }
16717 var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;
16718 return fn.apply(isBind ? thisArg : this, args);
16719 }
16720 return wrapper;
16721 }
16722
16723 /**
16724 * Creates a `_.ceil`, `_.floor`, or `_.round` function.
16725 *
16726 * @private
16727 * @param {string} methodName The name of the `Math` method to use when rounding.
16728 * @returns {Function} Returns the new round function.
16729 */
16730 function createRound(methodName) {
16731 var func = Math[methodName];
16732 return function(number, precision) {
16733 precision = precision === undefined ? 0 : (+precision || 0);
16734 if (precision) {
16735 precision = pow(10, precision);
16736 return func(number * precision) / precision;
16737 }
16738 return func(number);
16739 };
16740 }
16741
16742 /**
16743 * Creates a `_.sortedIndex` or `_.sortedLastIndex` function.
16744 *
16745 * @private
16746 * @param {boolean} [retHighest] Specify returning the highest qualified index.
16747 * @returns {Function} Returns the new index function.
16748 */
16749 function createSortedIndex(retHighest) {
16750 return function(array, value, iteratee, thisArg) {
16751 var callback = getCallback(iteratee);
16752 return (iteratee == null && callback === baseCallback)
16753 ? binaryIndex(array, value, retHighest)
16754 : binaryIndexBy(array, value, callback(iteratee, thisArg, 1), retHighest);
16755 };
16756 }
16757
16758 /**
16759 * Creates a function that either curries or invokes `func` with optional
16760 * `this` binding and partially applied arguments.
16761 *
16762 * @private
16763 * @param {Function|string} func The function or method name to reference.
16764 * @param {number} bitmask The bitmask of flags.
16765 * The bitmask may be composed of the following flags:
16766 * 1 - `_.bind`
16767 * 2 - `_.bindKey`
16768 * 4 - `_.curry` or `_.curryRight` of a bound function
16769 * 8 - `_.curry`
16770 * 16 - `_.curryRight`
16771 * 32 - `_.partial`
16772 * 64 - `_.partialRight`
16773 * 128 - `_.rearg`
16774 * 256 - `_.ary`
16775 * @param {*} [thisArg] The `this` binding of `func`.
16776 * @param {Array} [partials] The arguments to be partially applied.
16777 * @param {Array} [holders] The `partials` placeholder indexes.
16778 * @param {Array} [argPos] The argument positions of the new function.
16779 * @param {number} [ary] The arity cap of `func`.
16780 * @param {number} [arity] The arity of `func`.
16781 * @returns {Function} Returns the new wrapped function.
16782 */
16783 function createWrapper(func, bitmask, thisArg, partials, holders, argPos, ary, arity) {
16784 var isBindKey = bitmask & BIND_KEY_FLAG;
16785 if (!isBindKey && typeof func != 'function') {
16786 throw new TypeError(FUNC_ERROR_TEXT);
16787 }
16788 var length = partials ? partials.length : 0;
16789 if (!length) {
16790 bitmask &= ~(PARTIAL_FLAG | PARTIAL_RIGHT_FLAG);
16791 partials = holders = undefined;
16792 }
16793 length -= (holders ? holders.length : 0);
16794 if (bitmask & PARTIAL_RIGHT_FLAG) {
16795 var partialsRight = partials,
16796 holdersRight = holders;
16797
16798 partials = holders = undefined;
16799 }
16800 var data = isBindKey ? undefined : getData(func),
16801 newData = [func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity];
16802
16803 if (data) {
16804 mergeData(newData, data);
16805 bitmask = newData[1];
16806 arity = newData[9];
16807 }
16808 newData[9] = arity == null
16809 ? (isBindKey ? 0 : func.length)
16810 : (nativeMax(arity - length, 0) || 0);
16811
16812 if (bitmask == BIND_FLAG) {
16813 var result = createBindWrapper(newData[0], newData[2]);
16814 } else if ((bitmask == PARTIAL_FLAG || bitmask == (BIND_FLAG | PARTIAL_FLAG)) && !newData[4].length) {
16815 result = createPartialWrapper.apply(undefined, newData);
16816 } else {
16817 result = createHybridWrapper.apply(undefined, newData);
16818 }
16819 var setter = data ? baseSetData : setData;
16820 return setter(result, newData);
16821 }
16822
16823 /**
16824 * A specialized version of `baseIsEqualDeep` for arrays with support for
16825 * partial deep comparisons.
16826 *
16827 * @private
16828 * @param {Array} array The array to compare.
16829 * @param {Array} other The other array to compare.
16830 * @param {Function} equalFunc The function to determine equivalents of values.
16831 * @param {Function} [customizer] The function to customize comparing arrays.
16832 * @param {boolean} [isLoose] Specify performing partial comparisons.
16833 * @param {Array} [stackA] Tracks traversed `value` objects.
16834 * @param {Array} [stackB] Tracks traversed `other` objects.
16835 * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.
16836 */
16837 function equalArrays(array, other, equalFunc, customizer, isLoose, stackA, stackB) {
16838 var index = -1,
16839 arrLength = array.length,
16840 othLength = other.length;
16841
16842 if (arrLength != othLength && !(isLoose && othLength > arrLength)) {
16843 return false;
16844 }
16845 // Ignore non-index properties.
16846 while (++index < arrLength) {
16847 var arrValue = array[index],
16848 othValue = other[index],
16849 result = customizer ? customizer(isLoose ? othValue : arrValue, isLoose ? arrValue : othValue, index) : undefined;
16850
16851 if (result !== undefined) {
16852 if (result) {
16853 continue;
16854 }
16855 return false;
16856 }
16857 // Recursively compare arrays (susceptible to call stack limits).
16858 if (isLoose) {
16859 if (!arraySome(other, function(othValue) {
16860 return arrValue === othValue || equalFunc(arrValue, othValue, customizer, isLoose, stackA, stackB);
16861 })) {
16862 return false;
16863 }
16864 } else if (!(arrValue === othValue || equalFunc(arrValue, othValue, customizer, isLoose, stackA, stackB))) {
16865 return false;
16866 }
16867 }
16868 return true;
16869 }
16870
16871 /**
16872 * A specialized version of `baseIsEqualDeep` for comparing objects of
16873 * the same `toStringTag`.
16874 *
16875 * **Note:** This function only supports comparing values with tags of
16876 * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
16877 *
16878 * @private
16879 * @param {Object} object The object to compare.
16880 * @param {Object} other The other object to compare.
16881 * @param {string} tag The `toStringTag` of the objects to compare.
16882 * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
16883 */
16884 function equalByTag(object, other, tag) {
16885 switch (tag) {
16886 case boolTag:
16887 case dateTag:
16888 // Coerce dates and booleans to numbers, dates to milliseconds and booleans
16889 // to `1` or `0` treating invalid dates coerced to `NaN` as not equal.
16890 return +object == +other;
16891
16892 case errorTag:
16893 return object.name == other.name && object.message == other.message;
16894
16895 case numberTag:
16896 // Treat `NaN` vs. `NaN` as equal.
16897 return (object != +object)
16898 ? other != +other
16899 : object == +other;
16900
16901 case regexpTag:
16902 case stringTag:
16903 // Coerce regexes to strings and treat strings primitives and string
16904 // objects as equal. See https://es5.github.io/#x15.10.6.4 for more details.
16905 return object == (other + '');
16906 }
16907 return false;
16908 }
16909
16910 /**
16911 * A specialized version of `baseIsEqualDeep` for objects with support for
16912 * partial deep comparisons.
16913 *
16914 * @private
16915 * @param {Object} object The object to compare.
16916 * @param {Object} other The other object to compare.
16917 * @param {Function} equalFunc The function to determine equivalents of values.
16918 * @param {Function} [customizer] The function to customize comparing values.
16919 * @param {boolean} [isLoose] Specify performing partial comparisons.
16920 * @param {Array} [stackA] Tracks traversed `value` objects.
16921 * @param {Array} [stackB] Tracks traversed `other` objects.
16922 * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
16923 */
16924 function equalObjects(object, other, equalFunc, customizer, isLoose, stackA, stackB) {
16925 var objProps = keys(object),
16926 objLength = objProps.length,
16927 othProps = keys(other),
16928 othLength = othProps.length;
16929
16930 if (objLength != othLength && !isLoose) {
16931 return false;
16932 }
16933 var index = objLength;
16934 while (index--) {
16935 var key = objProps[index];
16936 if (!(isLoose ? key in other : hasOwnProperty.call(other, key))) {
16937 return false;
16938 }
16939 }
16940 var skipCtor = isLoose;
16941 while (++index < objLength) {
16942 key = objProps[index];
16943 var objValue = object[key],
16944 othValue = other[key],
16945 result = customizer ? customizer(isLoose ? othValue : objValue, isLoose? objValue : othValue, key) : undefined;
16946
16947 // Recursively compare objects (susceptible to call stack limits).
16948 if (!(result === undefined ? equalFunc(objValue, othValue, customizer, isLoose, stackA, stackB) : result)) {
16949 return false;
16950 }
16951 skipCtor || (skipCtor = key == 'constructor');
16952 }
16953 if (!skipCtor) {
16954 var objCtor = object.constructor,
16955 othCtor = other.constructor;
16956
16957 // Non `Object` object instances with different constructors are not equal.
16958 if (objCtor != othCtor &&
16959 ('constructor' in object && 'constructor' in other) &&
16960 !(typeof objCtor == 'function' && objCtor instanceof objCtor &&
16961 typeof othCtor == 'function' && othCtor instanceof othCtor)) {
16962 return false;
16963 }
16964 }
16965 return true;
16966 }
16967
16968 /**
16969 * Gets the appropriate "callback" function. If the `_.callback` method is
16970 * customized this function returns the custom method, otherwise it returns
16971 * the `baseCallback` function. If arguments are provided the chosen function
16972 * is invoked with them and its result is returned.
16973 *
16974 * @private
16975 * @returns {Function} Returns the chosen function or its result.
16976 */
16977 function getCallback(func, thisArg, argCount) {
16978 var result = lodash.callback || callback;
16979 result = result === callback ? baseCallback : result;
16980 return argCount ? result(func, thisArg, argCount) : result;
16981 }
16982
16983 /**
16984 * Gets metadata for `func`.
16985 *
16986 * @private
16987 * @param {Function} func The function to query.
16988 * @returns {*} Returns the metadata for `func`.
16989 */
16990 var getData = !metaMap ? noop : function(func) {
16991 return metaMap.get(func);
16992 };
16993
16994 /**
16995 * Gets the name of `func`.
16996 *
16997 * @private
16998 * @param {Function} func The function to query.
16999 * @returns {string} Returns the function name.
17000 */
17001 function getFuncName(func) {
17002 var result = func.name,
17003 array = realNames[result],
17004 length = array ? array.length : 0;
17005
17006 while (length--) {
17007 var data = array[length],
17008 otherFunc = data.func;
17009 if (otherFunc == null || otherFunc == func) {
17010 return data.name;
17011 }
17012 }
17013 return result;
17014 }
17015
17016 /**
17017 * Gets the appropriate "indexOf" function. If the `_.indexOf` method is
17018 * customized this function returns the custom method, otherwise it returns
17019 * the `baseIndexOf` function. If arguments are provided the chosen function
17020 * is invoked with them and its result is returned.
17021 *
17022 * @private
17023 * @returns {Function|number} Returns the chosen function or its result.
17024 */
17025 function getIndexOf(collection, target, fromIndex) {
17026 var result = lodash.indexOf || indexOf;
17027 result = result === indexOf ? baseIndexOf : result;
17028 return collection ? result(collection, target, fromIndex) : result;
17029 }
17030
17031 /**
17032 * Gets the "length" property value of `object`.
17033 *
17034 * **Note:** This function is used to avoid a [JIT bug](https://bugs.webkit.org/show_bug.cgi?id=142792)
17035 * that affects Safari on at least iOS 8.1-8.3 ARM64.
17036 *
17037 * @private
17038 * @param {Object} object The object to query.
17039 * @returns {*} Returns the "length" value.
17040 */
17041 var getLength = baseProperty('length');
17042
17043 /**
17044 * Gets the propery names, values, and compare flags of `object`.
17045 *
17046 * @private
17047 * @param {Object} object The object to query.
17048 * @returns {Array} Returns the match data of `object`.
17049 */
17050 function getMatchData(object) {
17051 var result = pairs(object),
17052 length = result.length;
17053
17054 while (length--) {
17055 result[length][2] = isStrictComparable(result[length][1]);
17056 }
17057 return result;
17058 }
17059
17060 /**
17061 * Gets the native function at `key` of `object`.
17062 *
17063 * @private
17064 * @param {Object} object The object to query.
17065 * @param {string} key The key of the method to get.
17066 * @returns {*} Returns the function if it's native, else `undefined`.
17067 */
17068 function getNative(object, key) {
17069 var value = object == null ? undefined : object[key];
17070 return isNative(value) ? value : undefined;
17071 }
17072
17073 /**
17074 * Gets the view, applying any `transforms` to the `start` and `end` positions.
17075 *
17076 * @private
17077 * @param {number} start The start of the view.
17078 * @param {number} end The end of the view.
17079 * @param {Array} transforms The transformations to apply to the view.
17080 * @returns {Object} Returns an object containing the `start` and `end`
17081 * positions of the view.
17082 */
17083 function getView(start, end, transforms) {
17084 var index = -1,
17085 length = transforms.length;
17086
17087 while (++index < length) {
17088 var data = transforms[index],
17089 size = data.size;
17090
17091 switch (data.type) {
17092 case 'drop': start += size; break;
17093 case 'dropRight': end -= size; break;
17094 case 'take': end = nativeMin(end, start + size); break;
17095 case 'takeRight': start = nativeMax(start, end - size); break;
17096 }
17097 }
17098 return { 'start': start, 'end': end };
17099 }
17100
17101 /**
17102 * Initializes an array clone.
17103 *
17104 * @private
17105 * @param {Array} array The array to clone.
17106 * @returns {Array} Returns the initialized clone.
17107 */
17108 function initCloneArray(array) {
17109 var length = array.length,
17110 result = new array.constructor(length);
17111
17112 // Add array properties assigned by `RegExp#exec`.
17113 if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) {
17114 result.index = array.index;
17115 result.input = array.input;
17116 }
17117 return result;
17118 }
17119
17120 /**
17121 * Initializes an object clone.
17122 *
17123 * @private
17124 * @param {Object} object The object to clone.
17125 * @returns {Object} Returns the initialized clone.
17126 */
17127 function initCloneObject(object) {
17128 var Ctor = object.constructor;
17129 if (!(typeof Ctor == 'function' && Ctor instanceof Ctor)) {
17130 Ctor = Object;
17131 }
17132 return new Ctor;
17133 }
17134
17135 /**
17136 * Initializes an object clone based on its `toStringTag`.
17137 *
17138 * **Note:** This function only supports cloning values with tags of
17139 * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
17140 *
17141 * @private
17142 * @param {Object} object The object to clone.
17143 * @param {string} tag The `toStringTag` of the object to clone.
17144 * @param {boolean} [isDeep] Specify a deep clone.
17145 * @returns {Object} Returns the initialized clone.
17146 */
17147 function initCloneByTag(object, tag, isDeep) {
17148 var Ctor = object.constructor;
17149 switch (tag) {
17150 case arrayBufferTag:
17151 return bufferClone(object);
17152
17153 case boolTag:
17154 case dateTag:
17155 return new Ctor(+object);
17156
17157 case float32Tag: case float64Tag:
17158 case int8Tag: case int16Tag: case int32Tag:
17159 case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag:
17160 var buffer = object.buffer;
17161 return new Ctor(isDeep ? bufferClone(buffer) : buffer, object.byteOffset, object.length);
17162
17163 case numberTag:
17164 case stringTag:
17165 return new Ctor(object);
17166
17167 case regexpTag:
17168 var result = new Ctor(object.source, reFlags.exec(object));
17169 result.lastIndex = object.lastIndex;
17170 }
17171 return result;
17172 }
17173
17174 /**
17175 * Invokes the method at `path` on `object`.
17176 *
17177 * @private
17178 * @param {Object} object The object to query.
17179 * @param {Array|string} path The path of the method to invoke.
17180 * @param {Array} args The arguments to invoke the method with.
17181 * @returns {*} Returns the result of the invoked method.
17182 */
17183 function invokePath(object, path, args) {
17184 if (object != null && !isKey(path, object)) {
17185 path = toPath(path);
17186 object = path.length == 1 ? object : baseGet(object, baseSlice(path, 0, -1));
17187 path = last(path);
17188 }
17189 var func = object == null ? object : object[path];
17190 return func == null ? undefined : func.apply(object, args);
17191 }
17192
17193 /**
17194 * Checks if `value` is array-like.
17195 *
17196 * @private
17197 * @param {*} value The value to check.
17198 * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
17199 */
17200 function isArrayLike(value) {
17201 return value != null && isLength(getLength(value));
17202 }
17203
17204 /**
17205 * Checks if `value` is a valid array-like index.
17206 *
17207 * @private
17208 * @param {*} value The value to check.
17209 * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
17210 * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
17211 */
17212 function isIndex(value, length) {
17213 value = (typeof value == 'number' || reIsUint.test(value)) ? +value : -1;
17214 length = length == null ? MAX_SAFE_INTEGER : length;
17215 return value > -1 && value % 1 == 0 && value < length;
17216 }
17217
17218 /**
17219 * Checks if the provided arguments are from an iteratee call.
17220 *
17221 * @private
17222 * @param {*} value The potential iteratee value argument.
17223 * @param {*} index The potential iteratee index or key argument.
17224 * @param {*} object The potential iteratee object argument.
17225 * @returns {boolean} Returns `true` if the arguments are from an iteratee call, else `false`.
17226 */
17227 function isIterateeCall(value, index, object) {
17228 if (!isObject(object)) {
17229 return false;
17230 }
17231 var type = typeof index;
17232 if (type == 'number'
17233 ? (isArrayLike(object) && isIndex(index, object.length))
17234 : (type == 'string' && index in object)) {
17235 var other = object[index];
17236 return value === value ? (value === other) : (other !== other);
17237 }
17238 return false;
17239 }
17240
17241 /**
17242 * Checks if `value` is a property name and not a property path.
17243 *
17244 * @private
17245 * @param {*} value The value to check.
17246 * @param {Object} [object] The object to query keys on.
17247 * @returns {boolean} Returns `true` if `value` is a property name, else `false`.
17248 */
17249 function isKey(value, object) {
17250 var type = typeof value;
17251 if ((type == 'string' && reIsPlainProp.test(value)) || type == 'number') {
17252 return true;
17253 }
17254 if (isArray(value)) {
17255 return false;
17256 }
17257 var result = !reIsDeepProp.test(value);
17258 return result || (object != null && value in toObject(object));
17259 }
17260
17261 /**
17262 * Checks if `func` has a lazy counterpart.
17263 *
17264 * @private
17265 * @param {Function} func The function to check.
17266 * @returns {boolean} Returns `true` if `func` has a lazy counterpart, else `false`.
17267 */
17268 function isLaziable(func) {
17269 var funcName = getFuncName(func);
17270 if (!(funcName in LazyWrapper.prototype)) {
17271 return false;
17272 }
17273 var other = lodash[funcName];
17274 if (func === other) {
17275 return true;
17276 }
17277 var data = getData(other);
17278 return !!data && func === data[0];
17279 }
17280
17281 /**
17282 * Checks if `value` is a valid array-like length.
17283 *
17284 * **Note:** This function is based on [`ToLength`](http://ecma-international.org/ecma-262/6.0/#sec-tolength).
17285 *
17286 * @private
17287 * @param {*} value The value to check.
17288 * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
17289 */
17290 function isLength(value) {
17291 return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
17292 }
17293
17294 /**
17295 * Checks if `value` is suitable for strict equality comparisons, i.e. `===`.
17296 *
17297 * @private
17298 * @param {*} value The value to check.
17299 * @returns {boolean} Returns `true` if `value` if suitable for strict
17300 * equality comparisons, else `false`.
17301 */
17302 function isStrictComparable(value) {
17303 return value === value && !isObject(value);
17304 }
17305
17306 /**
17307 * Merges the function metadata of `source` into `data`.
17308 *
17309 * Merging metadata reduces the number of wrappers required to invoke a function.
17310 * This is possible because methods like `_.bind`, `_.curry`, and `_.partial`
17311 * may be applied regardless of execution order. Methods like `_.ary` and `_.rearg`
17312 * augment function arguments, making the order in which they are executed important,
17313 * preventing the merging of metadata. However, we make an exception for a safe
17314 * common case where curried functions have `_.ary` and or `_.rearg` applied.
17315 *
17316 * @private
17317 * @param {Array} data The destination metadata.
17318 * @param {Array} source The source metadata.
17319 * @returns {Array} Returns `data`.
17320 */
17321 function mergeData(data, source) {
17322 var bitmask = data[1],
17323 srcBitmask = source[1],
17324 newBitmask = bitmask | srcBitmask,
17325 isCommon = newBitmask < ARY_FLAG;
17326
17327 var isCombo =
17328 (srcBitmask == ARY_FLAG && bitmask == CURRY_FLAG) ||
17329 (srcBitmask == ARY_FLAG && bitmask == REARG_FLAG && data[7].length <= source[8]) ||
17330 (srcBitmask == (ARY_FLAG | REARG_FLAG) && bitmask == CURRY_FLAG);
17331
17332 // Exit early if metadata can't be merged.
17333 if (!(isCommon || isCombo)) {
17334 return data;
17335 }
17336 // Use source `thisArg` if available.
17337 if (srcBitmask & BIND_FLAG) {
17338 data[2] = source[2];
17339 // Set when currying a bound function.
17340 newBitmask |= (bitmask & BIND_FLAG) ? 0 : CURRY_BOUND_FLAG;
17341 }
17342 // Compose partial arguments.
17343 var value = source[3];
17344 if (value) {
17345 var partials = data[3];
17346 data[3] = partials ? composeArgs(partials, value, source[4]) : arrayCopy(value);
17347 data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : arrayCopy(source[4]);
17348 }
17349 // Compose partial right arguments.
17350 value = source[5];
17351 if (value) {
17352 partials = data[5];
17353 data[5] = partials ? composeArgsRight(partials, value, source[6]) : arrayCopy(value);
17354 data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : arrayCopy(source[6]);
17355 }
17356 // Use source `argPos` if available.
17357 value = source[7];
17358 if (value) {
17359 data[7] = arrayCopy(value);
17360 }
17361 // Use source `ary` if it's smaller.
17362 if (srcBitmask & ARY_FLAG) {
17363 data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]);
17364 }
17365 // Use source `arity` if one is not provided.
17366 if (data[9] == null) {
17367 data[9] = source[9];
17368 }
17369 // Use source `func` and merge bitmasks.
17370 data[0] = source[0];
17371 data[1] = newBitmask;
17372
17373 return data;
17374 }
17375
17376 /**
17377 * Used by `_.defaultsDeep` to customize its `_.merge` use.
17378 *
17379 * @private
17380 * @param {*} objectValue The destination object property value.
17381 * @param {*} sourceValue The source object property value.
17382 * @returns {*} Returns the value to assign to the destination object.
17383 */
17384 function mergeDefaults(objectValue, sourceValue) {
17385 return objectValue === undefined ? sourceValue : merge(objectValue, sourceValue, mergeDefaults);
17386 }
17387
17388 /**
17389 * A specialized version of `_.pick` which picks `object` properties specified
17390 * by `props`.
17391 *
17392 * @private
17393 * @param {Object} object The source object.
17394 * @param {string[]} props The property names to pick.
17395 * @returns {Object} Returns the new object.
17396 */
17397 function pickByArray(object, props) {
17398 object = toObject(object);
17399
17400 var index = -1,
17401 length = props.length,
17402 result = {};
17403
17404 while (++index < length) {
17405 var key = props[index];
17406 if (key in object) {
17407 result[key] = object[key];
17408 }
17409 }
17410 return result;
17411 }
17412
17413 /**
17414 * A specialized version of `_.pick` which picks `object` properties `predicate`
17415 * returns truthy for.
17416 *
17417 * @private
17418 * @param {Object} object The source object.
17419 * @param {Function} predicate The function invoked per iteration.
17420 * @returns {Object} Returns the new object.
17421 */
17422 function pickByCallback(object, predicate) {
17423 var result = {};
17424 baseForIn(object, function(value, key, object) {
17425 if (predicate(value, key, object)) {
17426 result[key] = value;
17427 }
17428 });
17429 return result;
17430 }
17431
17432 /**
17433 * Reorder `array` according to the specified indexes where the element at
17434 * the first index is assigned as the first element, the element at
17435 * the second index is assigned as the second element, and so on.
17436 *
17437 * @private
17438 * @param {Array} array The array to reorder.
17439 * @param {Array} indexes The arranged array indexes.
17440 * @returns {Array} Returns `array`.
17441 */
17442 function reorder(array, indexes) {
17443 var arrLength = array.length,
17444 length = nativeMin(indexes.length, arrLength),
17445 oldArray = arrayCopy(array);
17446
17447 while (length--) {
17448 var index = indexes[length];
17449 array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined;
17450 }
17451 return array;
17452 }
17453
17454 /**
17455 * Sets metadata for `func`.
17456 *
17457 * **Note:** If this function becomes hot, i.e. is invoked a lot in a short
17458 * period of time, it will trip its breaker and transition to an identity function
17459 * to avoid garbage collection pauses in V8. See [V8 issue 2070](https://code.google.com/p/v8/issues/detail?id=2070)
17460 * for more details.
17461 *
17462 * @private
17463 * @param {Function} func The function to associate metadata with.
17464 * @param {*} data The metadata.
17465 * @returns {Function} Returns `func`.
17466 */
17467 var setData = (function() {
17468 var count = 0,
17469 lastCalled = 0;
17470
17471 return function(key, value) {
17472 var stamp = now(),
17473 remaining = HOT_SPAN - (stamp - lastCalled);
17474
17475 lastCalled = stamp;
17476 if (remaining > 0) {
17477 if (++count >= HOT_COUNT) {
17478 return key;
17479 }
17480 } else {
17481 count = 0;
17482 }
17483 return baseSetData(key, value);
17484 };
17485 }());
17486
17487 /**
17488 * A fallback implementation of `Object.keys` which creates an array of the
17489 * own enumerable property names of `object`.
17490 *
17491 * @private
17492 * @param {Object} object The object to query.
17493 * @returns {Array} Returns the array of property names.
17494 */
17495 function shimKeys(object) {
17496 var props = keysIn(object),
17497 propsLength = props.length,
17498 length = propsLength && object.length;
17499
17500 var allowIndexes = !!length && isLength(length) &&
17501 (isArray(object) || isArguments(object));
17502
17503 var index = -1,
17504 result = [];
17505
17506 while (++index < propsLength) {
17507 var key = props[index];
17508 if ((allowIndexes && isIndex(key, length)) || hasOwnProperty.call(object, key)) {
17509 result.push(key);
17510 }
17511 }
17512 return result;
17513 }
17514
17515 /**
17516 * Converts `value` to an array-like object if it's not one.
17517 *
17518 * @private
17519 * @param {*} value The value to process.
17520 * @returns {Array|Object} Returns the array-like object.
17521 */
17522 function toIterable(value) {
17523 if (value == null) {
17524 return [];
17525 }
17526 if (!isArrayLike(value)) {
17527 return values(value);
17528 }
17529 return isObject(value) ? value : Object(value);
17530 }
17531
17532 /**
17533 * Converts `value` to an object if it's not one.
17534 *
17535 * @private
17536 * @param {*} value The value to process.
17537 * @returns {Object} Returns the object.
17538 */
17539 function toObject(value) {
17540 return isObject(value) ? value : Object(value);
17541 }
17542
17543 /**
17544 * Converts `value` to property path array if it's not one.
17545 *
17546 * @private
17547 * @param {*} value The value to process.
17548 * @returns {Array} Returns the property path array.
17549 */
17550 function toPath(value) {
17551 if (isArray(value)) {
17552 return value;
17553 }
17554 var result = [];
17555 baseToString(value).replace(rePropName, function(match, number, quote, string) {
17556 result.push(quote ? string.replace(reEscapeChar, '$1') : (number || match));
17557 });
17558 return result;
17559 }
17560
17561 /**
17562 * Creates a clone of `wrapper`.
17563 *
17564 * @private
17565 * @param {Object} wrapper The wrapper to clone.
17566 * @returns {Object} Returns the cloned wrapper.
17567 */
17568 function wrapperClone(wrapper) {
17569 return wrapper instanceof LazyWrapper
17570 ? wrapper.clone()
17571 : new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__, arrayCopy(wrapper.__actions__));
17572 }
17573
17574 /*------------------------------------------------------------------------*/
17575
17576 /**
17577 * Creates an array of elements split into groups the length of `size`.
17578 * If `collection` can't be split evenly, the final chunk will be the remaining
17579 * elements.
17580 *
17581 * @static
17582 * @memberOf _
17583 * @category Array
17584 * @param {Array} array The array to process.
17585 * @param {number} [size=1] The length of each chunk.
17586 * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
17587 * @returns {Array} Returns the new array containing chunks.
17588 * @example
17589 *
17590 * _.chunk(['a', 'b', 'c', 'd'], 2);
17591 * // => [['a', 'b'], ['c', 'd']]
17592 *
17593 * _.chunk(['a', 'b', 'c', 'd'], 3);
17594 * // => [['a', 'b', 'c'], ['d']]
17595 */
17596 function chunk(array, size, guard) {
17597 if (guard ? isIterateeCall(array, size, guard) : size == null) {
17598 size = 1;
17599 } else {
17600 size = nativeMax(nativeFloor(size) || 1, 1);
17601 }
17602 var index = 0,
17603 length = array ? array.length : 0,
17604 resIndex = -1,
17605 result = Array(nativeCeil(length / size));
17606
17607 while (index < length) {
17608 result[++resIndex] = baseSlice(array, index, (index += size));
17609 }
17610 return result;
17611 }
17612
17613 /**
17614 * Creates an array with all falsey values removed. The values `false`, `null`,
17615 * `0`, `""`, `undefined`, and `NaN` are falsey.
17616 *
17617 * @static
17618 * @memberOf _
17619 * @category Array
17620 * @param {Array} array The array to compact.
17621 * @returns {Array} Returns the new array of filtered values.
17622 * @example
17623 *
17624 * _.compact([0, 1, false, 2, '', 3]);
17625 * // => [1, 2, 3]
17626 */
17627 function compact(array) {
17628 var index = -1,
17629 length = array ? array.length : 0,
17630 resIndex = -1,
17631 result = [];
17632
17633 while (++index < length) {
17634 var value = array[index];
17635 if (value) {
17636 result[++resIndex] = value;
17637 }
17638 }
17639 return result;
17640 }
17641
17642 /**
17643 * Creates an array of unique `array` values not included in the other
17644 * provided arrays using [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
17645 * for equality comparisons.
17646 *
17647 * @static
17648 * @memberOf _
17649 * @category Array
17650 * @param {Array} array The array to inspect.
17651 * @param {...Array} [values] The arrays of values to exclude.
17652 * @returns {Array} Returns the new array of filtered values.
17653 * @example
17654 *
17655 * _.difference([1, 2, 3], [4, 2]);
17656 * // => [1, 3]
17657 */
17658 var difference = restParam(function(array, values) {
17659 return (isObjectLike(array) && isArrayLike(array))
17660 ? baseDifference(array, baseFlatten(values, false, true))
17661 : [];
17662 });
17663
17664 /**
17665 * Creates a slice of `array` with `n` elements dropped from the beginning.
17666 *
17667 * @static
17668 * @memberOf _
17669 * @category Array
17670 * @param {Array} array The array to query.
17671 * @param {number} [n=1] The number of elements to drop.
17672 * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
17673 * @returns {Array} Returns the slice of `array`.
17674 * @example
17675 *
17676 * _.drop([1, 2, 3]);
17677 * // => [2, 3]
17678 *
17679 * _.drop([1, 2, 3], 2);
17680 * // => [3]
17681 *
17682 * _.drop([1, 2, 3], 5);
17683 * // => []
17684 *
17685 * _.drop([1, 2, 3], 0);
17686 * // => [1, 2, 3]
17687 */
17688 function drop(array, n, guard) {
17689 var length = array ? array.length : 0;
17690 if (!length) {
17691 return [];
17692 }
17693 if (guard ? isIterateeCall(array, n, guard) : n == null) {
17694 n = 1;
17695 }
17696 return baseSlice(array, n < 0 ? 0 : n);
17697 }
17698
17699 /**
17700 * Creates a slice of `array` with `n` elements dropped from the end.
17701 *
17702 * @static
17703 * @memberOf _
17704 * @category Array
17705 * @param {Array} array The array to query.
17706 * @param {number} [n=1] The number of elements to drop.
17707 * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
17708 * @returns {Array} Returns the slice of `array`.
17709 * @example
17710 *
17711 * _.dropRight([1, 2, 3]);
17712 * // => [1, 2]
17713 *
17714 * _.dropRight([1, 2, 3], 2);
17715 * // => [1]
17716 *
17717 * _.dropRight([1, 2, 3], 5);
17718 * // => []
17719 *
17720 * _.dropRight([1, 2, 3], 0);
17721 * // => [1, 2, 3]
17722 */
17723 function dropRight(array, n, guard) {
17724 var length = array ? array.length : 0;
17725 if (!length) {
17726 return [];
17727 }
17728 if (guard ? isIterateeCall(array, n, guard) : n == null) {
17729 n = 1;
17730 }
17731 n = length - (+n || 0);
17732 return baseSlice(array, 0, n < 0 ? 0 : n);
17733 }
17734
17735 /**
17736 * Creates a slice of `array` excluding elements dropped from the end.
17737 * Elements are dropped until `predicate` returns falsey. The predicate is
17738 * bound to `thisArg` and invoked with three arguments: (value, index, array).
17739 *
17740 * If a property name is provided for `predicate` the created `_.property`
17741 * style callback returns the property value of the given element.
17742 *
17743 * If a value is also provided for `thisArg` the created `_.matchesProperty`
17744 * style callback returns `true` for elements that have a matching property
17745 * value, else `false`.
17746 *
17747 * If an object is provided for `predicate` the created `_.matches` style
17748 * callback returns `true` for elements that match the properties of the given
17749 * object, else `false`.
17750 *
17751 * @static
17752 * @memberOf _
17753 * @category Array
17754 * @param {Array} array The array to query.
17755 * @param {Function|Object|string} [predicate=_.identity] The function invoked
17756 * per iteration.
17757 * @param {*} [thisArg] The `this` binding of `predicate`.
17758 * @returns {Array} Returns the slice of `array`.
17759 * @example
17760 *
17761 * _.dropRightWhile([1, 2, 3], function(n) {
17762 * return n > 1;
17763 * });
17764 * // => [1]
17765 *
17766 * var users = [
17767 * { 'user': 'barney', 'active': true },
17768 * { 'user': 'fred', 'active': false },
17769 * { 'user': 'pebbles', 'active': false }
17770 * ];
17771 *
17772 * // using the `_.matches` callback shorthand
17773 * _.pluck(_.dropRightWhile(users, { 'user': 'pebbles', 'active': false }), 'user');
17774 * // => ['barney', 'fred']
17775 *
17776 * // using the `_.matchesProperty` callback shorthand
17777 * _.pluck(_.dropRightWhile(users, 'active', false), 'user');
17778 * // => ['barney']
17779 *
17780 * // using the `_.property` callback shorthand
17781 * _.pluck(_.dropRightWhile(users, 'active'), 'user');
17782 * // => ['barney', 'fred', 'pebbles']
17783 */
17784 function dropRightWhile(array, predicate, thisArg) {
17785 return (array && array.length)
17786 ? baseWhile(array, getCallback(predicate, thisArg, 3), true, true)
17787 : [];
17788 }
17789
17790 /**
17791 * Creates a slice of `array` excluding elements dropped from the beginning.
17792 * Elements are dropped until `predicate` returns falsey. The predicate is
17793 * bound to `thisArg` and invoked with three arguments: (value, index, array).
17794 *
17795 * If a property name is provided for `predicate` the created `_.property`
17796 * style callback returns the property value of the given element.
17797 *
17798 * If a value is also provided for `thisArg` the created `_.matchesProperty`
17799 * style callback returns `true` for elements that have a matching property
17800 * value, else `false`.
17801 *
17802 * If an object is provided for `predicate` the created `_.matches` style
17803 * callback returns `true` for elements that have the properties of the given
17804 * object, else `false`.
17805 *
17806 * @static
17807 * @memberOf _
17808 * @category Array
17809 * @param {Array} array The array to query.
17810 * @param {Function|Object|string} [predicate=_.identity] The function invoked
17811 * per iteration.
17812 * @param {*} [thisArg] The `this` binding of `predicate`.
17813 * @returns {Array} Returns the slice of `array`.
17814 * @example
17815 *
17816 * _.dropWhile([1, 2, 3], function(n) {
17817 * return n < 3;
17818 * });
17819 * // => [3]
17820 *
17821 * var users = [
17822 * { 'user': 'barney', 'active': false },
17823 * { 'user': 'fred', 'active': false },
17824 * { 'user': 'pebbles', 'active': true }
17825 * ];
17826 *
17827 * // using the `_.matches` callback shorthand
17828 * _.pluck(_.dropWhile(users, { 'user': 'barney', 'active': false }), 'user');
17829 * // => ['fred', 'pebbles']
17830 *
17831 * // using the `_.matchesProperty` callback shorthand
17832 * _.pluck(_.dropWhile(users, 'active', false), 'user');
17833 * // => ['pebbles']
17834 *
17835 * // using the `_.property` callback shorthand
17836 * _.pluck(_.dropWhile(users, 'active'), 'user');
17837 * // => ['barney', 'fred', 'pebbles']
17838 */
17839 function dropWhile(array, predicate, thisArg) {
17840 return (array && array.length)
17841 ? baseWhile(array, getCallback(predicate, thisArg, 3), true)
17842 : [];
17843 }
17844
17845 /**
17846 * Fills elements of `array` with `value` from `start` up to, but not
17847 * including, `end`.
17848 *
17849 * **Note:** This method mutates `array`.
17850 *
17851 * @static
17852 * @memberOf _
17853 * @category Array
17854 * @param {Array} array The array to fill.
17855 * @param {*} value The value to fill `array` with.
17856 * @param {number} [start=0] The start position.
17857 * @param {number} [end=array.length] The end position.
17858 * @returns {Array} Returns `array`.
17859 * @example
17860 *
17861 * var array = [1, 2, 3];
17862 *
17863 * _.fill(array, 'a');
17864 * console.log(array);
17865 * // => ['a', 'a', 'a']
17866 *
17867 * _.fill(Array(3), 2);
17868 * // => [2, 2, 2]
17869 *
17870 * _.fill([4, 6, 8], '*', 1, 2);
17871 * // => [4, '*', 8]
17872 */
17873 function fill(array, value, start, end) {
17874 var length = array ? array.length : 0;
17875 if (!length) {
17876 return [];
17877 }
17878 if (start && typeof start != 'number' && isIterateeCall(array, value, start)) {
17879 start = 0;
17880 end = length;
17881 }
17882 return baseFill(array, value, start, end);
17883 }
17884
17885 /**
17886 * This method is like `_.find` except that it returns the index of the first
17887 * element `predicate` returns truthy for instead of the element itself.
17888 *
17889 * If a property name is provided for `predicate` the created `_.property`
17890 * style callback returns the property value of the given element.
17891 *
17892 * If a value is also provided for `thisArg` the created `_.matchesProperty`
17893 * style callback returns `true` for elements that have a matching property
17894 * value, else `false`.
17895 *
17896 * If an object is provided for `predicate` the created `_.matches` style
17897 * callback returns `true` for elements that have the properties of the given
17898 * object, else `false`.
17899 *
17900 * @static
17901 * @memberOf _
17902 * @category Array
17903 * @param {Array} array The array to search.
17904 * @param {Function|Object|string} [predicate=_.identity] The function invoked
17905 * per iteration.
17906 * @param {*} [thisArg] The `this` binding of `predicate`.
17907 * @returns {number} Returns the index of the found element, else `-1`.
17908 * @example
17909 *
17910 * var users = [
17911 * { 'user': 'barney', 'active': false },
17912 * { 'user': 'fred', 'active': false },
17913 * { 'user': 'pebbles', 'active': true }
17914 * ];
17915 *
17916 * _.findIndex(users, function(chr) {
17917 * return chr.user == 'barney';
17918 * });
17919 * // => 0
17920 *
17921 * // using the `_.matches` callback shorthand
17922 * _.findIndex(users, { 'user': 'fred', 'active': false });
17923 * // => 1
17924 *
17925 * // using the `_.matchesProperty` callback shorthand
17926 * _.findIndex(users, 'active', false);
17927 * // => 0
17928 *
17929 * // using the `_.property` callback shorthand
17930 * _.findIndex(users, 'active');
17931 * // => 2
17932 */
17933 var findIndex = createFindIndex();
17934
17935 /**
17936 * This method is like `_.findIndex` except that it iterates over elements
17937 * of `collection` from right to left.
17938 *
17939 * If a property name is provided for `predicate` the created `_.property`
17940 * style callback returns the property value of the given element.
17941 *
17942 * If a value is also provided for `thisArg` the created `_.matchesProperty`
17943 * style callback returns `true` for elements that have a matching property
17944 * value, else `false`.
17945 *
17946 * If an object is provided for `predicate` the created `_.matches` style
17947 * callback returns `true` for elements that have the properties of the given
17948 * object, else `false`.
17949 *
17950 * @static
17951 * @memberOf _
17952 * @category Array
17953 * @param {Array} array The array to search.
17954 * @param {Function|Object|string} [predicate=_.identity] The function invoked
17955 * per iteration.
17956 * @param {*} [thisArg] The `this` binding of `predicate`.
17957 * @returns {number} Returns the index of the found element, else `-1`.
17958 * @example
17959 *
17960 * var users = [
17961 * { 'user': 'barney', 'active': true },
17962 * { 'user': 'fred', 'active': false },
17963 * { 'user': 'pebbles', 'active': false }
17964 * ];
17965 *
17966 * _.findLastIndex(users, function(chr) {
17967 * return chr.user == 'pebbles';
17968 * });
17969 * // => 2
17970 *
17971 * // using the `_.matches` callback shorthand
17972 * _.findLastIndex(users, { 'user': 'barney', 'active': true });
17973 * // => 0
17974 *
17975 * // using the `_.matchesProperty` callback shorthand
17976 * _.findLastIndex(users, 'active', false);
17977 * // => 2
17978 *
17979 * // using the `_.property` callback shorthand
17980 * _.findLastIndex(users, 'active');
17981 * // => 0
17982 */
17983 var findLastIndex = createFindIndex(true);
17984
17985 /**
17986 * Gets the first element of `array`.
17987 *
17988 * @static
17989 * @memberOf _
17990 * @alias head
17991 * @category Array
17992 * @param {Array} array The array to query.
17993 * @returns {*} Returns the first element of `array`.
17994 * @example
17995 *
17996 * _.first([1, 2, 3]);
17997 * // => 1
17998 *
17999 * _.first([]);
18000 * // => undefined
18001 */
18002 function first(array) {
18003 return array ? array[0] : undefined;
18004 }
18005
18006 /**
18007 * Flattens a nested array. If `isDeep` is `true` the array is recursively
18008 * flattened, otherwise it is only flattened a single level.
18009 *
18010 * @static
18011 * @memberOf _
18012 * @category Array
18013 * @param {Array} array The array to flatten.
18014 * @param {boolean} [isDeep] Specify a deep flatten.
18015 * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
18016 * @returns {Array} Returns the new flattened array.
18017 * @example
18018 *
18019 * _.flatten([1, [2, 3, [4]]]);
18020 * // => [1, 2, 3, [4]]
18021 *
18022 * // using `isDeep`
18023 * _.flatten([1, [2, 3, [4]]], true);
18024 * // => [1, 2, 3, 4]
18025 */
18026 function flatten(array, isDeep, guard) {
18027 var length = array ? array.length : 0;
18028 if (guard && isIterateeCall(array, isDeep, guard)) {
18029 isDeep = false;
18030 }
18031 return length ? baseFlatten(array, isDeep) : [];
18032 }
18033
18034 /**
18035 * Recursively flattens a nested array.
18036 *
18037 * @static
18038 * @memberOf _
18039 * @category Array
18040 * @param {Array} array The array to recursively flatten.
18041 * @returns {Array} Returns the new flattened array.
18042 * @example
18043 *
18044 * _.flattenDeep([1, [2, 3, [4]]]);
18045 * // => [1, 2, 3, 4]
18046 */
18047 function flattenDeep(array) {
18048 var length = array ? array.length : 0;
18049 return length ? baseFlatten(array, true) : [];
18050 }
18051
18052 /**
18053 * Gets the index at which the first occurrence of `value` is found in `array`
18054 * using [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
18055 * for equality comparisons. If `fromIndex` is negative, it is used as the offset
18056 * from the end of `array`. If `array` is sorted providing `true` for `fromIndex`
18057 * performs a faster binary search.
18058 *
18059 * @static
18060 * @memberOf _
18061 * @category Array
18062 * @param {Array} array The array to search.
18063 * @param {*} value The value to search for.
18064 * @param {boolean|number} [fromIndex=0] The index to search from or `true`
18065 * to perform a binary search on a sorted array.
18066 * @returns {number} Returns the index of the matched value, else `-1`.
18067 * @example
18068 *
18069 * _.indexOf([1, 2, 1, 2], 2);
18070 * // => 1
18071 *
18072 * // using `fromIndex`
18073 * _.indexOf([1, 2, 1, 2], 2, 2);
18074 * // => 3
18075 *
18076 * // performing a binary search
18077 * _.indexOf([1, 1, 2, 2], 2, true);
18078 * // => 2
18079 */
18080 function indexOf(array, value, fromIndex) {
18081 var length = array ? array.length : 0;
18082 if (!length) {
18083 return -1;
18084 }
18085 if (typeof fromIndex == 'number') {
18086 fromIndex = fromIndex < 0 ? nativeMax(length + fromIndex, 0) : fromIndex;
18087 } else if (fromIndex) {
18088 var index = binaryIndex(array, value);
18089 if (index < length &&
18090 (value === value ? (value === array[index]) : (array[index] !== array[index]))) {
18091 return index;
18092 }
18093 return -1;
18094 }
18095 return baseIndexOf(array, value, fromIndex || 0);
18096 }
18097
18098 /**
18099 * Gets all but the last element of `array`.
18100 *
18101 * @static
18102 * @memberOf _
18103 * @category Array
18104 * @param {Array} array The array to query.
18105 * @returns {Array} Returns the slice of `array`.
18106 * @example
18107 *
18108 * _.initial([1, 2, 3]);
18109 * // => [1, 2]
18110 */
18111 function initial(array) {
18112 return dropRight(array, 1);
18113 }
18114
18115 /**
18116 * Creates an array of unique values that are included in all of the provided
18117 * arrays using [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
18118 * for equality comparisons.
18119 *
18120 * @static
18121 * @memberOf _
18122 * @category Array
18123 * @param {...Array} [arrays] The arrays to inspect.
18124 * @returns {Array} Returns the new array of shared values.
18125 * @example
18126 * _.intersection([1, 2], [4, 2], [2, 1]);
18127 * // => [2]
18128 */
18129 var intersection = restParam(function(arrays) {
18130 var othLength = arrays.length,
18131 othIndex = othLength,
18132 caches = Array(length),
18133 indexOf = getIndexOf(),
18134 isCommon = indexOf == baseIndexOf,
18135 result = [];
18136
18137 while (othIndex--) {
18138 var value = arrays[othIndex] = isArrayLike(value = arrays[othIndex]) ? value : [];
18139 caches[othIndex] = (isCommon && value.length >= 120) ? createCache(othIndex && value) : null;
18140 }
18141 var array = arrays[0],
18142 index = -1,
18143 length = array ? array.length : 0,
18144 seen = caches[0];
18145
18146 outer:
18147 while (++index < length) {
18148 value = array[index];
18149 if ((seen ? cacheIndexOf(seen, value) : indexOf(result, value, 0)) < 0) {
18150 var othIndex = othLength;
18151 while (--othIndex) {
18152 var cache = caches[othIndex];
18153 if ((cache ? cacheIndexOf(cache, value) : indexOf(arrays[othIndex], value, 0)) < 0) {
18154 continue outer;
18155 }
18156 }
18157 if (seen) {
18158 seen.push(value);
18159 }
18160 result.push(value);
18161 }
18162 }
18163 return result;
18164 });
18165
18166 /**
18167 * Gets the last element of `array`.
18168 *
18169 * @static
18170 * @memberOf _
18171 * @category Array
18172 * @param {Array} array The array to query.
18173 * @returns {*} Returns the last element of `array`.
18174 * @example
18175 *
18176 * _.last([1, 2, 3]);
18177 * // => 3
18178 */
18179 function last(array) {
18180 var length = array ? array.length : 0;
18181 return length ? array[length - 1] : undefined;
18182 }
18183
18184 /**
18185 * This method is like `_.indexOf` except that it iterates over elements of
18186 * `array` from right to left.
18187 *
18188 * @static
18189 * @memberOf _
18190 * @category Array
18191 * @param {Array} array The array to search.
18192 * @param {*} value The value to search for.
18193 * @param {boolean|number} [fromIndex=array.length-1] The index to search from
18194 * or `true` to perform a binary search on a sorted array.
18195 * @returns {number} Returns the index of the matched value, else `-1`.
18196 * @example
18197 *
18198 * _.lastIndexOf([1, 2, 1, 2], 2);
18199 * // => 3
18200 *
18201 * // using `fromIndex`
18202 * _.lastIndexOf([1, 2, 1, 2], 2, 2);
18203 * // => 1
18204 *
18205 * // performing a binary search
18206 * _.lastIndexOf([1, 1, 2, 2], 2, true);
18207 * // => 3
18208 */
18209 function lastIndexOf(array, value, fromIndex) {
18210 var length = array ? array.length : 0;
18211 if (!length) {
18212 return -1;
18213 }
18214 var index = length;
18215 if (typeof fromIndex == 'number') {
18216 index = (fromIndex < 0 ? nativeMax(length + fromIndex, 0) : nativeMin(fromIndex || 0, length - 1)) + 1;
18217 } else if (fromIndex) {
18218 index = binaryIndex(array, value, true) - 1;
18219 var other = array[index];
18220 if (value === value ? (value === other) : (other !== other)) {
18221 return index;
18222 }
18223 return -1;
18224 }
18225 if (value !== value) {
18226 return indexOfNaN(array, index, true);
18227 }
18228 while (index--) {
18229 if (array[index] === value) {
18230 return index;
18231 }
18232 }
18233 return -1;
18234 }
18235
18236 /**
18237 * Removes all provided values from `array` using
18238 * [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
18239 * for equality comparisons.
18240 *
18241 * **Note:** Unlike `_.without`, this method mutates `array`.
18242 *
18243 * @static
18244 * @memberOf _
18245 * @category Array
18246 * @param {Array} array The array to modify.
18247 * @param {...*} [values] The values to remove.
18248 * @returns {Array} Returns `array`.
18249 * @example
18250 *
18251 * var array = [1, 2, 3, 1, 2, 3];
18252 *
18253 * _.pull(array, 2, 3);
18254 * console.log(array);
18255 * // => [1, 1]
18256 */
18257 function pull() {
18258 var args = arguments,
18259 array = args[0];
18260
18261 if (!(array && array.length)) {
18262 return array;
18263 }
18264 var index = 0,
18265 indexOf = getIndexOf(),
18266 length = args.length;
18267
18268 while (++index < length) {
18269 var fromIndex = 0,
18270 value = args[index];
18271
18272 while ((fromIndex = indexOf(array, value, fromIndex)) > -1) {
18273 splice.call(array, fromIndex, 1);
18274 }
18275 }
18276 return array;
18277 }
18278
18279 /**
18280 * Removes elements from `array` corresponding to the given indexes and returns
18281 * an array of the removed elements. Indexes may be specified as an array of
18282 * indexes or as individual arguments.
18283 *
18284 * **Note:** Unlike `_.at`, this method mutates `array`.
18285 *
18286 * @static
18287 * @memberOf _
18288 * @category Array
18289 * @param {Array} array The array to modify.
18290 * @param {...(number|number[])} [indexes] The indexes of elements to remove,
18291 * specified as individual indexes or arrays of indexes.
18292 * @returns {Array} Returns the new array of removed elements.
18293 * @example
18294 *
18295 * var array = [5, 10, 15, 20];
18296 * var evens = _.pullAt(array, 1, 3);
18297 *
18298 * console.log(array);
18299 * // => [5, 15]
18300 *
18301 * console.log(evens);
18302 * // => [10, 20]
18303 */
18304 var pullAt = restParam(function(array, indexes) {
18305 indexes = baseFlatten(indexes);
18306
18307 var result = baseAt(array, indexes);
18308 basePullAt(array, indexes.sort(baseCompareAscending));
18309 return result;
18310 });
18311
18312 /**
18313 * Removes all elements from `array` that `predicate` returns truthy for
18314 * and returns an array of the removed elements. The predicate is bound to
18315 * `thisArg` and invoked with three arguments: (value, index, array).
18316 *
18317 * If a property name is provided for `predicate` the created `_.property`
18318 * style callback returns the property value of the given element.
18319 *
18320 * If a value is also provided for `thisArg` the created `_.matchesProperty`
18321 * style callback returns `true` for elements that have a matching property
18322 * value, else `false`.
18323 *
18324 * If an object is provided for `predicate` the created `_.matches` style
18325 * callback returns `true` for elements that have the properties of the given
18326 * object, else `false`.
18327 *
18328 * **Note:** Unlike `_.filter`, this method mutates `array`.
18329 *
18330 * @static
18331 * @memberOf _
18332 * @category Array
18333 * @param {Array} array The array to modify.
18334 * @param {Function|Object|string} [predicate=_.identity] The function invoked
18335 * per iteration.
18336 * @param {*} [thisArg] The `this` binding of `predicate`.
18337 * @returns {Array} Returns the new array of removed elements.
18338 * @example
18339 *
18340 * var array = [1, 2, 3, 4];
18341 * var evens = _.remove(array, function(n) {
18342 * return n % 2 == 0;
18343 * });
18344 *
18345 * console.log(array);
18346 * // => [1, 3]
18347 *
18348 * console.log(evens);
18349 * // => [2, 4]
18350 */
18351 function remove(array, predicate, thisArg) {
18352 var result = [];
18353 if (!(array && array.length)) {
18354 return result;
18355 }
18356 var index = -1,
18357 indexes = [],
18358 length = array.length;
18359
18360 predicate = getCallback(predicate, thisArg, 3);
18361 while (++index < length) {
18362 var value = array[index];
18363 if (predicate(value, index, array)) {
18364 result.push(value);
18365 indexes.push(index);
18366 }
18367 }
18368 basePullAt(array, indexes);
18369 return result;
18370 }
18371
18372 /**
18373 * Gets all but the first element of `array`.
18374 *
18375 * @static
18376 * @memberOf _
18377 * @alias tail
18378 * @category Array
18379 * @param {Array} array The array to query.
18380 * @returns {Array} Returns the slice of `array`.
18381 * @example
18382 *
18383 * _.rest([1, 2, 3]);
18384 * // => [2, 3]
18385 */
18386 function rest(array) {
18387 return drop(array, 1);
18388 }
18389
18390 /**
18391 * Creates a slice of `array` from `start` up to, but not including, `end`.
18392 *
18393 * **Note:** This method is used instead of `Array#slice` to support node
18394 * lists in IE < 9 and to ensure dense arrays are returned.
18395 *
18396 * @static
18397 * @memberOf _
18398 * @category Array
18399 * @param {Array} array The array to slice.
18400 * @param {number} [start=0] The start position.
18401 * @param {number} [end=array.length] The end position.
18402 * @returns {Array} Returns the slice of `array`.
18403 */
18404 function slice(array, start, end) {
18405 var length = array ? array.length : 0;
18406 if (!length) {
18407 return [];
18408 }
18409 if (end && typeof end != 'number' && isIterateeCall(array, start, end)) {
18410 start = 0;
18411 end = length;
18412 }
18413 return baseSlice(array, start, end);
18414 }
18415
18416 /**
18417 * Uses a binary search to determine the lowest index at which `value` should
18418 * be inserted into `array` in order to maintain its sort order. If an iteratee
18419 * function is provided it is invoked for `value` and each element of `array`
18420 * to compute their sort ranking. The iteratee is bound to `thisArg` and
18421 * invoked with one argument; (value).
18422 *
18423 * If a property name is provided for `iteratee` the created `_.property`
18424 * style callback returns the property value of the given element.
18425 *
18426 * If a value is also provided for `thisArg` the created `_.matchesProperty`
18427 * style callback returns `true` for elements that have a matching property
18428 * value, else `false`.
18429 *
18430 * If an object is provided for `iteratee` the created `_.matches` style
18431 * callback returns `true` for elements that have the properties of the given
18432 * object, else `false`.
18433 *
18434 * @static
18435 * @memberOf _
18436 * @category Array
18437 * @param {Array} array The sorted array to inspect.
18438 * @param {*} value The value to evaluate.
18439 * @param {Function|Object|string} [iteratee=_.identity] The function invoked
18440 * per iteration.
18441 * @param {*} [thisArg] The `this` binding of `iteratee`.
18442 * @returns {number} Returns the index at which `value` should be inserted
18443 * into `array`.
18444 * @example
18445 *
18446 * _.sortedIndex([30, 50], 40);
18447 * // => 1
18448 *
18449 * _.sortedIndex([4, 4, 5, 5], 5);
18450 * // => 2
18451 *
18452 * var dict = { 'data': { 'thirty': 30, 'forty': 40, 'fifty': 50 } };
18453 *
18454 * // using an iteratee function
18455 * _.sortedIndex(['thirty', 'fifty'], 'forty', function(word) {
18456 * return this.data[word];
18457 * }, dict);
18458 * // => 1
18459 *
18460 * // using the `_.property` callback shorthand
18461 * _.sortedIndex([{ 'x': 30 }, { 'x': 50 }], { 'x': 40 }, 'x');
18462 * // => 1
18463 */
18464 var sortedIndex = createSortedIndex();
18465
18466 /**
18467 * This method is like `_.sortedIndex` except that it returns the highest
18468 * index at which `value` should be inserted into `array` in order to
18469 * maintain its sort order.
18470 *
18471 * @static
18472 * @memberOf _
18473 * @category Array
18474 * @param {Array} array The sorted array to inspect.
18475 * @param {*} value The value to evaluate.
18476 * @param {Function|Object|string} [iteratee=_.identity] The function invoked
18477 * per iteration.
18478 * @param {*} [thisArg] The `this` binding of `iteratee`.
18479 * @returns {number} Returns the index at which `value` should be inserted
18480 * into `array`.
18481 * @example
18482 *
18483 * _.sortedLastIndex([4, 4, 5, 5], 5);
18484 * // => 4
18485 */
18486 var sortedLastIndex = createSortedIndex(true);
18487
18488 /**
18489 * Creates a slice of `array` with `n` elements taken from the beginning.
18490 *
18491 * @static
18492 * @memberOf _
18493 * @category Array
18494 * @param {Array} array The array to query.
18495 * @param {number} [n=1] The number of elements to take.
18496 * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
18497 * @returns {Array} Returns the slice of `array`.
18498 * @example
18499 *
18500 * _.take([1, 2, 3]);
18501 * // => [1]
18502 *
18503 * _.take([1, 2, 3], 2);
18504 * // => [1, 2]
18505 *
18506 * _.take([1, 2, 3], 5);
18507 * // => [1, 2, 3]
18508 *
18509 * _.take([1, 2, 3], 0);
18510 * // => []
18511 */
18512 function take(array, n, guard) {
18513 var length = array ? array.length : 0;
18514 if (!length) {
18515 return [];
18516 }
18517 if (guard ? isIterateeCall(array, n, guard) : n == null) {
18518 n = 1;
18519 }
18520 return baseSlice(array, 0, n < 0 ? 0 : n);
18521 }
18522
18523 /**
18524 * Creates a slice of `array` with `n` elements taken from the end.
18525 *
18526 * @static
18527 * @memberOf _
18528 * @category Array
18529 * @param {Array} array The array to query.
18530 * @param {number} [n=1] The number of elements to take.
18531 * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
18532 * @returns {Array} Returns the slice of `array`.
18533 * @example
18534 *
18535 * _.takeRight([1, 2, 3]);
18536 * // => [3]
18537 *
18538 * _.takeRight([1, 2, 3], 2);
18539 * // => [2, 3]
18540 *
18541 * _.takeRight([1, 2, 3], 5);
18542 * // => [1, 2, 3]
18543 *
18544 * _.takeRight([1, 2, 3], 0);
18545 * // => []
18546 */
18547 function takeRight(array, n, guard) {
18548 var length = array ? array.length : 0;
18549 if (!length) {
18550 return [];
18551 }
18552 if (guard ? isIterateeCall(array, n, guard) : n == null) {
18553 n = 1;
18554 }
18555 n = length - (+n || 0);
18556 return baseSlice(array, n < 0 ? 0 : n);
18557 }
18558
18559 /**
18560 * Creates a slice of `array` with elements taken from the end. Elements are
18561 * taken until `predicate` returns falsey. The predicate is bound to `thisArg`
18562 * and invoked with three arguments: (value, index, array).
18563 *
18564 * If a property name is provided for `predicate` the created `_.property`
18565 * style callback returns the property value of the given element.
18566 *
18567 * If a value is also provided for `thisArg` the created `_.matchesProperty`
18568 * style callback returns `true` for elements that have a matching property
18569 * value, else `false`.
18570 *
18571 * If an object is provided for `predicate` the created `_.matches` style
18572 * callback returns `true` for elements that have the properties of the given
18573 * object, else `false`.
18574 *
18575 * @static
18576 * @memberOf _
18577 * @category Array
18578 * @param {Array} array The array to query.
18579 * @param {Function|Object|string} [predicate=_.identity] The function invoked
18580 * per iteration.
18581 * @param {*} [thisArg] The `this` binding of `predicate`.
18582 * @returns {Array} Returns the slice of `array`.
18583 * @example
18584 *
18585 * _.takeRightWhile([1, 2, 3], function(n) {
18586 * return n > 1;
18587 * });
18588 * // => [2, 3]
18589 *
18590 * var users = [
18591 * { 'user': 'barney', 'active': true },
18592 * { 'user': 'fred', 'active': false },
18593 * { 'user': 'pebbles', 'active': false }
18594 * ];
18595 *
18596 * // using the `_.matches` callback shorthand
18597 * _.pluck(_.takeRightWhile(users, { 'user': 'pebbles', 'active': false }), 'user');
18598 * // => ['pebbles']
18599 *
18600 * // using the `_.matchesProperty` callback shorthand
18601 * _.pluck(_.takeRightWhile(users, 'active', false), 'user');
18602 * // => ['fred', 'pebbles']
18603 *
18604 * // using the `_.property` callback shorthand
18605 * _.pluck(_.takeRightWhile(users, 'active'), 'user');
18606 * // => []
18607 */
18608 function takeRightWhile(array, predicate, thisArg) {
18609 return (array && array.length)
18610 ? baseWhile(array, getCallback(predicate, thisArg, 3), false, true)
18611 : [];
18612 }
18613
18614 /**
18615 * Creates a slice of `array` with elements taken from the beginning. Elements
18616 * are taken until `predicate` returns falsey. The predicate is bound to
18617 * `thisArg` and invoked with three arguments: (value, index, array).
18618 *
18619 * If a property name is provided for `predicate` the created `_.property`
18620 * style callback returns the property value of the given element.
18621 *
18622 * If a value is also provided for `thisArg` the created `_.matchesProperty`
18623 * style callback returns `true` for elements that have a matching property
18624 * value, else `false`.
18625 *
18626 * If an object is provided for `predicate` the created `_.matches` style
18627 * callback returns `true` for elements that have the properties of the given
18628 * object, else `false`.
18629 *
18630 * @static
18631 * @memberOf _
18632 * @category Array
18633 * @param {Array} array The array to query.
18634 * @param {Function|Object|string} [predicate=_.identity] The function invoked
18635 * per iteration.
18636 * @param {*} [thisArg] The `this` binding of `predicate`.
18637 * @returns {Array} Returns the slice of `array`.
18638 * @example
18639 *
18640 * _.takeWhile([1, 2, 3], function(n) {
18641 * return n < 3;
18642 * });
18643 * // => [1, 2]
18644 *
18645 * var users = [
18646 * { 'user': 'barney', 'active': false },
18647 * { 'user': 'fred', 'active': false},
18648 * { 'user': 'pebbles', 'active': true }
18649 * ];
18650 *
18651 * // using the `_.matches` callback shorthand
18652 * _.pluck(_.takeWhile(users, { 'user': 'barney', 'active': false }), 'user');
18653 * // => ['barney']
18654 *
18655 * // using the `_.matchesProperty` callback shorthand
18656 * _.pluck(_.takeWhile(users, 'active', false), 'user');
18657 * // => ['barney', 'fred']
18658 *
18659 * // using the `_.property` callback shorthand
18660 * _.pluck(_.takeWhile(users, 'active'), 'user');
18661 * // => []
18662 */
18663 function takeWhile(array, predicate, thisArg) {
18664 return (array && array.length)
18665 ? baseWhile(array, getCallback(predicate, thisArg, 3))
18666 : [];
18667 }
18668
18669 /**
18670 * Creates an array of unique values, in order, from all of the provided arrays
18671 * using [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
18672 * for equality comparisons.
18673 *
18674 * @static
18675 * @memberOf _
18676 * @category Array
18677 * @param {...Array} [arrays] The arrays to inspect.
18678 * @returns {Array} Returns the new array of combined values.
18679 * @example
18680 *
18681 * _.union([1, 2], [4, 2], [2, 1]);
18682 * // => [1, 2, 4]
18683 */
18684 var union = restParam(function(arrays) {
18685 return baseUniq(baseFlatten(arrays, false, true));
18686 });
18687
18688 /**
18689 * Creates a duplicate-free version of an array, using
18690 * [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
18691 * for equality comparisons, in which only the first occurence of each element
18692 * is kept. Providing `true` for `isSorted` performs a faster search algorithm
18693 * for sorted arrays. If an iteratee function is provided it is invoked for
18694 * each element in the array to generate the criterion by which uniqueness
18695 * is computed. The `iteratee` is bound to `thisArg` and invoked with three
18696 * arguments: (value, index, array).
18697 *
18698 * If a property name is provided for `iteratee` the created `_.property`
18699 * style callback returns the property value of the given element.
18700 *
18701 * If a value is also provided for `thisArg` the created `_.matchesProperty`
18702 * style callback returns `true` for elements that have a matching property
18703 * value, else `false`.
18704 *
18705 * If an object is provided for `iteratee` the created `_.matches` style
18706 * callback returns `true` for elements that have the properties of the given
18707 * object, else `false`.
18708 *
18709 * @static
18710 * @memberOf _
18711 * @alias unique
18712 * @category Array
18713 * @param {Array} array The array to inspect.
18714 * @param {boolean} [isSorted] Specify the array is sorted.
18715 * @param {Function|Object|string} [iteratee] The function invoked per iteration.
18716 * @param {*} [thisArg] The `this` binding of `iteratee`.
18717 * @returns {Array} Returns the new duplicate-value-free array.
18718 * @example
18719 *
18720 * _.uniq([2, 1, 2]);
18721 * // => [2, 1]
18722 *
18723 * // using `isSorted`
18724 * _.uniq([1, 1, 2], true);
18725 * // => [1, 2]
18726 *
18727 * // using an iteratee function
18728 * _.uniq([1, 2.5, 1.5, 2], function(n) {
18729 * return this.floor(n);
18730 * }, Math);
18731 * // => [1, 2.5]
18732 *
18733 * // using the `_.property` callback shorthand
18734 * _.uniq([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x');
18735 * // => [{ 'x': 1 }, { 'x': 2 }]
18736 */
18737 function uniq(array, isSorted, iteratee, thisArg) {
18738 var length = array ? array.length : 0;
18739 if (!length) {
18740 return [];
18741 }
18742 if (isSorted != null && typeof isSorted != 'boolean') {
18743 thisArg = iteratee;
18744 iteratee = isIterateeCall(array, isSorted, thisArg) ? undefined : isSorted;
18745 isSorted = false;
18746 }
18747 var callback = getCallback();
18748 if (!(iteratee == null && callback === baseCallback)) {
18749 iteratee = callback(iteratee, thisArg, 3);
18750 }
18751 return (isSorted && getIndexOf() == baseIndexOf)
18752 ? sortedUniq(array, iteratee)
18753 : baseUniq(array, iteratee);
18754 }
18755
18756 /**
18757 * This method is like `_.zip` except that it accepts an array of grouped
18758 * elements and creates an array regrouping the elements to their pre-zip
18759 * configuration.
18760 *
18761 * @static
18762 * @memberOf _
18763 * @category Array
18764 * @param {Array} array The array of grouped elements to process.
18765 * @returns {Array} Returns the new array of regrouped elements.
18766 * @example
18767 *
18768 * var zipped = _.zip(['fred', 'barney'], [30, 40], [true, false]);
18769 * // => [['fred', 30, true], ['barney', 40, false]]
18770 *
18771 * _.unzip(zipped);
18772 * // => [['fred', 'barney'], [30, 40], [true, false]]
18773 */
18774 function unzip(array) {
18775 if (!(array && array.length)) {
18776 return [];
18777 }
18778 var index = -1,
18779 length = 0;
18780
18781 array = arrayFilter(array, function(group) {
18782 if (isArrayLike(group)) {
18783 length = nativeMax(group.length, length);
18784 return true;
18785 }
18786 });
18787 var result = Array(length);
18788 while (++index < length) {
18789 result[index] = arrayMap(array, baseProperty(index));
18790 }
18791 return result;
18792 }
18793
18794 /**
18795 * This method is like `_.unzip` except that it accepts an iteratee to specify
18796 * how regrouped values should be combined. The `iteratee` is bound to `thisArg`
18797 * and invoked with four arguments: (accumulator, value, index, group).
18798 *
18799 * @static
18800 * @memberOf _
18801 * @category Array
18802 * @param {Array} array The array of grouped elements to process.
18803 * @param {Function} [iteratee] The function to combine regrouped values.
18804 * @param {*} [thisArg] The `this` binding of `iteratee`.
18805 * @returns {Array} Returns the new array of regrouped elements.
18806 * @example
18807 *
18808 * var zipped = _.zip([1, 2], [10, 20], [100, 200]);
18809 * // => [[1, 10, 100], [2, 20, 200]]
18810 *
18811 * _.unzipWith(zipped, _.add);
18812 * // => [3, 30, 300]
18813 */
18814 function unzipWith(array, iteratee, thisArg) {
18815 var length = array ? array.length : 0;
18816 if (!length) {
18817 return [];
18818 }
18819 var result = unzip(array);
18820 if (iteratee == null) {
18821 return result;
18822 }
18823 iteratee = bindCallback(iteratee, thisArg, 4);
18824 return arrayMap(result, function(group) {
18825 return arrayReduce(group, iteratee, undefined, true);
18826 });
18827 }
18828
18829 /**
18830 * Creates an array excluding all provided values using
18831 * [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
18832 * for equality comparisons.
18833 *
18834 * @static
18835 * @memberOf _
18836 * @category Array
18837 * @param {Array} array The array to filter.
18838 * @param {...*} [values] The values to exclude.
18839 * @returns {Array} Returns the new array of filtered values.
18840 * @example
18841 *
18842 * _.without([1, 2, 1, 3], 1, 2);
18843 * // => [3]
18844 */
18845 var without = restParam(function(array, values) {
18846 return isArrayLike(array)
18847 ? baseDifference(array, values)
18848 : [];
18849 });
18850
18851 /**
18852 * Creates an array of unique values that is the [symmetric difference](https://en.wikipedia.org/wiki/Symmetric_difference)
18853 * of the provided arrays.
18854 *
18855 * @static
18856 * @memberOf _
18857 * @category Array
18858 * @param {...Array} [arrays] The arrays to inspect.
18859 * @returns {Array} Returns the new array of values.
18860 * @example
18861 *
18862 * _.xor([1, 2], [4, 2]);
18863 * // => [1, 4]
18864 */
18865 function xor() {
18866 var index = -1,
18867 length = arguments.length;
18868
18869 while (++index < length) {
18870 var array = arguments[index];
18871 if (isArrayLike(array)) {
18872 var result = result
18873 ? arrayPush(baseDifference(result, array), baseDifference(array, result))
18874 : array;
18875 }
18876 }
18877 return result ? baseUniq(result) : [];
18878 }
18879
18880 /**
18881 * Creates an array of grouped elements, the first of which contains the first
18882 * elements of the given arrays, the second of which contains the second elements
18883 * of the given arrays, and so on.
18884 *
18885 * @static
18886 * @memberOf _
18887 * @category Array
18888 * @param {...Array} [arrays] The arrays to process.
18889 * @returns {Array} Returns the new array of grouped elements.
18890 * @example
18891 *
18892 * _.zip(['fred', 'barney'], [30, 40], [true, false]);
18893 * // => [['fred', 30, true], ['barney', 40, false]]
18894 */
18895 var zip = restParam(unzip);
18896
18897 /**
18898 * The inverse of `_.pairs`; this method returns an object composed from arrays
18899 * of property names and values. Provide either a single two dimensional array,
18900 * e.g. `[[key1, value1], [key2, value2]]` or two arrays, one of property names
18901 * and one of corresponding values.
18902 *
18903 * @static
18904 * @memberOf _
18905 * @alias object
18906 * @category Array
18907 * @param {Array} props The property names.
18908 * @param {Array} [values=[]] The property values.
18909 * @returns {Object} Returns the new object.
18910 * @example
18911 *
18912 * _.zipObject([['fred', 30], ['barney', 40]]);
18913 * // => { 'fred': 30, 'barney': 40 }
18914 *
18915 * _.zipObject(['fred', 'barney'], [30, 40]);
18916 * // => { 'fred': 30, 'barney': 40 }
18917 */
18918 function zipObject(props, values) {
18919 var index = -1,
18920 length = props ? props.length : 0,
18921 result = {};
18922
18923 if (length && !values && !isArray(props[0])) {
18924 values = [];
18925 }
18926 while (++index < length) {
18927 var key = props[index];
18928 if (values) {
18929 result[key] = values[index];
18930 } else if (key) {
18931 result[key[0]] = key[1];
18932 }
18933 }
18934 return result;
18935 }
18936
18937 /**
18938 * This method is like `_.zip` except that it accepts an iteratee to specify
18939 * how grouped values should be combined. The `iteratee` is bound to `thisArg`
18940 * and invoked with four arguments: (accumulator, value, index, group).
18941 *
18942 * @static
18943 * @memberOf _
18944 * @category Array
18945 * @param {...Array} [arrays] The arrays to process.
18946 * @param {Function} [iteratee] The function to combine grouped values.
18947 * @param {*} [thisArg] The `this` binding of `iteratee`.
18948 * @returns {Array} Returns the new array of grouped elements.
18949 * @example
18950 *
18951 * _.zipWith([1, 2], [10, 20], [100, 200], _.add);
18952 * // => [111, 222]
18953 */
18954 var zipWith = restParam(function(arrays) {
18955 var length = arrays.length,
18956 iteratee = length > 2 ? arrays[length - 2] : undefined,
18957 thisArg = length > 1 ? arrays[length - 1] : undefined;
18958
18959 if (length > 2 && typeof iteratee == 'function') {
18960 length -= 2;
18961 } else {
18962 iteratee = (length > 1 && typeof thisArg == 'function') ? (--length, thisArg) : undefined;
18963 thisArg = undefined;
18964 }
18965 arrays.length = length;
18966 return unzipWith(arrays, iteratee, thisArg);
18967 });
18968
18969 /*------------------------------------------------------------------------*/
18970
18971 /**
18972 * Creates a `lodash` object that wraps `value` with explicit method
18973 * chaining enabled.
18974 *
18975 * @static
18976 * @memberOf _
18977 * @category Chain
18978 * @param {*} value The value to wrap.
18979 * @returns {Object} Returns the new `lodash` wrapper instance.
18980 * @example
18981 *
18982 * var users = [
18983 * { 'user': 'barney', 'age': 36 },
18984 * { 'user': 'fred', 'age': 40 },
18985 * { 'user': 'pebbles', 'age': 1 }
18986 * ];
18987 *
18988 * var youngest = _.chain(users)
18989 * .sortBy('age')
18990 * .map(function(chr) {
18991 * return chr.user + ' is ' + chr.age;
18992 * })
18993 * .first()
18994 * .value();
18995 * // => 'pebbles is 1'
18996 */
18997 function chain(value) {
18998 var result = lodash(value);
18999 result.__chain__ = true;
19000 return result;
19001 }
19002
19003 /**
19004 * This method invokes `interceptor` and returns `value`. The interceptor is
19005 * bound to `thisArg` and invoked with one argument; (value). The purpose of
19006 * this method is to "tap into" a method chain in order to perform operations
19007 * on intermediate results within the chain.
19008 *
19009 * @static
19010 * @memberOf _
19011 * @category Chain
19012 * @param {*} value The value to provide to `interceptor`.
19013 * @param {Function} interceptor The function to invoke.
19014 * @param {*} [thisArg] The `this` binding of `interceptor`.
19015 * @returns {*} Returns `value`.
19016 * @example
19017 *
19018 * _([1, 2, 3])
19019 * .tap(function(array) {
19020 * array.pop();
19021 * })
19022 * .reverse()
19023 * .value();
19024 * // => [2, 1]
19025 */
19026 function tap(value, interceptor, thisArg) {
19027 interceptor.call(thisArg, value);
19028 return value;
19029 }
19030
19031 /**
19032 * This method is like `_.tap` except that it returns the result of `interceptor`.
19033 *
19034 * @static
19035 * @memberOf _
19036 * @category Chain
19037 * @param {*} value The value to provide to `interceptor`.
19038 * @param {Function} interceptor The function to invoke.
19039 * @param {*} [thisArg] The `this` binding of `interceptor`.
19040 * @returns {*} Returns the result of `interceptor`.
19041 * @example
19042 *
19043 * _(' abc ')
19044 * .chain()
19045 * .trim()
19046 * .thru(function(value) {
19047 * return [value];
19048 * })
19049 * .value();
19050 * // => ['abc']
19051 */
19052 function thru(value, interceptor, thisArg) {
19053 return interceptor.call(thisArg, value);
19054 }
19055
19056 /**
19057 * Enables explicit method chaining on the wrapper object.
19058 *
19059 * @name chain
19060 * @memberOf _
19061 * @category Chain
19062 * @returns {Object} Returns the new `lodash` wrapper instance.
19063 * @example
19064 *
19065 * var users = [
19066 * { 'user': 'barney', 'age': 36 },
19067 * { 'user': 'fred', 'age': 40 }
19068 * ];
19069 *
19070 * // without explicit chaining
19071 * _(users).first();
19072 * // => { 'user': 'barney', 'age': 36 }
19073 *
19074 * // with explicit chaining
19075 * _(users).chain()
19076 * .first()
19077 * .pick('user')
19078 * .value();
19079 * // => { 'user': 'barney' }
19080 */
19081 function wrapperChain() {
19082 return chain(this);
19083 }
19084
19085 /**
19086 * Executes the chained sequence and returns the wrapped result.
19087 *
19088 * @name commit
19089 * @memberOf _
19090 * @category Chain
19091 * @returns {Object} Returns the new `lodash` wrapper instance.
19092 * @example
19093 *
19094 * var array = [1, 2];
19095 * var wrapped = _(array).push(3);
19096 *
19097 * console.log(array);
19098 * // => [1, 2]
19099 *
19100 * wrapped = wrapped.commit();
19101 * console.log(array);
19102 * // => [1, 2, 3]
19103 *
19104 * wrapped.last();
19105 * // => 3
19106 *
19107 * console.log(array);
19108 * // => [1, 2, 3]
19109 */
19110 function wrapperCommit() {
19111 return new LodashWrapper(this.value(), this.__chain__);
19112 }
19113
19114 /**
19115 * Creates a new array joining a wrapped array with any additional arrays
19116 * and/or values.
19117 *
19118 * @name concat
19119 * @memberOf _
19120 * @category Chain
19121 * @param {...*} [values] The values to concatenate.
19122 * @returns {Array} Returns the new concatenated array.
19123 * @example
19124 *
19125 * var array = [1];
19126 * var wrapped = _(array).concat(2, [3], [[4]]);
19127 *
19128 * console.log(wrapped.value());
19129 * // => [1, 2, 3, [4]]
19130 *
19131 * console.log(array);
19132 * // => [1]
19133 */
19134 var wrapperConcat = restParam(function(values) {
19135 values = baseFlatten(values);
19136 return this.thru(function(array) {
19137 return arrayConcat(isArray(array) ? array : [toObject(array)], values);
19138 });
19139 });
19140
19141 /**
19142 * Creates a clone of the chained sequence planting `value` as the wrapped value.
19143 *
19144 * @name plant
19145 * @memberOf _
19146 * @category Chain
19147 * @returns {Object} Returns the new `lodash` wrapper instance.
19148 * @example
19149 *
19150 * var array = [1, 2];
19151 * var wrapped = _(array).map(function(value) {
19152 * return Math.pow(value, 2);
19153 * });
19154 *
19155 * var other = [3, 4];
19156 * var otherWrapped = wrapped.plant(other);
19157 *
19158 * otherWrapped.value();
19159 * // => [9, 16]
19160 *
19161 * wrapped.value();
19162 * // => [1, 4]
19163 */
19164 function wrapperPlant(value) {
19165 var result,
19166 parent = this;
19167
19168 while (parent instanceof baseLodash) {
19169 var clone = wrapperClone(parent);
19170 if (result) {
19171 previous.__wrapped__ = clone;
19172 } else {
19173 result = clone;
19174 }
19175 var previous = clone;
19176 parent = parent.__wrapped__;
19177 }
19178 previous.__wrapped__ = value;
19179 return result;
19180 }
19181
19182 /**
19183 * Reverses the wrapped array so the first element becomes the last, the
19184 * second element becomes the second to last, and so on.
19185 *
19186 * **Note:** This method mutates the wrapped array.
19187 *
19188 * @name reverse
19189 * @memberOf _
19190 * @category Chain
19191 * @returns {Object} Returns the new reversed `lodash` wrapper instance.
19192 * @example
19193 *
19194 * var array = [1, 2, 3];
19195 *
19196 * _(array).reverse().value()
19197 * // => [3, 2, 1]
19198 *
19199 * console.log(array);
19200 * // => [3, 2, 1]
19201 */
19202 function wrapperReverse() {
19203 var value = this.__wrapped__;
19204
19205 var interceptor = function(value) {
19206 return (wrapped && wrapped.__dir__ < 0) ? value : value.reverse();
19207 };
19208 if (value instanceof LazyWrapper) {
19209 var wrapped = value;
19210 if (this.__actions__.length) {
19211 wrapped = new LazyWrapper(this);
19212 }
19213 wrapped = wrapped.reverse();
19214 wrapped.__actions__.push({ 'func': thru, 'args': [interceptor], 'thisArg': undefined });
19215 return new LodashWrapper(wrapped, this.__chain__);
19216 }
19217 return this.thru(interceptor);
19218 }
19219
19220 /**
19221 * Produces the result of coercing the unwrapped value to a string.
19222 *
19223 * @name toString
19224 * @memberOf _
19225 * @category Chain
19226 * @returns {string} Returns the coerced string value.
19227 * @example
19228 *
19229 * _([1, 2, 3]).toString();
19230 * // => '1,2,3'
19231 */
19232 function wrapperToString() {
19233 return (this.value() + '');
19234 }
19235
19236 /**
19237 * Executes the chained sequence to extract the unwrapped value.
19238 *
19239 * @name value
19240 * @memberOf _
19241 * @alias run, toJSON, valueOf
19242 * @category Chain
19243 * @returns {*} Returns the resolved unwrapped value.
19244 * @example
19245 *
19246 * _([1, 2, 3]).value();
19247 * // => [1, 2, 3]
19248 */
19249 function wrapperValue() {
19250 return baseWrapperValue(this.__wrapped__, this.__actions__);
19251 }
19252
19253 /*------------------------------------------------------------------------*/
19254
19255 /**
19256 * Creates an array of elements corresponding to the given keys, or indexes,
19257 * of `collection`. Keys may be specified as individual arguments or as arrays
19258 * of keys.
19259 *
19260 * @static
19261 * @memberOf _
19262 * @category Collection
19263 * @param {Array|Object|string} collection The collection to iterate over.
19264 * @param {...(number|number[]|string|string[])} [props] The property names
19265 * or indexes of elements to pick, specified individually or in arrays.
19266 * @returns {Array} Returns the new array of picked elements.
19267 * @example
19268 *
19269 * _.at(['a', 'b', 'c'], [0, 2]);
19270 * // => ['a', 'c']
19271 *
19272 * _.at(['barney', 'fred', 'pebbles'], 0, 2);
19273 * // => ['barney', 'pebbles']
19274 */
19275 var at = restParam(function(collection, props) {
19276 return baseAt(collection, baseFlatten(props));
19277 });
19278
19279 /**
19280 * Creates an object composed of keys generated from the results of running
19281 * each element of `collection` through `iteratee`. The corresponding value
19282 * of each key is the number of times the key was returned by `iteratee`.
19283 * The `iteratee` is bound to `thisArg` and invoked with three arguments:
19284 * (value, index|key, collection).
19285 *
19286 * If a property name is provided for `iteratee` the created `_.property`
19287 * style callback returns the property value of the given element.
19288 *
19289 * If a value is also provided for `thisArg` the created `_.matchesProperty`
19290 * style callback returns `true` for elements that have a matching property
19291 * value, else `false`.
19292 *
19293 * If an object is provided for `iteratee` the created `_.matches` style
19294 * callback returns `true` for elements that have the properties of the given
19295 * object, else `false`.
19296 *
19297 * @static
19298 * @memberOf _
19299 * @category Collection
19300 * @param {Array|Object|string} collection The collection to iterate over.
19301 * @param {Function|Object|string} [iteratee=_.identity] The function invoked
19302 * per iteration.
19303 * @param {*} [thisArg] The `this` binding of `iteratee`.
19304 * @returns {Object} Returns the composed aggregate object.
19305 * @example
19306 *
19307 * _.countBy([4.3, 6.1, 6.4], function(n) {
19308 * return Math.floor(n);
19309 * });
19310 * // => { '4': 1, '6': 2 }
19311 *
19312 * _.countBy([4.3, 6.1, 6.4], function(n) {
19313 * return this.floor(n);
19314 * }, Math);
19315 * // => { '4': 1, '6': 2 }
19316 *
19317 * _.countBy(['one', 'two', 'three'], 'length');
19318 * // => { '3': 2, '5': 1 }
19319 */
19320 var countBy = createAggregator(function(result, value, key) {
19321 hasOwnProperty.call(result, key) ? ++result[key] : (result[key] = 1);
19322 });
19323
19324 /**
19325 * Checks if `predicate` returns truthy for **all** elements of `collection`.
19326 * The predicate is bound to `thisArg` and invoked with three arguments:
19327 * (value, index|key, collection).
19328 *
19329 * If a property name is provided for `predicate` the created `_.property`
19330 * style callback returns the property value of the given element.
19331 *
19332 * If a value is also provided for `thisArg` the created `_.matchesProperty`
19333 * style callback returns `true` for elements that have a matching property
19334 * value, else `false`.
19335 *
19336 * If an object is provided for `predicate` the created `_.matches` style
19337 * callback returns `true` for elements that have the properties of the given
19338 * object, else `false`.
19339 *
19340 * @static
19341 * @memberOf _
19342 * @alias all
19343 * @category Collection
19344 * @param {Array|Object|string} collection The collection to iterate over.
19345 * @param {Function|Object|string} [predicate=_.identity] The function invoked
19346 * per iteration.
19347 * @param {*} [thisArg] The `this` binding of `predicate`.
19348 * @returns {boolean} Returns `true` if all elements pass the predicate check,
19349 * else `false`.
19350 * @example
19351 *
19352 * _.every([true, 1, null, 'yes'], Boolean);
19353 * // => false
19354 *
19355 * var users = [
19356 * { 'user': 'barney', 'active': false },
19357 * { 'user': 'fred', 'active': false }
19358 * ];
19359 *
19360 * // using the `_.matches` callback shorthand
19361 * _.every(users, { 'user': 'barney', 'active': false });
19362 * // => false
19363 *
19364 * // using the `_.matchesProperty` callback shorthand
19365 * _.every(users, 'active', false);
19366 * // => true
19367 *
19368 * // using the `_.property` callback shorthand
19369 * _.every(users, 'active');
19370 * // => false
19371 */
19372 function every(collection, predicate, thisArg) {
19373 var func = isArray(collection) ? arrayEvery : baseEvery;
19374 if (thisArg && isIterateeCall(collection, predicate, thisArg)) {
19375 predicate = undefined;
19376 }
19377 if (typeof predicate != 'function' || thisArg !== undefined) {
19378 predicate = getCallback(predicate, thisArg, 3);
19379 }
19380 return func(collection, predicate);
19381 }
19382
19383 /**
19384 * Iterates over elements of `collection`, returning an array of all elements
19385 * `predicate` returns truthy for. The predicate is bound to `thisArg` and
19386 * invoked with three arguments: (value, index|key, collection).
19387 *
19388 * If a property name is provided for `predicate` the created `_.property`
19389 * style callback returns the property value of the given element.
19390 *
19391 * If a value is also provided for `thisArg` the created `_.matchesProperty`
19392 * style callback returns `true` for elements that have a matching property
19393 * value, else `false`.
19394 *
19395 * If an object is provided for `predicate` the created `_.matches` style
19396 * callback returns `true` for elements that have the properties of the given
19397 * object, else `false`.
19398 *
19399 * @static
19400 * @memberOf _
19401 * @alias select
19402 * @category Collection
19403 * @param {Array|Object|string} collection The collection to iterate over.
19404 * @param {Function|Object|string} [predicate=_.identity] The function invoked
19405 * per iteration.
19406 * @param {*} [thisArg] The `this` binding of `predicate`.
19407 * @returns {Array} Returns the new filtered array.
19408 * @example
19409 *
19410 * _.filter([4, 5, 6], function(n) {
19411 * return n % 2 == 0;
19412 * });
19413 * // => [4, 6]
19414 *
19415 * var users = [
19416 * { 'user': 'barney', 'age': 36, 'active': true },
19417 * { 'user': 'fred', 'age': 40, 'active': false }
19418 * ];
19419 *
19420 * // using the `_.matches` callback shorthand
19421 * _.pluck(_.filter(users, { 'age': 36, 'active': true }), 'user');
19422 * // => ['barney']
19423 *
19424 * // using the `_.matchesProperty` callback shorthand
19425 * _.pluck(_.filter(users, 'active', false), 'user');
19426 * // => ['fred']
19427 *
19428 * // using the `_.property` callback shorthand
19429 * _.pluck(_.filter(users, 'active'), 'user');
19430 * // => ['barney']
19431 */
19432 function filter(collection, predicate, thisArg) {
19433 var func = isArray(collection) ? arrayFilter : baseFilter;
19434 predicate = getCallback(predicate, thisArg, 3);
19435 return func(collection, predicate);
19436 }
19437
19438 /**
19439 * Iterates over elements of `collection`, returning the first element
19440 * `predicate` returns truthy for. The predicate is bound to `thisArg` and
19441 * invoked with three arguments: (value, index|key, collection).
19442 *
19443 * If a property name is provided for `predicate` the created `_.property`
19444 * style callback returns the property value of the given element.
19445 *
19446 * If a value is also provided for `thisArg` the created `_.matchesProperty`
19447 * style callback returns `true` for elements that have a matching property
19448 * value, else `false`.
19449 *
19450 * If an object is provided for `predicate` the created `_.matches` style
19451 * callback returns `true` for elements that have the properties of the given
19452 * object, else `false`.
19453 *
19454 * @static
19455 * @memberOf _
19456 * @alias detect
19457 * @category Collection
19458 * @param {Array|Object|string} collection The collection to search.
19459 * @param {Function|Object|string} [predicate=_.identity] The function invoked
19460 * per iteration.
19461 * @param {*} [thisArg] The `this` binding of `predicate`.
19462 * @returns {*} Returns the matched element, else `undefined`.
19463 * @example
19464 *
19465 * var users = [
19466 * { 'user': 'barney', 'age': 36, 'active': true },
19467 * { 'user': 'fred', 'age': 40, 'active': false },
19468 * { 'user': 'pebbles', 'age': 1, 'active': true }
19469 * ];
19470 *
19471 * _.result(_.find(users, function(chr) {
19472 * return chr.age < 40;
19473 * }), 'user');
19474 * // => 'barney'
19475 *
19476 * // using the `_.matches` callback shorthand
19477 * _.result(_.find(users, { 'age': 1, 'active': true }), 'user');
19478 * // => 'pebbles'
19479 *
19480 * // using the `_.matchesProperty` callback shorthand
19481 * _.result(_.find(users, 'active', false), 'user');
19482 * // => 'fred'
19483 *
19484 * // using the `_.property` callback shorthand
19485 * _.result(_.find(users, 'active'), 'user');
19486 * // => 'barney'
19487 */
19488 var find = createFind(baseEach);
19489
19490 /**
19491 * This method is like `_.find` except that it iterates over elements of
19492 * `collection` from right to left.
19493 *
19494 * @static
19495 * @memberOf _
19496 * @category Collection
19497 * @param {Array|Object|string} collection The collection to search.
19498 * @param {Function|Object|string} [predicate=_.identity] The function invoked
19499 * per iteration.
19500 * @param {*} [thisArg] The `this` binding of `predicate`.
19501 * @returns {*} Returns the matched element, else `undefined`.
19502 * @example
19503 *
19504 * _.findLast([1, 2, 3, 4], function(n) {
19505 * return n % 2 == 1;
19506 * });
19507 * // => 3
19508 */
19509 var findLast = createFind(baseEachRight, true);
19510
19511 /**
19512 * Performs a deep comparison between each element in `collection` and the
19513 * source object, returning the first element that has equivalent property
19514 * values.
19515 *
19516 * **Note:** This method supports comparing arrays, booleans, `Date` objects,
19517 * numbers, `Object` objects, regexes, and strings. Objects are compared by
19518 * their own, not inherited, enumerable properties. For comparing a single
19519 * own or inherited property value see `_.matchesProperty`.
19520 *
19521 * @static
19522 * @memberOf _
19523 * @category Collection
19524 * @param {Array|Object|string} collection The collection to search.
19525 * @param {Object} source The object of property values to match.
19526 * @returns {*} Returns the matched element, else `undefined`.
19527 * @example
19528 *
19529 * var users = [
19530 * { 'user': 'barney', 'age': 36, 'active': true },
19531 * { 'user': 'fred', 'age': 40, 'active': false }
19532 * ];
19533 *
19534 * _.result(_.findWhere(users, { 'age': 36, 'active': true }), 'user');
19535 * // => 'barney'
19536 *
19537 * _.result(_.findWhere(users, { 'age': 40, 'active': false }), 'user');
19538 * // => 'fred'
19539 */
19540 function findWhere(collection, source) {
19541 return find(collection, baseMatches(source));
19542 }
19543
19544 /**
19545 * Iterates over elements of `collection` invoking `iteratee` for each element.
19546 * The `iteratee` is bound to `thisArg` and invoked with three arguments:
19547 * (value, index|key, collection). Iteratee functions may exit iteration early
19548 * by explicitly returning `false`.
19549 *
19550 * **Note:** As with other "Collections" methods, objects with a "length" property
19551 * are iterated like arrays. To avoid this behavior `_.forIn` or `_.forOwn`
19552 * may be used for object iteration.
19553 *
19554 * @static
19555 * @memberOf _
19556 * @alias each
19557 * @category Collection
19558 * @param {Array|Object|string} collection The collection to iterate over.
19559 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
19560 * @param {*} [thisArg] The `this` binding of `iteratee`.
19561 * @returns {Array|Object|string} Returns `collection`.
19562 * @example
19563 *
19564 * _([1, 2]).forEach(function(n) {
19565 * console.log(n);
19566 * }).value();
19567 * // => logs each value from left to right and returns the array
19568 *
19569 * _.forEach({ 'a': 1, 'b': 2 }, function(n, key) {
19570 * console.log(n, key);
19571 * });
19572 * // => logs each value-key pair and returns the object (iteration order is not guaranteed)
19573 */
19574 var forEach = createForEach(arrayEach, baseEach);
19575
19576 /**
19577 * This method is like `_.forEach` except that it iterates over elements of
19578 * `collection` from right to left.
19579 *
19580 * @static
19581 * @memberOf _
19582 * @alias eachRight
19583 * @category Collection
19584 * @param {Array|Object|string} collection The collection to iterate over.
19585 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
19586 * @param {*} [thisArg] The `this` binding of `iteratee`.
19587 * @returns {Array|Object|string} Returns `collection`.
19588 * @example
19589 *
19590 * _([1, 2]).forEachRight(function(n) {
19591 * console.log(n);
19592 * }).value();
19593 * // => logs each value from right to left and returns the array
19594 */
19595 var forEachRight = createForEach(arrayEachRight, baseEachRight);
19596
19597 /**
19598 * Creates an object composed of keys generated from the results of running
19599 * each element of `collection` through `iteratee`. The corresponding value
19600 * of each key is an array of the elements responsible for generating the key.
19601 * The `iteratee` is bound to `thisArg` and invoked with three arguments:
19602 * (value, index|key, collection).
19603 *
19604 * If a property name is provided for `iteratee` the created `_.property`
19605 * style callback returns the property value of the given element.
19606 *
19607 * If a value is also provided for `thisArg` the created `_.matchesProperty`
19608 * style callback returns `true` for elements that have a matching property
19609 * value, else `false`.
19610 *
19611 * If an object is provided for `iteratee` the created `_.matches` style
19612 * callback returns `true` for elements that have the properties of the given
19613 * object, else `false`.
19614 *
19615 * @static
19616 * @memberOf _
19617 * @category Collection
19618 * @param {Array|Object|string} collection The collection to iterate over.
19619 * @param {Function|Object|string} [iteratee=_.identity] The function invoked
19620 * per iteration.
19621 * @param {*} [thisArg] The `this` binding of `iteratee`.
19622 * @returns {Object} Returns the composed aggregate object.
19623 * @example
19624 *
19625 * _.groupBy([4.2, 6.1, 6.4], function(n) {
19626 * return Math.floor(n);
19627 * });
19628 * // => { '4': [4.2], '6': [6.1, 6.4] }
19629 *
19630 * _.groupBy([4.2, 6.1, 6.4], function(n) {
19631 * return this.floor(n);
19632 * }, Math);
19633 * // => { '4': [4.2], '6': [6.1, 6.4] }
19634 *
19635 * // using the `_.property` callback shorthand
19636 * _.groupBy(['one', 'two', 'three'], 'length');
19637 * // => { '3': ['one', 'two'], '5': ['three'] }
19638 */
19639 var groupBy = createAggregator(function(result, value, key) {
19640 if (hasOwnProperty.call(result, key)) {
19641 result[key].push(value);
19642 } else {
19643 result[key] = [value];
19644 }
19645 });
19646
19647 /**
19648 * Checks if `value` is in `collection` using
19649 * [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
19650 * for equality comparisons. If `fromIndex` is negative, it is used as the offset
19651 * from the end of `collection`.
19652 *
19653 * @static
19654 * @memberOf _
19655 * @alias contains, include
19656 * @category Collection
19657 * @param {Array|Object|string} collection The collection to search.
19658 * @param {*} target The value to search for.
19659 * @param {number} [fromIndex=0] The index to search from.
19660 * @param- {Object} [guard] Enables use as a callback for functions like `_.reduce`.
19661 * @returns {boolean} Returns `true` if a matching element is found, else `false`.
19662 * @example
19663 *
19664 * _.includes([1, 2, 3], 1);
19665 * // => true
19666 *
19667 * _.includes([1, 2, 3], 1, 2);
19668 * // => false
19669 *
19670 * _.includes({ 'user': 'fred', 'age': 40 }, 'fred');
19671 * // => true
19672 *
19673 * _.includes('pebbles', 'eb');
19674 * // => true
19675 */
19676 function includes(collection, target, fromIndex, guard) {
19677 var length = collection ? getLength(collection) : 0;
19678 if (!isLength(length)) {
19679 collection = values(collection);
19680 length = collection.length;
19681 }
19682 if (typeof fromIndex != 'number' || (guard && isIterateeCall(target, fromIndex, guard))) {
19683 fromIndex = 0;
19684 } else {
19685 fromIndex = fromIndex < 0 ? nativeMax(length + fromIndex, 0) : (fromIndex || 0);
19686 }
19687 return (typeof collection == 'string' || !isArray(collection) && isString(collection))
19688 ? (fromIndex <= length && collection.indexOf(target, fromIndex) > -1)
19689 : (!!length && getIndexOf(collection, target, fromIndex) > -1);
19690 }
19691
19692 /**
19693 * Creates an object composed of keys generated from the results of running
19694 * each element of `collection` through `iteratee`. The corresponding value
19695 * of each key is the last element responsible for generating the key. The
19696 * iteratee function is bound to `thisArg` and invoked with three arguments:
19697 * (value, index|key, collection).
19698 *
19699 * If a property name is provided for `iteratee` the created `_.property`
19700 * style callback returns the property value of the given element.
19701 *
19702 * If a value is also provided for `thisArg` the created `_.matchesProperty`
19703 * style callback returns `true` for elements that have a matching property
19704 * value, else `false`.
19705 *
19706 * If an object is provided for `iteratee` the created `_.matches` style
19707 * callback returns `true` for elements that have the properties of the given
19708 * object, else `false`.
19709 *
19710 * @static
19711 * @memberOf _
19712 * @category Collection
19713 * @param {Array|Object|string} collection The collection to iterate over.
19714 * @param {Function|Object|string} [iteratee=_.identity] The function invoked
19715 * per iteration.
19716 * @param {*} [thisArg] The `this` binding of `iteratee`.
19717 * @returns {Object} Returns the composed aggregate object.
19718 * @example
19719 *
19720 * var keyData = [
19721 * { 'dir': 'left', 'code': 97 },
19722 * { 'dir': 'right', 'code': 100 }
19723 * ];
19724 *
19725 * _.indexBy(keyData, 'dir');
19726 * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } }
19727 *
19728 * _.indexBy(keyData, function(object) {
19729 * return String.fromCharCode(object.code);
19730 * });
19731 * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } }
19732 *
19733 * _.indexBy(keyData, function(object) {
19734 * return this.fromCharCode(object.code);
19735 * }, String);
19736 * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } }
19737 */
19738 var indexBy = createAggregator(function(result, value, key) {
19739 result[key] = value;
19740 });
19741
19742 /**
19743 * Invokes the method at `path` of each element in `collection`, returning
19744 * an array of the results of each invoked method. Any additional arguments
19745 * are provided to each invoked method. If `methodName` is a function it is
19746 * invoked for, and `this` bound to, each element in `collection`.
19747 *
19748 * @static
19749 * @memberOf _
19750 * @category Collection
19751 * @param {Array|Object|string} collection The collection to iterate over.
19752 * @param {Array|Function|string} path The path of the method to invoke or
19753 * the function invoked per iteration.
19754 * @param {...*} [args] The arguments to invoke the method with.
19755 * @returns {Array} Returns the array of results.
19756 * @example
19757 *
19758 * _.invoke([[5, 1, 7], [3, 2, 1]], 'sort');
19759 * // => [[1, 5, 7], [1, 2, 3]]
19760 *
19761 * _.invoke([123, 456], String.prototype.split, '');
19762 * // => [['1', '2', '3'], ['4', '5', '6']]
19763 */
19764 var invoke = restParam(function(collection, path, args) {
19765 var index = -1,
19766 isFunc = typeof path == 'function',
19767 isProp = isKey(path),
19768 result = isArrayLike(collection) ? Array(collection.length) : [];
19769
19770 baseEach(collection, function(value) {
19771 var func = isFunc ? path : ((isProp && value != null) ? value[path] : undefined);
19772 result[++index] = func ? func.apply(value, args) : invokePath(value, path, args);
19773 });
19774 return result;
19775 });
19776
19777 /**
19778 * Creates an array of values by running each element in `collection` through
19779 * `iteratee`. The `iteratee` is bound to `thisArg` and invoked with three
19780 * arguments: (value, index|key, collection).
19781 *
19782 * If a property name is provided for `iteratee` the created `_.property`
19783 * style callback returns the property value of the given element.
19784 *
19785 * If a value is also provided for `thisArg` the created `_.matchesProperty`
19786 * style callback returns `true` for elements that have a matching property
19787 * value, else `false`.
19788 *
19789 * If an object is provided for `iteratee` the created `_.matches` style
19790 * callback returns `true` for elements that have the properties of the given
19791 * object, else `false`.
19792 *
19793 * Many lodash methods are guarded to work as iteratees for methods like
19794 * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`.
19795 *
19796 * The guarded methods are:
19797 * `ary`, `callback`, `chunk`, `clone`, `create`, `curry`, `curryRight`,
19798 * `drop`, `dropRight`, `every`, `fill`, `flatten`, `invert`, `max`, `min`,
19799 * `parseInt`, `slice`, `sortBy`, `take`, `takeRight`, `template`, `trim`,
19800 * `trimLeft`, `trimRight`, `trunc`, `random`, `range`, `sample`, `some`,
19801 * `sum`, `uniq`, and `words`
19802 *
19803 * @static
19804 * @memberOf _
19805 * @alias collect
19806 * @category Collection
19807 * @param {Array|Object|string} collection The collection to iterate over.
19808 * @param {Function|Object|string} [iteratee=_.identity] The function invoked
19809 * per iteration.
19810 * @param {*} [thisArg] The `this` binding of `iteratee`.
19811 * @returns {Array} Returns the new mapped array.
19812 * @example
19813 *
19814 * function timesThree(n) {
19815 * return n * 3;
19816 * }
19817 *
19818 * _.map([1, 2], timesThree);
19819 * // => [3, 6]
19820 *
19821 * _.map({ 'a': 1, 'b': 2 }, timesThree);
19822 * // => [3, 6] (iteration order is not guaranteed)
19823 *
19824 * var users = [
19825 * { 'user': 'barney' },
19826 * { 'user': 'fred' }
19827 * ];
19828 *
19829 * // using the `_.property` callback shorthand
19830 * _.map(users, 'user');
19831 * // => ['barney', 'fred']
19832 */
19833 function map(collection, iteratee, thisArg) {
19834 var func = isArray(collection) ? arrayMap : baseMap;
19835 iteratee = getCallback(iteratee, thisArg, 3);
19836 return func(collection, iteratee);
19837 }
19838
19839 /**
19840 * Creates an array of elements split into two groups, the first of which
19841 * contains elements `predicate` returns truthy for, while the second of which
19842 * contains elements `predicate` returns falsey for. The predicate is bound
19843 * to `thisArg` and invoked with three arguments: (value, index|key, collection).
19844 *
19845 * If a property name is provided for `predicate` the created `_.property`
19846 * style callback returns the property value of the given element.
19847 *
19848 * If a value is also provided for `thisArg` the created `_.matchesProperty`
19849 * style callback returns `true` for elements that have a matching property
19850 * value, else `false`.
19851 *
19852 * If an object is provided for `predicate` the created `_.matches` style
19853 * callback returns `true` for elements that have the properties of the given
19854 * object, else `false`.
19855 *
19856 * @static
19857 * @memberOf _
19858 * @category Collection
19859 * @param {Array|Object|string} collection The collection to iterate over.
19860 * @param {Function|Object|string} [predicate=_.identity] The function invoked
19861 * per iteration.
19862 * @param {*} [thisArg] The `this` binding of `predicate`.
19863 * @returns {Array} Returns the array of grouped elements.
19864 * @example
19865 *
19866 * _.partition([1, 2, 3], function(n) {
19867 * return n % 2;
19868 * });
19869 * // => [[1, 3], [2]]
19870 *
19871 * _.partition([1.2, 2.3, 3.4], function(n) {
19872 * return this.floor(n) % 2;
19873 * }, Math);
19874 * // => [[1.2, 3.4], [2.3]]
19875 *
19876 * var users = [
19877 * { 'user': 'barney', 'age': 36, 'active': false },
19878 * { 'user': 'fred', 'age': 40, 'active': true },
19879 * { 'user': 'pebbles', 'age': 1, 'active': false }
19880 * ];
19881 *
19882 * var mapper = function(array) {
19883 * return _.pluck(array, 'user');
19884 * };
19885 *
19886 * // using the `_.matches` callback shorthand
19887 * _.map(_.partition(users, { 'age': 1, 'active': false }), mapper);
19888 * // => [['pebbles'], ['barney', 'fred']]
19889 *
19890 * // using the `_.matchesProperty` callback shorthand
19891 * _.map(_.partition(users, 'active', false), mapper);
19892 * // => [['barney', 'pebbles'], ['fred']]
19893 *
19894 * // using the `_.property` callback shorthand
19895 * _.map(_.partition(users, 'active'), mapper);
19896 * // => [['fred'], ['barney', 'pebbles']]
19897 */
19898 var partition = createAggregator(function(result, value, key) {
19899 result[key ? 0 : 1].push(value);
19900 }, function() { return [[], []]; });
19901
19902 /**
19903 * Gets the property value of `path` from all elements in `collection`.
19904 *
19905 * @static
19906 * @memberOf _
19907 * @category Collection
19908 * @param {Array|Object|string} collection The collection to iterate over.
19909 * @param {Array|string} path The path of the property to pluck.
19910 * @returns {Array} Returns the property values.
19911 * @example
19912 *
19913 * var users = [
19914 * { 'user': 'barney', 'age': 36 },
19915 * { 'user': 'fred', 'age': 40 }
19916 * ];
19917 *
19918 * _.pluck(users, 'user');
19919 * // => ['barney', 'fred']
19920 *
19921 * var userIndex = _.indexBy(users, 'user');
19922 * _.pluck(userIndex, 'age');
19923 * // => [36, 40] (iteration order is not guaranteed)
19924 */
19925 function pluck(collection, path) {
19926 return map(collection, property(path));
19927 }
19928
19929 /**
19930 * Reduces `collection` to a value which is the accumulated result of running
19931 * each element in `collection` through `iteratee`, where each successive
19932 * invocation is supplied the return value of the previous. If `accumulator`
19933 * is not provided the first element of `collection` is used as the initial
19934 * value. The `iteratee` is bound to `thisArg` and invoked with four arguments:
19935 * (accumulator, value, index|key, collection).
19936 *
19937 * Many lodash methods are guarded to work as iteratees for methods like
19938 * `_.reduce`, `_.reduceRight`, and `_.transform`.
19939 *
19940 * The guarded methods are:
19941 * `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `sortByAll`,
19942 * and `sortByOrder`
19943 *
19944 * @static
19945 * @memberOf _
19946 * @alias foldl, inject
19947 * @category Collection
19948 * @param {Array|Object|string} collection The collection to iterate over.
19949 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
19950 * @param {*} [accumulator] The initial value.
19951 * @param {*} [thisArg] The `this` binding of `iteratee`.
19952 * @returns {*} Returns the accumulated value.
19953 * @example
19954 *
19955 * _.reduce([1, 2], function(total, n) {
19956 * return total + n;
19957 * });
19958 * // => 3
19959 *
19960 * _.reduce({ 'a': 1, 'b': 2 }, function(result, n, key) {
19961 * result[key] = n * 3;
19962 * return result;
19963 * }, {});
19964 * // => { 'a': 3, 'b': 6 } (iteration order is not guaranteed)
19965 */
19966 var reduce = createReduce(arrayReduce, baseEach);
19967
19968 /**
19969 * This method is like `_.reduce` except that it iterates over elements of
19970 * `collection` from right to left.
19971 *
19972 * @static
19973 * @memberOf _
19974 * @alias foldr
19975 * @category Collection
19976 * @param {Array|Object|string} collection The collection to iterate over.
19977 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
19978 * @param {*} [accumulator] The initial value.
19979 * @param {*} [thisArg] The `this` binding of `iteratee`.
19980 * @returns {*} Returns the accumulated value.
19981 * @example
19982 *
19983 * var array = [[0, 1], [2, 3], [4, 5]];
19984 *
19985 * _.reduceRight(array, function(flattened, other) {
19986 * return flattened.concat(other);
19987 * }, []);
19988 * // => [4, 5, 2, 3, 0, 1]
19989 */
19990 var reduceRight = createReduce(arrayReduceRight, baseEachRight);
19991
19992 /**
19993 * The opposite of `_.filter`; this method returns the elements of `collection`
19994 * that `predicate` does **not** return truthy for.
19995 *
19996 * @static
19997 * @memberOf _
19998 * @category Collection
19999 * @param {Array|Object|string} collection The collection to iterate over.
20000 * @param {Function|Object|string} [predicate=_.identity] The function invoked
20001 * per iteration.
20002 * @param {*} [thisArg] The `this` binding of `predicate`.
20003 * @returns {Array} Returns the new filtered array.
20004 * @example
20005 *
20006 * _.reject([1, 2, 3, 4], function(n) {
20007 * return n % 2 == 0;
20008 * });
20009 * // => [1, 3]
20010 *
20011 * var users = [
20012 * { 'user': 'barney', 'age': 36, 'active': false },
20013 * { 'user': 'fred', 'age': 40, 'active': true }
20014 * ];
20015 *
20016 * // using the `_.matches` callback shorthand
20017 * _.pluck(_.reject(users, { 'age': 40, 'active': true }), 'user');
20018 * // => ['barney']
20019 *
20020 * // using the `_.matchesProperty` callback shorthand
20021 * _.pluck(_.reject(users, 'active', false), 'user');
20022 * // => ['fred']
20023 *
20024 * // using the `_.property` callback shorthand
20025 * _.pluck(_.reject(users, 'active'), 'user');
20026 * // => ['barney']
20027 */
20028 function reject(collection, predicate, thisArg) {
20029 var func = isArray(collection) ? arrayFilter : baseFilter;
20030 predicate = getCallback(predicate, thisArg, 3);
20031 return func(collection, function(value, index, collection) {
20032 return !predicate(value, index, collection);
20033 });
20034 }
20035
20036 /**
20037 * Gets a random element or `n` random elements from a collection.
20038 *
20039 * @static
20040 * @memberOf _
20041 * @category Collection
20042 * @param {Array|Object|string} collection The collection to sample.
20043 * @param {number} [n] The number of elements to sample.
20044 * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
20045 * @returns {*} Returns the random sample(s).
20046 * @example
20047 *
20048 * _.sample([1, 2, 3, 4]);
20049 * // => 2
20050 *
20051 * _.sample([1, 2, 3, 4], 2);
20052 * // => [3, 1]
20053 */
20054 function sample(collection, n, guard) {
20055 if (guard ? isIterateeCall(collection, n, guard) : n == null) {
20056 collection = toIterable(collection);
20057 var length = collection.length;
20058 return length > 0 ? collection[baseRandom(0, length - 1)] : undefined;
20059 }
20060 var index = -1,
20061 result = toArray(collection),
20062 length = result.length,
20063 lastIndex = length - 1;
20064
20065 n = nativeMin(n < 0 ? 0 : (+n || 0), length);
20066 while (++index < n) {
20067 var rand = baseRandom(index, lastIndex),
20068 value = result[rand];
20069
20070 result[rand] = result[index];
20071 result[index] = value;
20072 }
20073 result.length = n;
20074 return result;
20075 }
20076
20077 /**
20078 * Creates an array of shuffled values, using a version of the
20079 * [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle).
20080 *
20081 * @static
20082 * @memberOf _
20083 * @category Collection
20084 * @param {Array|Object|string} collection The collection to shuffle.
20085 * @returns {Array} Returns the new shuffled array.
20086 * @example
20087 *
20088 * _.shuffle([1, 2, 3, 4]);
20089 * // => [4, 1, 3, 2]
20090 */
20091 function shuffle(collection) {
20092 return sample(collection, POSITIVE_INFINITY);
20093 }
20094
20095 /**
20096 * Gets the size of `collection` by returning its length for array-like
20097 * values or the number of own enumerable properties for objects.
20098 *
20099 * @static
20100 * @memberOf _
20101 * @category Collection
20102 * @param {Array|Object|string} collection The collection to inspect.
20103 * @returns {number} Returns the size of `collection`.
20104 * @example
20105 *
20106 * _.size([1, 2, 3]);
20107 * // => 3
20108 *
20109 * _.size({ 'a': 1, 'b': 2 });
20110 * // => 2
20111 *
20112 * _.size('pebbles');
20113 * // => 7
20114 */
20115 function size(collection) {
20116 var length = collection ? getLength(collection) : 0;
20117 return isLength(length) ? length : keys(collection).length;
20118 }
20119
20120 /**
20121 * Checks if `predicate` returns truthy for **any** element of `collection`.
20122 * The function returns as soon as it finds a passing value and does not iterate
20123 * over the entire collection. The predicate is bound to `thisArg` and invoked
20124 * with three arguments: (value, index|key, collection).
20125 *
20126 * If a property name is provided for `predicate` the created `_.property`
20127 * style callback returns the property value of the given element.
20128 *
20129 * If a value is also provided for `thisArg` the created `_.matchesProperty`
20130 * style callback returns `true` for elements that have a matching property
20131 * value, else `false`.
20132 *
20133 * If an object is provided for `predicate` the created `_.matches` style
20134 * callback returns `true` for elements that have the properties of the given
20135 * object, else `false`.
20136 *
20137 * @static
20138 * @memberOf _
20139 * @alias any
20140 * @category Collection
20141 * @param {Array|Object|string} collection The collection to iterate over.
20142 * @param {Function|Object|string} [predicate=_.identity] The function invoked
20143 * per iteration.
20144 * @param {*} [thisArg] The `this` binding of `predicate`.
20145 * @returns {boolean} Returns `true` if any element passes the predicate check,
20146 * else `false`.
20147 * @example
20148 *
20149 * _.some([null, 0, 'yes', false], Boolean);
20150 * // => true
20151 *
20152 * var users = [
20153 * { 'user': 'barney', 'active': true },
20154 * { 'user': 'fred', 'active': false }
20155 * ];
20156 *
20157 * // using the `_.matches` callback shorthand
20158 * _.some(users, { 'user': 'barney', 'active': false });
20159 * // => false
20160 *
20161 * // using the `_.matchesProperty` callback shorthand
20162 * _.some(users, 'active', false);
20163 * // => true
20164 *
20165 * // using the `_.property` callback shorthand
20166 * _.some(users, 'active');
20167 * // => true
20168 */
20169 function some(collection, predicate, thisArg) {
20170 var func = isArray(collection) ? arraySome : baseSome;
20171 if (thisArg && isIterateeCall(collection, predicate, thisArg)) {
20172 predicate = undefined;
20173 }
20174 if (typeof predicate != 'function' || thisArg !== undefined) {
20175 predicate = getCallback(predicate, thisArg, 3);
20176 }
20177 return func(collection, predicate);
20178 }
20179
20180 /**
20181 * Creates an array of elements, sorted in ascending order by the results of
20182 * running each element in a collection through `iteratee`. This method performs
20183 * a stable sort, that is, it preserves the original sort order of equal elements.
20184 * The `iteratee` is bound to `thisArg` and invoked with three arguments:
20185 * (value, index|key, collection).
20186 *
20187 * If a property name is provided for `iteratee` the created `_.property`
20188 * style callback returns the property value of the given element.
20189 *
20190 * If a value is also provided for `thisArg` the created `_.matchesProperty`
20191 * style callback returns `true` for elements that have a matching property
20192 * value, else `false`.
20193 *
20194 * If an object is provided for `iteratee` the created `_.matches` style
20195 * callback returns `true` for elements that have the properties of the given
20196 * object, else `false`.
20197 *
20198 * @static
20199 * @memberOf _
20200 * @category Collection
20201 * @param {Array|Object|string} collection The collection to iterate over.
20202 * @param {Function|Object|string} [iteratee=_.identity] The function invoked
20203 * per iteration.
20204 * @param {*} [thisArg] The `this` binding of `iteratee`.
20205 * @returns {Array} Returns the new sorted array.
20206 * @example
20207 *
20208 * _.sortBy([1, 2, 3], function(n) {
20209 * return Math.sin(n);
20210 * });
20211 * // => [3, 1, 2]
20212 *
20213 * _.sortBy([1, 2, 3], function(n) {
20214 * return this.sin(n);
20215 * }, Math);
20216 * // => [3, 1, 2]
20217 *
20218 * var users = [
20219 * { 'user': 'fred' },
20220 * { 'user': 'pebbles' },
20221 * { 'user': 'barney' }
20222 * ];
20223 *
20224 * // using the `_.property` callback shorthand
20225 * _.pluck(_.sortBy(users, 'user'), 'user');
20226 * // => ['barney', 'fred', 'pebbles']
20227 */
20228 function sortBy(collection, iteratee, thisArg) {
20229 if (collection == null) {
20230 return [];
20231 }
20232 if (thisArg && isIterateeCall(collection, iteratee, thisArg)) {
20233 iteratee = undefined;
20234 }
20235 var index = -1;
20236 iteratee = getCallback(iteratee, thisArg, 3);
20237
20238 var result = baseMap(collection, function(value, key, collection) {
20239 return { 'criteria': iteratee(value, key, collection), 'index': ++index, 'value': value };
20240 });
20241 return baseSortBy(result, compareAscending);
20242 }
20243
20244 /**
20245 * This method is like `_.sortBy` except that it can sort by multiple iteratees
20246 * or property names.
20247 *
20248 * If a property name is provided for an iteratee the created `_.property`
20249 * style callback returns the property value of the given element.
20250 *
20251 * If an object is provided for an iteratee the created `_.matches` style
20252 * callback returns `true` for elements that have the properties of the given
20253 * object, else `false`.
20254 *
20255 * @static
20256 * @memberOf _
20257 * @category Collection
20258 * @param {Array|Object|string} collection The collection to iterate over.
20259 * @param {...(Function|Function[]|Object|Object[]|string|string[])} iteratees
20260 * The iteratees to sort by, specified as individual values or arrays of values.
20261 * @returns {Array} Returns the new sorted array.
20262 * @example
20263 *
20264 * var users = [
20265 * { 'user': 'fred', 'age': 48 },
20266 * { 'user': 'barney', 'age': 36 },
20267 * { 'user': 'fred', 'age': 42 },
20268 * { 'user': 'barney', 'age': 34 }
20269 * ];
20270 *
20271 * _.map(_.sortByAll(users, ['user', 'age']), _.values);
20272 * // => [['barney', 34], ['barney', 36], ['fred', 42], ['fred', 48]]
20273 *
20274 * _.map(_.sortByAll(users, 'user', function(chr) {
20275 * return Math.floor(chr.age / 10);
20276 * }), _.values);
20277 * // => [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 42]]
20278 */
20279 var sortByAll = restParam(function(collection, iteratees) {
20280 if (collection == null) {
20281 return [];
20282 }
20283 var guard = iteratees[2];
20284 if (guard && isIterateeCall(iteratees[0], iteratees[1], guard)) {
20285 iteratees.length = 1;
20286 }
20287 return baseSortByOrder(collection, baseFlatten(iteratees), []);
20288 });
20289
20290 /**
20291 * This method is like `_.sortByAll` except that it allows specifying the
20292 * sort orders of the iteratees to sort by. If `orders` is unspecified, all
20293 * values are sorted in ascending order. Otherwise, a value is sorted in
20294 * ascending order if its corresponding order is "asc", and descending if "desc".
20295 *
20296 * If a property name is provided for an iteratee the created `_.property`
20297 * style callback returns the property value of the given element.
20298 *
20299 * If an object is provided for an iteratee the created `_.matches` style
20300 * callback returns `true` for elements that have the properties of the given
20301 * object, else `false`.
20302 *
20303 * @static
20304 * @memberOf _
20305 * @category Collection
20306 * @param {Array|Object|string} collection The collection to iterate over.
20307 * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by.
20308 * @param {boolean[]} [orders] The sort orders of `iteratees`.
20309 * @param- {Object} [guard] Enables use as a callback for functions like `_.reduce`.
20310 * @returns {Array} Returns the new sorted array.
20311 * @example
20312 *
20313 * var users = [
20314 * { 'user': 'fred', 'age': 48 },
20315 * { 'user': 'barney', 'age': 34 },
20316 * { 'user': 'fred', 'age': 42 },
20317 * { 'user': 'barney', 'age': 36 }
20318 * ];
20319 *
20320 * // sort by `user` in ascending order and by `age` in descending order
20321 * _.map(_.sortByOrder(users, ['user', 'age'], ['asc', 'desc']), _.values);
20322 * // => [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 42]]
20323 */
20324 function sortByOrder(collection, iteratees, orders, guard) {
20325 if (collection == null) {
20326 return [];
20327 }
20328 if (guard && isIterateeCall(iteratees, orders, guard)) {
20329 orders = undefined;
20330 }
20331 if (!isArray(iteratees)) {
20332 iteratees = iteratees == null ? [] : [iteratees];
20333 }
20334 if (!isArray(orders)) {
20335 orders = orders == null ? [] : [orders];
20336 }
20337 return baseSortByOrder(collection, iteratees, orders);
20338 }
20339
20340 /**
20341 * Performs a deep comparison between each element in `collection` and the
20342 * source object, returning an array of all elements that have equivalent
20343 * property values.
20344 *
20345 * **Note:** This method supports comparing arrays, booleans, `Date` objects,
20346 * numbers, `Object` objects, regexes, and strings. Objects are compared by
20347 * their own, not inherited, enumerable properties. For comparing a single
20348 * own or inherited property value see `_.matchesProperty`.
20349 *
20350 * @static
20351 * @memberOf _
20352 * @category Collection
20353 * @param {Array|Object|string} collection The collection to search.
20354 * @param {Object} source The object of property values to match.
20355 * @returns {Array} Returns the new filtered array.
20356 * @example
20357 *
20358 * var users = [
20359 * { 'user': 'barney', 'age': 36, 'active': false, 'pets': ['hoppy'] },
20360 * { 'user': 'fred', 'age': 40, 'active': true, 'pets': ['baby puss', 'dino'] }
20361 * ];
20362 *
20363 * _.pluck(_.where(users, { 'age': 36, 'active': false }), 'user');
20364 * // => ['barney']
20365 *
20366 * _.pluck(_.where(users, { 'pets': ['dino'] }), 'user');
20367 * // => ['fred']
20368 */
20369 function where(collection, source) {
20370 return filter(collection, baseMatches(source));
20371 }
20372
20373 /*------------------------------------------------------------------------*/
20374
20375 /**
20376 * Gets the number of milliseconds that have elapsed since the Unix epoch
20377 * (1 January 1970 00:00:00 UTC).
20378 *
20379 * @static
20380 * @memberOf _
20381 * @category Date
20382 * @example
20383 *
20384 * _.defer(function(stamp) {
20385 * console.log(_.now() - stamp);
20386 * }, _.now());
20387 * // => logs the number of milliseconds it took for the deferred function to be invoked
20388 */
20389 var now = nativeNow || function() {
20390 return new Date().getTime();
20391 };
20392
20393 /*------------------------------------------------------------------------*/
20394
20395 /**
20396 * The opposite of `_.before`; this method creates a function that invokes
20397 * `func` once it is called `n` or more times.
20398 *
20399 * @static
20400 * @memberOf _
20401 * @category Function
20402 * @param {number} n The number of calls before `func` is invoked.
20403 * @param {Function} func The function to restrict.
20404 * @returns {Function} Returns the new restricted function.
20405 * @example
20406 *
20407 * var saves = ['profile', 'settings'];
20408 *
20409 * var done = _.after(saves.length, function() {
20410 * console.log('done saving!');
20411 * });
20412 *
20413 * _.forEach(saves, function(type) {
20414 * asyncSave({ 'type': type, 'complete': done });
20415 * });
20416 * // => logs 'done saving!' after the two async saves have completed
20417 */
20418 function after(n, func) {
20419 if (typeof func != 'function') {
20420 if (typeof n == 'function') {
20421 var temp = n;
20422 n = func;
20423 func = temp;
20424 } else {
20425 throw new TypeError(FUNC_ERROR_TEXT);
20426 }
20427 }
20428 n = nativeIsFinite(n = +n) ? n : 0;
20429 return function() {
20430 if (--n < 1) {
20431 return func.apply(this, arguments);
20432 }
20433 };
20434 }
20435
20436 /**
20437 * Creates a function that accepts up to `n` arguments ignoring any
20438 * additional arguments.
20439 *
20440 * @static
20441 * @memberOf _
20442 * @category Function
20443 * @param {Function} func The function to cap arguments for.
20444 * @param {number} [n=func.length] The arity cap.
20445 * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
20446 * @returns {Function} Returns the new function.
20447 * @example
20448 *
20449 * _.map(['6', '8', '10'], _.ary(parseInt, 1));
20450 * // => [6, 8, 10]
20451 */
20452 function ary(func, n, guard) {
20453 if (guard && isIterateeCall(func, n, guard)) {
20454 n = undefined;
20455 }
20456 n = (func && n == null) ? func.length : nativeMax(+n || 0, 0);
20457 return createWrapper(func, ARY_FLAG, undefined, undefined, undefined, undefined, n);
20458 }
20459
20460 /**
20461 * Creates a function that invokes `func`, with the `this` binding and arguments
20462 * of the created function, while it is called less than `n` times. Subsequent
20463 * calls to the created function return the result of the last `func` invocation.
20464 *
20465 * @static
20466 * @memberOf _
20467 * @category Function
20468 * @param {number} n The number of calls at which `func` is no longer invoked.
20469 * @param {Function} func The function to restrict.
20470 * @returns {Function} Returns the new restricted function.
20471 * @example
20472 *
20473 * jQuery('#add').on('click', _.before(5, addContactToList));
20474 * // => allows adding up to 4 contacts to the list
20475 */
20476 function before(n, func) {
20477 var result;
20478 if (typeof func != 'function') {
20479 if (typeof n == 'function') {
20480 var temp = n;
20481 n = func;
20482 func = temp;
20483 } else {
20484 throw new TypeError(FUNC_ERROR_TEXT);
20485 }
20486 }
20487 return function() {
20488 if (--n > 0) {
20489 result = func.apply(this, arguments);
20490 }
20491 if (n <= 1) {
20492 func = undefined;
20493 }
20494 return result;
20495 };
20496 }
20497
20498 /**
20499 * Creates a function that invokes `func` with the `this` binding of `thisArg`
20500 * and prepends any additional `_.bind` arguments to those provided to the
20501 * bound function.
20502 *
20503 * The `_.bind.placeholder` value, which defaults to `_` in monolithic builds,
20504 * may be used as a placeholder for partially applied arguments.
20505 *
20506 * **Note:** Unlike native `Function#bind` this method does not set the "length"
20507 * property of bound functions.
20508 *
20509 * @static
20510 * @memberOf _
20511 * @category Function
20512 * @param {Function} func The function to bind.
20513 * @param {*} thisArg The `this` binding of `func`.
20514 * @param {...*} [partials] The arguments to be partially applied.
20515 * @returns {Function} Returns the new bound function.
20516 * @example
20517 *
20518 * var greet = function(greeting, punctuation) {
20519 * return greeting + ' ' + this.user + punctuation;
20520 * };
20521 *
20522 * var object = { 'user': 'fred' };
20523 *
20524 * var bound = _.bind(greet, object, 'hi');
20525 * bound('!');
20526 * // => 'hi fred!'
20527 *
20528 * // using placeholders
20529 * var bound = _.bind(greet, object, _, '!');
20530 * bound('hi');
20531 * // => 'hi fred!'
20532 */
20533 var bind = restParam(function(func, thisArg, partials) {
20534 var bitmask = BIND_FLAG;
20535 if (partials.length) {
20536 var holders = replaceHolders(partials, bind.placeholder);
20537 bitmask |= PARTIAL_FLAG;
20538 }
20539 return createWrapper(func, bitmask, thisArg, partials, holders);
20540 });
20541
20542 /**
20543 * Binds methods of an object to the object itself, overwriting the existing
20544 * method. Method names may be specified as individual arguments or as arrays
20545 * of method names. If no method names are provided all enumerable function
20546 * properties, own and inherited, of `object` are bound.
20547 *
20548 * **Note:** This method does not set the "length" property of bound functions.
20549 *
20550 * @static
20551 * @memberOf _
20552 * @category Function
20553 * @param {Object} object The object to bind and assign the bound methods to.
20554 * @param {...(string|string[])} [methodNames] The object method names to bind,
20555 * specified as individual method names or arrays of method names.
20556 * @returns {Object} Returns `object`.
20557 * @example
20558 *
20559 * var view = {
20560 * 'label': 'docs',
20561 * 'onClick': function() {
20562 * console.log('clicked ' + this.label);
20563 * }
20564 * };
20565 *
20566 * _.bindAll(view);
20567 * jQuery('#docs').on('click', view.onClick);
20568 * // => logs 'clicked docs' when the element is clicked
20569 */
20570 var bindAll = restParam(function(object, methodNames) {
20571 methodNames = methodNames.length ? baseFlatten(methodNames) : functions(object);
20572
20573 var index = -1,
20574 length = methodNames.length;
20575
20576 while (++index < length) {
20577 var key = methodNames[index];
20578 object[key] = createWrapper(object[key], BIND_FLAG, object);
20579 }
20580 return object;
20581 });
20582
20583 /**
20584 * Creates a function that invokes the method at `object[key]` and prepends
20585 * any additional `_.bindKey` arguments to those provided to the bound function.
20586 *
20587 * This method differs from `_.bind` by allowing bound functions to reference
20588 * methods that may be redefined or don't yet exist.
20589 * See [Peter Michaux's article](http://peter.michaux.ca/articles/lazy-function-definition-pattern)
20590 * for more details.
20591 *
20592 * The `_.bindKey.placeholder` value, which defaults to `_` in monolithic
20593 * builds, may be used as a placeholder for partially applied arguments.
20594 *
20595 * @static
20596 * @memberOf _
20597 * @category Function
20598 * @param {Object} object The object the method belongs to.
20599 * @param {string} key The key of the method.
20600 * @param {...*} [partials] The arguments to be partially applied.
20601 * @returns {Function} Returns the new bound function.
20602 * @example
20603 *
20604 * var object = {
20605 * 'user': 'fred',
20606 * 'greet': function(greeting, punctuation) {
20607 * return greeting + ' ' + this.user + punctuation;
20608 * }
20609 * };
20610 *
20611 * var bound = _.bindKey(object, 'greet', 'hi');
20612 * bound('!');
20613 * // => 'hi fred!'
20614 *
20615 * object.greet = function(greeting, punctuation) {
20616 * return greeting + 'ya ' + this.user + punctuation;
20617 * };
20618 *
20619 * bound('!');
20620 * // => 'hiya fred!'
20621 *
20622 * // using placeholders
20623 * var bound = _.bindKey(object, 'greet', _, '!');
20624 * bound('hi');
20625 * // => 'hiya fred!'
20626 */
20627 var bindKey = restParam(function(object, key, partials) {
20628 var bitmask = BIND_FLAG | BIND_KEY_FLAG;
20629 if (partials.length) {
20630 var holders = replaceHolders(partials, bindKey.placeholder);
20631 bitmask |= PARTIAL_FLAG;
20632 }
20633 return createWrapper(key, bitmask, object, partials, holders);
20634 });
20635
20636 /**
20637 * Creates a function that accepts one or more arguments of `func` that when
20638 * called either invokes `func` returning its result, if all `func` arguments
20639 * have been provided, or returns a function that accepts one or more of the
20640 * remaining `func` arguments, and so on. The arity of `func` may be specified
20641 * if `func.length` is not sufficient.
20642 *
20643 * The `_.curry.placeholder` value, which defaults to `_` in monolithic builds,
20644 * may be used as a placeholder for provided arguments.
20645 *
20646 * **Note:** This method does not set the "length" property of curried functions.
20647 *
20648 * @static
20649 * @memberOf _
20650 * @category Function
20651 * @param {Function} func The function to curry.
20652 * @param {number} [arity=func.length] The arity of `func`.
20653 * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
20654 * @returns {Function} Returns the new curried function.
20655 * @example
20656 *
20657 * var abc = function(a, b, c) {
20658 * return [a, b, c];
20659 * };
20660 *
20661 * var curried = _.curry(abc);
20662 *
20663 * curried(1)(2)(3);
20664 * // => [1, 2, 3]
20665 *
20666 * curried(1, 2)(3);
20667 * // => [1, 2, 3]
20668 *
20669 * curried(1, 2, 3);
20670 * // => [1, 2, 3]
20671 *
20672 * // using placeholders
20673 * curried(1)(_, 3)(2);
20674 * // => [1, 2, 3]
20675 */
20676 var curry = createCurry(CURRY_FLAG);
20677
20678 /**
20679 * This method is like `_.curry` except that arguments are applied to `func`
20680 * in the manner of `_.partialRight` instead of `_.partial`.
20681 *
20682 * The `_.curryRight.placeholder` value, which defaults to `_` in monolithic
20683 * builds, may be used as a placeholder for provided arguments.
20684 *
20685 * **Note:** This method does not set the "length" property of curried functions.
20686 *
20687 * @static
20688 * @memberOf _
20689 * @category Function
20690 * @param {Function} func The function to curry.
20691 * @param {number} [arity=func.length] The arity of `func`.
20692 * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
20693 * @returns {Function} Returns the new curried function.
20694 * @example
20695 *
20696 * var abc = function(a, b, c) {
20697 * return [a, b, c];
20698 * };
20699 *
20700 * var curried = _.curryRight(abc);
20701 *
20702 * curried(3)(2)(1);
20703 * // => [1, 2, 3]
20704 *
20705 * curried(2, 3)(1);
20706 * // => [1, 2, 3]
20707 *
20708 * curried(1, 2, 3);
20709 * // => [1, 2, 3]
20710 *
20711 * // using placeholders
20712 * curried(3)(1, _)(2);
20713 * // => [1, 2, 3]
20714 */
20715 var curryRight = createCurry(CURRY_RIGHT_FLAG);
20716
20717 /**
20718 * Creates a debounced function that delays invoking `func` until after `wait`
20719 * milliseconds have elapsed since the last time the debounced function was
20720 * invoked. The debounced function comes with a `cancel` method to cancel
20721 * delayed invocations. Provide an options object to indicate that `func`
20722 * should be invoked on the leading and/or trailing edge of the `wait` timeout.
20723 * Subsequent calls to the debounced function return the result of the last
20724 * `func` invocation.
20725 *
20726 * **Note:** If `leading` and `trailing` options are `true`, `func` is invoked
20727 * on the trailing edge of the timeout only if the the debounced function is
20728 * invoked more than once during the `wait` timeout.
20729 *
20730 * See [David Corbacho's article](http://drupalmotion.com/article/debounce-and-throttle-visual-explanation)
20731 * for details over the differences between `_.debounce` and `_.throttle`.
20732 *
20733 * @static
20734 * @memberOf _
20735 * @category Function
20736 * @param {Function} func The function to debounce.
20737 * @param {number} [wait=0] The number of milliseconds to delay.
20738 * @param {Object} [options] The options object.
20739 * @param {boolean} [options.leading=false] Specify invoking on the leading
20740 * edge of the timeout.
20741 * @param {number} [options.maxWait] The maximum time `func` is allowed to be
20742 * delayed before it is invoked.
20743 * @param {boolean} [options.trailing=true] Specify invoking on the trailing
20744 * edge of the timeout.
20745 * @returns {Function} Returns the new debounced function.
20746 * @example
20747 *
20748 * // avoid costly calculations while the window size is in flux
20749 * jQuery(window).on('resize', _.debounce(calculateLayout, 150));
20750 *
20751 * // invoke `sendMail` when the click event is fired, debouncing subsequent calls
20752 * jQuery('#postbox').on('click', _.debounce(sendMail, 300, {
20753 * 'leading': true,
20754 * 'trailing': false
20755 * }));
20756 *
20757 * // ensure `batchLog` is invoked once after 1 second of debounced calls
20758 * var source = new EventSource('/stream');
20759 * jQuery(source).on('message', _.debounce(batchLog, 250, {
20760 * 'maxWait': 1000
20761 * }));
20762 *
20763 * // cancel a debounced call
20764 * var todoChanges = _.debounce(batchLog, 1000);
20765 * Object.observe(models.todo, todoChanges);
20766 *
20767 * Object.observe(models, function(changes) {
20768 * if (_.find(changes, { 'user': 'todo', 'type': 'delete'})) {
20769 * todoChanges.cancel();
20770 * }
20771 * }, ['delete']);
20772 *
20773 * // ...at some point `models.todo` is changed
20774 * models.todo.completed = true;
20775 *
20776 * // ...before 1 second has passed `models.todo` is deleted
20777 * // which cancels the debounced `todoChanges` call
20778 * delete models.todo;
20779 */
20780 function debounce(func, wait, options) {
20781 var args,
20782 maxTimeoutId,
20783 result,
20784 stamp,
20785 thisArg,
20786 timeoutId,
20787 trailingCall,
20788 lastCalled = 0,
20789 maxWait = false,
20790 trailing = true;
20791
20792 if (typeof func != 'function') {
20793 throw new TypeError(FUNC_ERROR_TEXT);
20794 }
20795 wait = wait < 0 ? 0 : (+wait || 0);
20796 if (options === true) {
20797 var leading = true;
20798 trailing = false;
20799 } else if (isObject(options)) {
20800 leading = !!options.leading;
20801 maxWait = 'maxWait' in options && nativeMax(+options.maxWait || 0, wait);
20802 trailing = 'trailing' in options ? !!options.trailing : trailing;
20803 }
20804
20805 function cancel() {
20806 if (timeoutId) {
20807 clearTimeout(timeoutId);
20808 }
20809 if (maxTimeoutId) {
20810 clearTimeout(maxTimeoutId);
20811 }
20812 lastCalled = 0;
20813 maxTimeoutId = timeoutId = trailingCall = undefined;
20814 }
20815
20816 function complete(isCalled, id) {
20817 if (id) {
20818 clearTimeout(id);
20819 }
20820 maxTimeoutId = timeoutId = trailingCall = undefined;
20821 if (isCalled) {
20822 lastCalled = now();
20823 result = func.apply(thisArg, args);
20824 if (!timeoutId && !maxTimeoutId) {
20825 args = thisArg = undefined;
20826 }
20827 }
20828 }
20829
20830 function delayed() {
20831 var remaining = wait - (now() - stamp);
20832 if (remaining <= 0 || remaining > wait) {
20833 complete(trailingCall, maxTimeoutId);
20834 } else {
20835 timeoutId = setTimeout(delayed, remaining);
20836 }
20837 }
20838
20839 function maxDelayed() {
20840 complete(trailing, timeoutId);
20841 }
20842
20843 function debounced() {
20844 args = arguments;
20845 stamp = now();
20846 thisArg = this;
20847 trailingCall = trailing && (timeoutId || !leading);
20848
20849 if (maxWait === false) {
20850 var leadingCall = leading && !timeoutId;
20851 } else {
20852 if (!maxTimeoutId && !leading) {
20853 lastCalled = stamp;
20854 }
20855 var remaining = maxWait - (stamp - lastCalled),
20856 isCalled = remaining <= 0 || remaining > maxWait;
20857
20858 if (isCalled) {
20859 if (maxTimeoutId) {
20860 maxTimeoutId = clearTimeout(maxTimeoutId);
20861 }
20862 lastCalled = stamp;
20863 result = func.apply(thisArg, args);
20864 }
20865 else if (!maxTimeoutId) {
20866 maxTimeoutId = setTimeout(maxDelayed, remaining);
20867 }
20868 }
20869 if (isCalled && timeoutId) {
20870 timeoutId = clearTimeout(timeoutId);
20871 }
20872 else if (!timeoutId && wait !== maxWait) {
20873 timeoutId = setTimeout(delayed, wait);
20874 }
20875 if (leadingCall) {
20876 isCalled = true;
20877 result = func.apply(thisArg, args);
20878 }
20879 if (isCalled && !timeoutId && !maxTimeoutId) {
20880 args = thisArg = undefined;
20881 }
20882 return result;
20883 }
20884 debounced.cancel = cancel;
20885 return debounced;
20886 }
20887
20888 /**
20889 * Defers invoking the `func` until the current call stack has cleared. Any
20890 * additional arguments are provided to `func` when it is invoked.
20891 *
20892 * @static
20893 * @memberOf _
20894 * @category Function
20895 * @param {Function} func The function to defer.
20896 * @param {...*} [args] The arguments to invoke the function with.
20897 * @returns {number} Returns the timer id.
20898 * @example
20899 *
20900 * _.defer(function(text) {
20901 * console.log(text);
20902 * }, 'deferred');
20903 * // logs 'deferred' after one or more milliseconds
20904 */
20905 var defer = restParam(function(func, args) {
20906 return baseDelay(func, 1, args);
20907 });
20908
20909 /**
20910 * Invokes `func` after `wait` milliseconds. Any additional arguments are
20911 * provided to `func` when it is invoked.
20912 *
20913 * @static
20914 * @memberOf _
20915 * @category Function
20916 * @param {Function} func The function to delay.
20917 * @param {number} wait The number of milliseconds to delay invocation.
20918 * @param {...*} [args] The arguments to invoke the function with.
20919 * @returns {number} Returns the timer id.
20920 * @example
20921 *
20922 * _.delay(function(text) {
20923 * console.log(text);
20924 * }, 1000, 'later');
20925 * // => logs 'later' after one second
20926 */
20927 var delay = restParam(function(func, wait, args) {
20928 return baseDelay(func, wait, args);
20929 });
20930
20931 /**
20932 * Creates a function that returns the result of invoking the provided
20933 * functions with the `this` binding of the created function, where each
20934 * successive invocation is supplied the return value of the previous.
20935 *
20936 * @static
20937 * @memberOf _
20938 * @category Function
20939 * @param {...Function} [funcs] Functions to invoke.
20940 * @returns {Function} Returns the new function.
20941 * @example
20942 *
20943 * function square(n) {
20944 * return n * n;
20945 * }
20946 *
20947 * var addSquare = _.flow(_.add, square);
20948 * addSquare(1, 2);
20949 * // => 9
20950 */
20951 var flow = createFlow();
20952
20953 /**
20954 * This method is like `_.flow` except that it creates a function that
20955 * invokes the provided functions from right to left.
20956 *
20957 * @static
20958 * @memberOf _
20959 * @alias backflow, compose
20960 * @category Function
20961 * @param {...Function} [funcs] Functions to invoke.
20962 * @returns {Function} Returns the new function.
20963 * @example
20964 *
20965 * function square(n) {
20966 * return n * n;
20967 * }
20968 *
20969 * var addSquare = _.flowRight(square, _.add);
20970 * addSquare(1, 2);
20971 * // => 9
20972 */
20973 var flowRight = createFlow(true);
20974
20975 /**
20976 * Creates a function that memoizes the result of `func`. If `resolver` is
20977 * provided it determines the cache key for storing the result based on the
20978 * arguments provided to the memoized function. By default, the first argument
20979 * provided to the memoized function is coerced to a string and used as the
20980 * cache key. The `func` is invoked with the `this` binding of the memoized
20981 * function.
20982 *
20983 * **Note:** The cache is exposed as the `cache` property on the memoized
20984 * function. Its creation may be customized by replacing the `_.memoize.Cache`
20985 * constructor with one whose instances implement the [`Map`](http://ecma-international.org/ecma-262/6.0/#sec-properties-of-the-map-prototype-object)
20986 * method interface of `get`, `has`, and `set`.
20987 *
20988 * @static
20989 * @memberOf _
20990 * @category Function
20991 * @param {Function} func The function to have its output memoized.
20992 * @param {Function} [resolver] The function to resolve the cache key.
20993 * @returns {Function} Returns the new memoizing function.
20994 * @example
20995 *
20996 * var upperCase = _.memoize(function(string) {
20997 * return string.toUpperCase();
20998 * });
20999 *
21000 * upperCase('fred');
21001 * // => 'FRED'
21002 *
21003 * // modifying the result cache
21004 * upperCase.cache.set('fred', 'BARNEY');
21005 * upperCase('fred');
21006 * // => 'BARNEY'
21007 *
21008 * // replacing `_.memoize.Cache`
21009 * var object = { 'user': 'fred' };
21010 * var other = { 'user': 'barney' };
21011 * var identity = _.memoize(_.identity);
21012 *
21013 * identity(object);
21014 * // => { 'user': 'fred' }
21015 * identity(other);
21016 * // => { 'user': 'fred' }
21017 *
21018 * _.memoize.Cache = WeakMap;
21019 * var identity = _.memoize(_.identity);
21020 *
21021 * identity(object);
21022 * // => { 'user': 'fred' }
21023 * identity(other);
21024 * // => { 'user': 'barney' }
21025 */
21026 function memoize(func, resolver) {
21027 if (typeof func != 'function' || (resolver && typeof resolver != 'function')) {
21028 throw new TypeError(FUNC_ERROR_TEXT);
21029 }
21030 var memoized = function() {
21031 var args = arguments,
21032 key = resolver ? resolver.apply(this, args) : args[0],
21033 cache = memoized.cache;
21034
21035 if (cache.has(key)) {
21036 return cache.get(key);
21037 }
21038 var result = func.apply(this, args);
21039 memoized.cache = cache.set(key, result);
21040 return result;
21041 };
21042 memoized.cache = new memoize.Cache;
21043 return memoized;
21044 }
21045
21046 /**
21047 * Creates a function that runs each argument through a corresponding
21048 * transform function.
21049 *
21050 * @static
21051 * @memberOf _
21052 * @category Function
21053 * @param {Function} func The function to wrap.
21054 * @param {...(Function|Function[])} [transforms] The functions to transform
21055 * arguments, specified as individual functions or arrays of functions.
21056 * @returns {Function} Returns the new function.
21057 * @example
21058 *
21059 * function doubled(n) {
21060 * return n * 2;
21061 * }
21062 *
21063 * function square(n) {
21064 * return n * n;
21065 * }
21066 *
21067 * var modded = _.modArgs(function(x, y) {
21068 * return [x, y];
21069 * }, square, doubled);
21070 *
21071 * modded(1, 2);
21072 * // => [1, 4]
21073 *
21074 * modded(5, 10);
21075 * // => [25, 20]
21076 */
21077 var modArgs = restParam(function(func, transforms) {
21078 transforms = baseFlatten(transforms);
21079 if (typeof func != 'function' || !arrayEvery(transforms, baseIsFunction)) {
21080 throw new TypeError(FUNC_ERROR_TEXT);
21081 }
21082 var length = transforms.length;
21083 return restParam(function(args) {
21084 var index = nativeMin(args.length, length);
21085 while (index--) {
21086 args[index] = transforms[index](args[index]);
21087 }
21088 return func.apply(this, args);
21089 });
21090 });
21091
21092 /**
21093 * Creates a function that negates the result of the predicate `func`. The
21094 * `func` predicate is invoked with the `this` binding and arguments of the
21095 * created function.
21096 *
21097 * @static
21098 * @memberOf _
21099 * @category Function
21100 * @param {Function} predicate The predicate to negate.
21101 * @returns {Function} Returns the new function.
21102 * @example
21103 *
21104 * function isEven(n) {
21105 * return n % 2 == 0;
21106 * }
21107 *
21108 * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven));
21109 * // => [1, 3, 5]
21110 */
21111 function negate(predicate) {
21112 if (typeof predicate != 'function') {
21113 throw new TypeError(FUNC_ERROR_TEXT);
21114 }
21115 return function() {
21116 return !predicate.apply(this, arguments);
21117 };
21118 }
21119
21120 /**
21121 * Creates a function that is restricted to invoking `func` once. Repeat calls
21122 * to the function return the value of the first call. The `func` is invoked
21123 * with the `this` binding and arguments of the created function.
21124 *
21125 * @static
21126 * @memberOf _
21127 * @category Function
21128 * @param {Function} func The function to restrict.
21129 * @returns {Function} Returns the new restricted function.
21130 * @example
21131 *
21132 * var initialize = _.once(createApplication);
21133 * initialize();
21134 * initialize();
21135 * // `initialize` invokes `createApplication` once
21136 */
21137 function once(func) {
21138 return before(2, func);
21139 }
21140
21141 /**
21142 * Creates a function that invokes `func` with `partial` arguments prepended
21143 * to those provided to the new function. This method is like `_.bind` except
21144 * it does **not** alter the `this` binding.
21145 *
21146 * The `_.partial.placeholder` value, which defaults to `_` in monolithic
21147 * builds, may be used as a placeholder for partially applied arguments.
21148 *
21149 * **Note:** This method does not set the "length" property of partially
21150 * applied functions.
21151 *
21152 * @static
21153 * @memberOf _
21154 * @category Function
21155 * @param {Function} func The function to partially apply arguments to.
21156 * @param {...*} [partials] The arguments to be partially applied.
21157 * @returns {Function} Returns the new partially applied function.
21158 * @example
21159 *
21160 * var greet = function(greeting, name) {
21161 * return greeting + ' ' + name;
21162 * };
21163 *
21164 * var sayHelloTo = _.partial(greet, 'hello');
21165 * sayHelloTo('fred');
21166 * // => 'hello fred'
21167 *
21168 * // using placeholders
21169 * var greetFred = _.partial(greet, _, 'fred');
21170 * greetFred('hi');
21171 * // => 'hi fred'
21172 */
21173 var partial = createPartial(PARTIAL_FLAG);
21174
21175 /**
21176 * This method is like `_.partial` except that partially applied arguments
21177 * are appended to those provided to the new function.
21178 *
21179 * The `_.partialRight.placeholder` value, which defaults to `_` in monolithic
21180 * builds, may be used as a placeholder for partially applied arguments.
21181 *
21182 * **Note:** This method does not set the "length" property of partially
21183 * applied functions.
21184 *
21185 * @static
21186 * @memberOf _
21187 * @category Function
21188 * @param {Function} func The function to partially apply arguments to.
21189 * @param {...*} [partials] The arguments to be partially applied.
21190 * @returns {Function} Returns the new partially applied function.
21191 * @example
21192 *
21193 * var greet = function(greeting, name) {
21194 * return greeting + ' ' + name;
21195 * };
21196 *
21197 * var greetFred = _.partialRight(greet, 'fred');
21198 * greetFred('hi');
21199 * // => 'hi fred'
21200 *
21201 * // using placeholders
21202 * var sayHelloTo = _.partialRight(greet, 'hello', _);
21203 * sayHelloTo('fred');
21204 * // => 'hello fred'
21205 */
21206 var partialRight = createPartial(PARTIAL_RIGHT_FLAG);
21207
21208 /**
21209 * Creates a function that invokes `func` with arguments arranged according
21210 * to the specified indexes where the argument value at the first index is
21211 * provided as the first argument, the argument value at the second index is
21212 * provided as the second argument, and so on.
21213 *
21214 * @static
21215 * @memberOf _
21216 * @category Function
21217 * @param {Function} func The function to rearrange arguments for.
21218 * @param {...(number|number[])} indexes The arranged argument indexes,
21219 * specified as individual indexes or arrays of indexes.
21220 * @returns {Function} Returns the new function.
21221 * @example
21222 *
21223 * var rearged = _.rearg(function(a, b, c) {
21224 * return [a, b, c];
21225 * }, 2, 0, 1);
21226 *
21227 * rearged('b', 'c', 'a')
21228 * // => ['a', 'b', 'c']
21229 *
21230 * var map = _.rearg(_.map, [1, 0]);
21231 * map(function(n) {
21232 * return n * 3;
21233 * }, [1, 2, 3]);
21234 * // => [3, 6, 9]
21235 */
21236 var rearg = restParam(function(func, indexes) {
21237 return createWrapper(func, REARG_FLAG, undefined, undefined, undefined, baseFlatten(indexes));
21238 });
21239
21240 /**
21241 * Creates a function that invokes `func` with the `this` binding of the
21242 * created function and arguments from `start` and beyond provided as an array.
21243 *
21244 * **Note:** This method is based on the [rest parameter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters).
21245 *
21246 * @static
21247 * @memberOf _
21248 * @category Function
21249 * @param {Function} func The function to apply a rest parameter to.
21250 * @param {number} [start=func.length-1] The start position of the rest parameter.
21251 * @returns {Function} Returns the new function.
21252 * @example
21253 *
21254 * var say = _.restParam(function(what, names) {
21255 * return what + ' ' + _.initial(names).join(', ') +
21256 * (_.size(names) > 1 ? ', & ' : '') + _.last(names);
21257 * });
21258 *
21259 * say('hello', 'fred', 'barney', 'pebbles');
21260 * // => 'hello fred, barney, & pebbles'
21261 */
21262 function restParam(func, start) {
21263 if (typeof func != 'function') {
21264 throw new TypeError(FUNC_ERROR_TEXT);
21265 }
21266 start = nativeMax(start === undefined ? (func.length - 1) : (+start || 0), 0);
21267 return function() {
21268 var args = arguments,
21269 index = -1,
21270 length = nativeMax(args.length - start, 0),
21271 rest = Array(length);
21272
21273 while (++index < length) {
21274 rest[index] = args[start + index];
21275 }
21276 switch (start) {
21277 case 0: return func.call(this, rest);
21278 case 1: return func.call(this, args[0], rest);
21279 case 2: return func.call(this, args[0], args[1], rest);
21280 }
21281 var otherArgs = Array(start + 1);
21282 index = -1;
21283 while (++index < start) {
21284 otherArgs[index] = args[index];
21285 }
21286 otherArgs[start] = rest;
21287 return func.apply(this, otherArgs);
21288 };
21289 }
21290
21291 /**
21292 * Creates a function that invokes `func` with the `this` binding of the created
21293 * function and an array of arguments much like [`Function#apply`](https://es5.github.io/#x15.3.4.3).
21294 *
21295 * **Note:** This method is based on the [spread operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator).
21296 *
21297 * @static
21298 * @memberOf _
21299 * @category Function
21300 * @param {Function} func The function to spread arguments over.
21301 * @returns {Function} Returns the new function.
21302 * @example
21303 *
21304 * var say = _.spread(function(who, what) {
21305 * return who + ' says ' + what;
21306 * });
21307 *
21308 * say(['fred', 'hello']);
21309 * // => 'fred says hello'
21310 *
21311 * // with a Promise
21312 * var numbers = Promise.all([
21313 * Promise.resolve(40),
21314 * Promise.resolve(36)
21315 * ]);
21316 *
21317 * numbers.then(_.spread(function(x, y) {
21318 * return x + y;
21319 * }));
21320 * // => a Promise of 76
21321 */
21322 function spread(func) {
21323 if (typeof func != 'function') {
21324 throw new TypeError(FUNC_ERROR_TEXT);
21325 }
21326 return function(array) {
21327 return func.apply(this, array);
21328 };
21329 }
21330
21331 /**
21332 * Creates a throttled function that only invokes `func` at most once per
21333 * every `wait` milliseconds. The throttled function comes with a `cancel`
21334 * method to cancel delayed invocations. Provide an options object to indicate
21335 * that `func` should be invoked on the leading and/or trailing edge of the
21336 * `wait` timeout. Subsequent calls to the throttled function return the
21337 * result of the last `func` call.
21338 *
21339 * **Note:** If `leading` and `trailing` options are `true`, `func` is invoked
21340 * on the trailing edge of the timeout only if the the throttled function is
21341 * invoked more than once during the `wait` timeout.
21342 *
21343 * See [David Corbacho's article](http://drupalmotion.com/article/debounce-and-throttle-visual-explanation)
21344 * for details over the differences between `_.throttle` and `_.debounce`.
21345 *
21346 * @static
21347 * @memberOf _
21348 * @category Function
21349 * @param {Function} func The function to throttle.
21350 * @param {number} [wait=0] The number of milliseconds to throttle invocations to.
21351 * @param {Object} [options] The options object.
21352 * @param {boolean} [options.leading=true] Specify invoking on the leading
21353 * edge of the timeout.
21354 * @param {boolean} [options.trailing=true] Specify invoking on the trailing
21355 * edge of the timeout.
21356 * @returns {Function} Returns the new throttled function.
21357 * @example
21358 *
21359 * // avoid excessively updating the position while scrolling
21360 * jQuery(window).on('scroll', _.throttle(updatePosition, 100));
21361 *
21362 * // invoke `renewToken` when the click event is fired, but not more than once every 5 minutes
21363 * jQuery('.interactive').on('click', _.throttle(renewToken, 300000, {
21364 * 'trailing': false
21365 * }));
21366 *
21367 * // cancel a trailing throttled call
21368 * jQuery(window).on('popstate', throttled.cancel);
21369 */
21370 function throttle(func, wait, options) {
21371 var leading = true,
21372 trailing = true;
21373
21374 if (typeof func != 'function') {
21375 throw new TypeError(FUNC_ERROR_TEXT);
21376 }
21377 if (options === false) {
21378 leading = false;
21379 } else if (isObject(options)) {
21380 leading = 'leading' in options ? !!options.leading : leading;
21381 trailing = 'trailing' in options ? !!options.trailing : trailing;
21382 }
21383 return debounce(func, wait, { 'leading': leading, 'maxWait': +wait, 'trailing': trailing });
21384 }
21385
21386 /**
21387 * Creates a function that provides `value` to the wrapper function as its
21388 * first argument. Any additional arguments provided to the function are
21389 * appended to those provided to the wrapper function. The wrapper is invoked
21390 * with the `this` binding of the created function.
21391 *
21392 * @static
21393 * @memberOf _
21394 * @category Function
21395 * @param {*} value The value to wrap.
21396 * @param {Function} wrapper The wrapper function.
21397 * @returns {Function} Returns the new function.
21398 * @example
21399 *
21400 * var p = _.wrap(_.escape, function(func, text) {
21401 * return '<p>' + func(text) + '</p>';
21402 * });
21403 *
21404 * p('fred, barney, & pebbles');
21405 * // => '<p>fred, barney, &amp; pebbles</p>'
21406 */
21407 function wrap(value, wrapper) {
21408 wrapper = wrapper == null ? identity : wrapper;
21409 return createWrapper(wrapper, PARTIAL_FLAG, undefined, [value], []);
21410 }
21411
21412 /*------------------------------------------------------------------------*/
21413
21414 /**
21415 * Creates a clone of `value`. If `isDeep` is `true` nested objects are cloned,
21416 * otherwise they are assigned by reference. If `customizer` is provided it is
21417 * invoked to produce the cloned values. If `customizer` returns `undefined`
21418 * cloning is handled by the method instead. The `customizer` is bound to
21419 * `thisArg` and invoked with two argument; (value [, index|key, object]).
21420 *
21421 * **Note:** This method is loosely based on the
21422 * [structured clone algorithm](http://www.w3.org/TR/html5/infrastructure.html#internal-structured-cloning-algorithm).
21423 * The enumerable properties of `arguments` objects and objects created by
21424 * constructors other than `Object` are cloned to plain `Object` objects. An
21425 * empty object is returned for uncloneable values such as functions, DOM nodes,
21426 * Maps, Sets, and WeakMaps.
21427 *
21428 * @static
21429 * @memberOf _
21430 * @category Lang
21431 * @param {*} value The value to clone.
21432 * @param {boolean} [isDeep] Specify a deep clone.
21433 * @param {Function} [customizer] The function to customize cloning values.
21434 * @param {*} [thisArg] The `this` binding of `customizer`.
21435 * @returns {*} Returns the cloned value.
21436 * @example
21437 *
21438 * var users = [
21439 * { 'user': 'barney' },
21440 * { 'user': 'fred' }
21441 * ];
21442 *
21443 * var shallow = _.clone(users);
21444 * shallow[0] === users[0];
21445 * // => true
21446 *
21447 * var deep = _.clone(users, true);
21448 * deep[0] === users[0];
21449 * // => false
21450 *
21451 * // using a customizer callback
21452 * var el = _.clone(document.body, function(value) {
21453 * if (_.isElement(value)) {
21454 * return value.cloneNode(false);
21455 * }
21456 * });
21457 *
21458 * el === document.body
21459 * // => false
21460 * el.nodeName
21461 * // => BODY
21462 * el.childNodes.length;
21463 * // => 0
21464 */
21465 function clone(value, isDeep, customizer, thisArg) {
21466 if (isDeep && typeof isDeep != 'boolean' && isIterateeCall(value, isDeep, customizer)) {
21467 isDeep = false;
21468 }
21469 else if (typeof isDeep == 'function') {
21470 thisArg = customizer;
21471 customizer = isDeep;
21472 isDeep = false;
21473 }
21474 return typeof customizer == 'function'
21475 ? baseClone(value, isDeep, bindCallback(customizer, thisArg, 1))
21476 : baseClone(value, isDeep);
21477 }
21478
21479 /**
21480 * Creates a deep clone of `value`. If `customizer` is provided it is invoked
21481 * to produce the cloned values. If `customizer` returns `undefined` cloning
21482 * is handled by the method instead. The `customizer` is bound to `thisArg`
21483 * and invoked with two argument; (value [, index|key, object]).
21484 *
21485 * **Note:** This method is loosely based on the
21486 * [structured clone algorithm](http://www.w3.org/TR/html5/infrastructure.html#internal-structured-cloning-algorithm).
21487 * The enumerable properties of `arguments` objects and objects created by
21488 * constructors other than `Object` are cloned to plain `Object` objects. An
21489 * empty object is returned for uncloneable values such as functions, DOM nodes,
21490 * Maps, Sets, and WeakMaps.
21491 *
21492 * @static
21493 * @memberOf _
21494 * @category Lang
21495 * @param {*} value The value to deep clone.
21496 * @param {Function} [customizer] The function to customize cloning values.
21497 * @param {*} [thisArg] The `this` binding of `customizer`.
21498 * @returns {*} Returns the deep cloned value.
21499 * @example
21500 *
21501 * var users = [
21502 * { 'user': 'barney' },
21503 * { 'user': 'fred' }
21504 * ];
21505 *
21506 * var deep = _.cloneDeep(users);
21507 * deep[0] === users[0];
21508 * // => false
21509 *
21510 * // using a customizer callback
21511 * var el = _.cloneDeep(document.body, function(value) {
21512 * if (_.isElement(value)) {
21513 * return value.cloneNode(true);
21514 * }
21515 * });
21516 *
21517 * el === document.body
21518 * // => false
21519 * el.nodeName
21520 * // => BODY
21521 * el.childNodes.length;
21522 * // => 20
21523 */
21524 function cloneDeep(value, customizer, thisArg) {
21525 return typeof customizer == 'function'
21526 ? baseClone(value, true, bindCallback(customizer, thisArg, 1))
21527 : baseClone(value, true);
21528 }
21529
21530 /**
21531 * Checks if `value` is greater than `other`.
21532 *
21533 * @static
21534 * @memberOf _
21535 * @category Lang
21536 * @param {*} value The value to compare.
21537 * @param {*} other The other value to compare.
21538 * @returns {boolean} Returns `true` if `value` is greater than `other`, else `false`.
21539 * @example
21540 *
21541 * _.gt(3, 1);
21542 * // => true
21543 *
21544 * _.gt(3, 3);
21545 * // => false
21546 *
21547 * _.gt(1, 3);
21548 * // => false
21549 */
21550 function gt(value, other) {
21551 return value > other;
21552 }
21553
21554 /**
21555 * Checks if `value` is greater than or equal to `other`.
21556 *
21557 * @static
21558 * @memberOf _
21559 * @category Lang
21560 * @param {*} value The value to compare.
21561 * @param {*} other The other value to compare.
21562 * @returns {boolean} Returns `true` if `value` is greater than or equal to `other`, else `false`.
21563 * @example
21564 *
21565 * _.gte(3, 1);
21566 * // => true
21567 *
21568 * _.gte(3, 3);
21569 * // => true
21570 *
21571 * _.gte(1, 3);
21572 * // => false
21573 */
21574 function gte(value, other) {
21575 return value >= other;
21576 }
21577
21578 /**
21579 * Checks if `value` is classified as an `arguments` object.
21580 *
21581 * @static
21582 * @memberOf _
21583 * @category Lang
21584 * @param {*} value The value to check.
21585 * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
21586 * @example
21587 *
21588 * _.isArguments(function() { return arguments; }());
21589 * // => true
21590 *
21591 * _.isArguments([1, 2, 3]);
21592 * // => false
21593 */
21594 function isArguments(value) {
21595 return isObjectLike(value) && isArrayLike(value) &&
21596 hasOwnProperty.call(value, 'callee') && !propertyIsEnumerable.call(value, 'callee');
21597 }
21598
21599 /**
21600 * Checks if `value` is classified as an `Array` object.
21601 *
21602 * @static
21603 * @memberOf _
21604 * @category Lang
21605 * @param {*} value The value to check.
21606 * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
21607 * @example
21608 *
21609 * _.isArray([1, 2, 3]);
21610 * // => true
21611 *
21612 * _.isArray(function() { return arguments; }());
21613 * // => false
21614 */
21615 var isArray = nativeIsArray || function(value) {
21616 return isObjectLike(value) && isLength(value.length) && objToString.call(value) == arrayTag;
21617 };
21618
21619 /**
21620 * Checks if `value` is classified as a boolean primitive or object.
21621 *
21622 * @static
21623 * @memberOf _
21624 * @category Lang
21625 * @param {*} value The value to check.
21626 * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
21627 * @example
21628 *
21629 * _.isBoolean(false);
21630 * // => true
21631 *
21632 * _.isBoolean(null);
21633 * // => false
21634 */
21635 function isBoolean(value) {
21636 return value === true || value === false || (isObjectLike(value) && objToString.call(value) == boolTag);
21637 }
21638
21639 /**
21640 * Checks if `value` is classified as a `Date` object.
21641 *
21642 * @static
21643 * @memberOf _
21644 * @category Lang
21645 * @param {*} value The value to check.
21646 * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
21647 * @example
21648 *
21649 * _.isDate(new Date);
21650 * // => true
21651 *
21652 * _.isDate('Mon April 23 2012');
21653 * // => false
21654 */
21655 function isDate(value) {
21656 return isObjectLike(value) && objToString.call(value) == dateTag;
21657 }
21658
21659 /**
21660 * Checks if `value` is a DOM element.
21661 *
21662 * @static
21663 * @memberOf _
21664 * @category Lang
21665 * @param {*} value The value to check.
21666 * @returns {boolean} Returns `true` if `value` is a DOM element, else `false`.
21667 * @example
21668 *
21669 * _.isElement(document.body);
21670 * // => true
21671 *
21672 * _.isElement('<body>');
21673 * // => false
21674 */
21675 function isElement(value) {
21676 return !!value && value.nodeType === 1 && isObjectLike(value) && !isPlainObject(value);
21677 }
21678
21679 /**
21680 * Checks if `value` is empty. A value is considered empty unless it is an
21681 * `arguments` object, array, string, or jQuery-like collection with a length
21682 * greater than `0` or an object with own enumerable properties.
21683 *
21684 * @static
21685 * @memberOf _
21686 * @category Lang
21687 * @param {Array|Object|string} value The value to inspect.
21688 * @returns {boolean} Returns `true` if `value` is empty, else `false`.
21689 * @example
21690 *
21691 * _.isEmpty(null);
21692 * // => true
21693 *
21694 * _.isEmpty(true);
21695 * // => true
21696 *
21697 * _.isEmpty(1);
21698 * // => true
21699 *
21700 * _.isEmpty([1, 2, 3]);
21701 * // => false
21702 *
21703 * _.isEmpty({ 'a': 1 });
21704 * // => false
21705 */
21706 function isEmpty(value) {
21707 if (value == null) {
21708 return true;
21709 }
21710 if (isArrayLike(value) && (isArray(value) || isString(value) || isArguments(value) ||
21711 (isObjectLike(value) && isFunction(value.splice)))) {
21712 return !value.length;
21713 }
21714 return !keys(value).length;
21715 }
21716
21717 /**
21718 * Performs a deep comparison between two values to determine if they are
21719 * equivalent. If `customizer` is provided it is invoked to compare values.
21720 * If `customizer` returns `undefined` comparisons are handled by the method
21721 * instead. The `customizer` is bound to `thisArg` and invoked with three
21722 * arguments: (value, other [, index|key]).
21723 *
21724 * **Note:** This method supports comparing arrays, booleans, `Date` objects,
21725 * numbers, `Object` objects, regexes, and strings. Objects are compared by
21726 * their own, not inherited, enumerable properties. Functions and DOM nodes
21727 * are **not** supported. Provide a customizer function to extend support
21728 * for comparing other values.
21729 *
21730 * @static
21731 * @memberOf _
21732 * @alias eq
21733 * @category Lang
21734 * @param {*} value The value to compare.
21735 * @param {*} other The other value to compare.
21736 * @param {Function} [customizer] The function to customize value comparisons.
21737 * @param {*} [thisArg] The `this` binding of `customizer`.
21738 * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
21739 * @example
21740 *
21741 * var object = { 'user': 'fred' };
21742 * var other = { 'user': 'fred' };
21743 *
21744 * object == other;
21745 * // => false
21746 *
21747 * _.isEqual(object, other);
21748 * // => true
21749 *
21750 * // using a customizer callback
21751 * var array = ['hello', 'goodbye'];
21752 * var other = ['hi', 'goodbye'];
21753 *
21754 * _.isEqual(array, other, function(value, other) {
21755 * if (_.every([value, other], RegExp.prototype.test, /^h(?:i|ello)$/)) {
21756 * return true;
21757 * }
21758 * });
21759 * // => true
21760 */
21761 function isEqual(value, other, customizer, thisArg) {
21762 customizer = typeof customizer == 'function' ? bindCallback(customizer, thisArg, 3) : undefined;
21763 var result = customizer ? customizer(value, other) : undefined;
21764 return result === undefined ? baseIsEqual(value, other, customizer) : !!result;
21765 }
21766
21767 /**
21768 * Checks if `value` is an `Error`, `EvalError`, `RangeError`, `ReferenceError`,
21769 * `SyntaxError`, `TypeError`, or `URIError` object.
21770 *
21771 * @static
21772 * @memberOf _
21773 * @category Lang
21774 * @param {*} value The value to check.
21775 * @returns {boolean} Returns `true` if `value` is an error object, else `false`.
21776 * @example
21777 *
21778 * _.isError(new Error);
21779 * // => true
21780 *
21781 * _.isError(Error);
21782 * // => false
21783 */
21784 function isError(value) {
21785 return isObjectLike(value) && typeof value.message == 'string' && objToString.call(value) == errorTag;
21786 }
21787
21788 /**
21789 * Checks if `value` is a finite primitive number.
21790 *
21791 * **Note:** This method is based on [`Number.isFinite`](http://ecma-international.org/ecma-262/6.0/#sec-number.isfinite).
21792 *
21793 * @static
21794 * @memberOf _
21795 * @category Lang
21796 * @param {*} value The value to check.
21797 * @returns {boolean} Returns `true` if `value` is a finite number, else `false`.
21798 * @example
21799 *
21800 * _.isFinite(10);
21801 * // => true
21802 *
21803 * _.isFinite('10');
21804 * // => false
21805 *
21806 * _.isFinite(true);
21807 * // => false
21808 *
21809 * _.isFinite(Object(10));
21810 * // => false
21811 *
21812 * _.isFinite(Infinity);
21813 * // => false
21814 */
21815 function isFinite(value) {
21816 return typeof value == 'number' && nativeIsFinite(value);
21817 }
21818
21819 /**
21820 * Checks if `value` is classified as a `Function` object.
21821 *
21822 * @static
21823 * @memberOf _
21824 * @category Lang
21825 * @param {*} value The value to check.
21826 * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
21827 * @example
21828 *
21829 * _.isFunction(_);
21830 * // => true
21831 *
21832 * _.isFunction(/abc/);
21833 * // => false
21834 */
21835 function isFunction(value) {
21836 // The use of `Object#toString` avoids issues with the `typeof` operator
21837 // in older versions of Chrome and Safari which return 'function' for regexes
21838 // and Safari 8 equivalents which return 'object' for typed array constructors.
21839 return isObject(value) && objToString.call(value) == funcTag;
21840 }
21841
21842 /**
21843 * Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`.
21844 * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
21845 *
21846 * @static
21847 * @memberOf _
21848 * @category Lang
21849 * @param {*} value The value to check.
21850 * @returns {boolean} Returns `true` if `value` is an object, else `false`.
21851 * @example
21852 *
21853 * _.isObject({});
21854 * // => true
21855 *
21856 * _.isObject([1, 2, 3]);
21857 * // => true
21858 *
21859 * _.isObject(1);
21860 * // => false
21861 */
21862 function isObject(value) {
21863 // Avoid a V8 JIT bug in Chrome 19-20.
21864 // See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
21865 var type = typeof value;
21866 return !!value && (type == 'object' || type == 'function');
21867 }
21868
21869 /**
21870 * Performs a deep comparison between `object` and `source` to determine if
21871 * `object` contains equivalent property values. If `customizer` is provided
21872 * it is invoked to compare values. If `customizer` returns `undefined`
21873 * comparisons are handled by the method instead. The `customizer` is bound
21874 * to `thisArg` and invoked with three arguments: (value, other, index|key).
21875 *
21876 * **Note:** This method supports comparing properties of arrays, booleans,
21877 * `Date` objects, numbers, `Object` objects, regexes, and strings. Functions
21878 * and DOM nodes are **not** supported. Provide a customizer function to extend
21879 * support for comparing other values.
21880 *
21881 * @static
21882 * @memberOf _
21883 * @category Lang
21884 * @param {Object} object The object to inspect.
21885 * @param {Object} source The object of property values to match.
21886 * @param {Function} [customizer] The function to customize value comparisons.
21887 * @param {*} [thisArg] The `this` binding of `customizer`.
21888 * @returns {boolean} Returns `true` if `object` is a match, else `false`.
21889 * @example
21890 *
21891 * var object = { 'user': 'fred', 'age': 40 };
21892 *
21893 * _.isMatch(object, { 'age': 40 });
21894 * // => true
21895 *
21896 * _.isMatch(object, { 'age': 36 });
21897 * // => false
21898 *
21899 * // using a customizer callback
21900 * var object = { 'greeting': 'hello' };
21901 * var source = { 'greeting': 'hi' };
21902 *
21903 * _.isMatch(object, source, function(value, other) {
21904 * return _.every([value, other], RegExp.prototype.test, /^h(?:i|ello)$/) || undefined;
21905 * });
21906 * // => true
21907 */
21908 function isMatch(object, source, customizer, thisArg) {
21909 customizer = typeof customizer == 'function' ? bindCallback(customizer, thisArg, 3) : undefined;
21910 return baseIsMatch(object, getMatchData(source), customizer);
21911 }
21912
21913 /**
21914 * Checks if `value` is `NaN`.
21915 *
21916 * **Note:** This method is not the same as [`isNaN`](https://es5.github.io/#x15.1.2.4)
21917 * which returns `true` for `undefined` and other non-numeric values.
21918 *
21919 * @static
21920 * @memberOf _
21921 * @category Lang
21922 * @param {*} value The value to check.
21923 * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.
21924 * @example
21925 *
21926 * _.isNaN(NaN);
21927 * // => true
21928 *
21929 * _.isNaN(new Number(NaN));
21930 * // => true
21931 *
21932 * isNaN(undefined);
21933 * // => true
21934 *
21935 * _.isNaN(undefined);
21936 * // => false
21937 */
21938 function isNaN(value) {
21939 // An `NaN` primitive is the only value that is not equal to itself.
21940 // Perform the `toStringTag` check first to avoid errors with some host objects in IE.
21941 return isNumber(value) && value != +value;
21942 }
21943
21944 /**
21945 * Checks if `value` is a native function.
21946 *
21947 * @static
21948 * @memberOf _
21949 * @category Lang
21950 * @param {*} value The value to check.
21951 * @returns {boolean} Returns `true` if `value` is a native function, else `false`.
21952 * @example
21953 *
21954 * _.isNative(Array.prototype.push);
21955 * // => true
21956 *
21957 * _.isNative(_);
21958 * // => false
21959 */
21960 function isNative(value) {
21961 if (value == null) {
21962 return false;
21963 }
21964 if (isFunction(value)) {
21965 return reIsNative.test(fnToString.call(value));
21966 }
21967 return isObjectLike(value) && reIsHostCtor.test(value);
21968 }
21969
21970 /**
21971 * Checks if `value` is `null`.
21972 *
21973 * @static
21974 * @memberOf _
21975 * @category Lang
21976 * @param {*} value The value to check.
21977 * @returns {boolean} Returns `true` if `value` is `null`, else `false`.
21978 * @example
21979 *
21980 * _.isNull(null);
21981 * // => true
21982 *
21983 * _.isNull(void 0);
21984 * // => false
21985 */
21986 function isNull(value) {
21987 return value === null;
21988 }
21989
21990 /**
21991 * Checks if `value` is classified as a `Number` primitive or object.
21992 *
21993 * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are classified
21994 * as numbers, use the `_.isFinite` method.
21995 *
21996 * @static
21997 * @memberOf _
21998 * @category Lang
21999 * @param {*} value The value to check.
22000 * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
22001 * @example
22002 *
22003 * _.isNumber(8.4);
22004 * // => true
22005 *
22006 * _.isNumber(NaN);
22007 * // => true
22008 *
22009 * _.isNumber('8.4');
22010 * // => false
22011 */
22012 function isNumber(value) {
22013 return typeof value == 'number' || (isObjectLike(value) && objToString.call(value) == numberTag);
22014 }
22015
22016 /**
22017 * Checks if `value` is a plain object, that is, an object created by the
22018 * `Object` constructor or one with a `[[Prototype]]` of `null`.
22019 *
22020 * **Note:** This method assumes objects created by the `Object` constructor
22021 * have no inherited enumerable properties.
22022 *
22023 * @static
22024 * @memberOf _
22025 * @category Lang
22026 * @param {*} value The value to check.
22027 * @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
22028 * @example
22029 *
22030 * function Foo() {
22031 * this.a = 1;
22032 * }
22033 *
22034 * _.isPlainObject(new Foo);
22035 * // => false
22036 *
22037 * _.isPlainObject([1, 2, 3]);
22038 * // => false
22039 *
22040 * _.isPlainObject({ 'x': 0, 'y': 0 });
22041 * // => true
22042 *
22043 * _.isPlainObject(Object.create(null));
22044 * // => true
22045 */
22046 function isPlainObject(value) {
22047 var Ctor;
22048
22049 // Exit early for non `Object` objects.
22050 if (!(isObjectLike(value) && objToString.call(value) == objectTag && !isArguments(value)) ||
22051 (!hasOwnProperty.call(value, 'constructor') && (Ctor = value.constructor, typeof Ctor == 'function' && !(Ctor instanceof Ctor)))) {
22052 return false;
22053 }
22054 // IE < 9 iterates inherited properties before own properties. If the first
22055 // iterated property is an object's own property then there are no inherited
22056 // enumerable properties.
22057 var result;
22058 // In most environments an object's own properties are iterated before
22059 // its inherited properties. If the last iterated property is an object's
22060 // own property then there are no inherited enumerable properties.
22061 baseForIn(value, function(subValue, key) {
22062 result = key;
22063 });
22064 return result === undefined || hasOwnProperty.call(value, result);
22065 }
22066
22067 /**
22068 * Checks if `value` is classified as a `RegExp` object.
22069 *
22070 * @static
22071 * @memberOf _
22072 * @category Lang
22073 * @param {*} value The value to check.
22074 * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
22075 * @example
22076 *
22077 * _.isRegExp(/abc/);
22078 * // => true
22079 *
22080 * _.isRegExp('/abc/');
22081 * // => false
22082 */
22083 function isRegExp(value) {
22084 return isObject(value) && objToString.call(value) == regexpTag;
22085 }
22086
22087 /**
22088 * Checks if `value` is classified as a `String` primitive or object.
22089 *
22090 * @static
22091 * @memberOf _
22092 * @category Lang
22093 * @param {*} value The value to check.
22094 * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
22095 * @example
22096 *
22097 * _.isString('abc');
22098 * // => true
22099 *
22100 * _.isString(1);
22101 * // => false
22102 */
22103 function isString(value) {
22104 return typeof value == 'string' || (isObjectLike(value) && objToString.call(value) == stringTag);
22105 }
22106
22107 /**
22108 * Checks if `value` is classified as a typed array.
22109 *
22110 * @static
22111 * @memberOf _
22112 * @category Lang
22113 * @param {*} value The value to check.
22114 * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
22115 * @example
22116 *
22117 * _.isTypedArray(new Uint8Array);
22118 * // => true
22119 *
22120 * _.isTypedArray([]);
22121 * // => false
22122 */
22123 function isTypedArray(value) {
22124 return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[objToString.call(value)];
22125 }
22126
22127 /**
22128 * Checks if `value` is `undefined`.
22129 *
22130 * @static
22131 * @memberOf _
22132 * @category Lang
22133 * @param {*} value The value to check.
22134 * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`.
22135 * @example
22136 *
22137 * _.isUndefined(void 0);
22138 * // => true
22139 *
22140 * _.isUndefined(null);
22141 * // => false
22142 */
22143 function isUndefined(value) {
22144 return value === undefined;
22145 }
22146
22147 /**
22148 * Checks if `value` is less than `other`.
22149 *
22150 * @static
22151 * @memberOf _
22152 * @category Lang
22153 * @param {*} value The value to compare.
22154 * @param {*} other The other value to compare.
22155 * @returns {boolean} Returns `true` if `value` is less than `other`, else `false`.
22156 * @example
22157 *
22158 * _.lt(1, 3);
22159 * // => true
22160 *
22161 * _.lt(3, 3);
22162 * // => false
22163 *
22164 * _.lt(3, 1);
22165 * // => false
22166 */
22167 function lt(value, other) {
22168 return value < other;
22169 }
22170
22171 /**
22172 * Checks if `value` is less than or equal to `other`.
22173 *
22174 * @static
22175 * @memberOf _
22176 * @category Lang
22177 * @param {*} value The value to compare.
22178 * @param {*} other The other value to compare.
22179 * @returns {boolean} Returns `true` if `value` is less than or equal to `other`, else `false`.
22180 * @example
22181 *
22182 * _.lte(1, 3);
22183 * // => true
22184 *
22185 * _.lte(3, 3);
22186 * // => true
22187 *
22188 * _.lte(3, 1);
22189 * // => false
22190 */
22191 function lte(value, other) {
22192 return value <= other;
22193 }
22194
22195 /**
22196 * Converts `value` to an array.
22197 *
22198 * @static
22199 * @memberOf _
22200 * @category Lang
22201 * @param {*} value The value to convert.
22202 * @returns {Array} Returns the converted array.
22203 * @example
22204 *
22205 * (function() {
22206 * return _.toArray(arguments).slice(1);
22207 * }(1, 2, 3));
22208 * // => [2, 3]
22209 */
22210 function toArray(value) {
22211 var length = value ? getLength(value) : 0;
22212 if (!isLength(length)) {
22213 return values(value);
22214 }
22215 if (!length) {
22216 return [];
22217 }
22218 return arrayCopy(value);
22219 }
22220
22221 /**
22222 * Converts `value` to a plain object flattening inherited enumerable
22223 * properties of `value` to own properties of the plain object.
22224 *
22225 * @static
22226 * @memberOf _
22227 * @category Lang
22228 * @param {*} value The value to convert.
22229 * @returns {Object} Returns the converted plain object.
22230 * @example
22231 *
22232 * function Foo() {
22233 * this.b = 2;
22234 * }
22235 *
22236 * Foo.prototype.c = 3;
22237 *
22238 * _.assign({ 'a': 1 }, new Foo);
22239 * // => { 'a': 1, 'b': 2 }
22240 *
22241 * _.assign({ 'a': 1 }, _.toPlainObject(new Foo));
22242 * // => { 'a': 1, 'b': 2, 'c': 3 }
22243 */
22244 function toPlainObject(value) {
22245 return baseCopy(value, keysIn(value));
22246 }
22247
22248 /*------------------------------------------------------------------------*/
22249
22250 /**
22251 * Recursively merges own enumerable properties of the source object(s), that
22252 * don't resolve to `undefined` into the destination object. Subsequent sources
22253 * overwrite property assignments of previous sources. If `customizer` is
22254 * provided it is invoked to produce the merged values of the destination and
22255 * source properties. If `customizer` returns `undefined` merging is handled
22256 * by the method instead. The `customizer` is bound to `thisArg` and invoked
22257 * with five arguments: (objectValue, sourceValue, key, object, source).
22258 *
22259 * @static
22260 * @memberOf _
22261 * @category Object
22262 * @param {Object} object The destination object.
22263 * @param {...Object} [sources] The source objects.
22264 * @param {Function} [customizer] The function to customize assigned values.
22265 * @param {*} [thisArg] The `this` binding of `customizer`.
22266 * @returns {Object} Returns `object`.
22267 * @example
22268 *
22269 * var users = {
22270 * 'data': [{ 'user': 'barney' }, { 'user': 'fred' }]
22271 * };
22272 *
22273 * var ages = {
22274 * 'data': [{ 'age': 36 }, { 'age': 40 }]
22275 * };
22276 *
22277 * _.merge(users, ages);
22278 * // => { 'data': [{ 'user': 'barney', 'age': 36 }, { 'user': 'fred', 'age': 40 }] }
22279 *
22280 * // using a customizer callback
22281 * var object = {
22282 * 'fruits': ['apple'],
22283 * 'vegetables': ['beet']
22284 * };
22285 *
22286 * var other = {
22287 * 'fruits': ['banana'],
22288 * 'vegetables': ['carrot']
22289 * };
22290 *
22291 * _.merge(object, other, function(a, b) {
22292 * if (_.isArray(a)) {
22293 * return a.concat(b);
22294 * }
22295 * });
22296 * // => { 'fruits': ['apple', 'banana'], 'vegetables': ['beet', 'carrot'] }
22297 */
22298 var merge = createAssigner(baseMerge);
22299
22300 /**
22301 * Assigns own enumerable properties of source object(s) to the destination
22302 * object. Subsequent sources overwrite property assignments of previous sources.
22303 * If `customizer` is provided it is invoked to produce the assigned values.
22304 * The `customizer` is bound to `thisArg` and invoked with five arguments:
22305 * (objectValue, sourceValue, key, object, source).
22306 *
22307 * **Note:** This method mutates `object` and is based on
22308 * [`Object.assign`](http://ecma-international.org/ecma-262/6.0/#sec-object.assign).
22309 *
22310 * @static
22311 * @memberOf _
22312 * @alias extend
22313 * @category Object
22314 * @param {Object} object The destination object.
22315 * @param {...Object} [sources] The source objects.
22316 * @param {Function} [customizer] The function to customize assigned values.
22317 * @param {*} [thisArg] The `this` binding of `customizer`.
22318 * @returns {Object} Returns `object`.
22319 * @example
22320 *
22321 * _.assign({ 'user': 'barney' }, { 'age': 40 }, { 'user': 'fred' });
22322 * // => { 'user': 'fred', 'age': 40 }
22323 *
22324 * // using a customizer callback
22325 * var defaults = _.partialRight(_.assign, function(value, other) {
22326 * return _.isUndefined(value) ? other : value;
22327 * });
22328 *
22329 * defaults({ 'user': 'barney' }, { 'age': 36 }, { 'user': 'fred' });
22330 * // => { 'user': 'barney', 'age': 36 }
22331 */
22332 var assign = createAssigner(function(object, source, customizer) {
22333 return customizer
22334 ? assignWith(object, source, customizer)
22335 : baseAssign(object, source);
22336 });
22337
22338 /**
22339 * Creates an object that inherits from the given `prototype` object. If a
22340 * `properties` object is provided its own enumerable properties are assigned
22341 * to the created object.
22342 *
22343 * @static
22344 * @memberOf _
22345 * @category Object
22346 * @param {Object} prototype The object to inherit from.
22347 * @param {Object} [properties] The properties to assign to the object.
22348 * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
22349 * @returns {Object} Returns the new object.
22350 * @example
22351 *
22352 * function Shape() {
22353 * this.x = 0;
22354 * this.y = 0;
22355 * }
22356 *
22357 * function Circle() {
22358 * Shape.call(this);
22359 * }
22360 *
22361 * Circle.prototype = _.create(Shape.prototype, {
22362 * 'constructor': Circle
22363 * });
22364 *
22365 * var circle = new Circle;
22366 * circle instanceof Circle;
22367 * // => true
22368 *
22369 * circle instanceof Shape;
22370 * // => true
22371 */
22372 function create(prototype, properties, guard) {
22373 var result = baseCreate(prototype);
22374 if (guard && isIterateeCall(prototype, properties, guard)) {
22375 properties = undefined;
22376 }
22377 return properties ? baseAssign(result, properties) : result;
22378 }
22379
22380 /**
22381 * Assigns own enumerable properties of source object(s) to the destination
22382 * object for all destination properties that resolve to `undefined`. Once a
22383 * property is set, additional values of the same property are ignored.
22384 *
22385 * **Note:** This method mutates `object`.
22386 *
22387 * @static
22388 * @memberOf _
22389 * @category Object
22390 * @param {Object} object The destination object.
22391 * @param {...Object} [sources] The source objects.
22392 * @returns {Object} Returns `object`.
22393 * @example
22394 *
22395 * _.defaults({ 'user': 'barney' }, { 'age': 36 }, { 'user': 'fred' });
22396 * // => { 'user': 'barney', 'age': 36 }
22397 */
22398 var defaults = createDefaults(assign, assignDefaults);
22399
22400 /**
22401 * This method is like `_.defaults` except that it recursively assigns
22402 * default properties.
22403 *
22404 * **Note:** This method mutates `object`.
22405 *
22406 * @static
22407 * @memberOf _
22408 * @category Object
22409 * @param {Object} object The destination object.
22410 * @param {...Object} [sources] The source objects.
22411 * @returns {Object} Returns `object`.
22412 * @example
22413 *
22414 * _.defaultsDeep({ 'user': { 'name': 'barney' } }, { 'user': { 'name': 'fred', 'age': 36 } });
22415 * // => { 'user': { 'name': 'barney', 'age': 36 } }
22416 *
22417 */
22418 var defaultsDeep = createDefaults(merge, mergeDefaults);
22419
22420 /**
22421 * This method is like `_.find` except that it returns the key of the first
22422 * element `predicate` returns truthy for instead of the element itself.
22423 *
22424 * If a property name is provided for `predicate` the created `_.property`
22425 * style callback returns the property value of the given element.
22426 *
22427 * If a value is also provided for `thisArg` the created `_.matchesProperty`
22428 * style callback returns `true` for elements that have a matching property
22429 * value, else `false`.
22430 *
22431 * If an object is provided for `predicate` the created `_.matches` style
22432 * callback returns `true` for elements that have the properties of the given
22433 * object, else `false`.
22434 *
22435 * @static
22436 * @memberOf _
22437 * @category Object
22438 * @param {Object} object The object to search.
22439 * @param {Function|Object|string} [predicate=_.identity] The function invoked
22440 * per iteration.
22441 * @param {*} [thisArg] The `this` binding of `predicate`.
22442 * @returns {string|undefined} Returns the key of the matched element, else `undefined`.
22443 * @example
22444 *
22445 * var users = {
22446 * 'barney': { 'age': 36, 'active': true },
22447 * 'fred': { 'age': 40, 'active': false },
22448 * 'pebbles': { 'age': 1, 'active': true }
22449 * };
22450 *
22451 * _.findKey(users, function(chr) {
22452 * return chr.age < 40;
22453 * });
22454 * // => 'barney' (iteration order is not guaranteed)
22455 *
22456 * // using the `_.matches` callback shorthand
22457 * _.findKey(users, { 'age': 1, 'active': true });
22458 * // => 'pebbles'
22459 *
22460 * // using the `_.matchesProperty` callback shorthand
22461 * _.findKey(users, 'active', false);
22462 * // => 'fred'
22463 *
22464 * // using the `_.property` callback shorthand
22465 * _.findKey(users, 'active');
22466 * // => 'barney'
22467 */
22468 var findKey = createFindKey(baseForOwn);
22469
22470 /**
22471 * This method is like `_.findKey` except that it iterates over elements of
22472 * a collection in the opposite order.
22473 *
22474 * If a property name is provided for `predicate` the created `_.property`
22475 * style callback returns the property value of the given element.
22476 *
22477 * If a value is also provided for `thisArg` the created `_.matchesProperty`
22478 * style callback returns `true` for elements that have a matching property
22479 * value, else `false`.
22480 *
22481 * If an object is provided for `predicate` the created `_.matches` style
22482 * callback returns `true` for elements that have the properties of the given
22483 * object, else `false`.
22484 *
22485 * @static
22486 * @memberOf _
22487 * @category Object
22488 * @param {Object} object The object to search.
22489 * @param {Function|Object|string} [predicate=_.identity] The function invoked
22490 * per iteration.
22491 * @param {*} [thisArg] The `this` binding of `predicate`.
22492 * @returns {string|undefined} Returns the key of the matched element, else `undefined`.
22493 * @example
22494 *
22495 * var users = {
22496 * 'barney': { 'age': 36, 'active': true },
22497 * 'fred': { 'age': 40, 'active': false },
22498 * 'pebbles': { 'age': 1, 'active': true }
22499 * };
22500 *
22501 * _.findLastKey(users, function(chr) {
22502 * return chr.age < 40;
22503 * });
22504 * // => returns `pebbles` assuming `_.findKey` returns `barney`
22505 *
22506 * // using the `_.matches` callback shorthand
22507 * _.findLastKey(users, { 'age': 36, 'active': true });
22508 * // => 'barney'
22509 *
22510 * // using the `_.matchesProperty` callback shorthand
22511 * _.findLastKey(users, 'active', false);
22512 * // => 'fred'
22513 *
22514 * // using the `_.property` callback shorthand
22515 * _.findLastKey(users, 'active');
22516 * // => 'pebbles'
22517 */
22518 var findLastKey = createFindKey(baseForOwnRight);
22519
22520 /**
22521 * Iterates over own and inherited enumerable properties of an object invoking
22522 * `iteratee` for each property. The `iteratee` is bound to `thisArg` and invoked
22523 * with three arguments: (value, key, object). Iteratee functions may exit
22524 * iteration early by explicitly returning `false`.
22525 *
22526 * @static
22527 * @memberOf _
22528 * @category Object
22529 * @param {Object} object The object to iterate over.
22530 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
22531 * @param {*} [thisArg] The `this` binding of `iteratee`.
22532 * @returns {Object} Returns `object`.
22533 * @example
22534 *
22535 * function Foo() {
22536 * this.a = 1;
22537 * this.b = 2;
22538 * }
22539 *
22540 * Foo.prototype.c = 3;
22541 *
22542 * _.forIn(new Foo, function(value, key) {
22543 * console.log(key);
22544 * });
22545 * // => logs 'a', 'b', and 'c' (iteration order is not guaranteed)
22546 */
22547 var forIn = createForIn(baseFor);
22548
22549 /**
22550 * This method is like `_.forIn` except that it iterates over properties of
22551 * `object` in the opposite order.
22552 *
22553 * @static
22554 * @memberOf _
22555 * @category Object
22556 * @param {Object} object The object to iterate over.
22557 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
22558 * @param {*} [thisArg] The `this` binding of `iteratee`.
22559 * @returns {Object} Returns `object`.
22560 * @example
22561 *
22562 * function Foo() {
22563 * this.a = 1;
22564 * this.b = 2;
22565 * }
22566 *
22567 * Foo.prototype.c = 3;
22568 *
22569 * _.forInRight(new Foo, function(value, key) {
22570 * console.log(key);
22571 * });
22572 * // => logs 'c', 'b', and 'a' assuming `_.forIn ` logs 'a', 'b', and 'c'
22573 */
22574 var forInRight = createForIn(baseForRight);
22575
22576 /**
22577 * Iterates over own enumerable properties of an object invoking `iteratee`
22578 * for each property. The `iteratee` is bound to `thisArg` and invoked with
22579 * three arguments: (value, key, object). Iteratee functions may exit iteration
22580 * early by explicitly returning `false`.
22581 *
22582 * @static
22583 * @memberOf _
22584 * @category Object
22585 * @param {Object} object The object to iterate over.
22586 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
22587 * @param {*} [thisArg] The `this` binding of `iteratee`.
22588 * @returns {Object} Returns `object`.
22589 * @example
22590 *
22591 * function Foo() {
22592 * this.a = 1;
22593 * this.b = 2;
22594 * }
22595 *
22596 * Foo.prototype.c = 3;
22597 *
22598 * _.forOwn(new Foo, function(value, key) {
22599 * console.log(key);
22600 * });
22601 * // => logs 'a' and 'b' (iteration order is not guaranteed)
22602 */
22603 var forOwn = createForOwn(baseForOwn);
22604
22605 /**
22606 * This method is like `_.forOwn` except that it iterates over properties of
22607 * `object` in the opposite order.
22608 *
22609 * @static
22610 * @memberOf _
22611 * @category Object
22612 * @param {Object} object The object to iterate over.
22613 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
22614 * @param {*} [thisArg] The `this` binding of `iteratee`.
22615 * @returns {Object} Returns `object`.
22616 * @example
22617 *
22618 * function Foo() {
22619 * this.a = 1;
22620 * this.b = 2;
22621 * }
22622 *
22623 * Foo.prototype.c = 3;
22624 *
22625 * _.forOwnRight(new Foo, function(value, key) {
22626 * console.log(key);
22627 * });
22628 * // => logs 'b' and 'a' assuming `_.forOwn` logs 'a' and 'b'
22629 */
22630 var forOwnRight = createForOwn(baseForOwnRight);
22631
22632 /**
22633 * Creates an array of function property names from all enumerable properties,
22634 * own and inherited, of `object`.
22635 *
22636 * @static
22637 * @memberOf _
22638 * @alias methods
22639 * @category Object
22640 * @param {Object} object The object to inspect.
22641 * @returns {Array} Returns the new array of property names.
22642 * @example
22643 *
22644 * _.functions(_);
22645 * // => ['after', 'ary', 'assign', ...]
22646 */
22647 function functions(object) {
22648 return baseFunctions(object, keysIn(object));
22649 }
22650
22651 /**
22652 * Gets the property value at `path` of `object`. If the resolved value is
22653 * `undefined` the `defaultValue` is used in its place.
22654 *
22655 * @static
22656 * @memberOf _
22657 * @category Object
22658 * @param {Object} object The object to query.
22659 * @param {Array|string} path The path of the property to get.
22660 * @param {*} [defaultValue] The value returned if the resolved value is `undefined`.
22661 * @returns {*} Returns the resolved value.
22662 * @example
22663 *
22664 * var object = { 'a': [{ 'b': { 'c': 3 } }] };
22665 *
22666 * _.get(object, 'a[0].b.c');
22667 * // => 3
22668 *
22669 * _.get(object, ['a', '0', 'b', 'c']);
22670 * // => 3
22671 *
22672 * _.get(object, 'a.b.c', 'default');
22673 * // => 'default'
22674 */
22675 function get(object, path, defaultValue) {
22676 var result = object == null ? undefined : baseGet(object, toPath(path), path + '');
22677 return result === undefined ? defaultValue : result;
22678 }
22679
22680 /**
22681 * Checks if `path` is a direct property.
22682 *
22683 * @static
22684 * @memberOf _
22685 * @category Object
22686 * @param {Object} object The object to query.
22687 * @param {Array|string} path The path to check.
22688 * @returns {boolean} Returns `true` if `path` is a direct property, else `false`.
22689 * @example
22690 *
22691 * var object = { 'a': { 'b': { 'c': 3 } } };
22692 *
22693 * _.has(object, 'a');
22694 * // => true
22695 *
22696 * _.has(object, 'a.b.c');
22697 * // => true
22698 *
22699 * _.has(object, ['a', 'b', 'c']);
22700 * // => true
22701 */
22702 function has(object, path) {
22703 if (object == null) {
22704 return false;
22705 }
22706 var result = hasOwnProperty.call(object, path);
22707 if (!result && !isKey(path)) {
22708 path = toPath(path);
22709 object = path.length == 1 ? object : baseGet(object, baseSlice(path, 0, -1));
22710 if (object == null) {
22711 return false;
22712 }
22713 path = last(path);
22714 result = hasOwnProperty.call(object, path);
22715 }
22716 return result || (isLength(object.length) && isIndex(path, object.length) &&
22717 (isArray(object) || isArguments(object)));
22718 }
22719
22720 /**
22721 * Creates an object composed of the inverted keys and values of `object`.
22722 * If `object` contains duplicate values, subsequent values overwrite property
22723 * assignments of previous values unless `multiValue` is `true`.
22724 *
22725 * @static
22726 * @memberOf _
22727 * @category Object
22728 * @param {Object} object The object to invert.
22729 * @param {boolean} [multiValue] Allow multiple values per key.
22730 * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
22731 * @returns {Object} Returns the new inverted object.
22732 * @example
22733 *
22734 * var object = { 'a': 1, 'b': 2, 'c': 1 };
22735 *
22736 * _.invert(object);
22737 * // => { '1': 'c', '2': 'b' }
22738 *
22739 * // with `multiValue`
22740 * _.invert(object, true);
22741 * // => { '1': ['a', 'c'], '2': ['b'] }
22742 */
22743 function invert(object, multiValue, guard) {
22744 if (guard && isIterateeCall(object, multiValue, guard)) {
22745 multiValue = undefined;
22746 }
22747 var index = -1,
22748 props = keys(object),
22749 length = props.length,
22750 result = {};
22751
22752 while (++index < length) {
22753 var key = props[index],
22754 value = object[key];
22755
22756 if (multiValue) {
22757 if (hasOwnProperty.call(result, value)) {
22758 result[value].push(key);
22759 } else {
22760 result[value] = [key];
22761 }
22762 }
22763 else {
22764 result[value] = key;
22765 }
22766 }
22767 return result;
22768 }
22769
22770 /**
22771 * Creates an array of the own enumerable property names of `object`.
22772 *
22773 * **Note:** Non-object values are coerced to objects. See the
22774 * [ES spec](http://ecma-international.org/ecma-262/6.0/#sec-object.keys)
22775 * for more details.
22776 *
22777 * @static
22778 * @memberOf _
22779 * @category Object
22780 * @param {Object} object The object to query.
22781 * @returns {Array} Returns the array of property names.
22782 * @example
22783 *
22784 * function Foo() {
22785 * this.a = 1;
22786 * this.b = 2;
22787 * }
22788 *
22789 * Foo.prototype.c = 3;
22790 *
22791 * _.keys(new Foo);
22792 * // => ['a', 'b'] (iteration order is not guaranteed)
22793 *
22794 * _.keys('hi');
22795 * // => ['0', '1']
22796 */
22797 var keys = !nativeKeys ? shimKeys : function(object) {
22798 var Ctor = object == null ? undefined : object.constructor;
22799 if ((typeof Ctor == 'function' && Ctor.prototype === object) ||
22800 (typeof object != 'function' && isArrayLike(object))) {
22801 return shimKeys(object);
22802 }
22803 return isObject(object) ? nativeKeys(object) : [];
22804 };
22805
22806 /**
22807 * Creates an array of the own and inherited enumerable property names of `object`.
22808 *
22809 * **Note:** Non-object values are coerced to objects.
22810 *
22811 * @static
22812 * @memberOf _
22813 * @category Object
22814 * @param {Object} object The object to query.
22815 * @returns {Array} Returns the array of property names.
22816 * @example
22817 *
22818 * function Foo() {
22819 * this.a = 1;
22820 * this.b = 2;
22821 * }
22822 *
22823 * Foo.prototype.c = 3;
22824 *
22825 * _.keysIn(new Foo);
22826 * // => ['a', 'b', 'c'] (iteration order is not guaranteed)
22827 */
22828 function keysIn(object) {
22829 if (object == null) {
22830 return [];
22831 }
22832 if (!isObject(object)) {
22833 object = Object(object);
22834 }
22835 var length = object.length;
22836 length = (length && isLength(length) &&
22837 (isArray(object) || isArguments(object)) && length) || 0;
22838
22839 var Ctor = object.constructor,
22840 index = -1,
22841 isProto = typeof Ctor == 'function' && Ctor.prototype === object,
22842 result = Array(length),
22843 skipIndexes = length > 0;
22844
22845 while (++index < length) {
22846 result[index] = (index + '');
22847 }
22848 for (var key in object) {
22849 if (!(skipIndexes && isIndex(key, length)) &&
22850 !(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) {
22851 result.push(key);
22852 }
22853 }
22854 return result;
22855 }
22856
22857 /**
22858 * The opposite of `_.mapValues`; this method creates an object with the
22859 * same values as `object` and keys generated by running each own enumerable
22860 * property of `object` through `iteratee`.
22861 *
22862 * @static
22863 * @memberOf _
22864 * @category Object
22865 * @param {Object} object The object to iterate over.
22866 * @param {Function|Object|string} [iteratee=_.identity] The function invoked
22867 * per iteration.
22868 * @param {*} [thisArg] The `this` binding of `iteratee`.
22869 * @returns {Object} Returns the new mapped object.
22870 * @example
22871 *
22872 * _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) {
22873 * return key + value;
22874 * });
22875 * // => { 'a1': 1, 'b2': 2 }
22876 */
22877 var mapKeys = createObjectMapper(true);
22878
22879 /**
22880 * Creates an object with the same keys as `object` and values generated by
22881 * running each own enumerable property of `object` through `iteratee`. The
22882 * iteratee function is bound to `thisArg` and invoked with three arguments:
22883 * (value, key, object).
22884 *
22885 * If a property name is provided for `iteratee` the created `_.property`
22886 * style callback returns the property value of the given element.
22887 *
22888 * If a value is also provided for `thisArg` the created `_.matchesProperty`
22889 * style callback returns `true` for elements that have a matching property
22890 * value, else `false`.
22891 *
22892 * If an object is provided for `iteratee` the created `_.matches` style
22893 * callback returns `true` for elements that have the properties of the given
22894 * object, else `false`.
22895 *
22896 * @static
22897 * @memberOf _
22898 * @category Object
22899 * @param {Object} object The object to iterate over.
22900 * @param {Function|Object|string} [iteratee=_.identity] The function invoked
22901 * per iteration.
22902 * @param {*} [thisArg] The `this` binding of `iteratee`.
22903 * @returns {Object} Returns the new mapped object.
22904 * @example
22905 *
22906 * _.mapValues({ 'a': 1, 'b': 2 }, function(n) {
22907 * return n * 3;
22908 * });
22909 * // => { 'a': 3, 'b': 6 }
22910 *
22911 * var users = {
22912 * 'fred': { 'user': 'fred', 'age': 40 },
22913 * 'pebbles': { 'user': 'pebbles', 'age': 1 }
22914 * };
22915 *
22916 * // using the `_.property` callback shorthand
22917 * _.mapValues(users, 'age');
22918 * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)
22919 */
22920 var mapValues = createObjectMapper();
22921
22922 /**
22923 * The opposite of `_.pick`; this method creates an object composed of the
22924 * own and inherited enumerable properties of `object` that are not omitted.
22925 *
22926 * @static
22927 * @memberOf _
22928 * @category Object
22929 * @param {Object} object The source object.
22930 * @param {Function|...(string|string[])} [predicate] The function invoked per
22931 * iteration or property names to omit, specified as individual property
22932 * names or arrays of property names.
22933 * @param {*} [thisArg] The `this` binding of `predicate`.
22934 * @returns {Object} Returns the new object.
22935 * @example
22936 *
22937 * var object = { 'user': 'fred', 'age': 40 };
22938 *
22939 * _.omit(object, 'age');
22940 * // => { 'user': 'fred' }
22941 *
22942 * _.omit(object, _.isNumber);
22943 * // => { 'user': 'fred' }
22944 */
22945 var omit = restParam(function(object, props) {
22946 if (object == null) {
22947 return {};
22948 }
22949 if (typeof props[0] != 'function') {
22950 var props = arrayMap(baseFlatten(props), String);
22951 return pickByArray(object, baseDifference(keysIn(object), props));
22952 }
22953 var predicate = bindCallback(props[0], props[1], 3);
22954 return pickByCallback(object, function(value, key, object) {
22955 return !predicate(value, key, object);
22956 });
22957 });
22958
22959 /**
22960 * Creates a two dimensional array of the key-value pairs for `object`,
22961 * e.g. `[[key1, value1], [key2, value2]]`.
22962 *
22963 * @static
22964 * @memberOf _
22965 * @category Object
22966 * @param {Object} object The object to query.
22967 * @returns {Array} Returns the new array of key-value pairs.
22968 * @example
22969 *
22970 * _.pairs({ 'barney': 36, 'fred': 40 });
22971 * // => [['barney', 36], ['fred', 40]] (iteration order is not guaranteed)
22972 */
22973 function pairs(object) {
22974 object = toObject(object);
22975
22976 var index = -1,
22977 props = keys(object),
22978 length = props.length,
22979 result = Array(length);
22980
22981 while (++index < length) {
22982 var key = props[index];
22983 result[index] = [key, object[key]];
22984 }
22985 return result;
22986 }
22987
22988 /**
22989 * Creates an object composed of the picked `object` properties. Property
22990 * names may be specified as individual arguments or as arrays of property
22991 * names. If `predicate` is provided it is invoked for each property of `object`
22992 * picking the properties `predicate` returns truthy for. The predicate is
22993 * bound to `thisArg` and invoked with three arguments: (value, key, object).
22994 *
22995 * @static
22996 * @memberOf _
22997 * @category Object
22998 * @param {Object} object The source object.
22999 * @param {Function|...(string|string[])} [predicate] The function invoked per
23000 * iteration or property names to pick, specified as individual property
23001 * names or arrays of property names.
23002 * @param {*} [thisArg] The `this` binding of `predicate`.
23003 * @returns {Object} Returns the new object.
23004 * @example
23005 *
23006 * var object = { 'user': 'fred', 'age': 40 };
23007 *
23008 * _.pick(object, 'user');
23009 * // => { 'user': 'fred' }
23010 *
23011 * _.pick(object, _.isString);
23012 * // => { 'user': 'fred' }
23013 */
23014 var pick = restParam(function(object, props) {
23015 if (object == null) {
23016 return {};
23017 }
23018 return typeof props[0] == 'function'
23019 ? pickByCallback(object, bindCallback(props[0], props[1], 3))
23020 : pickByArray(object, baseFlatten(props));
23021 });
23022
23023 /**
23024 * This method is like `_.get` except that if the resolved value is a function
23025 * it is invoked with the `this` binding of its parent object and its result
23026 * is returned.
23027 *
23028 * @static
23029 * @memberOf _
23030 * @category Object
23031 * @param {Object} object The object to query.
23032 * @param {Array|string} path The path of the property to resolve.
23033 * @param {*} [defaultValue] The value returned if the resolved value is `undefined`.
23034 * @returns {*} Returns the resolved value.
23035 * @example
23036 *
23037 * var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] };
23038 *
23039 * _.result(object, 'a[0].b.c1');
23040 * // => 3
23041 *
23042 * _.result(object, 'a[0].b.c2');
23043 * // => 4
23044 *
23045 * _.result(object, 'a.b.c', 'default');
23046 * // => 'default'
23047 *
23048 * _.result(object, 'a.b.c', _.constant('default'));
23049 * // => 'default'
23050 */
23051 function result(object, path, defaultValue) {
23052 var result = object == null ? undefined : object[path];
23053 if (result === undefined) {
23054 if (object != null && !isKey(path, object)) {
23055 path = toPath(path);
23056 object = path.length == 1 ? object : baseGet(object, baseSlice(path, 0, -1));
23057 result = object == null ? undefined : object[last(path)];
23058 }
23059 result = result === undefined ? defaultValue : result;
23060 }
23061 return isFunction(result) ? result.call(object) : result;
23062 }
23063
23064 /**
23065 * Sets the property value of `path` on `object`. If a portion of `path`
23066 * does not exist it is created.
23067 *
23068 * @static
23069 * @memberOf _
23070 * @category Object
23071 * @param {Object} object The object to augment.
23072 * @param {Array|string} path The path of the property to set.
23073 * @param {*} value The value to set.
23074 * @returns {Object} Returns `object`.
23075 * @example
23076 *
23077 * var object = { 'a': [{ 'b': { 'c': 3 } }] };
23078 *
23079 * _.set(object, 'a[0].b.c', 4);
23080 * console.log(object.a[0].b.c);
23081 * // => 4
23082 *
23083 * _.set(object, 'x[0].y.z', 5);
23084 * console.log(object.x[0].y.z);
23085 * // => 5
23086 */
23087 function set(object, path, value) {
23088 if (object == null) {
23089 return object;
23090 }
23091 var pathKey = (path + '');
23092 path = (object[pathKey] != null || isKey(path, object)) ? [pathKey] : toPath(path);
23093
23094 var index = -1,
23095 length = path.length,
23096 lastIndex = length - 1,
23097 nested = object;
23098
23099 while (nested != null && ++index < length) {
23100 var key = path[index];
23101 if (isObject(nested)) {
23102 if (index == lastIndex) {
23103 nested[key] = value;
23104 } else if (nested[key] == null) {
23105 nested[key] = isIndex(path[index + 1]) ? [] : {};
23106 }
23107 }
23108 nested = nested[key];
23109 }
23110 return object;
23111 }
23112
23113 /**
23114 * An alternative to `_.reduce`; this method transforms `object` to a new
23115 * `accumulator` object which is the result of running each of its own enumerable
23116 * properties through `iteratee`, with each invocation potentially mutating
23117 * the `accumulator` object. The `iteratee` is bound to `thisArg` and invoked
23118 * with four arguments: (accumulator, value, key, object). Iteratee functions
23119 * may exit iteration early by explicitly returning `false`.
23120 *
23121 * @static
23122 * @memberOf _
23123 * @category Object
23124 * @param {Array|Object} object The object to iterate over.
23125 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
23126 * @param {*} [accumulator] The custom accumulator value.
23127 * @param {*} [thisArg] The `this` binding of `iteratee`.
23128 * @returns {*} Returns the accumulated value.
23129 * @example
23130 *
23131 * _.transform([2, 3, 4], function(result, n) {
23132 * result.push(n *= n);
23133 * return n % 2 == 0;
23134 * });
23135 * // => [4, 9]
23136 *
23137 * _.transform({ 'a': 1, 'b': 2 }, function(result, n, key) {
23138 * result[key] = n * 3;
23139 * });
23140 * // => { 'a': 3, 'b': 6 }
23141 */
23142 function transform(object, iteratee, accumulator, thisArg) {
23143 var isArr = isArray(object) || isTypedArray(object);
23144 iteratee = getCallback(iteratee, thisArg, 4);
23145
23146 if (accumulator == null) {
23147 if (isArr || isObject(object)) {
23148 var Ctor = object.constructor;
23149 if (isArr) {
23150 accumulator = isArray(object) ? new Ctor : [];
23151 } else {
23152 accumulator = baseCreate(isFunction(Ctor) ? Ctor.prototype : undefined);
23153 }
23154 } else {
23155 accumulator = {};
23156 }
23157 }
23158 (isArr ? arrayEach : baseForOwn)(object, function(value, index, object) {
23159 return iteratee(accumulator, value, index, object);
23160 });
23161 return accumulator;
23162 }
23163
23164 /**
23165 * Creates an array of the own enumerable property values of `object`.
23166 *
23167 * **Note:** Non-object values are coerced to objects.
23168 *
23169 * @static
23170 * @memberOf _
23171 * @category Object
23172 * @param {Object} object The object to query.
23173 * @returns {Array} Returns the array of property values.
23174 * @example
23175 *
23176 * function Foo() {
23177 * this.a = 1;
23178 * this.b = 2;
23179 * }
23180 *
23181 * Foo.prototype.c = 3;
23182 *
23183 * _.values(new Foo);
23184 * // => [1, 2] (iteration order is not guaranteed)
23185 *
23186 * _.values('hi');
23187 * // => ['h', 'i']
23188 */
23189 function values(object) {
23190 return baseValues(object, keys(object));
23191 }
23192
23193 /**
23194 * Creates an array of the own and inherited enumerable property values
23195 * of `object`.
23196 *
23197 * **Note:** Non-object values are coerced to objects.
23198 *
23199 * @static
23200 * @memberOf _
23201 * @category Object
23202 * @param {Object} object The object to query.
23203 * @returns {Array} Returns the array of property values.
23204 * @example
23205 *
23206 * function Foo() {
23207 * this.a = 1;
23208 * this.b = 2;
23209 * }
23210 *
23211 * Foo.prototype.c = 3;
23212 *
23213 * _.valuesIn(new Foo);
23214 * // => [1, 2, 3] (iteration order is not guaranteed)
23215 */
23216 function valuesIn(object) {
23217 return baseValues(object, keysIn(object));
23218 }
23219
23220 /*------------------------------------------------------------------------*/
23221
23222 /**
23223 * Checks if `n` is between `start` and up to but not including, `end`. If
23224 * `end` is not specified it is set to `start` with `start` then set to `0`.
23225 *
23226 * @static
23227 * @memberOf _
23228 * @category Number
23229 * @param {number} n The number to check.
23230 * @param {number} [start=0] The start of the range.
23231 * @param {number} end The end of the range.
23232 * @returns {boolean} Returns `true` if `n` is in the range, else `false`.
23233 * @example
23234 *
23235 * _.inRange(3, 2, 4);
23236 * // => true
23237 *
23238 * _.inRange(4, 8);
23239 * // => true
23240 *
23241 * _.inRange(4, 2);
23242 * // => false
23243 *
23244 * _.inRange(2, 2);
23245 * // => false
23246 *
23247 * _.inRange(1.2, 2);
23248 * // => true
23249 *
23250 * _.inRange(5.2, 4);
23251 * // => false
23252 */
23253 function inRange(value, start, end) {
23254 start = +start || 0;
23255 if (end === undefined) {
23256 end = start;
23257 start = 0;
23258 } else {
23259 end = +end || 0;
23260 }
23261 return value >= nativeMin(start, end) && value < nativeMax(start, end);
23262 }
23263
23264 /**
23265 * Produces a random number between `min` and `max` (inclusive). If only one
23266 * argument is provided a number between `0` and the given number is returned.
23267 * If `floating` is `true`, or either `min` or `max` are floats, a floating-point
23268 * number is returned instead of an integer.
23269 *
23270 * @static
23271 * @memberOf _
23272 * @category Number
23273 * @param {number} [min=0] The minimum possible value.
23274 * @param {number} [max=1] The maximum possible value.
23275 * @param {boolean} [floating] Specify returning a floating-point number.
23276 * @returns {number} Returns the random number.
23277 * @example
23278 *
23279 * _.random(0, 5);
23280 * // => an integer between 0 and 5
23281 *
23282 * _.random(5);
23283 * // => also an integer between 0 and 5
23284 *
23285 * _.random(5, true);
23286 * // => a floating-point number between 0 and 5
23287 *
23288 * _.random(1.2, 5.2);
23289 * // => a floating-point number between 1.2 and 5.2
23290 */
23291 function random(min, max, floating) {
23292 if (floating && isIterateeCall(min, max, floating)) {
23293 max = floating = undefined;
23294 }
23295 var noMin = min == null,
23296 noMax = max == null;
23297
23298 if (floating == null) {
23299 if (noMax && typeof min == 'boolean') {
23300 floating = min;
23301 min = 1;
23302 }
23303 else if (typeof max == 'boolean') {
23304 floating = max;
23305 noMax = true;
23306 }
23307 }
23308 if (noMin && noMax) {
23309 max = 1;
23310 noMax = false;
23311 }
23312 min = +min || 0;
23313 if (noMax) {
23314 max = min;
23315 min = 0;
23316 } else {
23317 max = +max || 0;
23318 }
23319 if (floating || min % 1 || max % 1) {
23320 var rand = nativeRandom();
23321 return nativeMin(min + (rand * (max - min + parseFloat('1e-' + ((rand + '').length - 1)))), max);
23322 }
23323 return baseRandom(min, max);
23324 }
23325
23326 /*------------------------------------------------------------------------*/
23327
23328 /**
23329 * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase).
23330 *
23331 * @static
23332 * @memberOf _
23333 * @category String
23334 * @param {string} [string=''] The string to convert.
23335 * @returns {string} Returns the camel cased string.
23336 * @example
23337 *
23338 * _.camelCase('Foo Bar');
23339 * // => 'fooBar'
23340 *
23341 * _.camelCase('--foo-bar');
23342 * // => 'fooBar'
23343 *
23344 * _.camelCase('__foo_bar__');
23345 * // => 'fooBar'
23346 */
23347 var camelCase = createCompounder(function(result, word, index) {
23348 word = word.toLowerCase();
23349 return result + (index ? (word.charAt(0).toUpperCase() + word.slice(1)) : word);
23350 });
23351
23352 /**
23353 * Capitalizes the first character of `string`.
23354 *
23355 * @static
23356 * @memberOf _
23357 * @category String
23358 * @param {string} [string=''] The string to capitalize.
23359 * @returns {string} Returns the capitalized string.
23360 * @example
23361 *
23362 * _.capitalize('fred');
23363 * // => 'Fred'
23364 */
23365 function capitalize(string) {
23366 string = baseToString(string);
23367 return string && (string.charAt(0).toUpperCase() + string.slice(1));
23368 }
23369
23370 /**
23371 * Deburrs `string` by converting [latin-1 supplementary letters](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table)
23372 * to basic latin letters and removing [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks).
23373 *
23374 * @static
23375 * @memberOf _
23376 * @category String
23377 * @param {string} [string=''] The string to deburr.
23378 * @returns {string} Returns the deburred string.
23379 * @example
23380 *
23381 * _.deburr('déjà vu');
23382 * // => 'deja vu'
23383 */
23384 function deburr(string) {
23385 string = baseToString(string);
23386 return string && string.replace(reLatin1, deburrLetter).replace(reComboMark, '');
23387 }
23388
23389 /**
23390 * Checks if `string` ends with the given target string.
23391 *
23392 * @static
23393 * @memberOf _
23394 * @category String
23395 * @param {string} [string=''] The string to search.
23396 * @param {string} [target] The string to search for.
23397 * @param {number} [position=string.length] The position to search from.
23398 * @returns {boolean} Returns `true` if `string` ends with `target`, else `false`.
23399 * @example
23400 *
23401 * _.endsWith('abc', 'c');
23402 * // => true
23403 *
23404 * _.endsWith('abc', 'b');
23405 * // => false
23406 *
23407 * _.endsWith('abc', 'b', 2);
23408 * // => true
23409 */
23410 function endsWith(string, target, position) {
23411 string = baseToString(string);
23412 target = (target + '');
23413
23414 var length = string.length;
23415 position = position === undefined
23416 ? length
23417 : nativeMin(position < 0 ? 0 : (+position || 0), length);
23418
23419 position -= target.length;
23420 return position >= 0 && string.indexOf(target, position) == position;
23421 }
23422
23423 /**
23424 * Converts the characters "&", "<", ">", '"', "'", and "\`", in `string` to
23425 * their corresponding HTML entities.
23426 *
23427 * **Note:** No other characters are escaped. To escape additional characters
23428 * use a third-party library like [_he_](https://mths.be/he).
23429 *
23430 * Though the ">" character is escaped for symmetry, characters like
23431 * ">" and "/" don't need escaping in HTML and have no special meaning
23432 * unless they're part of a tag or unquoted attribute value.
23433 * See [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands)
23434 * (under "semi-related fun fact") for more details.
23435 *
23436 * Backticks are escaped because in Internet Explorer < 9, they can break out
23437 * of attribute values or HTML comments. See [#59](https://html5sec.org/#59),
23438 * [#102](https://html5sec.org/#102), [#108](https://html5sec.org/#108), and
23439 * [#133](https://html5sec.org/#133) of the [HTML5 Security Cheatsheet](https://html5sec.org/)
23440 * for more details.
23441 *
23442 * When working with HTML you should always [quote attribute values](http://wonko.com/post/html-escaping)
23443 * to reduce XSS vectors.
23444 *
23445 * @static
23446 * @memberOf _
23447 * @category String
23448 * @param {string} [string=''] The string to escape.
23449 * @returns {string} Returns the escaped string.
23450 * @example
23451 *
23452 * _.escape('fred, barney, & pebbles');
23453 * // => 'fred, barney, &amp; pebbles'
23454 */
23455 function escape(string) {
23456 // Reset `lastIndex` because in IE < 9 `String#replace` does not.
23457 string = baseToString(string);
23458 return (string && reHasUnescapedHtml.test(string))
23459 ? string.replace(reUnescapedHtml, escapeHtmlChar)
23460 : string;
23461 }
23462
23463 /**
23464 * Escapes the `RegExp` special characters "\", "/", "^", "$", ".", "|", "?",
23465 * "*", "+", "(", ")", "[", "]", "{" and "}" in `string`.
23466 *
23467 * @static
23468 * @memberOf _
23469 * @category String
23470 * @param {string} [string=''] The string to escape.
23471 * @returns {string} Returns the escaped string.
23472 * @example
23473 *
23474 * _.escapeRegExp('[lodash](https://lodash.com/)');
23475 * // => '\[lodash\]\(https:\/\/lodash\.com\/\)'
23476 */
23477 function escapeRegExp(string) {
23478 string = baseToString(string);
23479 return (string && reHasRegExpChars.test(string))
23480 ? string.replace(reRegExpChars, escapeRegExpChar)
23481 : (string || '(?:)');
23482 }
23483
23484 /**
23485 * Converts `string` to [kebab case](https://en.wikipedia.org/wiki/Letter_case#Special_case_styles).
23486 *
23487 * @static
23488 * @memberOf _
23489 * @category String
23490 * @param {string} [string=''] The string to convert.
23491 * @returns {string} Returns the kebab cased string.
23492 * @example
23493 *
23494 * _.kebabCase('Foo Bar');
23495 * // => 'foo-bar'
23496 *
23497 * _.kebabCase('fooBar');
23498 * // => 'foo-bar'
23499 *
23500 * _.kebabCase('__foo_bar__');
23501 * // => 'foo-bar'
23502 */
23503 var kebabCase = createCompounder(function(result, word, index) {
23504 return result + (index ? '-' : '') + word.toLowerCase();
23505 });
23506
23507 /**
23508 * Pads `string` on the left and right sides if it's shorter than `length`.
23509 * Padding characters are truncated if they can't be evenly divided by `length`.
23510 *
23511 * @static
23512 * @memberOf _
23513 * @category String
23514 * @param {string} [string=''] The string to pad.
23515 * @param {number} [length=0] The padding length.
23516 * @param {string} [chars=' '] The string used as padding.
23517 * @returns {string} Returns the padded string.
23518 * @example
23519 *
23520 * _.pad('abc', 8);
23521 * // => ' abc '
23522 *
23523 * _.pad('abc', 8, '_-');
23524 * // => '_-abc_-_'
23525 *
23526 * _.pad('abc', 3);
23527 * // => 'abc'
23528 */
23529 function pad(string, length, chars) {
23530 string = baseToString(string);
23531 length = +length;
23532
23533 var strLength = string.length;
23534 if (strLength >= length || !nativeIsFinite(length)) {
23535 return string;
23536 }
23537 var mid = (length - strLength) / 2,
23538 leftLength = nativeFloor(mid),
23539 rightLength = nativeCeil(mid);
23540
23541 chars = createPadding('', rightLength, chars);
23542 return chars.slice(0, leftLength) + string + chars;
23543 }
23544
23545 /**
23546 * Pads `string` on the left side if it's shorter than `length`. Padding
23547 * characters are truncated if they exceed `length`.
23548 *
23549 * @static
23550 * @memberOf _
23551 * @category String
23552 * @param {string} [string=''] The string to pad.
23553 * @param {number} [length=0] The padding length.
23554 * @param {string} [chars=' '] The string used as padding.
23555 * @returns {string} Returns the padded string.
23556 * @example
23557 *
23558 * _.padLeft('abc', 6);
23559 * // => ' abc'
23560 *
23561 * _.padLeft('abc', 6, '_-');
23562 * // => '_-_abc'
23563 *
23564 * _.padLeft('abc', 3);
23565 * // => 'abc'
23566 */
23567 var padLeft = createPadDir();
23568
23569 /**
23570 * Pads `string` on the right side if it's shorter than `length`. Padding
23571 * characters are truncated if they exceed `length`.
23572 *
23573 * @static
23574 * @memberOf _
23575 * @category String
23576 * @param {string} [string=''] The string to pad.
23577 * @param {number} [length=0] The padding length.
23578 * @param {string} [chars=' '] The string used as padding.
23579 * @returns {string} Returns the padded string.
23580 * @example
23581 *
23582 * _.padRight('abc', 6);
23583 * // => 'abc '
23584 *
23585 * _.padRight('abc', 6, '_-');
23586 * // => 'abc_-_'
23587 *
23588 * _.padRight('abc', 3);
23589 * // => 'abc'
23590 */
23591 var padRight = createPadDir(true);
23592
23593 /**
23594 * Converts `string` to an integer of the specified radix. If `radix` is
23595 * `undefined` or `0`, a `radix` of `10` is used unless `value` is a hexadecimal,
23596 * in which case a `radix` of `16` is used.
23597 *
23598 * **Note:** This method aligns with the [ES5 implementation](https://es5.github.io/#E)
23599 * of `parseInt`.
23600 *
23601 * @static
23602 * @memberOf _
23603 * @category String
23604 * @param {string} string The string to convert.
23605 * @param {number} [radix] The radix to interpret `value` by.
23606 * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
23607 * @returns {number} Returns the converted integer.
23608 * @example
23609 *
23610 * _.parseInt('08');
23611 * // => 8
23612 *
23613 * _.map(['6', '08', '10'], _.parseInt);
23614 * // => [6, 8, 10]
23615 */
23616 function parseInt(string, radix, guard) {
23617 // Firefox < 21 and Opera < 15 follow ES3 for `parseInt`.
23618 // Chrome fails to trim leading <BOM> whitespace characters.
23619 // See https://code.google.com/p/v8/issues/detail?id=3109 for more details.
23620 if (guard ? isIterateeCall(string, radix, guard) : radix == null) {
23621 radix = 0;
23622 } else if (radix) {
23623 radix = +radix;
23624 }
23625 string = trim(string);
23626 return nativeParseInt(string, radix || (reHasHexPrefix.test(string) ? 16 : 10));
23627 }
23628
23629 /**
23630 * Repeats the given string `n` times.
23631 *
23632 * @static
23633 * @memberOf _
23634 * @category String
23635 * @param {string} [string=''] The string to repeat.
23636 * @param {number} [n=0] The number of times to repeat the string.
23637 * @returns {string} Returns the repeated string.
23638 * @example
23639 *
23640 * _.repeat('*', 3);
23641 * // => '***'
23642 *
23643 * _.repeat('abc', 2);
23644 * // => 'abcabc'
23645 *
23646 * _.repeat('abc', 0);
23647 * // => ''
23648 */
23649 function repeat(string, n) {
23650 var result = '';
23651 string = baseToString(string);
23652 n = +n;
23653 if (n < 1 || !string || !nativeIsFinite(n)) {
23654 return result;
23655 }
23656 // Leverage the exponentiation by squaring algorithm for a faster repeat.
23657 // See https://en.wikipedia.org/wiki/Exponentiation_by_squaring for more details.
23658 do {
23659 if (n % 2) {
23660 result += string;
23661 }
23662 n = nativeFloor(n / 2);
23663 string += string;
23664 } while (n);
23665
23666 return result;
23667 }
23668
23669 /**
23670 * Converts `string` to [snake case](https://en.wikipedia.org/wiki/Snake_case).
23671 *
23672 * @static
23673 * @memberOf _
23674 * @category String
23675 * @param {string} [string=''] The string to convert.
23676 * @returns {string} Returns the snake cased string.
23677 * @example
23678 *
23679 * _.snakeCase('Foo Bar');
23680 * // => 'foo_bar'
23681 *
23682 * _.snakeCase('fooBar');
23683 * // => 'foo_bar'
23684 *
23685 * _.snakeCase('--foo-bar');
23686 * // => 'foo_bar'
23687 */
23688 var snakeCase = createCompounder(function(result, word, index) {
23689 return result + (index ? '_' : '') + word.toLowerCase();
23690 });
23691
23692 /**
23693 * Converts `string` to [start case](https://en.wikipedia.org/wiki/Letter_case#Stylistic_or_specialised_usage).
23694 *
23695 * @static
23696 * @memberOf _
23697 * @category String
23698 * @param {string} [string=''] The string to convert.
23699 * @returns {string} Returns the start cased string.
23700 * @example
23701 *
23702 * _.startCase('--foo-bar');
23703 * // => 'Foo Bar'
23704 *
23705 * _.startCase('fooBar');
23706 * // => 'Foo Bar'
23707 *
23708 * _.startCase('__foo_bar__');
23709 * // => 'Foo Bar'
23710 */
23711 var startCase = createCompounder(function(result, word, index) {
23712 return result + (index ? ' ' : '') + (word.charAt(0).toUpperCase() + word.slice(1));
23713 });
23714
23715 /**
23716 * Checks if `string` starts with the given target string.
23717 *
23718 * @static
23719 * @memberOf _
23720 * @category String
23721 * @param {string} [string=''] The string to search.
23722 * @param {string} [target] The string to search for.
23723 * @param {number} [position=0] The position to search from.
23724 * @returns {boolean} Returns `true` if `string` starts with `target`, else `false`.
23725 * @example
23726 *
23727 * _.startsWith('abc', 'a');
23728 * // => true
23729 *
23730 * _.startsWith('abc', 'b');
23731 * // => false
23732 *
23733 * _.startsWith('abc', 'b', 1);
23734 * // => true
23735 */
23736 function startsWith(string, target, position) {
23737 string = baseToString(string);
23738 position = position == null
23739 ? 0
23740 : nativeMin(position < 0 ? 0 : (+position || 0), string.length);
23741
23742 return string.lastIndexOf(target, position) == position;
23743 }
23744
23745 /**
23746 * Creates a compiled template function that can interpolate data properties
23747 * in "interpolate" delimiters, HTML-escape interpolated data properties in
23748 * "escape" delimiters, and execute JavaScript in "evaluate" delimiters. Data
23749 * properties may be accessed as free variables in the template. If a setting
23750 * object is provided it takes precedence over `_.templateSettings` values.
23751 *
23752 * **Note:** In the development build `_.template` utilizes
23753 * [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl)
23754 * for easier debugging.
23755 *
23756 * For more information on precompiling templates see
23757 * [lodash's custom builds documentation](https://lodash.com/custom-builds).
23758 *
23759 * For more information on Chrome extension sandboxes see
23760 * [Chrome's extensions documentation](https://developer.chrome.com/extensions/sandboxingEval).
23761 *
23762 * @static
23763 * @memberOf _
23764 * @category String
23765 * @param {string} [string=''] The template string.
23766 * @param {Object} [options] The options object.
23767 * @param {RegExp} [options.escape] The HTML "escape" delimiter.
23768 * @param {RegExp} [options.evaluate] The "evaluate" delimiter.
23769 * @param {Object} [options.imports] An object to import into the template as free variables.
23770 * @param {RegExp} [options.interpolate] The "interpolate" delimiter.
23771 * @param {string} [options.sourceURL] The sourceURL of the template's compiled source.
23772 * @param {string} [options.variable] The data object variable name.
23773 * @param- {Object} [otherOptions] Enables the legacy `options` param signature.
23774 * @returns {Function} Returns the compiled template function.
23775 * @example
23776 *
23777 * // using the "interpolate" delimiter to create a compiled template
23778 * var compiled = _.template('hello <%= user %>!');
23779 * compiled({ 'user': 'fred' });
23780 * // => 'hello fred!'
23781 *
23782 * // using the HTML "escape" delimiter to escape data property values
23783 * var compiled = _.template('<b><%- value %></b>');
23784 * compiled({ 'value': '<script>' });
23785 * // => '<b>&lt;script&gt;</b>'
23786 *
23787 * // using the "evaluate" delimiter to execute JavaScript and generate HTML
23788 * var compiled = _.template('<% _.forEach(users, function(user) { %><li><%- user %></li><% }); %>');
23789 * compiled({ 'users': ['fred', 'barney'] });
23790 * // => '<li>fred</li><li>barney</li>'
23791 *
23792 * // using the internal `print` function in "evaluate" delimiters
23793 * var compiled = _.template('<% print("hello " + user); %>!');
23794 * compiled({ 'user': 'barney' });
23795 * // => 'hello barney!'
23796 *
23797 * // using the ES delimiter as an alternative to the default "interpolate" delimiter
23798 * var compiled = _.template('hello ${ user }!');
23799 * compiled({ 'user': 'pebbles' });
23800 * // => 'hello pebbles!'
23801 *
23802 * // using custom template delimiters
23803 * _.templateSettings.interpolate = /{{([\s\S]+?)}}/g;
23804 * var compiled = _.template('hello {{ user }}!');
23805 * compiled({ 'user': 'mustache' });
23806 * // => 'hello mustache!'
23807 *
23808 * // using backslashes to treat delimiters as plain text
23809 * var compiled = _.template('<%= "\\<%- value %\\>" %>');
23810 * compiled({ 'value': 'ignored' });
23811 * // => '<%- value %>'
23812 *
23813 * // using the `imports` option to import `jQuery` as `jq`
23814 * var text = '<% jq.each(users, function(user) { %><li><%- user %></li><% }); %>';
23815 * var compiled = _.template(text, { 'imports': { 'jq': jQuery } });
23816 * compiled({ 'users': ['fred', 'barney'] });
23817 * // => '<li>fred</li><li>barney</li>'
23818 *
23819 * // using the `sourceURL` option to specify a custom sourceURL for the template
23820 * var compiled = _.template('hello <%= user %>!', { 'sourceURL': '/basic/greeting.jst' });
23821 * compiled(data);
23822 * // => find the source of "greeting.jst" under the Sources tab or Resources panel of the web inspector
23823 *
23824 * // using the `variable` option to ensure a with-statement isn't used in the compiled template
23825 * var compiled = _.template('hi <%= data.user %>!', { 'variable': 'data' });
23826 * compiled.source;
23827 * // => function(data) {
23828 * // var __t, __p = '';
23829 * // __p += 'hi ' + ((__t = ( data.user )) == null ? '' : __t) + '!';
23830 * // return __p;
23831 * // }
23832 *
23833 * // using the `source` property to inline compiled templates for meaningful
23834 * // line numbers in error messages and a stack trace
23835 * fs.writeFileSync(path.join(cwd, 'jst.js'), '\
23836 * var JST = {\
23837 * "main": ' + _.template(mainText).source + '\
23838 * };\
23839 * ');
23840 */
23841 function template(string, options, otherOptions) {
23842 // Based on John Resig's `tmpl` implementation (http://ejohn.org/blog/javascript-micro-templating/)
23843 // and Laura Doktorova's doT.js (https://github.com/olado/doT).
23844 var settings = lodash.templateSettings;
23845
23846 if (otherOptions && isIterateeCall(string, options, otherOptions)) {
23847 options = otherOptions = undefined;
23848 }
23849 string = baseToString(string);
23850 options = assignWith(baseAssign({}, otherOptions || options), settings, assignOwnDefaults);
23851
23852 var imports = assignWith(baseAssign({}, options.imports), settings.imports, assignOwnDefaults),
23853 importsKeys = keys(imports),
23854 importsValues = baseValues(imports, importsKeys);
23855
23856 var isEscaping,
23857 isEvaluating,
23858 index = 0,
23859 interpolate = options.interpolate || reNoMatch,
23860 source = "__p += '";
23861
23862 // Compile the regexp to match each delimiter.
23863 var reDelimiters = RegExp(
23864 (options.escape || reNoMatch).source + '|' +
23865 interpolate.source + '|' +
23866 (interpolate === reInterpolate ? reEsTemplate : reNoMatch).source + '|' +
23867 (options.evaluate || reNoMatch).source + '|$'
23868 , 'g');
23869
23870 // Use a sourceURL for easier debugging.
23871 var sourceURL = '//# sourceURL=' +
23872 ('sourceURL' in options
23873 ? options.sourceURL
23874 : ('lodash.templateSources[' + (++templateCounter) + ']')
23875 ) + '\n';
23876
23877 string.replace(reDelimiters, function(match, escapeValue, interpolateValue, esTemplateValue, evaluateValue, offset) {
23878 interpolateValue || (interpolateValue = esTemplateValue);
23879
23880 // Escape characters that can't be included in string literals.
23881 source += string.slice(index, offset).replace(reUnescapedString, escapeStringChar);
23882
23883 // Replace delimiters with snippets.
23884 if (escapeValue) {
23885 isEscaping = true;
23886 source += "' +\n__e(" + escapeValue + ") +\n'";
23887 }
23888 if (evaluateValue) {
23889 isEvaluating = true;
23890 source += "';\n" + evaluateValue + ";\n__p += '";
23891 }
23892 if (interpolateValue) {
23893 source += "' +\n((__t = (" + interpolateValue + ")) == null ? '' : __t) +\n'";
23894 }
23895 index = offset + match.length;
23896
23897 // The JS engine embedded in Adobe products requires returning the `match`
23898 // string in order to produce the correct `offset` value.
23899 return match;
23900 });
23901
23902 source += "';\n";
23903
23904 // If `variable` is not specified wrap a with-statement around the generated
23905 // code to add the data object to the top of the scope chain.
23906 var variable = options.variable;
23907 if (!variable) {
23908 source = 'with (obj) {\n' + source + '\n}\n';
23909 }
23910 // Cleanup code by stripping empty strings.
23911 source = (isEvaluating ? source.replace(reEmptyStringLeading, '') : source)
23912 .replace(reEmptyStringMiddle, '$1')
23913 .replace(reEmptyStringTrailing, '$1;');
23914
23915 // Frame code as the function body.
23916 source = 'function(' + (variable || 'obj') + ') {\n' +
23917 (variable
23918 ? ''
23919 : 'obj || (obj = {});\n'
23920 ) +
23921 "var __t, __p = ''" +
23922 (isEscaping
23923 ? ', __e = _.escape'
23924 : ''
23925 ) +
23926 (isEvaluating
23927 ? ', __j = Array.prototype.join;\n' +
23928 "function print() { __p += __j.call(arguments, '') }\n"
23929 : ';\n'
23930 ) +
23931 source +
23932 'return __p\n}';
23933
23934 var result = attempt(function() {
23935 return Function(importsKeys, sourceURL + 'return ' + source).apply(undefined, importsValues);
23936 });
23937
23938 // Provide the compiled function's source by its `toString` method or
23939 // the `source` property as a convenience for inlining compiled templates.
23940 result.source = source;
23941 if (isError(result)) {
23942 throw result;
23943 }
23944 return result;
23945 }
23946
23947 /**
23948 * Removes leading and trailing whitespace or specified characters from `string`.
23949 *
23950 * @static
23951 * @memberOf _
23952 * @category String
23953 * @param {string} [string=''] The string to trim.
23954 * @param {string} [chars=whitespace] The characters to trim.
23955 * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
23956 * @returns {string} Returns the trimmed string.
23957 * @example
23958 *
23959 * _.trim(' abc ');
23960 * // => 'abc'
23961 *
23962 * _.trim('-_-abc-_-', '_-');
23963 * // => 'abc'
23964 *
23965 * _.map([' foo ', ' bar '], _.trim);
23966 * // => ['foo', 'bar']
23967 */
23968 function trim(string, chars, guard) {
23969 var value = string;
23970 string = baseToString(string);
23971 if (!string) {
23972 return string;
23973 }
23974 if (guard ? isIterateeCall(value, chars, guard) : chars == null) {
23975 return string.slice(trimmedLeftIndex(string), trimmedRightIndex(string) + 1);
23976 }
23977 chars = (chars + '');
23978 return string.slice(charsLeftIndex(string, chars), charsRightIndex(string, chars) + 1);
23979 }
23980
23981 /**
23982 * Removes leading whitespace or specified characters from `string`.
23983 *
23984 * @static
23985 * @memberOf _
23986 * @category String
23987 * @param {string} [string=''] The string to trim.
23988 * @param {string} [chars=whitespace] The characters to trim.
23989 * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
23990 * @returns {string} Returns the trimmed string.
23991 * @example
23992 *
23993 * _.trimLeft(' abc ');
23994 * // => 'abc '
23995 *
23996 * _.trimLeft('-_-abc-_-', '_-');
23997 * // => 'abc-_-'
23998 */
23999 function trimLeft(string, chars, guard) {
24000 var value = string;
24001 string = baseToString(string);
24002 if (!string) {
24003 return string;
24004 }
24005 if (guard ? isIterateeCall(value, chars, guard) : chars == null) {
24006 return string.slice(trimmedLeftIndex(string));
24007 }
24008 return string.slice(charsLeftIndex(string, (chars + '')));
24009 }
24010
24011 /**
24012 * Removes trailing whitespace or specified characters from `string`.
24013 *
24014 * @static
24015 * @memberOf _
24016 * @category String
24017 * @param {string} [string=''] The string to trim.
24018 * @param {string} [chars=whitespace] The characters to trim.
24019 * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
24020 * @returns {string} Returns the trimmed string.
24021 * @example
24022 *
24023 * _.trimRight(' abc ');
24024 * // => ' abc'
24025 *
24026 * _.trimRight('-_-abc-_-', '_-');
24027 * // => '-_-abc'
24028 */
24029 function trimRight(string, chars, guard) {
24030 var value = string;
24031 string = baseToString(string);
24032 if (!string) {
24033 return string;
24034 }
24035 if (guard ? isIterateeCall(value, chars, guard) : chars == null) {
24036 return string.slice(0, trimmedRightIndex(string) + 1);
24037 }
24038 return string.slice(0, charsRightIndex(string, (chars + '')) + 1);
24039 }
24040
24041 /**
24042 * Truncates `string` if it's longer than the given maximum string length.
24043 * The last characters of the truncated string are replaced with the omission
24044 * string which defaults to "...".
24045 *
24046 * @static
24047 * @memberOf _
24048 * @category String
24049 * @param {string} [string=''] The string to truncate.
24050 * @param {Object|number} [options] The options object or maximum string length.
24051 * @param {number} [options.length=30] The maximum string length.
24052 * @param {string} [options.omission='...'] The string to indicate text is omitted.
24053 * @param {RegExp|string} [options.separator] The separator pattern to truncate to.
24054 * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
24055 * @returns {string} Returns the truncated string.
24056 * @example
24057 *
24058 * _.trunc('hi-diddly-ho there, neighborino');
24059 * // => 'hi-diddly-ho there, neighbo...'
24060 *
24061 * _.trunc('hi-diddly-ho there, neighborino', 24);
24062 * // => 'hi-diddly-ho there, n...'
24063 *
24064 * _.trunc('hi-diddly-ho there, neighborino', {
24065 * 'length': 24,
24066 * 'separator': ' '
24067 * });
24068 * // => 'hi-diddly-ho there,...'
24069 *
24070 * _.trunc('hi-diddly-ho there, neighborino', {
24071 * 'length': 24,
24072 * 'separator': /,? +/
24073 * });
24074 * // => 'hi-diddly-ho there...'
24075 *
24076 * _.trunc('hi-diddly-ho there, neighborino', {
24077 * 'omission': ' [...]'
24078 * });
24079 * // => 'hi-diddly-ho there, neig [...]'
24080 */
24081 function trunc(string, options, guard) {
24082 if (guard && isIterateeCall(string, options, guard)) {
24083 options = undefined;
24084 }
24085 var length = DEFAULT_TRUNC_LENGTH,
24086 omission = DEFAULT_TRUNC_OMISSION;
24087
24088 if (options != null) {
24089 if (isObject(options)) {
24090 var separator = 'separator' in options ? options.separator : separator;
24091 length = 'length' in options ? (+options.length || 0) : length;
24092 omission = 'omission' in options ? baseToString(options.omission) : omission;
24093 } else {
24094 length = +options || 0;
24095 }
24096 }
24097 string = baseToString(string);
24098 if (length >= string.length) {
24099 return string;
24100 }
24101 var end = length - omission.length;
24102 if (end < 1) {
24103 return omission;
24104 }
24105 var result = string.slice(0, end);
24106 if (separator == null) {
24107 return result + omission;
24108 }
24109 if (isRegExp(separator)) {
24110 if (string.slice(end).search(separator)) {
24111 var match,
24112 newEnd,
24113 substring = string.slice(0, end);
24114
24115 if (!separator.global) {
24116 separator = RegExp(separator.source, (reFlags.exec(separator) || '') + 'g');
24117 }
24118 separator.lastIndex = 0;
24119 while ((match = separator.exec(substring))) {
24120 newEnd = match.index;
24121 }
24122 result = result.slice(0, newEnd == null ? end : newEnd);
24123 }
24124 } else if (string.indexOf(separator, end) != end) {
24125 var index = result.lastIndexOf(separator);
24126 if (index > -1) {
24127 result = result.slice(0, index);
24128 }
24129 }
24130 return result + omission;
24131 }
24132
24133 /**
24134 * The inverse of `_.escape`; this method converts the HTML entities
24135 * `&amp;`, `&lt;`, `&gt;`, `&quot;`, `&#39;`, and `&#96;` in `string` to their
24136 * corresponding characters.
24137 *
24138 * **Note:** No other HTML entities are unescaped. To unescape additional HTML
24139 * entities use a third-party library like [_he_](https://mths.be/he).
24140 *
24141 * @static
24142 * @memberOf _
24143 * @category String
24144 * @param {string} [string=''] The string to unescape.
24145 * @returns {string} Returns the unescaped string.
24146 * @example
24147 *
24148 * _.unescape('fred, barney, &amp; pebbles');
24149 * // => 'fred, barney, & pebbles'
24150 */
24151 function unescape(string) {
24152 string = baseToString(string);
24153 return (string && reHasEscapedHtml.test(string))
24154 ? string.replace(reEscapedHtml, unescapeHtmlChar)
24155 : string;
24156 }
24157
24158 /**
24159 * Splits `string` into an array of its words.
24160 *
24161 * @static
24162 * @memberOf _
24163 * @category String
24164 * @param {string} [string=''] The string to inspect.
24165 * @param {RegExp|string} [pattern] The pattern to match words.
24166 * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
24167 * @returns {Array} Returns the words of `string`.
24168 * @example
24169 *
24170 * _.words('fred, barney, & pebbles');
24171 * // => ['fred', 'barney', 'pebbles']
24172 *
24173 * _.words('fred, barney, & pebbles', /[^, ]+/g);
24174 * // => ['fred', 'barney', '&', 'pebbles']
24175 */
24176 function words(string, pattern, guard) {
24177 if (guard && isIterateeCall(string, pattern, guard)) {
24178 pattern = undefined;
24179 }
24180 string = baseToString(string);
24181 return string.match(pattern || reWords) || [];
24182 }
24183
24184 /*------------------------------------------------------------------------*/
24185
24186 /**
24187 * Attempts to invoke `func`, returning either the result or the caught error
24188 * object. Any additional arguments are provided to `func` when it is invoked.
24189 *
24190 * @static
24191 * @memberOf _
24192 * @category Utility
24193 * @param {Function} func The function to attempt.
24194 * @returns {*} Returns the `func` result or error object.
24195 * @example
24196 *
24197 * // avoid throwing errors for invalid selectors
24198 * var elements = _.attempt(function(selector) {
24199 * return document.querySelectorAll(selector);
24200 * }, '>_>');
24201 *
24202 * if (_.isError(elements)) {
24203 * elements = [];
24204 * }
24205 */
24206 var attempt = restParam(function(func, args) {
24207 try {
24208 return func.apply(undefined, args);
24209 } catch(e) {
24210 return isError(e) ? e : new Error(e);
24211 }
24212 });
24213
24214 /**
24215 * Creates a function that invokes `func` with the `this` binding of `thisArg`
24216 * and arguments of the created function. If `func` is a property name the
24217 * created callback returns the property value for a given element. If `func`
24218 * is an object the created callback returns `true` for elements that contain
24219 * the equivalent object properties, otherwise it returns `false`.
24220 *
24221 * @static
24222 * @memberOf _
24223 * @alias iteratee
24224 * @category Utility
24225 * @param {*} [func=_.identity] The value to convert to a callback.
24226 * @param {*} [thisArg] The `this` binding of `func`.
24227 * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
24228 * @returns {Function} Returns the callback.
24229 * @example
24230 *
24231 * var users = [
24232 * { 'user': 'barney', 'age': 36 },
24233 * { 'user': 'fred', 'age': 40 }
24234 * ];
24235 *
24236 * // wrap to create custom callback shorthands
24237 * _.callback = _.wrap(_.callback, function(callback, func, thisArg) {
24238 * var match = /^(.+?)__([gl]t)(.+)$/.exec(func);
24239 * if (!match) {
24240 * return callback(func, thisArg);
24241 * }
24242 * return function(object) {
24243 * return match[2] == 'gt'
24244 * ? object[match[1]] > match[3]
24245 * : object[match[1]] < match[3];
24246 * };
24247 * });
24248 *
24249 * _.filter(users, 'age__gt36');
24250 * // => [{ 'user': 'fred', 'age': 40 }]
24251 */
24252 function callback(func, thisArg, guard) {
24253 if (guard && isIterateeCall(func, thisArg, guard)) {
24254 thisArg = undefined;
24255 }
24256 return isObjectLike(func)
24257 ? matches(func)
24258 : baseCallback(func, thisArg);
24259 }
24260
24261 /**
24262 * Creates a function that returns `value`.
24263 *
24264 * @static
24265 * @memberOf _
24266 * @category Utility
24267 * @param {*} value The value to return from the new function.
24268 * @returns {Function} Returns the new function.
24269 * @example
24270 *
24271 * var object = { 'user': 'fred' };
24272 * var getter = _.constant(object);
24273 *
24274 * getter() === object;
24275 * // => true
24276 */
24277 function constant(value) {
24278 return function() {
24279 return value;
24280 };
24281 }
24282
24283 /**
24284 * This method returns the first argument provided to it.
24285 *
24286 * @static
24287 * @memberOf _
24288 * @category Utility
24289 * @param {*} value Any value.
24290 * @returns {*} Returns `value`.
24291 * @example
24292 *
24293 * var object = { 'user': 'fred' };
24294 *
24295 * _.identity(object) === object;
24296 * // => true
24297 */
24298 function identity(value) {
24299 return value;
24300 }
24301
24302 /**
24303 * Creates a function that performs a deep comparison between a given object
24304 * and `source`, returning `true` if the given object has equivalent property
24305 * values, else `false`.
24306 *
24307 * **Note:** This method supports comparing arrays, booleans, `Date` objects,
24308 * numbers, `Object` objects, regexes, and strings. Objects are compared by
24309 * their own, not inherited, enumerable properties. For comparing a single
24310 * own or inherited property value see `_.matchesProperty`.
24311 *
24312 * @static
24313 * @memberOf _
24314 * @category Utility
24315 * @param {Object} source The object of property values to match.
24316 * @returns {Function} Returns the new function.
24317 * @example
24318 *
24319 * var users = [
24320 * { 'user': 'barney', 'age': 36, 'active': true },
24321 * { 'user': 'fred', 'age': 40, 'active': false }
24322 * ];
24323 *
24324 * _.filter(users, _.matches({ 'age': 40, 'active': false }));
24325 * // => [{ 'user': 'fred', 'age': 40, 'active': false }]
24326 */
24327 function matches(source) {
24328 return baseMatches(baseClone(source, true));
24329 }
24330
24331 /**
24332 * Creates a function that compares the property value of `path` on a given
24333 * object to `value`.
24334 *
24335 * **Note:** This method supports comparing arrays, booleans, `Date` objects,
24336 * numbers, `Object` objects, regexes, and strings. Objects are compared by
24337 * their own, not inherited, enumerable properties.
24338 *
24339 * @static
24340 * @memberOf _
24341 * @category Utility
24342 * @param {Array|string} path The path of the property to get.
24343 * @param {*} srcValue The value to match.
24344 * @returns {Function} Returns the new function.
24345 * @example
24346 *
24347 * var users = [
24348 * { 'user': 'barney' },
24349 * { 'user': 'fred' }
24350 * ];
24351 *
24352 * _.find(users, _.matchesProperty('user', 'fred'));
24353 * // => { 'user': 'fred' }
24354 */
24355 function matchesProperty(path, srcValue) {
24356 return baseMatchesProperty(path, baseClone(srcValue, true));
24357 }
24358
24359 /**
24360 * Creates a function that invokes the method at `path` on a given object.
24361 * Any additional arguments are provided to the invoked method.
24362 *
24363 * @static
24364 * @memberOf _
24365 * @category Utility
24366 * @param {Array|string} path The path of the method to invoke.
24367 * @param {...*} [args] The arguments to invoke the method with.
24368 * @returns {Function} Returns the new function.
24369 * @example
24370 *
24371 * var objects = [
24372 * { 'a': { 'b': { 'c': _.constant(2) } } },
24373 * { 'a': { 'b': { 'c': _.constant(1) } } }
24374 * ];
24375 *
24376 * _.map(objects, _.method('a.b.c'));
24377 * // => [2, 1]
24378 *
24379 * _.invoke(_.sortBy(objects, _.method(['a', 'b', 'c'])), 'a.b.c');
24380 * // => [1, 2]
24381 */
24382 var method = restParam(function(path, args) {
24383 return function(object) {
24384 return invokePath(object, path, args);
24385 };
24386 });
24387
24388 /**
24389 * The opposite of `_.method`; this method creates a function that invokes
24390 * the method at a given path on `object`. Any additional arguments are
24391 * provided to the invoked method.
24392 *
24393 * @static
24394 * @memberOf _
24395 * @category Utility
24396 * @param {Object} object The object to query.
24397 * @param {...*} [args] The arguments to invoke the method with.
24398 * @returns {Function} Returns the new function.
24399 * @example
24400 *
24401 * var array = _.times(3, _.constant),
24402 * object = { 'a': array, 'b': array, 'c': array };
24403 *
24404 * _.map(['a[2]', 'c[0]'], _.methodOf(object));
24405 * // => [2, 0]
24406 *
24407 * _.map([['a', '2'], ['c', '0']], _.methodOf(object));
24408 * // => [2, 0]
24409 */
24410 var methodOf = restParam(function(object, args) {
24411 return function(path) {
24412 return invokePath(object, path, args);
24413 };
24414 });
24415
24416 /**
24417 * Adds all own enumerable function properties of a source object to the
24418 * destination object. If `object` is a function then methods are added to
24419 * its prototype as well.
24420 *
24421 * **Note:** Use `_.runInContext` to create a pristine `lodash` function to
24422 * avoid conflicts caused by modifying the original.
24423 *
24424 * @static
24425 * @memberOf _
24426 * @category Utility
24427 * @param {Function|Object} [object=lodash] The destination object.
24428 * @param {Object} source The object of functions to add.
24429 * @param {Object} [options] The options object.
24430 * @param {boolean} [options.chain=true] Specify whether the functions added
24431 * are chainable.
24432 * @returns {Function|Object} Returns `object`.
24433 * @example
24434 *
24435 * function vowels(string) {
24436 * return _.filter(string, function(v) {
24437 * return /[aeiou]/i.test(v);
24438 * });
24439 * }
24440 *
24441 * _.mixin({ 'vowels': vowels });
24442 * _.vowels('fred');
24443 * // => ['e']
24444 *
24445 * _('fred').vowels().value();
24446 * // => ['e']
24447 *
24448 * _.mixin({ 'vowels': vowels }, { 'chain': false });
24449 * _('fred').vowels();
24450 * // => ['e']
24451 */
24452 function mixin(object, source, options) {
24453 if (options == null) {
24454 var isObj = isObject(source),
24455 props = isObj ? keys(source) : undefined,
24456 methodNames = (props && props.length) ? baseFunctions(source, props) : undefined;
24457
24458 if (!(methodNames ? methodNames.length : isObj)) {
24459 methodNames = false;
24460 options = source;
24461 source = object;
24462 object = this;
24463 }
24464 }
24465 if (!methodNames) {
24466 methodNames = baseFunctions(source, keys(source));
24467 }
24468 var chain = true,
24469 index = -1,
24470 isFunc = isFunction(object),
24471 length = methodNames.length;
24472
24473 if (options === false) {
24474 chain = false;
24475 } else if (isObject(options) && 'chain' in options) {
24476 chain = options.chain;
24477 }
24478 while (++index < length) {
24479 var methodName = methodNames[index],
24480 func = source[methodName];
24481
24482 object[methodName] = func;
24483 if (isFunc) {
24484 object.prototype[methodName] = (function(func) {
24485 return function() {
24486 var chainAll = this.__chain__;
24487 if (chain || chainAll) {
24488 var result = object(this.__wrapped__),
24489 actions = result.__actions__ = arrayCopy(this.__actions__);
24490
24491 actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
24492 result.__chain__ = chainAll;
24493 return result;
24494 }
24495 return func.apply(object, arrayPush([this.value()], arguments));
24496 };
24497 }(func));
24498 }
24499 }
24500 return object;
24501 }
24502
24503 /**
24504 * Reverts the `_` variable to its previous value and returns a reference to
24505 * the `lodash` function.
24506 *
24507 * @static
24508 * @memberOf _
24509 * @category Utility
24510 * @returns {Function} Returns the `lodash` function.
24511 * @example
24512 *
24513 * var lodash = _.noConflict();
24514 */
24515 function noConflict() {
24516 root._ = oldDash;
24517 return this;
24518 }
24519
24520 /**
24521 * A no-operation function that returns `undefined` regardless of the
24522 * arguments it receives.
24523 *
24524 * @static
24525 * @memberOf _
24526 * @category Utility
24527 * @example
24528 *
24529 * var object = { 'user': 'fred' };
24530 *
24531 * _.noop(object) === undefined;
24532 * // => true
24533 */
24534 function noop() {
24535 // No operation performed.
24536 }
24537
24538 /**
24539 * Creates a function that returns the property value at `path` on a
24540 * given object.
24541 *
24542 * @static
24543 * @memberOf _
24544 * @category Utility
24545 * @param {Array|string} path The path of the property to get.
24546 * @returns {Function} Returns the new function.
24547 * @example
24548 *
24549 * var objects = [
24550 * { 'a': { 'b': { 'c': 2 } } },
24551 * { 'a': { 'b': { 'c': 1 } } }
24552 * ];
24553 *
24554 * _.map(objects, _.property('a.b.c'));
24555 * // => [2, 1]
24556 *
24557 * _.pluck(_.sortBy(objects, _.property(['a', 'b', 'c'])), 'a.b.c');
24558 * // => [1, 2]
24559 */
24560 function property(path) {
24561 return isKey(path) ? baseProperty(path) : basePropertyDeep(path);
24562 }
24563
24564 /**
24565 * The opposite of `_.property`; this method creates a function that returns
24566 * the property value at a given path on `object`.
24567 *
24568 * @static
24569 * @memberOf _
24570 * @category Utility
24571 * @param {Object} object The object to query.
24572 * @returns {Function} Returns the new function.
24573 * @example
24574 *
24575 * var array = [0, 1, 2],
24576 * object = { 'a': array, 'b': array, 'c': array };
24577 *
24578 * _.map(['a[2]', 'c[0]'], _.propertyOf(object));
24579 * // => [2, 0]
24580 *
24581 * _.map([['a', '2'], ['c', '0']], _.propertyOf(object));
24582 * // => [2, 0]
24583 */
24584 function propertyOf(object) {
24585 return function(path) {
24586 return baseGet(object, toPath(path), path + '');
24587 };
24588 }
24589
24590 /**
24591 * Creates an array of numbers (positive and/or negative) progressing from
24592 * `start` up to, but not including, `end`. If `end` is not specified it is
24593 * set to `start` with `start` then set to `0`. If `end` is less than `start`
24594 * a zero-length range is created unless a negative `step` is specified.
24595 *
24596 * @static
24597 * @memberOf _
24598 * @category Utility
24599 * @param {number} [start=0] The start of the range.
24600 * @param {number} end The end of the range.
24601 * @param {number} [step=1] The value to increment or decrement by.
24602 * @returns {Array} Returns the new array of numbers.
24603 * @example
24604 *
24605 * _.range(4);
24606 * // => [0, 1, 2, 3]
24607 *
24608 * _.range(1, 5);
24609 * // => [1, 2, 3, 4]
24610 *
24611 * _.range(0, 20, 5);
24612 * // => [0, 5, 10, 15]
24613 *
24614 * _.range(0, -4, -1);
24615 * // => [0, -1, -2, -3]
24616 *
24617 * _.range(1, 4, 0);
24618 * // => [1, 1, 1]
24619 *
24620 * _.range(0);
24621 * // => []
24622 */
24623 function range(start, end, step) {
24624 if (step && isIterateeCall(start, end, step)) {
24625 end = step = undefined;
24626 }
24627 start = +start || 0;
24628 step = step == null ? 1 : (+step || 0);
24629
24630 if (end == null) {
24631 end = start;
24632 start = 0;
24633 } else {
24634 end = +end || 0;
24635 }
24636 // Use `Array(length)` so engines like Chakra and V8 avoid slower modes.
24637 // See https://youtu.be/XAqIpGU8ZZk#t=17m25s for more details.
24638 var index = -1,
24639 length = nativeMax(nativeCeil((end - start) / (step || 1)), 0),
24640 result = Array(length);
24641
24642 while (++index < length) {
24643 result[index] = start;
24644 start += step;
24645 }
24646 return result;
24647 }
24648
24649 /**
24650 * Invokes the iteratee function `n` times, returning an array of the results
24651 * of each invocation. The `iteratee` is bound to `thisArg` and invoked with
24652 * one argument; (index).
24653 *
24654 * @static
24655 * @memberOf _
24656 * @category Utility
24657 * @param {number} n The number of times to invoke `iteratee`.
24658 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
24659 * @param {*} [thisArg] The `this` binding of `iteratee`.
24660 * @returns {Array} Returns the array of results.
24661 * @example
24662 *
24663 * var diceRolls = _.times(3, _.partial(_.random, 1, 6, false));
24664 * // => [3, 6, 4]
24665 *
24666 * _.times(3, function(n) {
24667 * mage.castSpell(n);
24668 * });
24669 * // => invokes `mage.castSpell(n)` three times with `n` of `0`, `1`, and `2`
24670 *
24671 * _.times(3, function(n) {
24672 * this.cast(n);
24673 * }, mage);
24674 * // => also invokes `mage.castSpell(n)` three times
24675 */
24676 function times(n, iteratee, thisArg) {
24677 n = nativeFloor(n);
24678
24679 // Exit early to avoid a JSC JIT bug in Safari 8
24680 // where `Array(0)` is treated as `Array(1)`.
24681 if (n < 1 || !nativeIsFinite(n)) {
24682 return [];
24683 }
24684 var index = -1,
24685 result = Array(nativeMin(n, MAX_ARRAY_LENGTH));
24686
24687 iteratee = bindCallback(iteratee, thisArg, 1);
24688 while (++index < n) {
24689 if (index < MAX_ARRAY_LENGTH) {
24690 result[index] = iteratee(index);
24691 } else {
24692 iteratee(index);
24693 }
24694 }
24695 return result;
24696 }
24697
24698 /**
24699 * Generates a unique ID. If `prefix` is provided the ID is appended to it.
24700 *
24701 * @static
24702 * @memberOf _
24703 * @category Utility
24704 * @param {string} [prefix] The value to prefix the ID with.
24705 * @returns {string} Returns the unique ID.
24706 * @example
24707 *
24708 * _.uniqueId('contact_');
24709 * // => 'contact_104'
24710 *
24711 * _.uniqueId();
24712 * // => '105'
24713 */
24714 function uniqueId(prefix) {
24715 var id = ++idCounter;
24716 return baseToString(prefix) + id;
24717 }
24718
24719 /*------------------------------------------------------------------------*/
24720
24721 /**
24722 * Adds two numbers.
24723 *
24724 * @static
24725 * @memberOf _
24726 * @category Math
24727 * @param {number} augend The first number to add.
24728 * @param {number} addend The second number to add.
24729 * @returns {number} Returns the sum.
24730 * @example
24731 *
24732 * _.add(6, 4);
24733 * // => 10
24734 */
24735 function add(augend, addend) {
24736 return (+augend || 0) + (+addend || 0);
24737 }
24738
24739 /**
24740 * Calculates `n` rounded up to `precision`.
24741 *
24742 * @static
24743 * @memberOf _
24744 * @category Math
24745 * @param {number} n The number to round up.
24746 * @param {number} [precision=0] The precision to round up to.
24747 * @returns {number} Returns the rounded up number.
24748 * @example
24749 *
24750 * _.ceil(4.006);
24751 * // => 5
24752 *
24753 * _.ceil(6.004, 2);
24754 * // => 6.01
24755 *
24756 * _.ceil(6040, -2);
24757 * // => 6100
24758 */
24759 var ceil = createRound('ceil');
24760
24761 /**
24762 * Calculates `n` rounded down to `precision`.
24763 *
24764 * @static
24765 * @memberOf _
24766 * @category Math
24767 * @param {number} n The number to round down.
24768 * @param {number} [precision=0] The precision to round down to.
24769 * @returns {number} Returns the rounded down number.
24770 * @example
24771 *
24772 * _.floor(4.006);
24773 * // => 4
24774 *
24775 * _.floor(0.046, 2);
24776 * // => 0.04
24777 *
24778 * _.floor(4060, -2);
24779 * // => 4000
24780 */
24781 var floor = createRound('floor');
24782
24783 /**
24784 * Gets the maximum value of `collection`. If `collection` is empty or falsey
24785 * `-Infinity` is returned. If an iteratee function is provided it is invoked
24786 * for each value in `collection` to generate the criterion by which the value
24787 * is ranked. The `iteratee` is bound to `thisArg` and invoked with three
24788 * arguments: (value, index, collection).
24789 *
24790 * If a property name is provided for `iteratee` the created `_.property`
24791 * style callback returns the property value of the given element.
24792 *
24793 * If a value is also provided for `thisArg` the created `_.matchesProperty`
24794 * style callback returns `true` for elements that have a matching property
24795 * value, else `false`.
24796 *
24797 * If an object is provided for `iteratee` the created `_.matches` style
24798 * callback returns `true` for elements that have the properties of the given
24799 * object, else `false`.
24800 *
24801 * @static
24802 * @memberOf _
24803 * @category Math
24804 * @param {Array|Object|string} collection The collection to iterate over.
24805 * @param {Function|Object|string} [iteratee] The function invoked per iteration.
24806 * @param {*} [thisArg] The `this` binding of `iteratee`.
24807 * @returns {*} Returns the maximum value.
24808 * @example
24809 *
24810 * _.max([4, 2, 8, 6]);
24811 * // => 8
24812 *
24813 * _.max([]);
24814 * // => -Infinity
24815 *
24816 * var users = [
24817 * { 'user': 'barney', 'age': 36 },
24818 * { 'user': 'fred', 'age': 40 }
24819 * ];
24820 *
24821 * _.max(users, function(chr) {
24822 * return chr.age;
24823 * });
24824 * // => { 'user': 'fred', 'age': 40 }
24825 *
24826 * // using the `_.property` callback shorthand
24827 * _.max(users, 'age');
24828 * // => { 'user': 'fred', 'age': 40 }
24829 */
24830 var max = createExtremum(gt, NEGATIVE_INFINITY);
24831
24832 /**
24833 * Gets the minimum value of `collection`. If `collection` is empty or falsey
24834 * `Infinity` is returned. If an iteratee function is provided it is invoked
24835 * for each value in `collection` to generate the criterion by which the value
24836 * is ranked. The `iteratee` is bound to `thisArg` and invoked with three
24837 * arguments: (value, index, collection).
24838 *
24839 * If a property name is provided for `iteratee` the created `_.property`
24840 * style callback returns the property value of the given element.
24841 *
24842 * If a value is also provided for `thisArg` the created `_.matchesProperty`
24843 * style callback returns `true` for elements that have a matching property
24844 * value, else `false`.
24845 *
24846 * If an object is provided for `iteratee` the created `_.matches` style
24847 * callback returns `true` for elements that have the properties of the given
24848 * object, else `false`.
24849 *
24850 * @static
24851 * @memberOf _
24852 * @category Math
24853 * @param {Array|Object|string} collection The collection to iterate over.
24854 * @param {Function|Object|string} [iteratee] The function invoked per iteration.
24855 * @param {*} [thisArg] The `this` binding of `iteratee`.
24856 * @returns {*} Returns the minimum value.
24857 * @example
24858 *
24859 * _.min([4, 2, 8, 6]);
24860 * // => 2
24861 *
24862 * _.min([]);
24863 * // => Infinity
24864 *
24865 * var users = [
24866 * { 'user': 'barney', 'age': 36 },
24867 * { 'user': 'fred', 'age': 40 }
24868 * ];
24869 *
24870 * _.min(users, function(chr) {
24871 * return chr.age;
24872 * });
24873 * // => { 'user': 'barney', 'age': 36 }
24874 *
24875 * // using the `_.property` callback shorthand
24876 * _.min(users, 'age');
24877 * // => { 'user': 'barney', 'age': 36 }
24878 */
24879 var min = createExtremum(lt, POSITIVE_INFINITY);
24880
24881 /**
24882 * Calculates `n` rounded to `precision`.
24883 *
24884 * @static
24885 * @memberOf _
24886 * @category Math
24887 * @param {number} n The number to round.
24888 * @param {number} [precision=0] The precision to round to.
24889 * @returns {number} Returns the rounded number.
24890 * @example
24891 *
24892 * _.round(4.006);
24893 * // => 4
24894 *
24895 * _.round(4.006, 2);
24896 * // => 4.01
24897 *
24898 * _.round(4060, -2);
24899 * // => 4100
24900 */
24901 var round = createRound('round');
24902
24903 /**
24904 * Gets the sum of the values in `collection`.
24905 *
24906 * @static
24907 * @memberOf _
24908 * @category Math
24909 * @param {Array|Object|string} collection The collection to iterate over.
24910 * @param {Function|Object|string} [iteratee] The function invoked per iteration.
24911 * @param {*} [thisArg] The `this` binding of `iteratee`.
24912 * @returns {number} Returns the sum.
24913 * @example
24914 *
24915 * _.sum([4, 6]);
24916 * // => 10
24917 *
24918 * _.sum({ 'a': 4, 'b': 6 });
24919 * // => 10
24920 *
24921 * var objects = [
24922 * { 'n': 4 },
24923 * { 'n': 6 }
24924 * ];
24925 *
24926 * _.sum(objects, function(object) {
24927 * return object.n;
24928 * });
24929 * // => 10
24930 *
24931 * // using the `_.property` callback shorthand
24932 * _.sum(objects, 'n');
24933 * // => 10
24934 */
24935 function sum(collection, iteratee, thisArg) {
24936 if (thisArg && isIterateeCall(collection, iteratee, thisArg)) {
24937 iteratee = undefined;
24938 }
24939 iteratee = getCallback(iteratee, thisArg, 3);
24940 return iteratee.length == 1
24941 ? arraySum(isArray(collection) ? collection : toIterable(collection), iteratee)
24942 : baseSum(collection, iteratee);
24943 }
24944
24945 /*------------------------------------------------------------------------*/
24946
24947 // Ensure wrappers are instances of `baseLodash`.
24948 lodash.prototype = baseLodash.prototype;
24949
24950 LodashWrapper.prototype = baseCreate(baseLodash.prototype);
24951 LodashWrapper.prototype.constructor = LodashWrapper;
24952
24953 LazyWrapper.prototype = baseCreate(baseLodash.prototype);
24954 LazyWrapper.prototype.constructor = LazyWrapper;
24955
24956 // Add functions to the `Map` cache.
24957 MapCache.prototype['delete'] = mapDelete;
24958 MapCache.prototype.get = mapGet;
24959 MapCache.prototype.has = mapHas;
24960 MapCache.prototype.set = mapSet;
24961
24962 // Add functions to the `Set` cache.
24963 SetCache.prototype.push = cachePush;
24964
24965 // Assign cache to `_.memoize`.
24966 memoize.Cache = MapCache;
24967
24968 // Add functions that return wrapped values when chaining.
24969 lodash.after = after;
24970 lodash.ary = ary;
24971 lodash.assign = assign;
24972 lodash.at = at;
24973 lodash.before = before;
24974 lodash.bind = bind;
24975 lodash.bindAll = bindAll;
24976 lodash.bindKey = bindKey;
24977 lodash.callback = callback;
24978 lodash.chain = chain;
24979 lodash.chunk = chunk;
24980 lodash.compact = compact;
24981 lodash.constant = constant;
24982 lodash.countBy = countBy;
24983 lodash.create = create;
24984 lodash.curry = curry;
24985 lodash.curryRight = curryRight;
24986 lodash.debounce = debounce;
24987 lodash.defaults = defaults;
24988 lodash.defaultsDeep = defaultsDeep;
24989 lodash.defer = defer;
24990 lodash.delay = delay;
24991 lodash.difference = difference;
24992 lodash.drop = drop;
24993 lodash.dropRight = dropRight;
24994 lodash.dropRightWhile = dropRightWhile;
24995 lodash.dropWhile = dropWhile;
24996 lodash.fill = fill;
24997 lodash.filter = filter;
24998 lodash.flatten = flatten;
24999 lodash.flattenDeep = flattenDeep;
25000 lodash.flow = flow;
25001 lodash.flowRight = flowRight;
25002 lodash.forEach = forEach;
25003 lodash.forEachRight = forEachRight;
25004 lodash.forIn = forIn;
25005 lodash.forInRight = forInRight;
25006 lodash.forOwn = forOwn;
25007 lodash.forOwnRight = forOwnRight;
25008 lodash.functions = functions;
25009 lodash.groupBy = groupBy;
25010 lodash.indexBy = indexBy;
25011 lodash.initial = initial;
25012 lodash.intersection = intersection;
25013 lodash.invert = invert;
25014 lodash.invoke = invoke;
25015 lodash.keys = keys;
25016 lodash.keysIn = keysIn;
25017 lodash.map = map;
25018 lodash.mapKeys = mapKeys;
25019 lodash.mapValues = mapValues;
25020 lodash.matches = matches;
25021 lodash.matchesProperty = matchesProperty;
25022 lodash.memoize = memoize;
25023 lodash.merge = merge;
25024 lodash.method = method;
25025 lodash.methodOf = methodOf;
25026 lodash.mixin = mixin;
25027 lodash.modArgs = modArgs;
25028 lodash.negate = negate;
25029 lodash.omit = omit;
25030 lodash.once = once;
25031 lodash.pairs = pairs;
25032 lodash.partial = partial;
25033 lodash.partialRight = partialRight;
25034 lodash.partition = partition;
25035 lodash.pick = pick;
25036 lodash.pluck = pluck;
25037 lodash.property = property;
25038 lodash.propertyOf = propertyOf;
25039 lodash.pull = pull;
25040 lodash.pullAt = pullAt;
25041 lodash.range = range;
25042 lodash.rearg = rearg;
25043 lodash.reject = reject;
25044 lodash.remove = remove;
25045 lodash.rest = rest;
25046 lodash.restParam = restParam;
25047 lodash.set = set;
25048 lodash.shuffle = shuffle;
25049 lodash.slice = slice;
25050 lodash.sortBy = sortBy;
25051 lodash.sortByAll = sortByAll;
25052 lodash.sortByOrder = sortByOrder;
25053 lodash.spread = spread;
25054 lodash.take = take;
25055 lodash.takeRight = takeRight;
25056 lodash.takeRightWhile = takeRightWhile;
25057 lodash.takeWhile = takeWhile;
25058 lodash.tap = tap;
25059 lodash.throttle = throttle;
25060 lodash.thru = thru;
25061 lodash.times = times;
25062 lodash.toArray = toArray;
25063 lodash.toPlainObject = toPlainObject;
25064 lodash.transform = transform;
25065 lodash.union = union;
25066 lodash.uniq = uniq;
25067 lodash.unzip = unzip;
25068 lodash.unzipWith = unzipWith;
25069 lodash.values = values;
25070 lodash.valuesIn = valuesIn;
25071 lodash.where = where;
25072 lodash.without = without;
25073 lodash.wrap = wrap;
25074 lodash.xor = xor;
25075 lodash.zip = zip;
25076 lodash.zipObject = zipObject;
25077 lodash.zipWith = zipWith;
25078
25079 // Add aliases.
25080 lodash.backflow = flowRight;
25081 lodash.collect = map;
25082 lodash.compose = flowRight;
25083 lodash.each = forEach;
25084 lodash.eachRight = forEachRight;
25085 lodash.extend = assign;
25086 lodash.iteratee = callback;
25087 lodash.methods = functions;
25088 lodash.object = zipObject;
25089 lodash.select = filter;
25090 lodash.tail = rest;
25091 lodash.unique = uniq;
25092
25093 // Add functions to `lodash.prototype`.
25094 mixin(lodash, lodash);
25095
25096 /*------------------------------------------------------------------------*/
25097
25098 // Add functions that return unwrapped values when chaining.
25099 lodash.add = add;
25100 lodash.attempt = attempt;
25101 lodash.camelCase = camelCase;
25102 lodash.capitalize = capitalize;
25103 lodash.ceil = ceil;
25104 lodash.clone = clone;
25105 lodash.cloneDeep = cloneDeep;
25106 lodash.deburr = deburr;
25107 lodash.endsWith = endsWith;
25108 lodash.escape = escape;
25109 lodash.escapeRegExp = escapeRegExp;
25110 lodash.every = every;
25111 lodash.find = find;
25112 lodash.findIndex = findIndex;
25113 lodash.findKey = findKey;
25114 lodash.findLast = findLast;
25115 lodash.findLastIndex = findLastIndex;
25116 lodash.findLastKey = findLastKey;
25117 lodash.findWhere = findWhere;
25118 lodash.first = first;
25119 lodash.floor = floor;
25120 lodash.get = get;
25121 lodash.gt = gt;
25122 lodash.gte = gte;
25123 lodash.has = has;
25124 lodash.identity = identity;
25125 lodash.includes = includes;
25126 lodash.indexOf = indexOf;
25127 lodash.inRange = inRange;
25128 lodash.isArguments = isArguments;
25129 lodash.isArray = isArray;
25130 lodash.isBoolean = isBoolean;
25131 lodash.isDate = isDate;
25132 lodash.isElement = isElement;
25133 lodash.isEmpty = isEmpty;
25134 lodash.isEqual = isEqual;
25135 lodash.isError = isError;
25136 lodash.isFinite = isFinite;
25137 lodash.isFunction = isFunction;
25138 lodash.isMatch = isMatch;
25139 lodash.isNaN = isNaN;
25140 lodash.isNative = isNative;
25141 lodash.isNull = isNull;
25142 lodash.isNumber = isNumber;
25143 lodash.isObject = isObject;
25144 lodash.isPlainObject = isPlainObject;
25145 lodash.isRegExp = isRegExp;
25146 lodash.isString = isString;
25147 lodash.isTypedArray = isTypedArray;
25148 lodash.isUndefined = isUndefined;
25149 lodash.kebabCase = kebabCase;
25150 lodash.last = last;
25151 lodash.lastIndexOf = lastIndexOf;
25152 lodash.lt = lt;
25153 lodash.lte = lte;
25154 lodash.max = max;
25155 lodash.min = min;
25156 lodash.noConflict = noConflict;
25157 lodash.noop = noop;
25158 lodash.now = now;
25159 lodash.pad = pad;
25160 lodash.padLeft = padLeft;
25161 lodash.padRight = padRight;
25162 lodash.parseInt = parseInt;
25163 lodash.random = random;
25164 lodash.reduce = reduce;
25165 lodash.reduceRight = reduceRight;
25166 lodash.repeat = repeat;
25167 lodash.result = result;
25168 lodash.round = round;
25169 lodash.runInContext = runInContext;
25170 lodash.size = size;
25171 lodash.snakeCase = snakeCase;
25172 lodash.some = some;
25173 lodash.sortedIndex = sortedIndex;
25174 lodash.sortedLastIndex = sortedLastIndex;
25175 lodash.startCase = startCase;
25176 lodash.startsWith = startsWith;
25177 lodash.sum = sum;
25178 lodash.template = template;
25179 lodash.trim = trim;
25180 lodash.trimLeft = trimLeft;
25181 lodash.trimRight = trimRight;
25182 lodash.trunc = trunc;
25183 lodash.unescape = unescape;
25184 lodash.uniqueId = uniqueId;
25185 lodash.words = words;
25186
25187 // Add aliases.
25188 lodash.all = every;
25189 lodash.any = some;
25190 lodash.contains = includes;
25191 lodash.eq = isEqual;
25192 lodash.detect = find;
25193 lodash.foldl = reduce;
25194 lodash.foldr = reduceRight;
25195 lodash.head = first;
25196 lodash.include = includes;
25197 lodash.inject = reduce;
25198
25199 mixin(lodash, (function() {
25200 var source = {};
25201 baseForOwn(lodash, function(func, methodName) {
25202 if (!lodash.prototype[methodName]) {
25203 source[methodName] = func;
25204 }
25205 });
25206 return source;
25207 }()), false);
25208
25209 /*------------------------------------------------------------------------*/
25210
25211 // Add functions capable of returning wrapped and unwrapped values when chaining.
25212 lodash.sample = sample;
25213
25214 lodash.prototype.sample = function(n) {
25215 if (!this.__chain__ && n == null) {
25216 return sample(this.value());
25217 }
25218 return this.thru(function(value) {
25219 return sample(value, n);
25220 });
25221 };
25222
25223 /*------------------------------------------------------------------------*/
25224
25225 /**
25226 * The semantic version number.
25227 *
25228 * @static
25229 * @memberOf _
25230 * @type string
25231 */
25232 lodash.VERSION = VERSION;
25233
25234 // Assign default placeholders.
25235 arrayEach(['bind', 'bindKey', 'curry', 'curryRight', 'partial', 'partialRight'], function(methodName) {
25236 lodash[methodName].placeholder = lodash;
25237 });
25238
25239 // Add `LazyWrapper` methods for `_.drop` and `_.take` variants.
25240 arrayEach(['drop', 'take'], function(methodName, index) {
25241 LazyWrapper.prototype[methodName] = function(n) {
25242 var filtered = this.__filtered__;
25243 if (filtered && !index) {
25244 return new LazyWrapper(this);
25245 }
25246 n = n == null ? 1 : nativeMax(nativeFloor(n) || 0, 0);
25247
25248 var result = this.clone();
25249 if (filtered) {
25250 result.__takeCount__ = nativeMin(result.__takeCount__, n);
25251 } else {
25252 result.__views__.push({ 'size': n, 'type': methodName + (result.__dir__ < 0 ? 'Right' : '') });
25253 }
25254 return result;
25255 };
25256
25257 LazyWrapper.prototype[methodName + 'Right'] = function(n) {
25258 return this.reverse()[methodName](n).reverse();
25259 };
25260 });
25261
25262 // Add `LazyWrapper` methods that accept an `iteratee` value.
25263 arrayEach(['filter', 'map', 'takeWhile'], function(methodName, index) {
25264 var type = index + 1,
25265 isFilter = type != LAZY_MAP_FLAG;
25266
25267 LazyWrapper.prototype[methodName] = function(iteratee, thisArg) {
25268 var result = this.clone();
25269 result.__iteratees__.push({ 'iteratee': getCallback(iteratee, thisArg, 1), 'type': type });
25270 result.__filtered__ = result.__filtered__ || isFilter;
25271 return result;
25272 };
25273 });
25274
25275 // Add `LazyWrapper` methods for `_.first` and `_.last`.
25276 arrayEach(['first', 'last'], function(methodName, index) {
25277 var takeName = 'take' + (index ? 'Right' : '');
25278
25279 LazyWrapper.prototype[methodName] = function() {
25280 return this[takeName](1).value()[0];
25281 };
25282 });
25283
25284 // Add `LazyWrapper` methods for `_.initial` and `_.rest`.
25285 arrayEach(['initial', 'rest'], function(methodName, index) {
25286 var dropName = 'drop' + (index ? '' : 'Right');
25287
25288 LazyWrapper.prototype[methodName] = function() {
25289 return this.__filtered__ ? new LazyWrapper(this) : this[dropName](1);
25290 };
25291 });
25292
25293 // Add `LazyWrapper` methods for `_.pluck` and `_.where`.
25294 arrayEach(['pluck', 'where'], function(methodName, index) {
25295 var operationName = index ? 'filter' : 'map',
25296 createCallback = index ? baseMatches : property;
25297
25298 LazyWrapper.prototype[methodName] = function(value) {
25299 return this[operationName](createCallback(value));
25300 };
25301 });
25302
25303 LazyWrapper.prototype.compact = function() {
25304 return this.filter(identity);
25305 };
25306
25307 LazyWrapper.prototype.reject = function(predicate, thisArg) {
25308 predicate = getCallback(predicate, thisArg, 1);
25309 return this.filter(function(value) {
25310 return !predicate(value);
25311 });
25312 };
25313
25314 LazyWrapper.prototype.slice = function(start, end) {
25315 start = start == null ? 0 : (+start || 0);
25316
25317 var result = this;
25318 if (result.__filtered__ && (start > 0 || end < 0)) {
25319 return new LazyWrapper(result);
25320 }
25321 if (start < 0) {
25322 result = result.takeRight(-start);
25323 } else if (start) {
25324 result = result.drop(start);
25325 }
25326 if (end !== undefined) {
25327 end = (+end || 0);
25328 result = end < 0 ? result.dropRight(-end) : result.take(end - start);
25329 }
25330 return result;
25331 };
25332
25333 LazyWrapper.prototype.takeRightWhile = function(predicate, thisArg) {
25334 return this.reverse().takeWhile(predicate, thisArg).reverse();
25335 };
25336
25337 LazyWrapper.prototype.toArray = function() {
25338 return this.take(POSITIVE_INFINITY);
25339 };
25340
25341 // Add `LazyWrapper` methods to `lodash.prototype`.
25342 baseForOwn(LazyWrapper.prototype, function(func, methodName) {
25343 var checkIteratee = /^(?:filter|map|reject)|While$/.test(methodName),
25344 retUnwrapped = /^(?:first|last)$/.test(methodName),
25345 lodashFunc = lodash[retUnwrapped ? ('take' + (methodName == 'last' ? 'Right' : '')) : methodName];
25346
25347 if (!lodashFunc) {
25348 return;
25349 }
25350 lodash.prototype[methodName] = function() {
25351 var args = retUnwrapped ? [1] : arguments,
25352 chainAll = this.__chain__,
25353 value = this.__wrapped__,
25354 isHybrid = !!this.__actions__.length,
25355 isLazy = value instanceof LazyWrapper,
25356 iteratee = args[0],
25357 useLazy = isLazy || isArray(value);
25358
25359 if (useLazy && checkIteratee && typeof iteratee == 'function' && iteratee.length != 1) {
25360 // Avoid lazy use if the iteratee has a "length" value other than `1`.
25361 isLazy = useLazy = false;
25362 }
25363 var interceptor = function(value) {
25364 return (retUnwrapped && chainAll)
25365 ? lodashFunc(value, 1)[0]
25366 : lodashFunc.apply(undefined, arrayPush([value], args));
25367 };
25368
25369 var action = { 'func': thru, 'args': [interceptor], 'thisArg': undefined },
25370 onlyLazy = isLazy && !isHybrid;
25371
25372 if (retUnwrapped && !chainAll) {
25373 if (onlyLazy) {
25374 value = value.clone();
25375 value.__actions__.push(action);
25376 return func.call(value);
25377 }
25378 return lodashFunc.call(undefined, this.value())[0];
25379 }
25380 if (!retUnwrapped && useLazy) {
25381 value = onlyLazy ? value : new LazyWrapper(this);
25382 var result = func.apply(value, args);
25383 result.__actions__.push(action);
25384 return new LodashWrapper(result, chainAll);
25385 }
25386 return this.thru(interceptor);
25387 };
25388 });
25389
25390 // Add `Array` and `String` methods to `lodash.prototype`.
25391 arrayEach(['join', 'pop', 'push', 'replace', 'shift', 'sort', 'splice', 'split', 'unshift'], function(methodName) {
25392 var func = (/^(?:replace|split)$/.test(methodName) ? stringProto : arrayProto)[methodName],
25393 chainName = /^(?:push|sort|unshift)$/.test(methodName) ? 'tap' : 'thru',
25394 retUnwrapped = /^(?:join|pop|replace|shift)$/.test(methodName);
25395
25396 lodash.prototype[methodName] = function() {
25397 var args = arguments;
25398 if (retUnwrapped && !this.__chain__) {
25399 return func.apply(this.value(), args);
25400 }
25401 return this[chainName](function(value) {
25402 return func.apply(value, args);
25403 });
25404 };
25405 });
25406
25407 // Map minified function names to their real names.
25408 baseForOwn(LazyWrapper.prototype, function(func, methodName) {
25409 var lodashFunc = lodash[methodName];
25410 if (lodashFunc) {
25411 var key = lodashFunc.name,
25412 names = realNames[key] || (realNames[key] = []);
25413
25414 names.push({ 'name': methodName, 'func': lodashFunc });
25415 }
25416 });
25417
25418 realNames[createHybridWrapper(undefined, BIND_KEY_FLAG).name] = [{ 'name': 'wrapper', 'func': undefined }];
25419
25420 // Add functions to the lazy wrapper.
25421 LazyWrapper.prototype.clone = lazyClone;
25422 LazyWrapper.prototype.reverse = lazyReverse;
25423 LazyWrapper.prototype.value = lazyValue;
25424
25425 // Add chaining functions to the `lodash` wrapper.
25426 lodash.prototype.chain = wrapperChain;
25427 lodash.prototype.commit = wrapperCommit;
25428 lodash.prototype.concat = wrapperConcat;
25429 lodash.prototype.plant = wrapperPlant;
25430 lodash.prototype.reverse = wrapperReverse;
25431 lodash.prototype.toString = wrapperToString;
25432 lodash.prototype.run = lodash.prototype.toJSON = lodash.prototype.valueOf = lodash.prototype.value = wrapperValue;
25433
25434 // Add function aliases to the `lodash` wrapper.
25435 lodash.prototype.collect = lodash.prototype.map;
25436 lodash.prototype.head = lodash.prototype.first;
25437 lodash.prototype.select = lodash.prototype.filter;
25438 lodash.prototype.tail = lodash.prototype.rest;
25439
25440 return lodash;
25441 }
25442
25443 /*--------------------------------------------------------------------------*/
25444
25445 // Export lodash.
25446 var _ = runInContext();
25447
25448 // Some AMD build optimizers like r.js check for condition patterns like the following:
25449 if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) {
25450 // Expose lodash to the global object when an AMD loader is present to avoid
25451 // errors in cases where lodash is loaded by a script tag and not intended
25452 // as an AMD module. See http://requirejs.org/docs/errors.html#mismatch for
25453 // more details.
25454 root._ = _;
25455
25456 // Define as an anonymous module so, through path mapping, it can be
25457 // referenced as the "underscore" module.
25458 define(function() {
25459 return _;
25460 });
25461 }
25462 // Check for `exports` after `define` in case a build optimizer adds an `exports` object.
25463 else if (freeExports && freeModule) {
25464 // Export for Node.js or RingoJS.
25465 if (moduleExports) {
25466 (freeModule.exports = _)._ = _;
25467 }
25468 // Export for Rhino with CommonJS support.
25469 else {
25470 freeExports._ = _;
25471 }
25472 }
25473 else {
25474 // Export for a browser or Rhino.
25475 root._ = _;
25476 }
25477}.call(this));
25478
25479}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
25480},{}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/ms/index.js":[function(require,module,exports){
25481/**
25482 * Helpers.
25483 */
25484
25485var s = 1000;
25486var m = s * 60;
25487var h = m * 60;
25488var d = h * 24;
25489var y = d * 365.25;
25490
25491/**
25492 * Parse or format the given `val`.
25493 *
25494 * Options:
25495 *
25496 * - `long` verbose formatting [false]
25497 *
25498 * @param {String|Number} val
25499 * @param {Object} options
25500 * @return {String|Number}
25501 * @api public
25502 */
25503
25504module.exports = function(val, options){
25505 options = options || {};
25506 if ('string' == typeof val) return parse(val);
25507 return options.long
25508 ? long(val)
25509 : short(val);
25510};
25511
25512/**
25513 * Parse the given `str` and return milliseconds.
25514 *
25515 * @param {String} str
25516 * @return {Number}
25517 * @api private
25518 */
25519
25520function parse(str) {
25521 str = '' + str;
25522 if (str.length > 10000) return;
25523 var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(str);
25524 if (!match) return;
25525 var n = parseFloat(match[1]);
25526 var type = (match[2] || 'ms').toLowerCase();
25527 switch (type) {
25528 case 'years':
25529 case 'year':
25530 case 'yrs':
25531 case 'yr':
25532 case 'y':
25533 return n * y;
25534 case 'days':
25535 case 'day':
25536 case 'd':
25537 return n * d;
25538 case 'hours':
25539 case 'hour':
25540 case 'hrs':
25541 case 'hr':
25542 case 'h':
25543 return n * h;
25544 case 'minutes':
25545 case 'minute':
25546 case 'mins':
25547 case 'min':
25548 case 'm':
25549 return n * m;
25550 case 'seconds':
25551 case 'second':
25552 case 'secs':
25553 case 'sec':
25554 case 's':
25555 return n * s;
25556 case 'milliseconds':
25557 case 'millisecond':
25558 case 'msecs':
25559 case 'msec':
25560 case 'ms':
25561 return n;
25562 }
25563}
25564
25565/**
25566 * Short format for `ms`.
25567 *
25568 * @param {Number} ms
25569 * @return {String}
25570 * @api private
25571 */
25572
25573function short(ms) {
25574 if (ms >= d) return Math.round(ms / d) + 'd';
25575 if (ms >= h) return Math.round(ms / h) + 'h';
25576 if (ms >= m) return Math.round(ms / m) + 'm';
25577 if (ms >= s) return Math.round(ms / s) + 's';
25578 return ms + 'ms';
25579}
25580
25581/**
25582 * Long format for `ms`.
25583 *
25584 * @param {Number} ms
25585 * @return {String}
25586 * @api private
25587 */
25588
25589function long(ms) {
25590 return plural(ms, d, 'day')
25591 || plural(ms, h, 'hour')
25592 || plural(ms, m, 'minute')
25593 || plural(ms, s, 'second')
25594 || ms + ' ms';
25595}
25596
25597/**
25598 * Pluralization helper.
25599 */
25600
25601function plural(ms, n, name) {
25602 if (ms < n) return;
25603 if (ms < n * 1.5) return Math.floor(ms / n) + ' ' + name;
25604 return Math.ceil(ms / n) + ' ' + name + 's';
25605}
25606
25607},{}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/parsejson/index.js":[function(require,module,exports){
25608(function (global){
25609/**
25610 * JSON parse.
25611 *
25612 * @see Based on jQuery#parseJSON (MIT) and JSON2
25613 * @api private
25614 */
25615
25616var rvalidchars = /^[\],:{}\s]*$/;
25617var rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g;
25618var rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g;
25619var rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g;
25620var rtrimLeft = /^\s+/;
25621var rtrimRight = /\s+$/;
25622
25623module.exports = function parsejson(data) {
25624 if ('string' != typeof data || !data) {
25625 return null;
25626 }
25627
25628 data = data.replace(rtrimLeft, '').replace(rtrimRight, '');
25629
25630 // Attempt to parse using the native JSON parser first
25631 if (global.JSON && JSON.parse) {
25632 return JSON.parse(data);
25633 }
25634
25635 if (rvalidchars.test(data.replace(rvalidescape, '@')
25636 .replace(rvalidtokens, ']')
25637 .replace(rvalidbraces, ''))) {
25638 return (new Function('return ' + data))();
25639 }
25640};
25641}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
25642},{}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/parseqs/index.js":[function(require,module,exports){
25643/**
25644 * Compiles a querystring
25645 * Returns string representation of the object
25646 *
25647 * @param {Object}
25648 * @api private
25649 */
25650
25651exports.encode = function (obj) {
25652 var str = '';
25653
25654 for (var i in obj) {
25655 if (obj.hasOwnProperty(i)) {
25656 if (str.length) str += '&';
25657 str += encodeURIComponent(i) + '=' + encodeURIComponent(obj[i]);
25658 }
25659 }
25660
25661 return str;
25662};
25663
25664/**
25665 * Parses a simple querystring into an object
25666 *
25667 * @param {String} qs
25668 * @api private
25669 */
25670
25671exports.decode = function(qs){
25672 var qry = {};
25673 var pairs = qs.split('&');
25674 for (var i = 0, l = pairs.length; i < l; i++) {
25675 var pair = pairs[i].split('=');
25676 qry[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
25677 }
25678 return qry;
25679};
25680
25681},{}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/parseuri/index.js":[function(require,module,exports){
25682/**
25683 * Parses an URI
25684 *
25685 * @author Steven Levithan <stevenlevithan.com> (MIT license)
25686 * @api private
25687 */
25688
25689var re = /^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
25690
25691var parts = [
25692 'source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'
25693];
25694
25695module.exports = function parseuri(str) {
25696 var src = str,
25697 b = str.indexOf('['),
25698 e = str.indexOf(']');
25699
25700 if (b != -1 && e != -1) {
25701 str = str.substring(0, b) + str.substring(b, e).replace(/:/g, ';') + str.substring(e, str.length);
25702 }
25703
25704 var m = re.exec(str || ''),
25705 uri = {},
25706 i = 14;
25707
25708 while (i--) {
25709 uri[parts[i]] = m[i] || '';
25710 }
25711
25712 if (b != -1 && e != -1) {
25713 uri.source = src;
25714 uri.host = uri.host.substring(1, uri.host.length - 1).replace(/;/g, ':');
25715 uri.authority = uri.authority.replace('[', '').replace(']', '').replace(/;/g, ':');
25716 uri.ipv6uri = true;
25717 }
25718
25719 return uri;
25720};
25721
25722},{}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/process/browser.js":[function(require,module,exports){
25723// shim for using process in browser
25724var process = module.exports = {};
25725
25726// cached from whatever global is present so that test runners that stub it
25727// don't break things. But we need to wrap it in a try catch in case it is
25728// wrapped in strict mode code which doesn't define any globals. It's inside a
25729// function because try/catches deoptimize in certain engines.
25730
25731var cachedSetTimeout;
25732var cachedClearTimeout;
25733
25734function defaultSetTimout() {
25735 throw new Error('setTimeout has not been defined');
25736}
25737function defaultClearTimeout () {
25738 throw new Error('clearTimeout has not been defined');
25739}
25740(function () {
25741 try {
25742 if (typeof setTimeout === 'function') {
25743 cachedSetTimeout = setTimeout;
25744 } else {
25745 cachedSetTimeout = defaultSetTimout;
25746 }
25747 } catch (e) {
25748 cachedSetTimeout = defaultSetTimout;
25749 }
25750 try {
25751 if (typeof clearTimeout === 'function') {
25752 cachedClearTimeout = clearTimeout;
25753 } else {
25754 cachedClearTimeout = defaultClearTimeout;
25755 }
25756 } catch (e) {
25757 cachedClearTimeout = defaultClearTimeout;
25758 }
25759} ())
25760function runTimeout(fun) {
25761 if (cachedSetTimeout === setTimeout) {
25762 //normal enviroments in sane situations
25763 return setTimeout(fun, 0);
25764 }
25765 // if setTimeout wasn't available but was latter defined
25766 if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
25767 cachedSetTimeout = setTimeout;
25768 return setTimeout(fun, 0);
25769 }
25770 try {
25771 // when when somebody has screwed with setTimeout but no I.E. maddness
25772 return cachedSetTimeout(fun, 0);
25773 } catch(e){
25774 try {
25775 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
25776 return cachedSetTimeout.call(null, fun, 0);
25777 } catch(e){
25778 // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
25779 return cachedSetTimeout.call(this, fun, 0);
25780 }
25781 }
25782
25783
25784}
25785function runClearTimeout(marker) {
25786 if (cachedClearTimeout === clearTimeout) {
25787 //normal enviroments in sane situations
25788 return clearTimeout(marker);
25789 }
25790 // if clearTimeout wasn't available but was latter defined
25791 if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
25792 cachedClearTimeout = clearTimeout;
25793 return clearTimeout(marker);
25794 }
25795 try {
25796 // when when somebody has screwed with setTimeout but no I.E. maddness
25797 return cachedClearTimeout(marker);
25798 } catch (e){
25799 try {
25800 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
25801 return cachedClearTimeout.call(null, marker);
25802 } catch (e){
25803 // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
25804 // Some versions of I.E. have different rules for clearTimeout vs setTimeout
25805 return cachedClearTimeout.call(this, marker);
25806 }
25807 }
25808
25809
25810
25811}
25812var queue = [];
25813var draining = false;
25814var currentQueue;
25815var queueIndex = -1;
25816
25817function cleanUpNextTick() {
25818 if (!draining || !currentQueue) {
25819 return;
25820 }
25821 draining = false;
25822 if (currentQueue.length) {
25823 queue = currentQueue.concat(queue);
25824 } else {
25825 queueIndex = -1;
25826 }
25827 if (queue.length) {
25828 drainQueue();
25829 }
25830}
25831
25832function drainQueue() {
25833 if (draining) {
25834 return;
25835 }
25836 var timeout = runTimeout(cleanUpNextTick);
25837 draining = true;
25838
25839 var len = queue.length;
25840 while(len) {
25841 currentQueue = queue;
25842 queue = [];
25843 while (++queueIndex < len) {
25844 if (currentQueue) {
25845 currentQueue[queueIndex].run();
25846 }
25847 }
25848 queueIndex = -1;
25849 len = queue.length;
25850 }
25851 currentQueue = null;
25852 draining = false;
25853 runClearTimeout(timeout);
25854}
25855
25856process.nextTick = function (fun) {
25857 var args = new Array(arguments.length - 1);
25858 if (arguments.length > 1) {
25859 for (var i = 1; i < arguments.length; i++) {
25860 args[i - 1] = arguments[i];
25861 }
25862 }
25863 queue.push(new Item(fun, args));
25864 if (queue.length === 1 && !draining) {
25865 runTimeout(drainQueue);
25866 }
25867};
25868
25869// v8 likes predictible objects
25870function Item(fun, array) {
25871 this.fun = fun;
25872 this.array = array;
25873}
25874Item.prototype.run = function () {
25875 this.fun.apply(null, this.array);
25876};
25877process.title = 'browser';
25878process.browser = true;
25879process.env = {};
25880process.argv = [];
25881process.version = ''; // empty string to avoid regexp issues
25882process.versions = {};
25883
25884function noop() {}
25885
25886process.on = noop;
25887process.addListener = noop;
25888process.once = noop;
25889process.off = noop;
25890process.removeListener = noop;
25891process.removeAllListeners = noop;
25892process.emit = noop;
25893
25894process.binding = function (name) {
25895 throw new Error('process.binding is not supported');
25896};
25897
25898process.cwd = function () { return '/' };
25899process.chdir = function (dir) {
25900 throw new Error('process.chdir is not supported');
25901};
25902process.umask = function() { return 0; };
25903
25904},{}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/lib/index.js":[function(require,module,exports){
25905
25906/**
25907 * Module dependencies.
25908 */
25909
25910var url = require('./url');
25911var parser = require('socket.io-parser');
25912var Manager = require('./manager');
25913var debug = require('debug')('socket.io-client');
25914
25915/**
25916 * Module exports.
25917 */
25918
25919module.exports = exports = lookup;
25920
25921/**
25922 * Managers cache.
25923 */
25924
25925var cache = exports.managers = {};
25926
25927/**
25928 * Looks up an existing `Manager` for multiplexing.
25929 * If the user summons:
25930 *
25931 * `io('http://localhost/a');`
25932 * `io('http://localhost/b');`
25933 *
25934 * We reuse the existing instance based on same scheme/port/host,
25935 * and we initialize sockets for each namespace.
25936 *
25937 * @api public
25938 */
25939
25940function lookup(uri, opts) {
25941 if (typeof uri == 'object') {
25942 opts = uri;
25943 uri = undefined;
25944 }
25945
25946 opts = opts || {};
25947
25948 var parsed = url(uri);
25949 var source = parsed.source;
25950 var id = parsed.id;
25951 var path = parsed.path;
25952 var sameNamespace = cache[id] && path in cache[id].nsps;
25953 var newConnection = opts.forceNew || opts['force new connection'] ||
25954 false === opts.multiplex || sameNamespace;
25955
25956 var io;
25957
25958 if (newConnection) {
25959 debug('ignoring socket cache for %s', source);
25960 io = Manager(source, opts);
25961 } else {
25962 if (!cache[id]) {
25963 debug('new io instance for %s', source);
25964 cache[id] = Manager(source, opts);
25965 }
25966 io = cache[id];
25967 }
25968
25969 return io.socket(parsed.path);
25970}
25971
25972/**
25973 * Protocol version.
25974 *
25975 * @api public
25976 */
25977
25978exports.protocol = parser.protocol;
25979
25980/**
25981 * `connect`.
25982 *
25983 * @param {String} uri
25984 * @api public
25985 */
25986
25987exports.connect = lookup;
25988
25989/**
25990 * Expose constructors for standalone build.
25991 *
25992 * @api public
25993 */
25994
25995exports.Manager = require('./manager');
25996exports.Socket = require('./socket');
25997
25998},{"./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/debug/browser.js","socket.io-parser":"/home/employee-2klic/projects/2klic_io-sdk/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){
25999
26000/**
26001 * Module dependencies.
26002 */
26003
26004var eio = require('engine.io-client');
26005var Socket = require('./socket');
26006var Emitter = require('component-emitter');
26007var parser = require('socket.io-parser');
26008var on = require('./on');
26009var bind = require('component-bind');
26010var debug = require('debug')('socket.io-client:manager');
26011var indexOf = require('indexof');
26012var Backoff = require('backo2');
26013
26014/**
26015 * IE6+ hasOwnProperty
26016 */
26017
26018var has = Object.prototype.hasOwnProperty;
26019
26020/**
26021 * Module exports
26022 */
26023
26024module.exports = Manager;
26025
26026/**
26027 * `Manager` constructor.
26028 *
26029 * @param {String} engine instance or engine uri/opts
26030 * @param {Object} options
26031 * @api public
26032 */
26033
26034function Manager(uri, opts){
26035 if (!(this instanceof Manager)) return new Manager(uri, opts);
26036 if (uri && ('object' == typeof uri)) {
26037 opts = uri;
26038 uri = undefined;
26039 }
26040 opts = opts || {};
26041
26042 opts.path = opts.path || '/socket.io';
26043 this.nsps = {};
26044 this.subs = [];
26045 this.opts = opts;
26046 this.reconnection(opts.reconnection !== false);
26047 this.reconnectionAttempts(opts.reconnectionAttempts || Infinity);
26048 this.reconnectionDelay(opts.reconnectionDelay || 1000);
26049 this.reconnectionDelayMax(opts.reconnectionDelayMax || 5000);
26050 this.randomizationFactor(opts.randomizationFactor || 0.5);
26051 this.backoff = new Backoff({
26052 min: this.reconnectionDelay(),
26053 max: this.reconnectionDelayMax(),
26054 jitter: this.randomizationFactor()
26055 });
26056 this.timeout(null == opts.timeout ? 20000 : opts.timeout);
26057 this.readyState = 'closed';
26058 this.uri = uri;
26059 this.connecting = [];
26060 this.lastPing = null;
26061 this.encoding = false;
26062 this.packetBuffer = [];
26063 this.encoder = new parser.Encoder();
26064 this.decoder = new parser.Decoder();
26065 this.autoConnect = opts.autoConnect !== false;
26066 if (this.autoConnect) this.open();
26067}
26068
26069/**
26070 * Propagate given event to sockets and emit on `this`
26071 *
26072 * @api private
26073 */
26074
26075Manager.prototype.emitAll = function() {
26076 this.emit.apply(this, arguments);
26077 for (var nsp in this.nsps) {
26078 if (has.call(this.nsps, nsp)) {
26079 this.nsps[nsp].emit.apply(this.nsps[nsp], arguments);
26080 }
26081 }
26082};
26083
26084/**
26085 * Update `socket.id` of all sockets
26086 *
26087 * @api private
26088 */
26089
26090Manager.prototype.updateSocketIds = function(){
26091 for (var nsp in this.nsps) {
26092 if (has.call(this.nsps, nsp)) {
26093 this.nsps[nsp].id = this.engine.id;
26094 }
26095 }
26096};
26097
26098/**
26099 * Mix in `Emitter`.
26100 */
26101
26102Emitter(Manager.prototype);
26103
26104/**
26105 * Sets the `reconnection` config.
26106 *
26107 * @param {Boolean} true/false if it should automatically reconnect
26108 * @return {Manager} self or value
26109 * @api public
26110 */
26111
26112Manager.prototype.reconnection = function(v){
26113 if (!arguments.length) return this._reconnection;
26114 this._reconnection = !!v;
26115 return this;
26116};
26117
26118/**
26119 * Sets the reconnection attempts config.
26120 *
26121 * @param {Number} max reconnection attempts before giving up
26122 * @return {Manager} self or value
26123 * @api public
26124 */
26125
26126Manager.prototype.reconnectionAttempts = function(v){
26127 if (!arguments.length) return this._reconnectionAttempts;
26128 this._reconnectionAttempts = v;
26129 return this;
26130};
26131
26132/**
26133 * Sets the delay between reconnections.
26134 *
26135 * @param {Number} delay
26136 * @return {Manager} self or value
26137 * @api public
26138 */
26139
26140Manager.prototype.reconnectionDelay = function(v){
26141 if (!arguments.length) return this._reconnectionDelay;
26142 this._reconnectionDelay = v;
26143 this.backoff && this.backoff.setMin(v);
26144 return this;
26145};
26146
26147Manager.prototype.randomizationFactor = function(v){
26148 if (!arguments.length) return this._randomizationFactor;
26149 this._randomizationFactor = v;
26150 this.backoff && this.backoff.setJitter(v);
26151 return this;
26152};
26153
26154/**
26155 * Sets the maximum delay between reconnections.
26156 *
26157 * @param {Number} delay
26158 * @return {Manager} self or value
26159 * @api public
26160 */
26161
26162Manager.prototype.reconnectionDelayMax = function(v){
26163 if (!arguments.length) return this._reconnectionDelayMax;
26164 this._reconnectionDelayMax = v;
26165 this.backoff && this.backoff.setMax(v);
26166 return this;
26167};
26168
26169/**
26170 * Sets the connection timeout. `false` to disable
26171 *
26172 * @return {Manager} self or value
26173 * @api public
26174 */
26175
26176Manager.prototype.timeout = function(v){
26177 if (!arguments.length) return this._timeout;
26178 this._timeout = v;
26179 return this;
26180};
26181
26182/**
26183 * Starts trying to reconnect if reconnection is enabled and we have not
26184 * started reconnecting yet
26185 *
26186 * @api private
26187 */
26188
26189Manager.prototype.maybeReconnectOnOpen = function() {
26190 // Only try to reconnect if it's the first time we're connecting
26191 if (!this.reconnecting && this._reconnection && this.backoff.attempts === 0) {
26192 // keeps reconnection from firing twice for the same reconnection loop
26193 this.reconnect();
26194 }
26195};
26196
26197
26198/**
26199 * Sets the current transport `socket`.
26200 *
26201 * @param {Function} optional, callback
26202 * @return {Manager} self
26203 * @api public
26204 */
26205
26206Manager.prototype.open =
26207Manager.prototype.connect = function(fn){
26208 debug('readyState %s', this.readyState);
26209 if (~this.readyState.indexOf('open')) return this;
26210
26211 debug('opening %s', this.uri);
26212 this.engine = eio(this.uri, this.opts);
26213 var socket = this.engine;
26214 var self = this;
26215 this.readyState = 'opening';
26216 this.skipReconnect = false;
26217
26218 // emit `open`
26219 var openSub = on(socket, 'open', function() {
26220 self.onopen();
26221 fn && fn();
26222 });
26223
26224 // emit `connect_error`
26225 var errorSub = on(socket, 'error', function(data){
26226 debug('connect_error');
26227 self.cleanup();
26228 self.readyState = 'closed';
26229 self.emitAll('connect_error', data);
26230 if (fn) {
26231 var err = new Error('Connection error');
26232 err.data = data;
26233 fn(err);
26234 } else {
26235 // Only do this if there is no fn to handle the error
26236 self.maybeReconnectOnOpen();
26237 }
26238 });
26239
26240 // emit `connect_timeout`
26241 if (false !== this._timeout) {
26242 var timeout = this._timeout;
26243 debug('connect attempt will timeout after %d', timeout);
26244
26245 // set timer
26246 var timer = setTimeout(function(){
26247 debug('connect attempt timed out after %d', timeout);
26248 openSub.destroy();
26249 socket.close();
26250 socket.emit('error', 'timeout');
26251 self.emitAll('connect_timeout', timeout);
26252 }, timeout);
26253
26254 this.subs.push({
26255 destroy: function(){
26256 clearTimeout(timer);
26257 }
26258 });
26259 }
26260
26261 this.subs.push(openSub);
26262 this.subs.push(errorSub);
26263
26264 return this;
26265};
26266
26267/**
26268 * Called upon transport open.
26269 *
26270 * @api private
26271 */
26272
26273Manager.prototype.onopen = function(){
26274 debug('open');
26275
26276 // clear old subs
26277 this.cleanup();
26278
26279 // mark as open
26280 this.readyState = 'open';
26281 this.emit('open');
26282
26283 // add new subs
26284 var socket = this.engine;
26285 this.subs.push(on(socket, 'data', bind(this, 'ondata')));
26286 this.subs.push(on(socket, 'ping', bind(this, 'onping')));
26287 this.subs.push(on(socket, 'pong', bind(this, 'onpong')));
26288 this.subs.push(on(socket, 'error', bind(this, 'onerror')));
26289 this.subs.push(on(socket, 'close', bind(this, 'onclose')));
26290 this.subs.push(on(this.decoder, 'decoded', bind(this, 'ondecoded')));
26291};
26292
26293/**
26294 * Called upon a ping.
26295 *
26296 * @api private
26297 */
26298
26299Manager.prototype.onping = function(){
26300 this.lastPing = new Date;
26301 this.emitAll('ping');
26302};
26303
26304/**
26305 * Called upon a packet.
26306 *
26307 * @api private
26308 */
26309
26310Manager.prototype.onpong = function(){
26311 this.emitAll('pong', new Date - this.lastPing);
26312};
26313
26314/**
26315 * Called with data.
26316 *
26317 * @api private
26318 */
26319
26320Manager.prototype.ondata = function(data){
26321 this.decoder.add(data);
26322};
26323
26324/**
26325 * Called when parser fully decodes a packet.
26326 *
26327 * @api private
26328 */
26329
26330Manager.prototype.ondecoded = function(packet) {
26331 this.emit('packet', packet);
26332};
26333
26334/**
26335 * Called upon socket error.
26336 *
26337 * @api private
26338 */
26339
26340Manager.prototype.onerror = function(err){
26341 debug('error', err);
26342 this.emitAll('error', err);
26343};
26344
26345/**
26346 * Creates a new socket for the given `nsp`.
26347 *
26348 * @return {Socket}
26349 * @api public
26350 */
26351
26352Manager.prototype.socket = function(nsp){
26353 var socket = this.nsps[nsp];
26354 if (!socket) {
26355 socket = new Socket(this, nsp);
26356 this.nsps[nsp] = socket;
26357 var self = this;
26358 socket.on('connecting', onConnecting);
26359 socket.on('connect', function(){
26360 socket.id = self.engine.id;
26361 });
26362
26363 if (this.autoConnect) {
26364 // manually call here since connecting evnet is fired before listening
26365 onConnecting();
26366 }
26367 }
26368
26369 function onConnecting() {
26370 if (!~indexOf(self.connecting, socket)) {
26371 self.connecting.push(socket);
26372 }
26373 }
26374
26375 return socket;
26376};
26377
26378/**
26379 * Called upon a socket close.
26380 *
26381 * @param {Socket} socket
26382 */
26383
26384Manager.prototype.destroy = function(socket){
26385 var index = indexOf(this.connecting, socket);
26386 if (~index) this.connecting.splice(index, 1);
26387 if (this.connecting.length) return;
26388
26389 this.close();
26390};
26391
26392/**
26393 * Writes a packet.
26394 *
26395 * @param {Object} packet
26396 * @api private
26397 */
26398
26399Manager.prototype.packet = function(packet){
26400 debug('writing packet %j', packet);
26401 var self = this;
26402
26403 if (!self.encoding) {
26404 // encode, then write to engine with result
26405 self.encoding = true;
26406 this.encoder.encode(packet, function(encodedPackets) {
26407 for (var i = 0; i < encodedPackets.length; i++) {
26408 self.engine.write(encodedPackets[i], packet.options);
26409 }
26410 self.encoding = false;
26411 self.processPacketQueue();
26412 });
26413 } else { // add packet to the queue
26414 self.packetBuffer.push(packet);
26415 }
26416};
26417
26418/**
26419 * If packet buffer is non-empty, begins encoding the
26420 * next packet in line.
26421 *
26422 * @api private
26423 */
26424
26425Manager.prototype.processPacketQueue = function() {
26426 if (this.packetBuffer.length > 0 && !this.encoding) {
26427 var pack = this.packetBuffer.shift();
26428 this.packet(pack);
26429 }
26430};
26431
26432/**
26433 * Clean up transport subscriptions and packet buffer.
26434 *
26435 * @api private
26436 */
26437
26438Manager.prototype.cleanup = function(){
26439 debug('cleanup');
26440
26441 var sub;
26442 while (sub = this.subs.shift()) sub.destroy();
26443
26444 this.packetBuffer = [];
26445 this.encoding = false;
26446 this.lastPing = null;
26447
26448 this.decoder.destroy();
26449};
26450
26451/**
26452 * Close the current socket.
26453 *
26454 * @api private
26455 */
26456
26457Manager.prototype.close =
26458Manager.prototype.disconnect = function(){
26459 debug('disconnect');
26460 this.skipReconnect = true;
26461 this.reconnecting = false;
26462 if ('opening' == this.readyState) {
26463 // `onclose` will not fire because
26464 // an open event never happened
26465 this.cleanup();
26466 }
26467 this.backoff.reset();
26468 this.readyState = 'closed';
26469 if (this.engine) this.engine.close();
26470};
26471
26472/**
26473 * Called upon engine close.
26474 *
26475 * @api private
26476 */
26477
26478Manager.prototype.onclose = function(reason){
26479 debug('onclose');
26480
26481 this.cleanup();
26482 this.backoff.reset();
26483 this.readyState = 'closed';
26484 this.emit('close', reason);
26485
26486 if (this._reconnection && !this.skipReconnect) {
26487 this.reconnect();
26488 }
26489};
26490
26491/**
26492 * Attempt a reconnection.
26493 *
26494 * @api private
26495 */
26496
26497Manager.prototype.reconnect = function(){
26498 if (this.reconnecting || this.skipReconnect) return this;
26499
26500 var self = this;
26501
26502 if (this.backoff.attempts >= this._reconnectionAttempts) {
26503 debug('reconnect failed');
26504 this.backoff.reset();
26505 this.emitAll('reconnect_failed');
26506 this.reconnecting = false;
26507 } else {
26508 var delay = this.backoff.duration();
26509 debug('will wait %dms before reconnect attempt', delay);
26510
26511 this.reconnecting = true;
26512 var timer = setTimeout(function(){
26513 if (self.skipReconnect) return;
26514
26515 debug('attempting reconnect');
26516 self.emitAll('reconnect_attempt', self.backoff.attempts);
26517 self.emitAll('reconnecting', self.backoff.attempts);
26518
26519 // check again for the case socket closed in above events
26520 if (self.skipReconnect) return;
26521
26522 self.open(function(err){
26523 if (err) {
26524 debug('reconnect attempt error');
26525 self.reconnecting = false;
26526 self.reconnect();
26527 self.emitAll('reconnect_error', err.data);
26528 } else {
26529 debug('reconnect success');
26530 self.onreconnect();
26531 }
26532 });
26533 }, delay);
26534
26535 this.subs.push({
26536 destroy: function(){
26537 clearTimeout(timer);
26538 }
26539 });
26540 }
26541};
26542
26543/**
26544 * Called upon successful reconnect.
26545 *
26546 * @api private
26547 */
26548
26549Manager.prototype.onreconnect = function(){
26550 var attempt = this.backoff.attempts;
26551 this.reconnecting = false;
26552 this.backoff.reset();
26553 this.updateSocketIds();
26554 this.emitAll('reconnect', attempt);
26555};
26556
26557},{"./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/backo2/index.js","component-bind":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/component-bind/index.js","component-emitter":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/component-emitter/index.js","debug":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/debug/browser.js","engine.io-client":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/engine.io-client/index.js","indexof":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/indexof/index.js","socket.io-parser":"/home/employee-2klic/projects/2klic_io-sdk/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){
26558
26559/**
26560 * Module exports.
26561 */
26562
26563module.exports = on;
26564
26565/**
26566 * Helper for subscriptions.
26567 *
26568 * @param {Object|EventEmitter} obj with `Emitter` mixin or `EventEmitter`
26569 * @param {String} event name
26570 * @param {Function} callback
26571 * @api public
26572 */
26573
26574function on(obj, ev, fn) {
26575 obj.on(ev, fn);
26576 return {
26577 destroy: function(){
26578 obj.removeListener(ev, fn);
26579 }
26580 };
26581}
26582
26583},{}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-client/lib/socket.js":[function(require,module,exports){
26584
26585/**
26586 * Module dependencies.
26587 */
26588
26589var parser = require('socket.io-parser');
26590var Emitter = require('component-emitter');
26591var toArray = require('to-array');
26592var on = require('./on');
26593var bind = require('component-bind');
26594var debug = require('debug')('socket.io-client:socket');
26595var hasBin = require('has-binary');
26596
26597/**
26598 * Module exports.
26599 */
26600
26601module.exports = exports = Socket;
26602
26603/**
26604 * Internal events (blacklisted).
26605 * These events can't be emitted by the user.
26606 *
26607 * @api private
26608 */
26609
26610var events = {
26611 connect: 1,
26612 connect_error: 1,
26613 connect_timeout: 1,
26614 connecting: 1,
26615 disconnect: 1,
26616 error: 1,
26617 reconnect: 1,
26618 reconnect_attempt: 1,
26619 reconnect_failed: 1,
26620 reconnect_error: 1,
26621 reconnecting: 1,
26622 ping: 1,
26623 pong: 1
26624};
26625
26626/**
26627 * Shortcut to `Emitter#emit`.
26628 */
26629
26630var emit = Emitter.prototype.emit;
26631
26632/**
26633 * `Socket` constructor.
26634 *
26635 * @api public
26636 */
26637
26638function Socket(io, nsp){
26639 this.io = io;
26640 this.nsp = nsp;
26641 this.json = this; // compat
26642 this.ids = 0;
26643 this.acks = {};
26644 this.receiveBuffer = [];
26645 this.sendBuffer = [];
26646 this.connected = false;
26647 this.disconnected = true;
26648 if (this.io.autoConnect) this.open();
26649}
26650
26651/**
26652 * Mix in `Emitter`.
26653 */
26654
26655Emitter(Socket.prototype);
26656
26657/**
26658 * Subscribe to open, close and packet events
26659 *
26660 * @api private
26661 */
26662
26663Socket.prototype.subEvents = function() {
26664 if (this.subs) return;
26665
26666 var io = this.io;
26667 this.subs = [
26668 on(io, 'open', bind(this, 'onopen')),
26669 on(io, 'packet', bind(this, 'onpacket')),
26670 on(io, 'close', bind(this, 'onclose'))
26671 ];
26672};
26673
26674/**
26675 * "Opens" the socket.
26676 *
26677 * @api public
26678 */
26679
26680Socket.prototype.open =
26681Socket.prototype.connect = function(){
26682 if (this.connected) return this;
26683
26684 this.subEvents();
26685 this.io.open(); // ensure open
26686 if ('open' == this.io.readyState) this.onopen();
26687 this.emit('connecting');
26688 return this;
26689};
26690
26691/**
26692 * Sends a `message` event.
26693 *
26694 * @return {Socket} self
26695 * @api public
26696 */
26697
26698Socket.prototype.send = function(){
26699 var args = toArray(arguments);
26700 args.unshift('message');
26701 this.emit.apply(this, args);
26702 return this;
26703};
26704
26705/**
26706 * Override `emit`.
26707 * If the event is in `events`, it's emitted normally.
26708 *
26709 * @param {String} event name
26710 * @return {Socket} self
26711 * @api public
26712 */
26713
26714Socket.prototype.emit = function(ev){
26715 if (events.hasOwnProperty(ev)) {
26716 emit.apply(this, arguments);
26717 return this;
26718 }
26719
26720 var args = toArray(arguments);
26721 var parserType = parser.EVENT; // default
26722 if (hasBin(args)) { parserType = parser.BINARY_EVENT; } // binary
26723 var packet = { type: parserType, data: args };
26724
26725 packet.options = {};
26726 packet.options.compress = !this.flags || false !== this.flags.compress;
26727
26728 // event ack callback
26729 if ('function' == typeof args[args.length - 1]) {
26730 debug('emitting packet with ack id %d', this.ids);
26731 this.acks[this.ids] = args.pop();
26732 packet.id = this.ids++;
26733 }
26734
26735 if (this.connected) {
26736 this.packet(packet);
26737 } else {
26738 this.sendBuffer.push(packet);
26739 }
26740
26741 delete this.flags;
26742
26743 return this;
26744};
26745
26746/**
26747 * Sends a packet.
26748 *
26749 * @param {Object} packet
26750 * @api private
26751 */
26752
26753Socket.prototype.packet = function(packet){
26754 packet.nsp = this.nsp;
26755 this.io.packet(packet);
26756};
26757
26758/**
26759 * Called upon engine `open`.
26760 *
26761 * @api private
26762 */
26763
26764Socket.prototype.onopen = function(){
26765 debug('transport is open - connecting');
26766
26767 // write connect packet if necessary
26768 if ('/' != this.nsp) {
26769 this.packet({ type: parser.CONNECT });
26770 }
26771};
26772
26773/**
26774 * Called upon engine `close`.
26775 *
26776 * @param {String} reason
26777 * @api private
26778 */
26779
26780Socket.prototype.onclose = function(reason){
26781 debug('close (%s)', reason);
26782 this.connected = false;
26783 this.disconnected = true;
26784 delete this.id;
26785 this.emit('disconnect', reason);
26786};
26787
26788/**
26789 * Called with socket packet.
26790 *
26791 * @param {Object} packet
26792 * @api private
26793 */
26794
26795Socket.prototype.onpacket = function(packet){
26796 if (packet.nsp != this.nsp) return;
26797
26798 switch (packet.type) {
26799 case parser.CONNECT:
26800 this.onconnect();
26801 break;
26802
26803 case parser.EVENT:
26804 this.onevent(packet);
26805 break;
26806
26807 case parser.BINARY_EVENT:
26808 this.onevent(packet);
26809 break;
26810
26811 case parser.ACK:
26812 this.onack(packet);
26813 break;
26814
26815 case parser.BINARY_ACK:
26816 this.onack(packet);
26817 break;
26818
26819 case parser.DISCONNECT:
26820 this.ondisconnect();
26821 break;
26822
26823 case parser.ERROR:
26824 this.emit('error', packet.data);
26825 break;
26826 }
26827};
26828
26829/**
26830 * Called upon a server event.
26831 *
26832 * @param {Object} packet
26833 * @api private
26834 */
26835
26836Socket.prototype.onevent = function(packet){
26837 var args = packet.data || [];
26838 debug('emitting event %j', args);
26839
26840 if (null != packet.id) {
26841 debug('attaching ack callback to event');
26842 args.push(this.ack(packet.id));
26843 }
26844
26845 if (this.connected) {
26846 emit.apply(this, args);
26847 } else {
26848 this.receiveBuffer.push(args);
26849 }
26850};
26851
26852/**
26853 * Produces an ack callback to emit with an event.
26854 *
26855 * @api private
26856 */
26857
26858Socket.prototype.ack = function(id){
26859 var self = this;
26860 var sent = false;
26861 return function(){
26862 // prevent double callbacks
26863 if (sent) return;
26864 sent = true;
26865 var args = toArray(arguments);
26866 debug('sending ack %j', args);
26867
26868 var type = hasBin(args) ? parser.BINARY_ACK : parser.ACK;
26869 self.packet({
26870 type: type,
26871 id: id,
26872 data: args
26873 });
26874 };
26875};
26876
26877/**
26878 * Called upon a server acknowlegement.
26879 *
26880 * @param {Object} packet
26881 * @api private
26882 */
26883
26884Socket.prototype.onack = function(packet){
26885 var ack = this.acks[packet.id];
26886 if ('function' == typeof ack) {
26887 debug('calling ack %s with %j', packet.id, packet.data);
26888 ack.apply(this, packet.data);
26889 delete this.acks[packet.id];
26890 } else {
26891 debug('bad ack %s', packet.id);
26892 }
26893};
26894
26895/**
26896 * Called upon server connect.
26897 *
26898 * @api private
26899 */
26900
26901Socket.prototype.onconnect = function(){
26902 this.connected = true;
26903 this.disconnected = false;
26904 this.emit('connect');
26905 this.emitBuffered();
26906};
26907
26908/**
26909 * Emit buffered events (received and emitted).
26910 *
26911 * @api private
26912 */
26913
26914Socket.prototype.emitBuffered = function(){
26915 var i;
26916 for (i = 0; i < this.receiveBuffer.length; i++) {
26917 emit.apply(this, this.receiveBuffer[i]);
26918 }
26919 this.receiveBuffer = [];
26920
26921 for (i = 0; i < this.sendBuffer.length; i++) {
26922 this.packet(this.sendBuffer[i]);
26923 }
26924 this.sendBuffer = [];
26925};
26926
26927/**
26928 * Called upon server disconnect.
26929 *
26930 * @api private
26931 */
26932
26933Socket.prototype.ondisconnect = function(){
26934 debug('server disconnect (%s)', this.nsp);
26935 this.destroy();
26936 this.onclose('io server disconnect');
26937};
26938
26939/**
26940 * Called upon forced client/server side disconnections,
26941 * this method ensures the manager stops tracking us and
26942 * that reconnections don't get triggered for this.
26943 *
26944 * @api private.
26945 */
26946
26947Socket.prototype.destroy = function(){
26948 if (this.subs) {
26949 // clean subscriptions to avoid reconnections
26950 for (var i = 0; i < this.subs.length; i++) {
26951 this.subs[i].destroy();
26952 }
26953 this.subs = null;
26954 }
26955
26956 this.io.destroy(this);
26957};
26958
26959/**
26960 * Disconnects the socket manually.
26961 *
26962 * @return {Socket} self
26963 * @api public
26964 */
26965
26966Socket.prototype.close =
26967Socket.prototype.disconnect = function(){
26968 if (this.connected) {
26969 debug('performing disconnect (%s)', this.nsp);
26970 this.packet({ type: parser.DISCONNECT });
26971 }
26972
26973 // remove socket from pool
26974 this.destroy();
26975
26976 if (this.connected) {
26977 // fire events
26978 this.onclose('io client disconnect');
26979 }
26980 return this;
26981};
26982
26983/**
26984 * Sets the compress flag.
26985 *
26986 * @param {Boolean} if `true`, compresses the sending data
26987 * @return {Socket} self
26988 * @api public
26989 */
26990
26991Socket.prototype.compress = function(compress){
26992 this.flags = this.flags || {};
26993 this.flags.compress = compress;
26994 return this;
26995};
26996
26997},{"./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/component-bind/index.js","component-emitter":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/component-emitter/index.js","debug":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/debug/browser.js","has-binary":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/has-binary/index.js","socket.io-parser":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-parser/index.js","to-array":"/home/employee-2klic/projects/2klic_io-sdk/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){
26998(function (global){
26999
27000/**
27001 * Module dependencies.
27002 */
27003
27004var parseuri = require('parseuri');
27005var debug = require('debug')('socket.io-client:url');
27006
27007/**
27008 * Module exports.
27009 */
27010
27011module.exports = url;
27012
27013/**
27014 * URL parser.
27015 *
27016 * @param {String} url
27017 * @param {Object} An object meant to mimic window.location.
27018 * Defaults to window.location.
27019 * @api public
27020 */
27021
27022function url(uri, loc){
27023 var obj = uri;
27024
27025 // default to window.location
27026 var loc = loc || global.location;
27027 if (null == uri) uri = loc.protocol + '//' + loc.host;
27028
27029 // relative path support
27030 if ('string' == typeof uri) {
27031 if ('/' == uri.charAt(0)) {
27032 if ('/' == uri.charAt(1)) {
27033 uri = loc.protocol + uri;
27034 } else {
27035 uri = loc.host + uri;
27036 }
27037 }
27038
27039 if (!/^(https?|wss?):\/\//.test(uri)) {
27040 debug('protocol-less url %s', uri);
27041 if ('undefined' != typeof loc) {
27042 uri = loc.protocol + '//' + uri;
27043 } else {
27044 uri = 'https://' + uri;
27045 }
27046 }
27047
27048 // parse
27049 debug('parse %s', uri);
27050 obj = parseuri(uri);
27051 }
27052
27053 // make sure we treat `localhost:80` and `localhost` equally
27054 if (!obj.port) {
27055 if (/^(http|ws)$/.test(obj.protocol)) {
27056 obj.port = '80';
27057 }
27058 else if (/^(http|ws)s$/.test(obj.protocol)) {
27059 obj.port = '443';
27060 }
27061 }
27062
27063 obj.path = obj.path || '/';
27064
27065 var ipv6 = obj.host.indexOf(':') !== -1;
27066 var host = ipv6 ? '[' + obj.host + ']' : obj.host;
27067
27068 // define unique id
27069 obj.id = obj.protocol + '://' + host + ':' + obj.port;
27070 // define href
27071 obj.href = obj.protocol + '://' + host + (loc && loc.port == obj.port ? '' : (':' + obj.port));
27072
27073 return obj;
27074}
27075
27076}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
27077},{"debug":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/debug/browser.js","parseuri":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/parseuri/index.js"}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-parser/binary.js":[function(require,module,exports){
27078(function (global){
27079/*global Blob,File*/
27080
27081/**
27082 * Module requirements
27083 */
27084
27085var isArray = require('isarray');
27086var isBuf = require('./is-buffer');
27087
27088/**
27089 * Replaces every Buffer | ArrayBuffer in packet with a numbered placeholder.
27090 * Anything with blobs or files should be fed through removeBlobs before coming
27091 * here.
27092 *
27093 * @param {Object} packet - socket.io event packet
27094 * @return {Object} with deconstructed packet and list of buffers
27095 * @api public
27096 */
27097
27098exports.deconstructPacket = function(packet){
27099 var buffers = [];
27100 var packetData = packet.data;
27101
27102 function _deconstructPacket(data) {
27103 if (!data) return data;
27104
27105 if (isBuf(data)) {
27106 var placeholder = { _placeholder: true, num: buffers.length };
27107 buffers.push(data);
27108 return placeholder;
27109 } else if (isArray(data)) {
27110 var newData = new Array(data.length);
27111 for (var i = 0; i < data.length; i++) {
27112 newData[i] = _deconstructPacket(data[i]);
27113 }
27114 return newData;
27115 } else if ('object' == typeof data && !(data instanceof Date)) {
27116 var newData = {};
27117 for (var key in data) {
27118 newData[key] = _deconstructPacket(data[key]);
27119 }
27120 return newData;
27121 }
27122 return data;
27123 }
27124
27125 var pack = packet;
27126 pack.data = _deconstructPacket(packetData);
27127 pack.attachments = buffers.length; // number of binary 'attachments'
27128 return {packet: pack, buffers: buffers};
27129};
27130
27131/**
27132 * Reconstructs a binary packet from its placeholder packet and buffers
27133 *
27134 * @param {Object} packet - event packet with placeholders
27135 * @param {Array} buffers - binary buffers to put in placeholder positions
27136 * @return {Object} reconstructed packet
27137 * @api public
27138 */
27139
27140exports.reconstructPacket = function(packet, buffers) {
27141 var curPlaceHolder = 0;
27142
27143 function _reconstructPacket(data) {
27144 if (data && data._placeholder) {
27145 var buf = buffers[data.num]; // appropriate buffer (should be natural order anyway)
27146 return buf;
27147 } else if (isArray(data)) {
27148 for (var i = 0; i < data.length; i++) {
27149 data[i] = _reconstructPacket(data[i]);
27150 }
27151 return data;
27152 } else if (data && 'object' == typeof data) {
27153 for (var key in data) {
27154 data[key] = _reconstructPacket(data[key]);
27155 }
27156 return data;
27157 }
27158 return data;
27159 }
27160
27161 packet.data = _reconstructPacket(packet.data);
27162 packet.attachments = undefined; // no longer useful
27163 return packet;
27164};
27165
27166/**
27167 * Asynchronously removes Blobs or Files from data via
27168 * FileReader's readAsArrayBuffer method. Used before encoding
27169 * data as msgpack. Calls callback with the blobless data.
27170 *
27171 * @param {Object} data
27172 * @param {Function} callback
27173 * @api private
27174 */
27175
27176exports.removeBlobs = function(data, callback) {
27177 function _removeBlobs(obj, curKey, containingObject) {
27178 if (!obj) return obj;
27179
27180 // convert any blob
27181 if ((global.Blob && obj instanceof Blob) ||
27182 (global.File && obj instanceof File)) {
27183 pendingBlobs++;
27184
27185 // async filereader
27186 var fileReader = new FileReader();
27187 fileReader.onload = function() { // this.result == arraybuffer
27188 if (containingObject) {
27189 containingObject[curKey] = this.result;
27190 }
27191 else {
27192 bloblessData = this.result;
27193 }
27194
27195 // if nothing pending its callback time
27196 if(! --pendingBlobs) {
27197 callback(bloblessData);
27198 }
27199 };
27200
27201 fileReader.readAsArrayBuffer(obj); // blob -> arraybuffer
27202 } else if (isArray(obj)) { // handle array
27203 for (var i = 0; i < obj.length; i++) {
27204 _removeBlobs(obj[i], i, obj);
27205 }
27206 } else if (obj && 'object' == typeof obj && !isBuf(obj)) { // and object
27207 for (var key in obj) {
27208 _removeBlobs(obj[key], key, obj);
27209 }
27210 }
27211 }
27212
27213 var pendingBlobs = 0;
27214 var bloblessData = data;
27215 _removeBlobs(bloblessData);
27216 if (!pendingBlobs) {
27217 callback(bloblessData);
27218 }
27219};
27220
27221}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
27222},{"./is-buffer":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-parser/is-buffer.js","isarray":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-parser/node_modules/isarray/index.js"}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-parser/index.js":[function(require,module,exports){
27223
27224/**
27225 * Module dependencies.
27226 */
27227
27228var debug = require('debug')('socket.io-parser');
27229var json = require('json3');
27230var isArray = require('isarray');
27231var Emitter = require('component-emitter');
27232var binary = require('./binary');
27233var isBuf = require('./is-buffer');
27234
27235/**
27236 * Protocol version.
27237 *
27238 * @api public
27239 */
27240
27241exports.protocol = 4;
27242
27243/**
27244 * Packet types.
27245 *
27246 * @api public
27247 */
27248
27249exports.types = [
27250 'CONNECT',
27251 'DISCONNECT',
27252 'EVENT',
27253 'ACK',
27254 'ERROR',
27255 'BINARY_EVENT',
27256 'BINARY_ACK'
27257];
27258
27259/**
27260 * Packet type `connect`.
27261 *
27262 * @api public
27263 */
27264
27265exports.CONNECT = 0;
27266
27267/**
27268 * Packet type `disconnect`.
27269 *
27270 * @api public
27271 */
27272
27273exports.DISCONNECT = 1;
27274
27275/**
27276 * Packet type `event`.
27277 *
27278 * @api public
27279 */
27280
27281exports.EVENT = 2;
27282
27283/**
27284 * Packet type `ack`.
27285 *
27286 * @api public
27287 */
27288
27289exports.ACK = 3;
27290
27291/**
27292 * Packet type `error`.
27293 *
27294 * @api public
27295 */
27296
27297exports.ERROR = 4;
27298
27299/**
27300 * Packet type 'binary event'
27301 *
27302 * @api public
27303 */
27304
27305exports.BINARY_EVENT = 5;
27306
27307/**
27308 * Packet type `binary ack`. For acks with binary arguments.
27309 *
27310 * @api public
27311 */
27312
27313exports.BINARY_ACK = 6;
27314
27315/**
27316 * Encoder constructor.
27317 *
27318 * @api public
27319 */
27320
27321exports.Encoder = Encoder;
27322
27323/**
27324 * Decoder constructor.
27325 *
27326 * @api public
27327 */
27328
27329exports.Decoder = Decoder;
27330
27331/**
27332 * A socket.io Encoder instance
27333 *
27334 * @api public
27335 */
27336
27337function Encoder() {}
27338
27339/**
27340 * Encode a packet as a single string if non-binary, or as a
27341 * buffer sequence, depending on packet type.
27342 *
27343 * @param {Object} obj - packet object
27344 * @param {Function} callback - function to handle encodings (likely engine.write)
27345 * @return Calls callback with Array of encodings
27346 * @api public
27347 */
27348
27349Encoder.prototype.encode = function(obj, callback){
27350 debug('encoding packet %j', obj);
27351
27352 if (exports.BINARY_EVENT == obj.type || exports.BINARY_ACK == obj.type) {
27353 encodeAsBinary(obj, callback);
27354 }
27355 else {
27356 var encoding = encodeAsString(obj);
27357 callback([encoding]);
27358 }
27359};
27360
27361/**
27362 * Encode packet as string.
27363 *
27364 * @param {Object} packet
27365 * @return {String} encoded
27366 * @api private
27367 */
27368
27369function encodeAsString(obj) {
27370 var str = '';
27371 var nsp = false;
27372
27373 // first is type
27374 str += obj.type;
27375
27376 // attachments if we have them
27377 if (exports.BINARY_EVENT == obj.type || exports.BINARY_ACK == obj.type) {
27378 str += obj.attachments;
27379 str += '-';
27380 }
27381
27382 // if we have a namespace other than `/`
27383 // we append it followed by a comma `,`
27384 if (obj.nsp && '/' != obj.nsp) {
27385 nsp = true;
27386 str += obj.nsp;
27387 }
27388
27389 // immediately followed by the id
27390 if (null != obj.id) {
27391 if (nsp) {
27392 str += ',';
27393 nsp = false;
27394 }
27395 str += obj.id;
27396 }
27397
27398 // json data
27399 if (null != obj.data) {
27400 if (nsp) str += ',';
27401 str += json.stringify(obj.data);
27402 }
27403
27404 debug('encoded %j as %s', obj, str);
27405 return str;
27406}
27407
27408/**
27409 * Encode packet as 'buffer sequence' by removing blobs, and
27410 * deconstructing packet into object with placeholders and
27411 * a list of buffers.
27412 *
27413 * @param {Object} packet
27414 * @return {Buffer} encoded
27415 * @api private
27416 */
27417
27418function encodeAsBinary(obj, callback) {
27419
27420 function writeEncoding(bloblessData) {
27421 var deconstruction = binary.deconstructPacket(bloblessData);
27422 var pack = encodeAsString(deconstruction.packet);
27423 var buffers = deconstruction.buffers;
27424
27425 buffers.unshift(pack); // add packet info to beginning of data list
27426 callback(buffers); // write all the buffers
27427 }
27428
27429 binary.removeBlobs(obj, writeEncoding);
27430}
27431
27432/**
27433 * A socket.io Decoder instance
27434 *
27435 * @return {Object} decoder
27436 * @api public
27437 */
27438
27439function Decoder() {
27440 this.reconstructor = null;
27441}
27442
27443/**
27444 * Mix in `Emitter` with Decoder.
27445 */
27446
27447Emitter(Decoder.prototype);
27448
27449/**
27450 * Decodes an ecoded packet string into packet JSON.
27451 *
27452 * @param {String} obj - encoded packet
27453 * @return {Object} packet
27454 * @api public
27455 */
27456
27457Decoder.prototype.add = function(obj) {
27458 var packet;
27459 if ('string' == typeof obj) {
27460 packet = decodeString(obj);
27461 if (exports.BINARY_EVENT == packet.type || exports.BINARY_ACK == packet.type) { // binary packet's json
27462 this.reconstructor = new BinaryReconstructor(packet);
27463
27464 // no attachments, labeled binary but no binary data to follow
27465 if (this.reconstructor.reconPack.attachments === 0) {
27466 this.emit('decoded', packet);
27467 }
27468 } else { // non-binary full packet
27469 this.emit('decoded', packet);
27470 }
27471 }
27472 else if (isBuf(obj) || obj.base64) { // raw binary data
27473 if (!this.reconstructor) {
27474 throw new Error('got binary data when not reconstructing a packet');
27475 } else {
27476 packet = this.reconstructor.takeBinaryData(obj);
27477 if (packet) { // received final buffer
27478 this.reconstructor = null;
27479 this.emit('decoded', packet);
27480 }
27481 }
27482 }
27483 else {
27484 throw new Error('Unknown type: ' + obj);
27485 }
27486};
27487
27488/**
27489 * Decode a packet String (JSON data)
27490 *
27491 * @param {String} str
27492 * @return {Object} packet
27493 * @api private
27494 */
27495
27496function decodeString(str) {
27497 var p = {};
27498 var i = 0;
27499
27500 // look up type
27501 p.type = Number(str.charAt(0));
27502 if (null == exports.types[p.type]) return error();
27503
27504 // look up attachments if type binary
27505 if (exports.BINARY_EVENT == p.type || exports.BINARY_ACK == p.type) {
27506 var buf = '';
27507 while (str.charAt(++i) != '-') {
27508 buf += str.charAt(i);
27509 if (i == str.length) break;
27510 }
27511 if (buf != Number(buf) || str.charAt(i) != '-') {
27512 throw new Error('Illegal attachments');
27513 }
27514 p.attachments = Number(buf);
27515 }
27516
27517 // look up namespace (if any)
27518 if ('/' == str.charAt(i + 1)) {
27519 p.nsp = '';
27520 while (++i) {
27521 var c = str.charAt(i);
27522 if (',' == c) break;
27523 p.nsp += c;
27524 if (i == str.length) break;
27525 }
27526 } else {
27527 p.nsp = '/';
27528 }
27529
27530 // look up id
27531 var next = str.charAt(i + 1);
27532 if ('' !== next && Number(next) == next) {
27533 p.id = '';
27534 while (++i) {
27535 var c = str.charAt(i);
27536 if (null == c || Number(c) != c) {
27537 --i;
27538 break;
27539 }
27540 p.id += str.charAt(i);
27541 if (i == str.length) break;
27542 }
27543 p.id = Number(p.id);
27544 }
27545
27546 // look up json data
27547 if (str.charAt(++i)) {
27548 try {
27549 p.data = json.parse(str.substr(i));
27550 } catch(e){
27551 return error();
27552 }
27553 }
27554
27555 debug('decoded %s as %j', str, p);
27556 return p;
27557}
27558
27559/**
27560 * Deallocates a parser's resources
27561 *
27562 * @api public
27563 */
27564
27565Decoder.prototype.destroy = function() {
27566 if (this.reconstructor) {
27567 this.reconstructor.finishedReconstruction();
27568 }
27569};
27570
27571/**
27572 * A manager of a binary event's 'buffer sequence'. Should
27573 * be constructed whenever a packet of type BINARY_EVENT is
27574 * decoded.
27575 *
27576 * @param {Object} packet
27577 * @return {BinaryReconstructor} initialized reconstructor
27578 * @api private
27579 */
27580
27581function BinaryReconstructor(packet) {
27582 this.reconPack = packet;
27583 this.buffers = [];
27584}
27585
27586/**
27587 * Method to be called when binary data received from connection
27588 * after a BINARY_EVENT packet.
27589 *
27590 * @param {Buffer | ArrayBuffer} binData - the raw binary data received
27591 * @return {null | Object} returns null if more binary data is expected or
27592 * a reconstructed packet object if all buffers have been received.
27593 * @api private
27594 */
27595
27596BinaryReconstructor.prototype.takeBinaryData = function(binData) {
27597 this.buffers.push(binData);
27598 if (this.buffers.length == this.reconPack.attachments) { // done with buffer list
27599 var packet = binary.reconstructPacket(this.reconPack, this.buffers);
27600 this.finishedReconstruction();
27601 return packet;
27602 }
27603 return null;
27604};
27605
27606/**
27607 * Cleans up binary packet reconstruction variables.
27608 *
27609 * @api private
27610 */
27611
27612BinaryReconstructor.prototype.finishedReconstruction = function() {
27613 this.reconPack = null;
27614 this.buffers = [];
27615};
27616
27617function error(data){
27618 return {
27619 type: exports.ERROR,
27620 data: 'parser error'
27621 };
27622}
27623
27624},{"./binary":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-parser/binary.js","./is-buffer":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-parser/is-buffer.js","component-emitter":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-parser/node_modules/component-emitter/index.js","debug":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/debug/browser.js","isarray":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-parser/node_modules/isarray/index.js","json3":"/home/employee-2klic/projects/2klic_io-sdk/node_modules/json3/lib/json3.js"}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-parser/is-buffer.js":[function(require,module,exports){
27625(function (global){
27626
27627module.exports = isBuf;
27628
27629/**
27630 * Returns true if obj is a buffer or an arraybuffer.
27631 *
27632 * @api private
27633 */
27634
27635function isBuf(obj) {
27636 return (global.Buffer && global.Buffer.isBuffer(obj)) ||
27637 (global.ArrayBuffer && obj instanceof ArrayBuffer);
27638}
27639
27640}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
27641},{}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-parser/node_modules/component-emitter/index.js":[function(require,module,exports){
27642arguments[4]["/home/employee-2klic/projects/2klic_io-sdk/node_modules/engine.io-client/node_modules/component-emitter/index.js"][0].apply(exports,arguments)
27643},{}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/socket.io-parser/node_modules/isarray/index.js":[function(require,module,exports){
27644arguments[4]["/home/employee-2klic/projects/2klic_io-sdk/node_modules/engine.io-parser/node_modules/isarray/index.js"][0].apply(exports,arguments)
27645},{}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/to-array/index.js":[function(require,module,exports){
27646module.exports = toArray
27647
27648function toArray(list, index) {
27649 var array = []
27650
27651 index = index || 0
27652
27653 for (var i = index || 0; i < list.length; i++) {
27654 array[i - index] = list[i]
27655 }
27656
27657 return array
27658}
27659
27660},{}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/utf8/utf8.js":[function(require,module,exports){
27661(function (global){
27662/*! https://mths.be/utf8js v2.0.0 by @mathias */
27663;(function(root) {
27664
27665 // Detect free variables `exports`
27666 var freeExports = typeof exports == 'object' && exports;
27667
27668 // Detect free variable `module`
27669 var freeModule = typeof module == 'object' && module &&
27670 module.exports == freeExports && module;
27671
27672 // Detect free variable `global`, from Node.js or Browserified code,
27673 // and use it as `root`
27674 var freeGlobal = typeof global == 'object' && global;
27675 if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) {
27676 root = freeGlobal;
27677 }
27678
27679 /*--------------------------------------------------------------------------*/
27680
27681 var stringFromCharCode = String.fromCharCode;
27682
27683 // Taken from https://mths.be/punycode
27684 function ucs2decode(string) {
27685 var output = [];
27686 var counter = 0;
27687 var length = string.length;
27688 var value;
27689 var extra;
27690 while (counter < length) {
27691 value = string.charCodeAt(counter++);
27692 if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
27693 // high surrogate, and there is a next character
27694 extra = string.charCodeAt(counter++);
27695 if ((extra & 0xFC00) == 0xDC00) { // low surrogate
27696 output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
27697 } else {
27698 // unmatched surrogate; only append this code unit, in case the next
27699 // code unit is the high surrogate of a surrogate pair
27700 output.push(value);
27701 counter--;
27702 }
27703 } else {
27704 output.push(value);
27705 }
27706 }
27707 return output;
27708 }
27709
27710 // Taken from https://mths.be/punycode
27711 function ucs2encode(array) {
27712 var length = array.length;
27713 var index = -1;
27714 var value;
27715 var output = '';
27716 while (++index < length) {
27717 value = array[index];
27718 if (value > 0xFFFF) {
27719 value -= 0x10000;
27720 output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
27721 value = 0xDC00 | value & 0x3FF;
27722 }
27723 output += stringFromCharCode(value);
27724 }
27725 return output;
27726 }
27727
27728 function checkScalarValue(codePoint) {
27729 if (codePoint >= 0xD800 && codePoint <= 0xDFFF) {
27730 throw Error(
27731 'Lone surrogate U+' + codePoint.toString(16).toUpperCase() +
27732 ' is not a scalar value'
27733 );
27734 }
27735 }
27736 /*--------------------------------------------------------------------------*/
27737
27738 function createByte(codePoint, shift) {
27739 return stringFromCharCode(((codePoint >> shift) & 0x3F) | 0x80);
27740 }
27741
27742 function encodeCodePoint(codePoint) {
27743 if ((codePoint & 0xFFFFFF80) == 0) { // 1-byte sequence
27744 return stringFromCharCode(codePoint);
27745 }
27746 var symbol = '';
27747 if ((codePoint & 0xFFFFF800) == 0) { // 2-byte sequence
27748 symbol = stringFromCharCode(((codePoint >> 6) & 0x1F) | 0xC0);
27749 }
27750 else if ((codePoint & 0xFFFF0000) == 0) { // 3-byte sequence
27751 checkScalarValue(codePoint);
27752 symbol = stringFromCharCode(((codePoint >> 12) & 0x0F) | 0xE0);
27753 symbol += createByte(codePoint, 6);
27754 }
27755 else if ((codePoint & 0xFFE00000) == 0) { // 4-byte sequence
27756 symbol = stringFromCharCode(((codePoint >> 18) & 0x07) | 0xF0);
27757 symbol += createByte(codePoint, 12);
27758 symbol += createByte(codePoint, 6);
27759 }
27760 symbol += stringFromCharCode((codePoint & 0x3F) | 0x80);
27761 return symbol;
27762 }
27763
27764 function utf8encode(string) {
27765 var codePoints = ucs2decode(string);
27766 var length = codePoints.length;
27767 var index = -1;
27768 var codePoint;
27769 var byteString = '';
27770 while (++index < length) {
27771 codePoint = codePoints[index];
27772 byteString += encodeCodePoint(codePoint);
27773 }
27774 return byteString;
27775 }
27776
27777 /*--------------------------------------------------------------------------*/
27778
27779 function readContinuationByte() {
27780 if (byteIndex >= byteCount) {
27781 throw Error('Invalid byte index');
27782 }
27783
27784 var continuationByte = byteArray[byteIndex] & 0xFF;
27785 byteIndex++;
27786
27787 if ((continuationByte & 0xC0) == 0x80) {
27788 return continuationByte & 0x3F;
27789 }
27790
27791 // If we end up here, it’s not a continuation byte
27792 throw Error('Invalid continuation byte');
27793 }
27794
27795 function decodeSymbol() {
27796 var byte1;
27797 var byte2;
27798 var byte3;
27799 var byte4;
27800 var codePoint;
27801
27802 if (byteIndex > byteCount) {
27803 throw Error('Invalid byte index');
27804 }
27805
27806 if (byteIndex == byteCount) {
27807 return false;
27808 }
27809
27810 // Read first byte
27811 byte1 = byteArray[byteIndex] & 0xFF;
27812 byteIndex++;
27813
27814 // 1-byte sequence (no continuation bytes)
27815 if ((byte1 & 0x80) == 0) {
27816 return byte1;
27817 }
27818
27819 // 2-byte sequence
27820 if ((byte1 & 0xE0) == 0xC0) {
27821 var byte2 = readContinuationByte();
27822 codePoint = ((byte1 & 0x1F) << 6) | byte2;
27823 if (codePoint >= 0x80) {
27824 return codePoint;
27825 } else {
27826 throw Error('Invalid continuation byte');
27827 }
27828 }
27829
27830 // 3-byte sequence (may include unpaired surrogates)
27831 if ((byte1 & 0xF0) == 0xE0) {
27832 byte2 = readContinuationByte();
27833 byte3 = readContinuationByte();
27834 codePoint = ((byte1 & 0x0F) << 12) | (byte2 << 6) | byte3;
27835 if (codePoint >= 0x0800) {
27836 checkScalarValue(codePoint);
27837 return codePoint;
27838 } else {
27839 throw Error('Invalid continuation byte');
27840 }
27841 }
27842
27843 // 4-byte sequence
27844 if ((byte1 & 0xF8) == 0xF0) {
27845 byte2 = readContinuationByte();
27846 byte3 = readContinuationByte();
27847 byte4 = readContinuationByte();
27848 codePoint = ((byte1 & 0x0F) << 0x12) | (byte2 << 0x0C) |
27849 (byte3 << 0x06) | byte4;
27850 if (codePoint >= 0x010000 && codePoint <= 0x10FFFF) {
27851 return codePoint;
27852 }
27853 }
27854
27855 throw Error('Invalid UTF-8 detected');
27856 }
27857
27858 var byteArray;
27859 var byteCount;
27860 var byteIndex;
27861 function utf8decode(byteString) {
27862 byteArray = ucs2decode(byteString);
27863 byteCount = byteArray.length;
27864 byteIndex = 0;
27865 var codePoints = [];
27866 var tmp;
27867 while ((tmp = decodeSymbol()) !== false) {
27868 codePoints.push(tmp);
27869 }
27870 return ucs2encode(codePoints);
27871 }
27872
27873 /*--------------------------------------------------------------------------*/
27874
27875 var utf8 = {
27876 'version': '2.0.0',
27877 'encode': utf8encode,
27878 'decode': utf8decode
27879 };
27880
27881 // Some AMD build optimizers, like r.js, check for specific condition patterns
27882 // like the following:
27883 if (
27884 typeof define == 'function' &&
27885 typeof define.amd == 'object' &&
27886 define.amd
27887 ) {
27888 define(function() {
27889 return utf8;
27890 });
27891 } else if (freeExports && !freeExports.nodeType) {
27892 if (freeModule) { // in Node.js or RingoJS v0.8.0+
27893 freeModule.exports = utf8;
27894 } else { // in Narwhal or RingoJS v0.7.0-
27895 var object = {};
27896 var hasOwnProperty = object.hasOwnProperty;
27897 for (var key in utf8) {
27898 hasOwnProperty.call(utf8, key) && (freeExports[key] = utf8[key]);
27899 }
27900 }
27901 } else { // in Rhino or a web browser
27902 root.utf8 = utf8;
27903 }
27904
27905}(this));
27906
27907}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
27908},{}],"/home/employee-2klic/projects/2klic_io-sdk/node_modules/yeast/index.js":[function(require,module,exports){
27909'use strict';
27910
27911var alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_'.split('')
27912 , length = 64
27913 , map = {}
27914 , seed = 0
27915 , i = 0
27916 , prev;
27917
27918/**
27919 * Return a string representing the specified number.
27920 *
27921 * @param {Number} num The number to convert.
27922 * @returns {String} The string representation of the number.
27923 * @api public
27924 */
27925function encode(num) {
27926 var encoded = '';
27927
27928 do {
27929 encoded = alphabet[num % length] + encoded;
27930 num = Math.floor(num / length);
27931 } while (num > 0);
27932
27933 return encoded;
27934}
27935
27936/**
27937 * Return the integer value specified by the given string.
27938 *
27939 * @param {String} str The string to convert.
27940 * @returns {Number} The integer value represented by the string.
27941 * @api public
27942 */
27943function decode(str) {
27944 var decoded = 0;
27945
27946 for (i = 0; i < str.length; i++) {
27947 decoded = decoded * length + map[str.charAt(i)];
27948 }
27949
27950 return decoded;
27951}
27952
27953/**
27954 * Yeast: A tiny growing id generator.
27955 *
27956 * @returns {String} A unique id.
27957 * @api public
27958 */
27959function yeast() {
27960 var now = encode(+new Date());
27961
27962 if (now !== prev) return seed = 0, prev = now;
27963 return now +'.'+ encode(seed++);
27964}
27965
27966//
27967// Map each character to its index.
27968//
27969for (; i < length; i++) map[alphabet[i]] = i;
27970
27971//
27972// Expose the `yeast`, `encode` and `decode` functions.
27973//
27974yeast.encode = encode;
27975yeast.decode = decode;
27976module.exports = yeast;
27977
27978},{}],"/home/employee-2klic/projects/2klic_io-sdk/src/index.js":[function(require,module,exports){
27979var HttpClient = require('./lib/http-client');
27980var events = require('events');
27981var inherits = require('inherits');
27982var StreamAPI = require('./lib/stream_api');
27983var _ = require('lodash');
27984var Logger = require('./lib/logger');
27985
27986function Klic(options){
27987 options = options || {};
27988 this.base_url = options.url || "https://api.2klic.io";
27989 this.apiVersion = options.apiVersion || "1.0";
27990 this.auth = options.auth || {};
27991
27992 this.logger = new Logger((options.log_level >= 0) ? options.log_level : 6);
27993
27994 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 });
27995
27996 // Install all supported API endpoints
27997 this.alarm = require("./lib/methods/alarm/alarm")({ platform: this });
27998 this.zones = require("./lib/methods/alarm/zones")({ platform: this });
27999 //this.sectors = require("./lib/methods/sectors")({ platform: this });
28000 this.noc = require("./lib/methods/noc/noc")({ platform: this });
28001 this.cameras = require("./lib/methods/cameras")({ platform: this });
28002 this.streams = require("./lib/methods/streams")({ platform: this });
28003 this.devices = require("./lib/methods/devices")({ platform: this });
28004 this.zwave = require("./lib/methods/zwave")({ platform: this });
28005 this.events = require("./lib/methods/events")({ platform: this });
28006 this.locations = require("./lib/methods/locations")({ platform: this });
28007 this.scenarios = require("./lib/methods/scenarios")({ platform: this });
28008 this.models = require("./lib/methods/models")({ platform: this });
28009 this.notifications = require("./lib/methods/notifications")({ platform: this });
28010 this.translations = require("./lib/methods/translations")({ platform: this });
28011 this.user = require("./lib/methods/user")({ platform: this });
28012 this.templates = require("./lib/methods/templates")({ platform: this });
28013 this.system = require("./lib/methods/system")({ platform: this });
28014 this.access = require("./lib/methods/access/access")({ platform: this });
28015}
28016
28017inherits(Klic, events.EventEmitter);
28018
28019Klic.prototype.authenticate = require('./lib/methods/authenticate');
28020Klic.prototype.register = require('./lib/methods/register');
28021
28022module.exports = Klic;
28023
28024},{"./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/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){
28025(function (Buffer){
28026var request = require('request');
28027
28028var MixinPromise = require('./mixin_promise');
28029var _ = require('lodash');
28030
28031function HttpClient(baseUrl, options) {
28032 options = options || {};
28033 this.url = baseUrl;
28034 this.app_key = options.app_key;
28035 this.app_type = options.app_type || 'browser';
28036 this.app_secret = options.app_secret;
28037 this.unsafe = options.unsafe;
28038 this.logger = options.logger;
28039 this.api_version = options.api_version;
28040 this.callback = _.noop;
28041 this.enableCallback = options.enableCallback || true;
28042}
28043
28044HttpClient.prototype.request = function(method, path, body, options) {
28045 var _this = this;
28046 this.logger.trace("Executing HTTP request " + method + " " + path);
28047
28048 if(arguments.length === 3) {
28049 options = body;
28050 body = undefined;
28051 }
28052 else if(arguments.length === 2) {
28053 options = {};
28054 }
28055
28056 options = options || {};
28057
28058 return new MixinPromise(function(resolve, reject) {
28059
28060 var headers = {};
28061
28062 if (options.token) {
28063 _this.logger.trace("Token was provided. Adding Authorization header");
28064 headers['authorization'] = "Bearer " + options.token;
28065 _this.logger.trace(headers['authorization']);
28066 }
28067 else if (options.basic) {
28068 _this.logger.trace("Basic credentials were provided. Adding Authorization header");
28069 var str = new Buffer(options.basic.username + ":" + options.basic.password, "utf8").toString("base64");
28070 headers['authorization'] = "Basic " + str;
28071 }
28072
28073 if (options.app_key || _this.app_key) {
28074 _this.logger.trace("Configuring X-App-Key to ", options.app_key || _this.app_key);
28075 headers['x-app-key'] = options.app_key || _this.app_key;
28076 }
28077
28078 if (options.unsafe || _this.unsafe) {
28079 _this.logger.trace("Indicating to the platform that we are in the browser (unsafe)");
28080 headers['x-unsafe-auth'] = options.unsafe || _this.unsafe;
28081 }
28082
28083 if (options.api_version || _this.api_version) {
28084 headers['x-api-version'] = options.api_version || _this.api_version;
28085 }
28086
28087 if (options.app_type || _this.app_type) {
28088 headers['x-app-type'] = options.app_type || _this.app_type;
28089 }
28090
28091 _this.logger.trace("Request URL is: " + method + " " + _this.url + path);
28092
28093 return new MixinPromise(function (resolve, reject) {
28094 request({
28095 method: method,
28096 url: _this.url + path,
28097 json: body,
28098 headers: headers,
28099 verbose: false,
28100 //withCredentials: true,
28101 timeout: options.timeout || 30000,
28102 qs: options.query || null
28103 }, function (err, resp, body) {
28104 if (err) {
28105 _this.logger.error("HTTP ERROR:", err);
28106 reject(err);
28107 }
28108 else {
28109 _this.logger.trace("Receive a valid HTTP response");
28110 if (resp.statusCode >= 400) {
28111 _this.logger.error("Receive status code %d", resp.statusCode);
28112 err = new Error("HTTP " + resp.statusCode + ": " + method + " " + path);
28113 err.statusCode = resp.statusCode;
28114 err.statusText = resp.statusText;
28115
28116 if (_isJson(body)) body = JSON.parse(body);
28117 err.code = body.code;
28118 err.parameters = body.parameters;
28119 err.message = body.message;
28120
28121 if (body.details) err.details = body.details;
28122
28123 err.error = resp.error;
28124 err.body = body;
28125 reject(err);
28126 }
28127 else if (resp.statusCode === 0) {
28128 _this.logger.error("Unable to connect to platform");
28129 err = new Error("Unable to connect to server");
28130 err.statusCode = 0;
28131 reject(err);
28132 }
28133 else if (body) {
28134 _this.logger.trace("Receive a valid body");
28135 if (_.isString(body)) {
28136 body = JSON.parse(body);
28137 }
28138
28139 if (body.data) {
28140 resolve(body);
28141 }
28142 else {
28143 _this.logger.trace("Resolving response promise. Status Code=", resp.statusCode);
28144 resolve({statusCode: resp.statusCode, data: body});
28145 }
28146 }
28147 else {
28148 _this.logger.trace("Resolving without body. Status code = %d", resp.statusCode);
28149 resolve({statusCode: resp.statusCode});
28150 }
28151 }
28152 });
28153 }).then(function (res) {
28154 resolve(res);
28155 }).catch(function (error) {
28156 if (_this.enableCallback) {
28157 var p = _this.callback(error);
28158 var isPromise = _.isObject(p) && _.isFunction(p.then);
28159
28160 if (isPromise) {
28161 p.then(function () {
28162 reject(error);
28163 });
28164 }
28165 else reject(error);
28166 }
28167 });
28168 });
28169};
28170
28171HttpClient.prototype.post = function(path, body, options) {
28172 if(typeof(body) === 'object') body = _.omit(body, function(prop){ if(typeof(prop)==='string' && !prop.length) return true });
28173 return this.request('POST', path, body, options);
28174};
28175
28176HttpClient.prototype.delete = function(path, options) {
28177 return this.request('DELETE', path, options);
28178};
28179
28180HttpClient.prototype.get = function(path, options) {
28181 return this.request('GET', path, options);
28182};
28183
28184HttpClient.prototype.put = function(path, body, options) {
28185 if(typeof(body) === 'object') body = _.omit(body, function(prop){ if(typeof(prop)==='string' && !prop.length) return true });
28186 if(arguments.length === 2) {
28187 options = body;
28188 body = undefined;
28189 }
28190 return this.request('PUT', path, body, options);
28191};
28192
28193HttpClient.prototype.patch = function(path, body, options) {
28194 if(typeof(body) === 'object') body = _.omit(body, function(prop){ if(typeof(prop)==='string' && !prop.length) return true });
28195 return this.request('PATCH', path, body, options);
28196};
28197
28198function _isJson(str) {
28199 try {
28200 JSON.parse(str);
28201 } catch (e) {
28202 return false;
28203 }
28204 return true;
28205}
28206
28207module.exports = HttpClient;
28208}).call(this,require("buffer").Buffer)
28209},{"./mixin_promise":"/home/employee-2klic/projects/2klic_io-sdk/src/lib/mixin_promise.js","buffer":"/home/employee-2klic/projects/2klic_io-sdk/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){
28210function Logger(level) {
28211 this.level = level;
28212}
28213
28214Logger.prototype.trace = function() {
28215 if(this.level > 9) {
28216 console.log.apply(console, arguments);
28217 }
28218};
28219
28220Logger.prototype.debug = function() {
28221 if(this.level > 7) {
28222 console.log.apply(console, arguments);
28223 }
28224};
28225
28226Logger.prototype.info = function() {
28227 if(this.level > 5) {
28228 console.log.apply(console, arguments);
28229 }
28230};
28231
28232Logger.prototype.warn = function() {
28233 if(this.level > 3) {
28234 console.log.apply(console, arguments);
28235 }
28236};
28237
28238Logger.prototype.error = function() {
28239 if(this.level > 1) {
28240 console.log.apply(console, arguments);
28241 }
28242};
28243
28244Logger.prototype.fatal = function() {
28245 console.log.apply(console, arguments);
28246};
28247
28248module.exports = Logger;
28249},{}],"/home/employee-2klic/projects/2klic_io-sdk/src/lib/methods/access/access.js":[function(require,module,exports){
28250'use strict';
28251var Cards = require("./cards");
28252
28253function Access(options) {
28254 options = options || {};
28255 this.platform = options.platform;
28256 this.cards = new Cards ({ platform: this.platform });
28257}
28258
28259Access.prototype.list = function(params){
28260 return this.platform.http.get('/access/', { query: params, token: this.platform.auth.token });
28261};
28262
28263Access.prototype.get = function(id, params){
28264 return this.platform.http.get('/access/'+id, { query: params, token: this.platform.auth.token });
28265};
28266
28267Access.prototype.create = function(accessData){
28268 return this.platform.http.post('/access', accessData, { token: this.platform.auth.token });
28269};
28270
28271Access.prototype.update = function(id, accessData){
28272 return this.platform.http.put('/access/' + id, accessData, { token: this.platform.auth.token });
28273};
28274
28275Access.prototype.patch = function(id, accessData){
28276 return this.platform.http.patch('/access/' + d, accessData, { token: this.platform.auth.token });
28277};
28278
28279Access.prototype.patch = function(id, accessData){
28280 return this.platform.http.patch('/access/' + id, accessData, { token: this.platform.auth.token });
28281};
28282
28283
28284module.exports = function(options) {
28285 options = options || {};
28286 return new Access(options);
28287};
28288
28289},{"./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){
28290'use strict';
28291
28292function Cards(options) {
28293 options = options || {};
28294 this.platform = options.platform;
28295}
28296
28297Cards.prototype.list= function(){
28298 return this.platform.http.get('/access/cards', { token: this.platform.auth.token });
28299};
28300
28301Cards.prototype.get= function(id){
28302 return this.platform.http.get('/access/cards/' + id, { token: this.platform.auth.token });
28303};
28304
28305Cards.prototype.create= function(cardData){
28306 return this.platform.http.post('/access/cards', cardData, { token: this.platform.auth.token });
28307};
28308
28309Cards.prototype.update= function(id, cardData){
28310 return this.platform.http.put('/access/cards/' + id, cardData, { token: this.platform.auth.token });
28311};
28312
28313Cards.prototype.patch = function(id, cardData){
28314 return this.platform.http.patch ('/access/cards/' + id, cardData, { token: this.platform.auth.token });
28315};
28316
28317module.exports = function(options) {
28318 options = options || {};
28319 return new Cards(options);
28320};
28321
28322},{}],"/home/employee-2klic/projects/2klic_io-sdk/src/lib/methods/alarm/alarm.js":[function(require,module,exports){
28323'use strict';
28324var User = require("./user");
28325var Pin = require("./pin");
28326var Zone = require("./zones");
28327
28328function Alarm(options) {
28329 options = options || {};
28330 this.platform = options.platform;
28331 this.user = new User({ platform: this.platform });
28332 this.pin = new Pin({ platform: this.platform });
28333 this.zones = new Zone({ platform: this.platform });
28334}
28335
28336// Provision an alarm system
28337Alarm.prototype.create = function(alarm){
28338 return this.platform.http.post('/alarms', alarm, { token: this.platform.auth.token });
28339};
28340
28341// Get a an alarm system state
28342Alarm.prototype.get = function(alarmId){
28343 return this.platform.http.get('/alarms/'+alarmId, { token: this.platform.auth.token });
28344};
28345
28346Alarm.prototype.list = function(){
28347 return this.platform.http.get('/alarms', { token: this.platform.auth.token });
28348};
28349
28350Alarm.prototype.patch = function(alarm, alarmId){
28351 return this.platform.http.patch('/alarms/'+alarmId, alarm, { token: this.platform.auth.token });
28352};
28353
28354Alarm.prototype.delete = function(alarmId){
28355 return this.platform.http.delete('/alarms/'+alarmId, { token: this.platform.auth.token });
28356};
28357
28358Alarm.prototype.getToken = function(alarmId, pin){
28359 return this.platform.http.post('/alarms/'+alarmId+'/auth/token', { pin: pin }, { token: this.platform.auth.token });
28360};
28361
28362// Reset the alarm service
28363Alarm.prototype.reset = function(alarmId){
28364 return this.platform.http.post('/alarms/'+alarmId+'/reset', {}, { token: this.platform.auth.token });
28365};
28366
28367Alarm.prototype.arm = function(alarmId, armToken, state, bypassedZoneIds){
28368 return this.platform.http.put('/alarms/'+alarmId, { state: state, bypassed: bypassedZoneIds }, { query: { armToken: armToken }, token: this.platform.auth.token });
28369};
28370
28371module.exports = function(options) {
28372 options = options || {};
28373 return new Alarm(options);
28374};
28375
28376
28377},{"./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){
28378'use strict';
28379
28380function Pin(options) {
28381 options = options || {};
28382 this.platform = options.platform;
28383}
28384
28385Pin.prototype.update = function(alarmId, userId, pin){
28386 return this.platform.http.put('/alarms/'+alarmId+'/users/'+userId+'/pin', pin, { token: this.platform.auth.token });
28387};
28388
28389module.exports = function(options) {
28390 options = options || {};
28391 return new Pin(options);
28392};
28393
28394
28395},{}],"/home/employee-2klic/projects/2klic_io-sdk/src/lib/methods/alarm/user.js":[function(require,module,exports){
28396'use strict';
28397
28398function User(options) {
28399 options = options || {};
28400 this.platform = options.platform;
28401}
28402
28403// Add a user to an alarm system
28404User.prototype.create = function(alarmId, userId){
28405 return this.platform.http.post('/alarms/'+alarmId+'/users/'+userId, {}, { token: this.platform.auth.token });
28406};
28407
28408// List users in an alarm system
28409User.prototype.list = function(alarmId){
28410 return this.platform.http.get('/alarms/'+alarmId+'/users', { token: this.platform.auth.token });
28411};
28412
28413// Delete a user in an alarm system
28414User.prototype.delete = function(alarmId, userId){
28415 if(userId) return this.platform.http.delete('/alarms/'+alarmId+'/users/'+userId, { token: this.platform.auth.token });
28416 else return this.platform.http.delete('/alarms/'+alarmId+'/users', { token: this.platform.auth.token });
28417};
28418
28419
28420
28421module.exports = function(options) {
28422 options = options || {};
28423 return new User(options);
28424};
28425
28426
28427},{}],"/home/employee-2klic/projects/2klic_io-sdk/src/lib/methods/alarm/zones.js":[function(require,module,exports){
28428'use strict';
28429
28430var _ = require('lodash');
28431
28432function Zones(options) {
28433 options = options || {};
28434 this.platform = options.platform;
28435}
28436
28437// Zones
28438Zones.prototype.create = function(alarmId, zone, query){
28439 if(_.get(query, 'populate')) query.populate = query.populate.toString();
28440 return this.platform.http.post('/alarms/'+alarmId+'/zones', zone, { query: query, token: this.platform.auth.token });
28441};
28442
28443Zones.prototype.list = function(alarmId, query){
28444 if(_.get(query, 'populate')) query.populate = query.populate.toString();
28445 return this.platform.http.get('/alarms/'+alarmId+'/zones', { query: query, token: this.platform.auth.token });
28446};
28447
28448Zones.prototype.get = function(alarmId, zoneId, query){
28449 if(_.get(query, 'populate')) query.populate = query.populate.toString();
28450 return this.platform.http.get('/alarms/'+alarmId+'/zones/'+zoneId, { query: query, token: this.platform.auth.token });
28451};
28452
28453Zones.prototype.update = function(alarmId, zone, query){
28454 if(_.get(query, 'populate')) query.populate = query.populate.toString();
28455 return this.platform.http.put('/alarms/'+alarmId+'/zones/'+zone._id, zone, { query: query, token: this.platform.auth.token });
28456};
28457
28458Zones.prototype.patch = function(alarmId, obj, zoneId, query){
28459 if(_.get(query, 'populate')) query.populate = query.populate.toString();
28460 return this.platform.http.patch('/alarms/'+alarmId+'/zones/'+zoneId, obj, { query: query, token: this.platform.auth.token });
28461};
28462
28463Zones.prototype.delete = function(alarmId, zoneId, query){
28464 if(_.get(query, 'populate')) query.populate = query.populate.toString();
28465 if(zoneId) return this.platform.http.delete('/alarms/'+alarmId+'/zones/'+zoneId, { token: this.platform.auth.token });
28466 else return this.platform.http.delete('/alarms/'+alarmId+'/zones', { query: query, token: this.platform.auth.token });
28467};
28468
28469module.exports = function(options) {
28470 options = options || {};
28471 return new Zones(options);
28472};
28473
28474
28475},{"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){
28476module.exports = (function() {
28477
28478 return function(credentials, options) {
28479 var _this = this, logger = this.logger;
28480 options = options || {};
28481
28482 logger.debug("Executing HTTP request GET /auth/token");
28483 return this.http.post("/auth/token", {}, {
28484 basic: {
28485 username: credentials.username,
28486 password: credentials.password
28487 }
28488 }).then(function(resp) {
28489 logger.trace(resp);
28490 if(!_this.auth) {
28491 logger.debug("No existing platform auth field. Initializing it");
28492 _this.auth = {};
28493 }
28494 if(resp) {
28495 logger.debug("Installing token %s as default platform auth mechanism", resp.data.token);
28496 _this.auth.token = resp.data.token;
28497 return resp.data;
28498 }
28499 else {
28500 logger.error("Invalid response received from platform");
28501 }
28502
28503 });
28504
28505 };
28506
28507})();
28508},{}],"/home/employee-2klic/projects/2klic_io-sdk/src/lib/methods/cameras.js":[function(require,module,exports){
28509'use strict';
28510
28511function Cameras(options) {
28512 options = options || {};
28513 this.platform = options.platform;
28514}
28515
28516Cameras.prototype.get = function(propertyId){
28517 return this.platform.http.get('/homes/'+propertyId+'/cameras/stream/all', { token: this.platform.auth.token });
28518};
28519
28520module.exports = function(options) {
28521 options = options || {};
28522 return new Cameras(options);
28523};
28524
28525
28526},{}],"/home/employee-2klic/projects/2klic_io-sdk/src/lib/methods/devices.js":[function(require,module,exports){
28527'use strict';
28528
28529var _ = require('lodash');
28530
28531function Devices(options) {
28532 options = options || {};
28533 this.platform = options.platform;
28534}
28535
28536Devices.prototype.list = function(query){
28537 if(_.get(query, 'populate')) query.populate = query.populate.toString();
28538 return this.platform.http.get('/devices', { query: query, token: this.platform.auth.token });
28539};
28540
28541Devices.prototype.get = function(deviceId, query){
28542 if(_.get(query, 'populate')) query.populate = query.populate.toString();
28543 return this.platform.http.get('/devices/'+deviceId, { query: query, token: this.platform.auth.token });
28544};
28545
28546Devices.prototype.getChildren = function(deviceId, level, query){
28547 if(_.get(query, 'populate')) query.populate = query.populate.toString();
28548 var query = _.merge({ showChildren: true, level: level }, query);
28549 return this.platform.http.get('/devices/'+deviceId, { query: query, token: this.platform.auth.token });
28550};
28551
28552Devices.prototype.create = function(device, query){
28553 if(_.get(query, 'populate')) query.populate = query.populate.toString();
28554 return this.platform.http.post('/devices', device, { query: query, token: this.platform.auth.token });
28555};
28556
28557Devices.prototype.update = function(device, query){
28558 if(_.get(query, 'populate')) query.populate = query.populate.toString();
28559 return this.platform.http.put('/devices/'+device._id, device, { query: query, token: this.platform.auth.token });
28560};
28561
28562Devices.prototype.patch = function(obj, deviceId, query){
28563 if(_.get(query, 'populate')) query.populate = query.populate.toString();
28564 return this.platform.http.patch('/devices/'+deviceId, obj, { query: query, token: this.platform.auth.token });
28565};
28566
28567Devices.prototype.delete = function(deviceId, query){
28568 if(_.get(query, 'populate')) query.populate = query.populate.toString();
28569 return this.platform.http.delete('/devices/'+deviceId, { query: query, token: this.platform.auth.token });
28570};
28571
28572// Reset a hub
28573Devices.prototype.reset = function(deviceId){
28574 return this.platform.http.put('/devices/'+deviceId+'/reset', {}, { token: this.platform.auth.token });
28575};
28576
28577Devices.prototype.updateCapability = function(deviceId, capabilityId, value, unit, timestamp){
28578 return this.platform.http.put('/devices/'+deviceId+'/caps/'+capabilityId, { value: value, unit: unit, timestamp: timestamp }, { token: this.platform.auth.token });
28579};
28580
28581Devices.prototype.patchCapability = function(deviceId, capabilityId, obj){
28582 return this.platform.http.patch('/devices/'+deviceId+'/caps/'+capabilityId, obj, { token: this.platform.auth.token });
28583};
28584
28585Devices.prototype.getCapability = function(deviceId, capabilityId){
28586 return this.platform.http.get('/devices/'+deviceId+'/caps/'+capabilityId, { token: this.platform.auth.token });
28587};
28588
28589Devices.prototype.listCapability = function(deviceId){
28590 return this.platform.http.get('/devices/'+deviceId+'/caps', { token: this.platform.auth.token });
28591};
28592
28593// Hub provisioning
28594Devices.prototype.provision = function(name, mac, model, location){
28595 var _this = this;
28596 var obj = _.merge({ name:name, mac:mac, model:model }, { location: location }); // optional location parameter
28597 return this.platform.http.post('/devices', obj)
28598 .then(function(res){
28599 //logger.debug("Installing token %s as default platform auth mechanism", resp.data.token);
28600 if(res.data.token) _this.platform.auth.token = res.data.token;
28601 return res;
28602 })
28603};
28604
28605// Controller Heartbeat
28606Devices.prototype.heartbeat = function(deviceId, sysHealth){
28607 return this.platform.http.post('/devices/'+deviceId+'/heartbeat', sysHealth, { token: this.platform.auth.token });
28608};
28609
28610Devices.prototype.listHeartbeat = function(deviceId, query){
28611 return this.platform.http.get('/devices/'+deviceId+'/heartbeat', { query: query, token: this.platform.auth.token });
28612};
28613
28614// Controller ping
28615Devices.prototype.ping = function(deviceId){
28616 return this.platform.http.post('/devices/'+deviceId+'/ping', {}, { token: this.platform.auth.token });
28617};
28618
28619module.exports = function(options) {
28620 options = options || {};
28621 return new Devices(options);
28622};
28623
28624
28625},{"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){
28626'use strict';
28627
28628function Events(options) {
28629 options = options || {};
28630 this.platform = options.platform;
28631}
28632
28633Events.prototype.create = function(resourcePath, eventType, resource, timestamp, requestId){
28634 return this.platform.http.post('/events', { path: resourcePath, resource: resource, timestamp: timestamp, type: eventType, request: requestId }, { token: this.platform.auth.token });
28635};
28636
28637module.exports = function(options) {
28638 options = options || {};
28639 return new Events(options);
28640};
28641
28642
28643},{}],"/home/employee-2klic/projects/2klic_io-sdk/src/lib/methods/locations.js":[function(require,module,exports){
28644'use strict';
28645
28646function Locations(options) {
28647 options = options || {};
28648 this.platform = options.platform;
28649}
28650
28651Locations.prototype.list = function(level){
28652 return this.platform.http.get('/locations', { query:{ level: level }, token: this.platform.auth.token });
28653};
28654
28655Locations.prototype.get = function(locationId, level){
28656 return this.platform.http.get('/locations/'+locationId, { query: { level: level }, token: this.platform.auth.token });
28657};
28658
28659Locations.prototype.getRoot = function(locationId, level){
28660 return this.platform.http.get('/locations/'+locationId, { query: { root: true, level: level }, token: this.platform.auth.token });
28661};
28662
28663Locations.prototype.create = function(location){
28664 return this.platform.http.post('/locations', location, { token: this.platform.auth.token });
28665};
28666
28667Locations.prototype.update = function(location){
28668 return this.platform.http.put('/locations/'+location._id, location, { token: this.platform.auth.token });
28669};
28670
28671Locations.prototype.patch = function(obj, locationId){
28672 return this.platform.http.patch('/locations/'+locationId, obj, { token: this.platform.auth.token });
28673};
28674
28675Locations.prototype.delete = function(locationId){
28676 return this.platform.http.delete('/locations/'+locationId, { token: this.platform.auth.token });
28677};
28678
28679module.exports = function(options) {
28680 options = options || {};
28681 return new Locations(options);
28682};
28683
28684
28685},{}],"/home/employee-2klic/projects/2klic_io-sdk/src/lib/methods/models.js":[function(require,module,exports){
28686'use strict';
28687
28688function Models(options) {
28689 options = options || {};
28690 this.platform = options.platform;
28691}
28692
28693Models.prototype.list = function(query){
28694 return this.platform.http.get('/models', { query: query, token: this.platform.auth.token });
28695};
28696
28697Models.prototype.get = function(id, query){
28698 return this.platform.http.get('/models/'+id, { query: query, token: this.platform.auth.token });
28699};
28700
28701Models.prototype.search = function(query){
28702 return this.platform.http.get('/models', { query: query, token: this.platform.auth.token });
28703};
28704
28705module.exports = function(options) {
28706 options = options || {};
28707 return new Models(options);
28708};
28709
28710
28711},{}],"/home/employee-2klic/projects/2klic_io-sdk/src/lib/methods/noc/customers.js":[function(require,module,exports){
28712'use strict';
28713
28714function NocCustomers(options) {
28715 options = options || {};
28716 this.platform = options.platform;
28717}
28718
28719NocCustomers.prototype.list= function(nocId){
28720 return this.platform.http.get('/nocs/' + nocId + '/customers', { token: this.platform.auth.token });
28721};
28722
28723NocCustomers.prototype.get= function(nocId, customerId){
28724 return this.platform.http.get('/nocs/' + nocId + '/customers/' + customerId, { token: this.platform.auth.token });
28725};
28726
28727NocCustomers.prototype.create= function(nocId, customer){
28728 return this.platform.http.post('/nocs/' + nocId + '/customers', customer, { token: this.platform.auth.token });
28729};
28730
28731NocCustomers.prototype.update= function(nocId, customerId, customer){
28732 return this.platform.http.put('/nocs/' + nocId + '/customers/' + customerId, customer, { token: this.platform.auth.token });
28733};
28734
28735NocCustomers.prototype.patch = function(nocId, customerId, customer){
28736 return this.platform.http.patch ('/nocs/' + nocId + '/customers/' + customerId, customer, { token: this.platform.auth.token });
28737};
28738
28739NocCustomers.prototype.listDevices = function(nocId, customerId, alarmSystemId){
28740 return this.platform.http.get('/nocs/' + nocId + '/customers/' + customerId + '/devices/' + alarmSystemId, { token: this.platform.auth.token });
28741};
28742
28743NocCustomers.prototype.getPredefinedServiceActions= function(nocId, customerId, alarmSystemId){
28744 return this.platform.http.get('/nocs/' + nocId + '/customers/' + customerId + '/alarmsystem/' + alarmSystemId + '/predefined-service-actions', { token: this.platform.auth.token });
28745};
28746
28747NocCustomers.prototype.listServiceActions= function(nocId, customerId){
28748 return this.platform.http.get('/nocs/' + nocId + '/customers/' + customerId + '/actions', { token: this.platform.auth.token });
28749};
28750
28751NocCustomers.prototype.getServiceAction= function(nocId, customerId, actionId){
28752 return this.platform.http.get('/nocs/' + nocId + '/customers/' + customerId + '/actions/' + actionId, { token: this.platform.auth.token });
28753};
28754
28755NocCustomers.prototype.createServiceAction= function(nocId, customerId, actionData){
28756 return this.platform.http.post('/nocs/' + nocId + '/customers/' + customerId + '/actions', actionData, { token: this.platform.auth.token });
28757};
28758
28759NocCustomers.prototype.updateServiceAction = function(nocId, customerId, actionId, actionData){
28760 return this.platform.http.put('/nocs/' + nocId + '/customers/' + customerId + '/actions/' + actionId, actionData, { token: this.platform.auth.token });
28761};
28762
28763NocCustomers.prototype.listInstallations= function(nocId){
28764 return this.platform.http.get('/nocs/' + nocId + '/customers/installations', { token: this.platform.auth.token });
28765};
28766
28767NocCustomers.prototype.getInstallation= function(nocId, installationId){
28768 return this.platform.http.get('/nocs/' + nocId + '/customers/installations/' + installationId, { token: this.platform.auth.token });
28769};
28770
28771NocCustomers.prototype.createInstallation= function(nocId, installationData){
28772 return this.platform.http.post('/nocs/' + nocId + '/customers/installations', installationData, { token: this.platform.auth.token });
28773};
28774
28775NocCustomers.prototype.updateInstallation= function(nocId, installationId, installationData){
28776 return this.platform.http.put('/nocs/' + nocId + '/customers/installations/' + installationId, installationData, { token: this.platform.auth.token });
28777};
28778
28779
28780module.exports = function(options) {
28781 options = options || {};
28782 return new NocCustomers(options);
28783};
28784
28785},{}],"/home/employee-2klic/projects/2klic_io-sdk/src/lib/methods/noc/noc.js":[function(require,module,exports){
28786'use strict';
28787var NocCustomers = require("./customers");
28788var NocTickets = require("./tickets");
28789var NocServices = require("./services");
28790var NocServiceActions = require("./service_actions");
28791
28792function Noc(options) {
28793 options = options || {};
28794 this.platform = options.platform;
28795 this.customers = new NocCustomers({ platform: this.platform });
28796 this.tickets = new NocTickets({ platform: this.platform });
28797 this.services = new NocServices({ platform: this.platform });
28798 this.service_actions = new NocServiceActions({ platform: this.platform });
28799}
28800
28801Noc.prototype.list = function() {
28802 return this.platform.http.get('/nocs/', { token: this.platform.auth.token });
28803};
28804
28805Noc.prototype.get = function(nocId){
28806 return this.platform.http.get('/nocs/' + nocId, { token: this.platform.auth.token });
28807};
28808
28809Noc.prototype.create = function(noc){
28810 return this.platform.http.post('/nocs', noc, { token: this.platform.auth.token });
28811};
28812
28813Noc.prototype.update = function(nocId, noc){
28814 return this.platform.http.put('/nocs/' + nocId, noc, { token: this.platform.auth.token });
28815};
28816
28817Noc.prototype.patch = function(nocId, noc){
28818 return this.platform.http.patch('/nocs/' + nocId, noc, { token: this.platform.auth.token });
28819};
28820
28821Noc.prototype.approve = function(nocId, approvalToken){
28822 return this.platform.http.put('/nocs/' + nocId + '/approve/' + approvalToken);
28823};
28824
28825Noc.prototype.approval_link = function(email){
28826 return this.platform.http.get('/nocs/approval-link/' + email);
28827};
28828
28829module.exports = function(options) {
28830 options = options || {};
28831 return new Noc(options);
28832};
28833
28834},{"./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){
28835'use strict';
28836
28837function NocServiceActions(options) {
28838 options = options || {};
28839 this.platform = options.platform;
28840}
28841
28842NocServiceActions.prototype.list= function(nocId){
28843 return this.platform.http.get('/nocs/' + nocId + '/service_actions', { token: this.platform.auth.token });
28844};
28845
28846NocServiceActions.prototype.get= function(nocId, serviceId){
28847 return this.platform.http.get('/nocs/' + nocId + '/service_actions/' + serviceId, { token: this.platform.auth.token });
28848};
28849
28850NocServiceActions.prototype.getPredefinedServiceActions= function(nocId){
28851 return this.platform.http.get('/nocs/' + nocId + '/service_actions/predefined', { token: this.platform.auth.token });
28852};
28853
28854NocServiceActions.prototype.create= function(nocId, serviceActions){
28855 return this.platform.http.post('/nocs/' + nocId + '/service_actions', serviceActions, { token: this.platform.auth.token });
28856};
28857
28858NocServiceActions.prototype.update= function(nocId, serviceId, serviceActions){
28859 return this.platform.http.put('/nocs/' + nocId + '/service_actions/' + serviceId, serviceActions, { token: this.platform.auth.token });
28860};
28861
28862NocServiceActions.prototype.patch = function(nocId, serviceId, serviceActions){
28863 return this.platform.http.patch ('/nocs/' + nocId + '/service_actions/' + serviceId, serviceActions, { token: this.platform.auth.token });
28864};
28865
28866module.exports = function(options) {
28867 options = options || {};
28868 return new NocServiceActions(options);
28869};
28870
28871},{}],"/home/employee-2klic/projects/2klic_io-sdk/src/lib/methods/noc/services.js":[function(require,module,exports){
28872'use strict';
28873
28874function NocServices(options) {
28875 options = options || {};
28876 this.platform = options.platform;
28877}
28878
28879NocServices.prototype.list= function(nocId){
28880 return this.platform.http.get('/nocs/' + nocId + '/services', { token: this.platform.auth.token });
28881};
28882
28883NocServices.prototype.get= function(nocId, serviceId){
28884 return this.platform.http.get('/nocs/' + nocId + '/services/' + serviceId, { token: this.platform.auth.token });
28885};
28886
28887NocServices.prototype.create= function(nocId, service){
28888 return this.platform.http.post('/nocs/' + nocId + '/services', service, { token: this.platform.auth.token });
28889};
28890
28891NocServices.prototype.update= function(nocId, serviceId, service){
28892 return this.platform.http.put('/nocs/' + nocId + '/services/' + serviceId, service, { token: this.platform.auth.token });
28893};
28894
28895NocServices.prototype.patch = function(nocId, serviceId, service){
28896 return this.platform.http.patch ('/nocs/' + nocId + '/services/' + serviceId, service, { token: this.platform.auth.token });
28897};
28898
28899module.exports = function(options) {
28900 options = options || {};
28901 return new NocServices(options);
28902};
28903
28904},{}],"/home/employee-2klic/projects/2klic_io-sdk/src/lib/methods/noc/tickets.js":[function(require,module,exports){
28905'use strict';
28906
28907function NocTickets(options) {
28908 options = options || {};
28909 this.platform = options.platform;
28910}
28911
28912NocTickets.prototype.list = function(nocId){
28913 return this.platform.http.get('/nocs/' + nocId + '/noc_tickets', { token: this.platform.auth.token });
28914};
28915
28916NocTickets.prototype.get = function(nocId, ticketId){
28917 return this.platform.http.get('/nocs/' + nocId + '/noc_tickets/' + ticketId, { token: this.platform.auth.token });
28918};
28919
28920NocTickets.prototype.update = function(nocId, ticketId, ticket){
28921 return this.platform.http.put('/nocs/' + nocId + '/noc_tickets/' + ticketId, ticket, { token: this.platform.auth.token });
28922};
28923
28924NocTickets.prototype.patch = function(nocId, ticketId, ticket){
28925 return this.platform.http.patch ('/nocs/' + nocId + '/noc_tickets/' + ticketId, ticket, { token: this.platform.auth.token });
28926};
28927
28928NocTickets.prototype.create = function(nocId, ticket){
28929 return this.platform.http.post('/nocs' + nocId + '/noc_ticket', ticket, { token: this.platform.auth.token });
28930};
28931
28932NocTickets.prototype.listDevices = function(nocId, ticketId){
28933 return this.platform.http.get('/nocs/' + nocId + '/noc_tickets/' + ticketId + '/devices', { token: this.platform.auth.token });
28934};
28935
28936NocTickets.prototype.listEvents = function(nocId, ticketId){
28937 return this.platform.http.get('/nocs/' + nocId + '/noc_tickets/' + ticketId + '/noc_ticket_events', { token: this.platform.auth.token });
28938};
28939
28940NocTickets.prototype.getEvent = function(nocId, ticketId, ticketEventId){
28941 return this.platform.http.get('/nocs/' + nocId + '/noc_tickets/' + ticketId + '/noc_ticket_events/' + ticketEventId, { token: this.platform.auth.token });
28942};
28943
28944NocTickets.prototype.createEvent = function(nocId, ticketId, ticketEvent){
28945 return this.platform.http.post('/nocs/' + nocId + '/noc_tickets/' + ticketId + '/noc_ticket_events', ticketEvent, { token: this.platform.auth.token });
28946};
28947
28948NocTickets.prototype.updateEvent= function(nocId, ticketId, ticketEventId, ticketEvent){
28949 return this.platform.http.put('/nocs/' + nocId + '/noc_tickets/' + ticketId + '/noc_ticket_events/' + ticketEventId, ticketEvent, { token: this.platform.auth.token });
28950};
28951
28952NocTickets.prototype.patchEvent = function(nocId, ticketId, ticketEventId, ticketEvent){
28953 return this.platform.http.patch ('/nocs/' + nocId + '/noc_tickets/' + ticketId + '/noc_ticket_events/' + ticketEventId, ticketEvent, { token: this.platform.auth.token });
28954};
28955
28956module.exports = function(options) {
28957 options = options || {};
28958 return new NocTickets(options);
28959};
28960
28961},{}],"/home/employee-2klic/projects/2klic_io-sdk/src/lib/methods/notifications.js":[function(require,module,exports){
28962'use strict';
28963
28964function Notifications(options) {
28965 options = options || {};
28966 this.platform = options.platform;
28967}
28968
28969Notifications.prototype.list = function(params){
28970 return this.platform.http.get('/notifications', { query: params, token: this.platform.auth.token });
28971};
28972
28973Notifications.prototype.get = function(locationId, params){
28974 return this.platform.http.get('/locations/'+locationId+'/notifications', { query: params, token: this.platform.auth.token });
28975};
28976
28977Notifications.prototype.patch = function(notificationId, obj){
28978 return this.platform.http.patch('/notifications/'+notificationId, obj, { token: this.platform.auth.token });
28979};
28980
28981Notifications.prototype.markRead = function(notificationId){
28982 return this.platform.http.patch('/notifications/'+notificationId, { read: true, readTs: Date.now() }, { token: this.platform.auth.token });
28983};
28984
28985Notifications.prototype.getConfig = function(){
28986 return this.platform.http.get('/notifications/config', { token: this.platform.auth.token });
28987};
28988
28989Notifications.prototype.updateConfig = function(config){
28990 return this.platform.http.put('/notifications/config' + (config._id ? "/"+config._id:""), config, { token: this.platform.auth.token });
28991};
28992
28993module.exports = function(options) {
28994 options = options || {};
28995 return new Notifications(options);
28996};
28997
28998
28999},{}],"/home/employee-2klic/projects/2klic_io-sdk/src/lib/methods/register.js":[function(require,module,exports){
29000module.exports = (function() {
29001
29002 return function(user, options) {
29003 var _this = this, logger = this.logger;
29004 options = options || {};
29005
29006 logger.debug("Executing HTTP request GET /auth/register");
29007 return this.http.post("/auth/register", user, options).then(function(resp) {
29008 logger.debug(resp);
29009 if(resp) {
29010 return resp.data;
29011 }
29012 else {
29013 logger.error("Invalid response received from platform");
29014 }
29015
29016 });
29017
29018 };
29019
29020})();
29021
29022},{}],"/home/employee-2klic/projects/2klic_io-sdk/src/lib/methods/scenarios.js":[function(require,module,exports){
29023'use strict';
29024
29025function Scenarios(options) {
29026 options = options || {};
29027 this.platform = options.platform;
29028}
29029
29030Scenarios.prototype.list = function(){
29031 return this.platform.http.get('/scenarios', { token: this.platform.auth.token });
29032};
29033
29034Scenarios.prototype.get = function(scenarioId){
29035 return this.platform.http.get('/scenarios/'+scenarioId, { token: this.platform.auth.token });
29036};
29037
29038Scenarios.prototype.create = function(scenario){
29039 return this.platform.http.post('/scenarios', scenario, { token: this.platform.auth.token });
29040};
29041
29042Scenarios.prototype.update = function(scenario){
29043 return this.platform.http.put('/scenarios/'+scenario._id, scenario, { token: this.platform.auth.token });
29044};
29045
29046Scenarios.prototype.patch = function(scenarioId, obj){
29047 return this.platform.http.patch('/scenarios/'+scenarioId, obj, { token: this.platform.auth.token });
29048};
29049
29050Scenarios.prototype.delete = function(scenarioId){
29051 return this.platform.http.delete('/scenarios/'+scenarioId, { token: this.platform.auth.token });
29052};
29053
29054module.exports = function(options) {
29055 options = options || {};
29056 return new Scenarios(options);
29057};
29058
29059
29060},{}],"/home/employee-2klic/projects/2klic_io-sdk/src/lib/methods/streams.js":[function(require,module,exports){
29061'use strict';
29062
29063function Streams(options) {
29064 options = options || {};
29065 this.platform = options.platform;
29066}
29067
29068Streams.prototype.list = function() {
29069 return this.platform.http.get('/streams', { token: this.platform.auth.token });
29070};
29071
29072Streams.prototype.listRecord = function( device ) {
29073 return this.platform.http.get('/streams/record/' + device, { token: this.platform.auth.token });
29074};
29075
29076Streams.prototype.startRecord = function( device, quality ) {
29077 return this.platform.http.get('/streams/record/' + device + '/' + quality + '/start', { token: this.platform.auth.token });
29078};
29079
29080Streams.prototype.stopRecord = function( device, quality ) {
29081 return this.platform.http.get('/streams/record/' + device + '/' + quality + '/stop', { token: this.platform.auth.token });
29082};
29083
29084Streams.prototype.startPlayback = function( record, timestamp ) {
29085 return this.platform.http.get('/streams/playback/' + record + '/start/' + timestamp, { token: this.platform.auth.token });
29086};
29087
29088Streams.prototype.updatePlayback = function( record, timestamp ) {
29089 return this.platform.http.get('/streams/playback/' + record + '/update/' + timestamp, { token: this.platform.auth.token });
29090};
29091
29092Streams.prototype.stopPlayback = function( record ) {
29093 return this.platform.http.get('/streams/playback/' + record + '/stop', { token: this.platform.auth.token });
29094};
29095
29096module.exports = function(options) {
29097 options = options || {};
29098 return new Streams(options);
29099};
29100
29101
29102},{}],"/home/employee-2klic/projects/2klic_io-sdk/src/lib/methods/system.js":[function(require,module,exports){
29103'use strict';
29104
29105function System(options) {
29106 options = options || {};
29107 this.platform = options.platform;
29108}
29109
29110System.prototype.info = function(){
29111 return this.platform.http.get('/system/info');
29112};
29113
29114module.exports = function(options) {
29115 options = options || {};
29116 return new System(options);
29117};
29118
29119},{}],"/home/employee-2klic/projects/2klic_io-sdk/src/lib/methods/templates.js":[function(require,module,exports){
29120'use strict';
29121
29122function Templates(options) {
29123 options = options || {};
29124 this.platform = options.platform;
29125}
29126
29127Templates.prototype.list = function(){
29128 return this.platform.http.get('/templates', { token: this.platform.auth.token });
29129};
29130
29131Templates.prototype.get = function(templateId, level){
29132 return this.platform.http.get('/templates/'+templateId, { query: { level: level }, token: this.platform.auth.token });
29133};
29134
29135Templates.prototype.create = function(template){
29136 return this.platform.http.post('/templates', template, { token: this.platform.auth.token });
29137};
29138
29139Templates.prototype.patch = function(obj, templateId){
29140 return this.platform.http.patch('/templates/'+templateId, obj, { token: this.platform.auth.token });
29141};
29142
29143Templates.prototype.delete = function(templateId){
29144 return this.platform.http.delete('/templates/'+templateId, { token: this.platform.auth.token });
29145};
29146
29147module.exports = function(options) {
29148 options = options || {};
29149 return new Templates(options);
29150};
29151
29152},{}],"/home/employee-2klic/projects/2klic_io-sdk/src/lib/methods/translations.js":[function(require,module,exports){
29153'use strict';
29154
29155function Translations(options) {
29156 options = options || {};
29157 this.platform = options.platform;
29158}
29159
29160Translations.prototype.list = function(){
29161 return this.platform.http.get('/translations', { token: this.platform.auth.token });
29162};
29163
29164Translations.prototype.get = function(key){
29165 return this.platform.http.get('/translations/'+key, { token: this.platform.auth.token });
29166};
29167
29168Translations.prototype.create = function(translation){
29169 return this.platform.http.post('/translations', translation, { token: this.platform.auth.token });
29170};
29171
29172Translations.prototype.update = function(key, translation){
29173 return this.platform.http.put('/translations/'+key, translation, { token: this.platform.auth.token });
29174};
29175
29176
29177module.exports = function(options) {
29178 options = options || {};
29179 return new Translations(options);
29180};
29181
29182
29183},{}],"/home/employee-2klic/projects/2klic_io-sdk/src/lib/methods/user.js":[function(require,module,exports){
29184'use strict';
29185
29186function User(options) {
29187 options = options || {};
29188 this.platform = options.platform;
29189}
29190
29191User.prototype.get = function(username){
29192 return this.platform.http.get('/users/'+username, { token: this.platform.auth.token });
29193};
29194
29195User.prototype.register = function(user){
29196 return this.platform.http.post('/auth/register', user);
29197};
29198
29199User.prototype.forgot = function(email){
29200 return this.platform.http.get('/auth/forgot/'+email);
29201};
29202
29203User.prototype.reset = function(resetToken){
29204 return this.platform.http.get('/auth/reset/'+resetToken);
29205};
29206
29207User.prototype.resetPassword = function(resetToken, passwordInfo){
29208 return this.platform.http.post('/auth/reset/'+resetToken, passwordInfo);
29209};
29210
29211User.prototype.confirm = function(key){
29212 return this.platform.http.get('/auth/confirm/'+key);
29213};
29214
29215User.prototype.changePassword = function(username, currentPassword, password){
29216 return this.platform.http.put('/users/'+username+'/password', { current:currentPassword, password:password }, { token: this.platform.auth.token });
29217};
29218
29219User.prototype.list = function(){
29220 return this.platform.http.get('/users', { token: this.platform.auth.token });
29221};
29222
29223User.prototype.listAlarmSystems = function(userId){
29224 return this.platform.http.get('/users/' + userId + '/alarms', { token: this.platform.auth.token });
29225};
29226
29227User.prototype.getCurrentUser = function(options){
29228 var token;
29229 options ? token = options.token : token = undefined;
29230 return this.platform.http.get('/users/me', { token: token || this.platform.auth.token });
29231};
29232
29233User.prototype.update = function(username, user){
29234 return this.platform.http.put('/users/'+username, user, { token: this.platform.auth.token });
29235};
29236
29237User.prototype.patch = function(username, obj){
29238 return this.platform.http.patch('/users/'+username, obj, { token: this.platform.auth.token });
29239};
29240
29241User.prototype.delete = function(username){
29242 return this.platform.http.delete('/users/'+username, { token: this.platform.auth.token });
29243};
29244
29245User.prototype.bindDevice = function(mac, location){
29246 return this.platform.http.post('/devices/bind', { mac: mac, location: location }, { token: this.platform.auth.token });
29247};
29248
29249module.exports = function(options) {
29250 options = options || {};
29251 return new User(options);
29252};
29253
29254},{}],"/home/employee-2klic/projects/2klic_io-sdk/src/lib/methods/zwave.js":[function(require,module,exports){
29255'use strict';
29256
29257function ZWave(options) {
29258 options = options || {};
29259 this.platform = options.platform;
29260}
29261
29262ZWave.prototype.exclusion = function(gatewayId){
29263 return this.platform.http.post('/devices/'+gatewayId+'/zwave/exclude', {}, { token: this.platform.auth.token });
29264};
29265
29266ZWave.prototype.removeFailed = function(gatewayId){
29267 return this.platform.http.delete('/devices/'+gatewayId+'/zwave/failed', {}, { token: this.platform.auth.token });
29268};
29269
29270module.exports = function(options) {
29271 options = options || {};
29272 return new ZWave(options);
29273};
29274
29275
29276},{}],"/home/employee-2klic/projects/2klic_io-sdk/src/lib/mixin_promise.js":[function(require,module,exports){
29277var P = require("bluebird").noConflict();
29278
29279P.prototype.mixin = function(cstor) {
29280 var o = new cstor();
29281 o.__p = this;
29282
29283 o.catch = function(fn) {
29284 this.__p.catch.call(this.__p, fn.bind(this));
29285 return this;
29286 };
29287
29288 o.then = o.ready = function(fn) {
29289 this.__p.then.call(this.__p, fn.bind(this));
29290 return this;
29291 };
29292
29293 o.finally = function(fn) {
29294 this.__p.finally.apply(this.__p, fn.bind(this));
29295 return this;
29296 };
29297
29298 return o;
29299};
29300
29301module.exports = P;
29302},{"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){
29303var socketIOClient = require('socket.io-client');
29304var events = require('events');
29305var inherits = require('inherits');
29306var _ = require('lodash');
29307
29308function Subscriber(channelString, handler) {
29309 this.channelString = channelString;
29310 this.handler = handler;
29311}
29312
29313Subscriber.prototype.handle = function(event) {
29314
29315 if(this.channelString.indexOf('*') !== -1) {
29316 var channel = this.channelString.split('/')[0];
29317 if(event.type.indexOf(channel) !== -1) {
29318 this.handler(event);
29319 }
29320 }
29321 else if(this.channelString === event.type) {
29322 return this.handler(event);
29323 }
29324
29325};
29326
29327function Channel(key, api) {
29328 this.key = key;
29329 this.api = api;
29330 events.EventEmitter.call(this);
29331}
29332inherits(Channel, events.EventEmitter);
29333
29334/*
29335 * Subscribe to the channel using scope token and
29336 * @param: options
29337 * token: A valid platform token providing access to private events as per the token scope
29338 * type: A string or array of event type to be notified (optional)
29339 * handler: A function that will be called with the event data
29340 * scope: The scope that will be used when calling the callback. default to global.
29341 * persistence: (optional). Provide a persistence strategy for unreceived events. (TBD)
29342 */
29343Channel.subscribe = function(options) {
29344 var subscribeKey = "/" + this.key + "/";
29345 if(_.isString(options.type)) {
29346 subscribeKey += options.type;
29347 }
29348 else {
29349 subscribeKey += "*";
29350 }
29351
29352 return this.api.subscribe(subscribeKey, (function(options) {
29353 var types = [];
29354 if(_.isString(options.type)) {
29355 types = options.type.split(',');
29356 }
29357 else {
29358 types = options.types;
29359 }
29360
29361 return function(event) {
29362 if(types.indexOf(event.type) !== -1) {
29363 options.handler.call(options.scope || this, event);
29364 }
29365 }
29366 })(options), { token: options.token, persistence: options.persistence });
29367};
29368
29369function _handleEvent(event) {
29370 var _this = this;
29371
29372 _.each(this.subscribers, function(subscriber) {
29373
29374 // Provide a simple mechanism to handle replies to specific events
29375 subscriber.handle(event, function(reply) {
29376 _this.socket.emit('reply', {
29377 replyTo: event.id,
29378 data: reply
29379 });
29380 });
29381
29382 });
29383
29384}
29385
29386function StreamAPI(options) {
29387 options = options || {};
29388
29389 this.url = options.url;
29390 this.subscribers = [];
29391
29392 this.socket = socketIOClient(options.url, options.socket);
29393
29394 events.EventEmitter.call(this);
29395
29396 // Connect all stream API event handlers
29397 this.socket.on('connect', function() {
29398 console.log("Stream API is CONNECTED to %s", this.url);
29399 this.emit('connect');
29400 }.bind(this));
29401
29402 this.socket.on('disconnect', function() {
29403 console.log("Stream API is DISCONNECTED from %s", this.url);
29404 this.emit('disconnect');
29405 }.bind(this));
29406
29407 this.socket.on('event', _handleEvent.bind(this));
29408
29409 // Create all secure channels
29410 StreamAPI.catalog = new Channel("catalog", this);
29411 StreamAPI.klic = new Channel("2klic", this);
29412 StreamAPI.marketplace = new Channel("marketplace", this);
29413 StreamAPI.social = new Channel("social", this);
29414 StreamAPI.profile = new Channel("profile", this);
29415 StreamAPI.system = new Channel("system", this);
29416
29417}
29418
29419inherits(StreamAPI, events.EventEmitter);
29420
29421StreamAPI.prototype.subscribe = function(channelString, handler, options) {
29422 options = options || {};
29423
29424 // Register a listener in our socket
29425 this.subscribers.push(new Subscriber(channelString, handler));
29426
29427 this.socket.emit('subscribe', {
29428 channel: channelString,
29429 token: options.token,
29430 persistence: options.persistence
29431 });
29432};
29433
29434module.exports = StreamAPI;
29435},{"events":"/home/employee-2klic/projects/2klic_io-sdk/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")
29436});
29437//# sourceMappingURL=2klic.js.map